Add hose-ebot command for Hose outbound discovery and approval callback

This commit is contained in:
gitea committed 2026-10-16 11:19:50 +08:00
1 parent 21e1a9d27a
commit bbff9338a0
15 files changed
+1242 -17

No files matched your search

+580
View File
@@ -0,0 +1,580 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { KyInstance } from "ky";
import { CorpConfigSchema } from "../../core/config/types.js";
import { classifyCliError } from "../../core/errors.js";
import { parseArgs } from "../parser.js";
import { handleHoseEbotCommand } from "./hose-ebot.js";
const ORIGINAL_ENV = {
tokenStore: process.env.SEAL_USE_TOKEN_STORE,
usageFile: process.env.SEAL_USE_USAGE_FILE
};
const ORIGINAL_FETCH = globalThis.fetch;
const ORIGINAL_LOG = console.log;
const ORIGINAL_ERROR = console.error;
let tempDir: string | undefined;
beforeEach(() => {
tempDir = mkdtempSync(join(tmpdir(), "seal-use-hose-ebot-area-"));
process.env.SEAL_USE_TOKEN_STORE = join(tempDir, "tokens.json");
process.env.SEAL_USE_USAGE_FILE = join(tempDir, "usage.json");
});
afterEach(() => {
restoreEnv("SEAL_USE_TOKEN_STORE", ORIGINAL_ENV.tokenStore);
restoreEnv("SEAL_USE_USAGE_FILE", ORIGINAL_ENV.usageFile);
globalThis.fetch = ORIGINAL_FETCH;
console.log = ORIGINAL_LOG;
console.error = ORIGINAL_ERROR;
if (tempDir) {
rmSync(tempDir, { recursive: true, force: true });
tempDir = undefined;
}
});
function restoreEnv(name: string, value: string | undefined) {
if (value === undefined) delete process.env[name];
else process.env[name] = value;
}
const hoseCorp = CorpConfigSchema.parse({
id: "hose-ebot",
name: "合思 EBot 测试企业",
environment: "test",
seal: { url: "https://hose-ebot.sealai.cc" },
source: {
type: "hose",
domain: "https://app.ekuaibao.com",
appKey: "key-1",
appSecurity: "sec-1",
closeToken: "web-session-token",
corpId: "ID01LG7ksGroB1",
staffId: "ID01LG7ksGroB1:ID01KsDgHaH5nN"
}
});
const hoseCorpNoOpenApiCredentials = CorpConfigSchema.parse({
...hoseCorp,
id: "hose-ebot-nocreds",
source: {
type: "hose",
domain: "https://app.ekuaibao.com",
closeToken: "web-session-token",
corpId: "ID01LG7ksGroB1",
staffId: "ID01LG7ksGroB1:ID01KsDgHaH5nN"
}
});
const sealCorp = CorpConfigSchema.parse({
id: "seal-ebot",
name: "原生 Seal 企业",
environment: "test",
seal: { url: "https://seal.test", endpoints: { approvalStylePreferences: "api/custom/preferences" } },
source: {
type: "seal",
sealUrl: "https://seal.test",
token: "mock-token",
staffId: "seal-staff",
corpId: "seal-corp"
}
});
const messageFixture = {
items: [
{
id: "ID01Vj4Zq1Lytp",
messageName: "希尔顿Seal AI审核1",
messageType: "flow",
enable: true,
signKey: "Q4H15lpixMyE7secretvalue",
callbackUrl: "https://sealai.cc/api/hosecloud/outbound?config_id=Q4H15lpixMyE7secretvalue",
corporationId: "ID01LG7ksGroB1",
actionEvent: ["backlog.processed"],
formFields: ["action", "flowId", "nodeId"]
},
{
id: "ID01Vj4VDa8CGH",
messageName: "完成回调",
messageType: "message",
enable: false,
signKey: "Q4H15lpixOtherSecret",
callbackUrl: "https://sealai.cc/api/hosecloud/complete",
corporationId: "ID01LG7ksGroB1",
actionEvent: ["flow.completed"]
}
]
};
const logFixture = {
items: [
{
id: "log-1",
name: "出站调用",
type: "INVOKING",
state: "SUCCESS",
createTime: 1727764000000,
flowId: { id: "FLOW-1", form: { code: "SN123" } },
nodeName: "AI 审核节点",
request: {
flowId: "FLOW-1",
nodeId: "NODE-1",
messageId: "MSG-1",
rejectionNum: 0
}
},
{
id: "log-2",
name: "审批回调",
type: "CALLBACK",
state: "SUCCESS",
createTime: 1727764010000,
flowId: { id: "FLOW-1", form: { code: "SN123" } },
nodeName: "AI 审核节点",
request: {
flowId: "FLOW-1",
nodeId: "NODE-1",
signKey: "Q4H15lpixMyE7secretvalue",
action: "accept",
comment: "AI 审核通过"
}
}
]
};
function mockFetch(responses: {
messages?: unknown;
logs?: unknown;
token?: unknown;
approval?: unknown;
}) {
const record: {
calls: number;
messageUrl?: string;
logUrl?: string;
logBody?: unknown;
tokenUrl?: string;
tokenBody?: unknown;
approvalUrl?: string;
approvalBody?: unknown;
} = { calls: 0 };
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
record.calls++;
const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : (input as Request).url;
let bodyText: string | undefined;
if (init?.body) {
bodyText = String(init.body);
} else if (input && typeof input === "object" && "clone" in input) {
bodyText = await (input as Request).clone().text().catch(() => undefined);
}
if (url.includes("/api/outbound/v1/message/messageLog")) {
record.logUrl = url;
record.logBody = bodyText ? JSON.parse(bodyText) : undefined;
return new Response(JSON.stringify(responses.logs ?? logFixture), {
status: 200,
headers: { "content-type": "application/json" }
});
}
if (url.includes("/api/outbound/v1/message")) {
record.messageUrl = url;
return new Response(JSON.stringify(responses.messages ?? messageFixture), {
status: 200,
headers: { "content-type": "application/json" }
});
}
if (url.includes("/api/openapi/v1/auth/getAccessToken") || url.includes("/api/openapi/v1/accessToken")) {
record.tokenUrl = url;
record.tokenBody = bodyText ? JSON.parse(bodyText) : undefined;
return new Response(
JSON.stringify(responses.token ?? { accessToken: "live-openapi-token" }),
{ status: 200, headers: { "content-type": "application/json" } }
);
}
if (url.includes("/api/openapi/v1/approval")) {
record.approvalUrl = url;
record.approvalBody = bodyText ? JSON.parse(bodyText) : undefined;
const resp = responses.approval ?? { value: { code: "204", message: "EBot执行完成" } };
return new Response(JSON.stringify(resp), {
status: 200,
headers: { "content-type": "application/json" }
});
}
return new Response(JSON.stringify({ error: "unexpected url", url }), { status: 500 });
}) as typeof fetch;
return record;
}
function fakeClient(integrations: Array<Record<string, unknown>> = []) {
return {
get: async () => ({
json: async () => ({ integrations })
})
} as unknown as KyInstance;
}
async function callHoseEbot(client: KyInstance, corp: typeof hoseCorp, argv: string[]) {
const lines: string[] = [];
console.log = (line: string) => lines.push(String(line));
console.error = () => {};
const args = parseArgs(argv);
await handleHoseEbotCommand(args.command[1], args.command[2], client, corp, args);
return JSON.parse(lines.join("\n")) as Record<string, unknown>;
}
async function captureError(action: () => Promise<unknown>): Promise<unknown> {
try {
await action();
} catch (error) {
return error;
}
throw new Error("expected action to throw, but it succeeded");
}
describe("hose-ebot messages", () => {
test("lists configured outbound messages with a masked signKey by default", async () => {
const record = mockFetch({});
const output = await callHoseEbot(fakeClient(), hoseCorp, ["hose-ebot", "messages"]);
expect(output.count).toBe(2);
expect(record.messageUrl).toContain("corpId=ID01LG7ksGroB1");
const messages = output.messages as Array<Record<string, unknown>>;
expect(messages[0]).toMatchObject({
id: "ID01Vj4Zq1Lytp",
messageName: "希尔顿Seal AI审核1",
messageType: "flow",
enable: true
});
// maskHoseSecurity keeps the first 8 and last 4 characters.
expect(messages[0]!.signKey).toBe("Q4H15lpi...alue");
expect(messages[0]!.signKey).not.toBe("Q4H15lpixMyE7secretvalue");
expect(messages[0]!.callbackUrl).toContain("config_id=Q4H15lpixMyE7secretvalue");
expect(output.revealed).toBe(false);
});
test("filters by type and reveals the signKey with --reveal", async () => {
mockFetch({});
const output = await callHoseEbot(fakeClient(), hoseCorp, [
"hose-ebot", "messages", "--type", "flow", "--reveal"
]);
expect(output.count).toBe(1);
expect(output.revealed).toBe(true);
const messages = output.messages as Array<Record<string, unknown>>;
expect(messages).toHaveLength(1);
expect(messages[0]!.signKey).toBe("Q4H15lpixMyE7secretvalue");
});
test("rejects a non-Hose enterprise with exit code 13", async () => {
const record = mockFetch({});
const error = await captureError(() =>
callHoseEbot(fakeClient(), sealCorp, ["hose-ebot", "messages"])
);
expect(classifyCliError(error).exitCode).toBe(13);
expect(record.calls).toBe(0);
});
});
describe("hose-ebot search", () => {
test("requires an SN and lists records with their unique ids", async () => {
const usageError = await captureError(() =>
callHoseEbot(fakeClient(), hoseCorp, ["hose-ebot", "search"])
);
expect(classifyCliError(usageError).exitCode).toBe(2);
const record = mockFetch({});
const output = await callHoseEbot(fakeClient(), hoseCorp, [
"hose-ebot", "search", "SN123", "--limit", "5"
]);
expect(output.count).toBe(2);
expect(output.sn).toBe("SN123");
expect(output.type).toBe("all");
expect(record.logBody).toMatchObject({
limit: { start: 0, count: 5 },
filterBy: '(flowId.form.code==("SN123"))'
});
const records = output.records as Array<Record<string, unknown>>;
expect(records[0]).toMatchObject({ id: "log-1", type: "INVOKING" });
expect((records[0]!.request as Record<string, unknown>).nodeId).toBe("NODE-1");
// Callback records embed signKey; masked unless --reveal.
expect((records[1]!.request as Record<string, unknown>).signKey).not.toBe(
"Q4H15lpixMyE7secretvalue"
);
});
test("filters to invoking or callback records with --type", async () => {
const record = mockFetch({});
const output = await callHoseEbot(fakeClient(), hoseCorp, [
"hose-ebot", "search", "SN123", "--type", "callback"
]);
expect(output.type).toBe("callback");
expect(output.count).toBe(1);
const records = output.records as Array<Record<string, unknown>>;
expect(records[0]!.type).toBe("CALLBACK");
// The client-side filter over-fetches first so the page stays full.
expect(record.logBody).toMatchObject({ limit: { start: 0, count: 80 } });
// Also accepts uppercase --type CALLBACK
const outputUpper = await callHoseEbot(fakeClient(), hoseCorp, [
"hose-ebot", "search", "SN123", "--type", "CALLBACK"
]);
expect(outputUpper.count).toBe(1);
});
test("reveals the record signKey with --reveal", async () => {
mockFetch({});
const output = await callHoseEbot(fakeClient(), hoseCorp, [
"hose-ebot", "search", "SN123", "--reveal"
]);
const records = output.records as Array<Record<string, unknown>>;
expect((records[1]!.request as Record<string, unknown>).signKey).toBe(
"Q4H15lpixMyE7secretvalue"
);
});
test("rejects an unknown verb with exit code 2", async () => {
const error = await captureError(() => callHoseEbot(fakeClient(), hoseCorp, ["hose-ebot", "banana"]));
expect(classifyCliError(error).exitCode).toBe(2);
expect(String((error as Error).message)).toContain("Unknown hose-ebot command");
});
});
describe("hose-ebot callback", () => {
const callbackArgv = (extra: string[] = []) => [
"hose-ebot", "callback",
"--flow-id", "FLOW-1",
"--node-id", "NODE-1",
"--action", "accept",
"--comment", "同意",
...extra
];
test("refuses to run without --yes/--confirm before any network call", async () => {
const record = mockFetch({});
const error = await captureError(() =>
callHoseEbot(fakeClient(), hoseCorp, callbackArgv(["--sign-key", "sig-1"]))
);
expect(classifyCliError(error).exitCode).toBe(10);
expect(record.calls).toBe(0);
expect(classifyCliError(error).nextAction).toContain("seal-use hose-ebot callback");
});
test("previews a masked payload with --dry-run without minting a token", async () => {
const record = mockFetch({});
const output = await callHoseEbot(fakeClient(), hoseCorp, [
...callbackArgv(["--sign-key", "sig-1", "--dry-run"])
]);
expect(output.preview).toBe(true);
expect(output.endpoint).toBe("https://app.ekuaibao.com/api/openapi/v1/approval");
const payload = output.payload as Record<string, unknown>;
expect(payload).toMatchObject({
flowId: "FLOW-1",
nodeId: "NODE-1",
action: "accept",
comment: "同意"
});
expect(payload.signKey).not.toBe("sig-1");
expect(record.calls).toBe(0);
});
test("mints a fresh accessToken and posts the callback on a confirmed run", async () => {
const record = mockFetch({});
const output = await callHoseEbot(fakeClient(), hoseCorp, callbackArgv([
"--sign-key", "sig-1",
"--yes"
]));
expect(output).toMatchObject({
ok: true,
code: "204",
message: "EBot执行完成",
flowId: "FLOW-1",
nodeId: "NODE-1",
action: "accept"
});
expect(record.approvalUrl).toContain("/api/openapi/v1/approval");
expect(record.approvalUrl).toContain("accessToken=live-openapi-token");
expect(record.approvalBody).toMatchObject({
signKey: "sig-1",
flowId: "FLOW-1",
nodeId: "NODE-1",
action: "accept",
comment: "同意"
});
});
test("normalizes action aliases like agree/approve/reject", async () => {
const record = mockFetch({});
await callHoseEbot(fakeClient(), hoseCorp, [
"hose-ebot", "callback",
"--sign-key", "sig-1",
"--flow-id", "FLOW-1",
"--node-id", "NODE-1",
"--action", "agree",
"--comment", "口语化同意",
"--yes"
]);
expect(record.approvalBody).toMatchObject({ action: "accept" });
await callHoseEbot(fakeClient(), hoseCorp, [
"hose-ebot", "callback",
"--sign-key", "sig-1",
"--flow-id", "FLOW-1",
"--node-id", "NODE-1",
"--action", "reject",
"--comment", "口语化驳回",
"--yes"
]);
expect(record.approvalBody).toMatchObject({ action: "refuse" });
});
test("passes optional callback fields through to the wire payload with camelCase support", async () => {
const record = mockFetch({});
await callHoseEbot(fakeClient(), hoseCorp, [
"hose-ebot", "callback",
"--sign-key", "sig-1",
"--flow-id", "FLOW-1",
"--node-id", "NODE-1",
"--action", "refuse",
"--comment", "驳回",
"--policy", "ALL",
"--addApproverIds", "staff-1,staff-2",
"--rejectTo", "NODE-0",
"--resubmitMethod", "TO_REJECTOR",
"--yes"
]);
expect(record.approvalBody).toMatchObject({
action: "refuse",
policy: "ALL",
addApproverIds: ["staff-1", "staff-2"],
rejectTo: "NODE-0",
resubmitMethod: "TO_REJECTOR"
});
});
test("resolves signKey from the sole Seal integration when --sign-key is omitted", async () => {
const record = mockFetch({});
const client = fakeClient([
{ type: "hosecloud", signKey: "integrated-key", outboundName: "AI review", mode: "assisted" }
]);
await callHoseEbot(client, hoseCorp, callbackArgv(["--yes"]));
expect(record.approvalBody).toMatchObject({ signKey: "integrated-key" });
});
test("maps upstream business codes to exit codes and references hose-ebot messages", async () => {
mockFetch({ approval: { value: { code: "401", message: "签名秘钥错误" } } });
const error401 = await captureError(() =>
callHoseEbot(fakeClient(), hoseCorp, callbackArgv(["--sign-key", "sig-1", "--yes"]))
);
expect(classifyCliError(error401).exitCode).toBe(11);
expect(String((error401 as Error).message)).toContain("seal-use hose-ebot messages --reveal");
mockFetch({ approval: { value: { code: "412", message: "当前的审批节点不为: xxx,请检查" } } });
const error412 = await captureError(() =>
callHoseEbot(fakeClient(), hoseCorp, callbackArgv(["--sign-key", "sig-1", "--yes"]))
);
expect(classifyCliError(error412).exitCode).toBe(1);
expect(String((error412 as Error).message)).toContain("seal-use hose-ebot search");
mockFetch({ approval: { value: { code: "400", message: "请求参数错误" } } });
const error400 = await captureError(() =>
callHoseEbot(fakeClient(), hoseCorp, callbackArgv(["--sign-key", "sig-1", "--yes"]))
);
expect(classifyCliError(error400).exitCode).toBe(13);
});
test("validates preAdd and aftAdd approver and policy requirements before network call", async () => {
const record = mockFetch({});
const preAddError = await captureError(() =>
callHoseEbot(
fakeClient(),
hoseCorp,
callbackArgv(["--action", "preAdd", "--sign-key", "sig-1", "--yes"])
)
);
expect(classifyCliError(preAddError).exitCode).toBe(13);
expect(String((preAddError as Error).message)).toContain("必须通过 --add-approver-ids 指定加签审批人");
expect(record.calls).toBe(0);
const aftAddPolicyError = await captureError(() =>
callHoseEbot(
fakeClient(),
hoseCorp,
callbackArgv([
"--action",
"aftAdd",
"--add-approver-ids",
"user1,user2",
"--sign-key",
"sig-1",
"--yes"
])
)
);
expect(classifyCliError(aftAddPolicyError).exitCode).toBe(13);
expect(String((aftAddPolicyError as Error).message)).toContain("必须指定会签方式 --policy ALL");
expect(record.calls).toBe(0);
});
test("normalizes lowercase policy and kebab-case resubmit-method", async () => {
const record = mockFetch({
approval: { value: { code: "204", message: "success" } }
});
await callHoseEbot(
fakeClient(),
hoseCorp,
callbackArgv([
"--action",
"aftAdd",
"--add-approver-ids",
"user1,user2",
"--policy",
"all",
"--resubmit-method",
"from-start",
"--sign-key",
"sig-1",
"--yes"
])
);
expect(record.approvalBody).toMatchObject({
action: "aftAdd",
addApproverIds: ["user1", "user2"],
policy: "ALL",
resubmitMethod: "FROM_START"
});
});
test("rejects a non-Hose enterprise with exit code 13", async () => {
const record = mockFetch({});
const error = await captureError(() =>
callHoseEbot(fakeClient(), sealCorp, callbackArgv(["--sign-key", "sig-1", "--yes"]))
);
expect(classifyCliError(error).exitCode).toBe(13);
expect(record.calls).toBe(0);
});
test("exits 13 when the Hose enterprise has no OpenAPI credentials", async () => {
const record = mockFetch({});
const error = await captureError(() =>
callHoseEbot(fakeClient(), hoseCorpNoOpenApiCredentials, callbackArgv(["--sign-key", "sig-1", "--yes"]))
);
expect(classifyCliError(error).exitCode).toBe(13);
expect(String((error as Error).message)).toContain("缺少合思凭证");
expect(record.calls).toBe(0);
});
});
+125
View File
@@ -0,0 +1,125 @@
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { CliError } from "../errors.js";
import { runCapability } from "../helpers.js";
import { booleanOption, numberOption, stringOption } from "../parser.js";
import { outputOptions } from "../printer.js";
import type { ParsedArgs } from "../types.js";
const USAGE =
"Usage:\n" +
" seal-use hose-ebot search <sn> [--type invoking|callback] [--limit <n>] [--reveal] [--corp <corpId>]\n" +
" seal-use hose-ebot messages [--type flow|message] [--reveal] [--corp <corpId>]\n" +
" seal-use hose-ebot callback --flow-id <flowId> --node-id <nodeId> --action <accept|refuse|preAdd|aftAdd> --comment <审批意见> [--sign-key <key>] [--dry-run] [--yes|--confirm] [--corp <corpId>]";
function normalizeEbotAction(raw: string | undefined): string | undefined {
if (!raw) return undefined;
const lower = raw.trim().toLowerCase();
if (lower === "accept" || lower === "agree" || lower === "approve") return "accept";
if (lower === "refuse" || lower === "reject") return "refuse";
if (lower === "preadd" || lower === "pre-add") return "preAdd";
if (lower === "aftadd" || lower === "aft-add" || lower === "postadd" || lower === "post-add") return "aftAdd";
return raw;
}
function normalizeEbotPolicy(raw: string | undefined): "ALL" | "ANY" | undefined {
if (!raw) return undefined;
const upper = raw.trim().toUpperCase();
if (upper === "ALL" || upper === "ANY") return upper;
return raw as "ALL" | "ANY";
}
function normalizeResubmitMethod(raw: string | undefined): "FROM_START" | "TO_REJECTOR" | undefined {
if (!raw) return undefined;
const norm = raw.trim().toUpperCase().replace(/-/g, "_");
if (norm === "FROM_START" || norm === "TO_REJECTOR") return norm;
return raw as "FROM_START" | "TO_REJECTOR";
}
/**
* First-level `seal-use hose-ebot` surface for the Hose EBot outbound & callback loop:
* search is the default entry (discover records by document SN), `messages`
* discovers outbound message configs and their signKey, and `callback` runs
* the approval callback.
*/
export async function handleHoseEbotCommand(
action: string | undefined,
maybeName: string | undefined,
client: Awaited<ReturnType<typeof createSealClient>>,
corp: CorpConfig,
args: ParsedArgs
) {
if (!action) {
throw new CliError(USAGE, 2);
}
if (action === "search") {
const sn = maybeName ?? stringOption(args.options.sn);
if (!sn) {
throw new CliError(`Missing document SN.\n\n${USAGE}`, 2);
}
const rawType = stringOption(args.options.type)?.trim().toLowerCase();
await runCapability(
"sealHoseOutboundSearch",
client,
corp,
{
sn,
type: rawType,
limit: numberOption(args.options.limit),
reveal: booleanOption(args.options.reveal) === true || booleanOption(args.options.r) === true
},
outputOptions(args.options)
);
return;
}
if (action === "messages") {
const rawType = stringOption(args.options.type)?.trim().toLowerCase();
await runCapability(
"sealHoseOutboundMessages",
client,
corp,
{
reveal: booleanOption(args.options.reveal) === true || booleanOption(args.options.r) === true,
type: rawType
},
outputOptions(args.options)
);
return;
}
if (action === "callback") {
const addApproverIdsRaw =
stringOption(args.options["add-approver-ids"]) ?? stringOption(args.options.addApproverIds);
await runCapability(
"sealHoseApprovalCallback",
client,
corp,
{
signKey: stringOption(args.options.signKey) ?? stringOption(args.options["sign-key"]),
flowId: stringOption(args.options.flowId) ?? stringOption(args.options["flow-id"]),
nodeId: stringOption(args.options.nodeId) ?? stringOption(args.options["node-id"]),
action: normalizeEbotAction(stringOption(args.options.action)),
comment: stringOption(args.options.comment),
policy: normalizeEbotPolicy(stringOption(args.options.policy)),
addApproverIds: addApproverIdsRaw
? addApproverIdsRaw.split(",").map((id) => id.trim()).filter(Boolean)
: undefined,
rejectTo: stringOption(args.options["reject-to"]) ?? stringOption(args.options.rejectTo),
resubmitMethod: normalizeResubmitMethod(
stringOption(args.options["resubmit-method"]) ?? stringOption(args.options.resubmitMethod)
),
dryRun: booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]),
confirm: booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true
},
outputOptions(args.options)
);
return;
}
throw new CliError(
`Unknown hose-ebot command: ${action}. Available: search, messages, callback. Run 'seal-use hose-ebot --help' for usage.`,
2
);
}