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 "../parse/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> = []) { 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; } async function captureError(action: () => Promise): Promise { 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>; 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>; 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>; expect(records[0]).toMatchObject({ id: "log-1", type: "INVOKING" }); expect((records[0]!.request as Record).nodeId).toBe("NODE-1"); // Callback records embed signKey; masked unless --reveal. expect((records[1]!.request as Record).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>; 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>; expect((records[1]!.request as Record).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; 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); }); });