From 2fc88e208c04b7ab15c3b254461ec74576bdc42d Mon Sep 17 00:00:00 2001 From: yunyingk Date: Sat, 10 Oct 2026 15:58:06 +0800 Subject: [PATCH] Add Hose outbound replay with CloseAPI log matching and safety guards --- src/cli/commands/deploy.ts | 34 +- src/cli/commands/webhook-replay.test.ts | 57 +++ src/cli/commands/webhook.ts | 37 ++ src/cli/help.ts | 13 + src/cli/parser.ts | 34 +- src/domains/seal/api.ts | 18 + src/domains/seal/capabilities/deploy.ts | 181 ++++++++ src/domains/seal/capabilities/index.ts | 1 + src/domains/seal/hose-outbound-replay.test.ts | 201 ++++++++ src/domains/seal/hose-outbound-replay.ts | 431 ++++++++++++++++++ 10 files changed, 988 insertions(+), 19 deletions(-) create mode 100644 src/domains/seal/hose-outbound-replay.test.ts create mode 100644 src/domains/seal/hose-outbound-replay.ts diff --git a/src/cli/commands/deploy.ts b/src/cli/commands/deploy.ts index ed4b1ca..a8b2b9d 100644 --- a/src/cli/commands/deploy.ts +++ b/src/cli/commands/deploy.ts @@ -2,7 +2,7 @@ import { readFileSync } from "node:fs"; import type { CorpConfig } from "../../core/config/types.js"; import type { createSealClient } from "../../core/http/factory.js"; import { runCapability } from "../helpers.js"; -import { booleanOption, jsonObject, stringOption } from "../parser.js"; +import { booleanOption, jsonObject, numberOption, stringOption } from "../parser.js"; import { outputOptions } from "../printer.js"; import type { ParsedArgs } from "../types.js"; import * as api from "../../domains/seal/api.js"; @@ -166,5 +166,35 @@ export async function handleDeployCommand( return; } - throw new Error(`Unknown deploy hosecloud action: ${action ?? ""}. Available: requirements, list, get, status, configure, sync.`); + if (action === "test-outbound" || action === "outbound-test") { + const signKey = target ?? stringOption(args.options.signKey) ?? stringOption(args.options["sign-key"]); + const flowId = stringOption(args.options.flowId) ?? stringOption(args.options["flow-id"]); + const sn = stringOption(args.options.sn) ?? stringOption(args.options.sourceDocumentSN); + const messageId = stringOption(args.options.messageId) ?? stringOption(args.options["message-id"]); + const nodeId = stringOption(args.options.nodeId) ?? stringOption(args.options["node-id"]); + const rejectionNum = numberOption(args.options.rejectionNum) ?? numberOption(args.options["rejection-num"]); + const corporationId = stringOption(args.options.corporationId) ?? stringOption(args.options["corporation-id"]); + const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]); + + await runCapability( + "sealDeployHosecloudTestOutbound", + client, + corp, + { + signKey, + flowId, + sn, + messageId, + nodeId, + rejectionNum, + corporationId, + dryRun + }, + outputOptions(args.options) + ); + return; + } + + throw new Error(`Unknown deploy hosecloud action: ${action ?? ""}. Available: requirements, list, get, status, configure, sync, test-outbound.`); } + diff --git a/src/cli/commands/webhook-replay.test.ts b/src/cli/commands/webhook-replay.test.ts index ee35bcf..c05d505 100644 --- a/src/cli/commands/webhook-replay.test.ts +++ b/src/cli/commands/webhook-replay.test.ts @@ -513,4 +513,61 @@ describe("seal-use webhook replay CLI", () => { const parsed = JSON.parse(forceResult.stdout); expect(parsed.targetCorp.id).toBe("prod-corp-target"); }); + + test("approval-runs replay --channel hose-outbound executes dry-run preview with safety guards", async () => { + setupMockEnv(); + + const mockHoseIntegrations = [ + { + type: "hosecloud", + signKey: "sign-key-xyz", + outboundName: "测试出站通道", + mode: "assisted", + corporationId: "corp-id-123" + } + ]; + + globalThis.fetch = (async (input: RequestInfo | URL) => { + const requestUrl = + typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; + + if ( + requestUrl.includes("api/v1/system/preferences/approval-style") || + requestUrl.includes("api/v1/agent/ai-approval/config") + ) { + return new Response( + JSON.stringify({ + data: { integrations: mockHoseIntegrations } + }), + { status: 200, headers: { "Content-Type": "application/json" } } + ); + } + return new Response("Not found", { status: 404 }); + }) as any; + + const result = await runCli([ + "approval-runs", + "replay", + "--sn", + "S26002992", + "--channel", + "hose-outbound", + "--message-id", + "ID01Wh05v0In3F", + "--flow-id", + "ID01Wah1FQ9faf", + "--dry-run" + ]); + + expect(result.isError).toBe(false); + expect(result.exitCode).toBe(0); + const parsed = JSON.parse(result.stdout); + expect(parsed.preview).toBe(true); + expect(parsed.channel).toBe("hose-outbound"); + expect(parsed.payload.messageId).toBe("ID01Wh05v0In3F"); + expect(parsed.payload.nodeId).toBe("FLOW:测试模拟节点_禁止流转"); + expect(parsed.safetyGuards.targetModeAssisted).toBe(true); + expect(parsed.safetyGuards.nodeId412Blocked).toBe(true); + }); }); + diff --git a/src/cli/commands/webhook.ts b/src/cli/commands/webhook.ts index 5d03165..c6724f4 100644 --- a/src/cli/commands/webhook.ts +++ b/src/cli/commands/webhook.ts @@ -12,6 +12,7 @@ import { resolveReplayCorpPair, type ReplayRecordsQuery } from "../../domains/seal/webhook-replay.js"; +import { executeHoseOutboundReplay } from "../../domains/seal/hose-outbound-replay.js"; import { checkWebhookReadiness, exportApprovalRunsToResourcePack, @@ -148,6 +149,42 @@ export async function handleWebhookCommand( const docIdPrefix = stringOption(args.options.docIdPrefix) ?? stringOption(args.options["doc-id-prefix"]); const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]); + const channel = + stringOption(args.options.channel) ?? + (booleanOption(args.options["hose-outbound"]) || booleanOption(args.options.outbound) ? "hose-outbound" : undefined); + + if (channel === "hose-outbound" || channel === "outbound") { + const flowId = stringOption(args.options.flowId) ?? stringOption(args.options["flow-id"]); + const messageId = stringOption(args.options.messageId) ?? stringOption(args.options["message-id"]); + const nodeId = stringOption(args.options.nodeId) ?? stringOption(args.options["node-id"]); + const corporationId = stringOption(args.options.corporationId) ?? stringOption(args.options["corporation-id"]); + const rejectionNum = numberOption(args.options.rejectionNum) ?? numberOption(args.options["rejection-num"]); + const targetSignKey = + stringOption(args.options.signKey) ?? + stringOption(args.options["sign-key"]) ?? + stringOption(args.options.webhook); + + const result = await executeHoseOutboundReplay({ + sourceCorp, + targetCorp, + sourceClient, + targetClient, + sn, + recordId, + flowId, + messageId, + nodeId, + corporationId, + rejectionNum, + targetSignKey, + dryRun, + force + }); + + printJson(result, outputOptions(args.options)); + return; + } + const query: ReplayRecordsQuery = { recordId, recordIds, diff --git a/src/cli/help.ts b/src/cli/help.ts index 6eca40d..2b18735 100644 --- a/src/cli/help.ts +++ b/src/cli/help.ts @@ -584,11 +584,16 @@ export const HELP_REGISTRY: AreaHelp[] = [ usage: [ "seal-use approval-runs replay [--webhook ] [--sn-suffix ] [--dry-run] [--corp ]", "seal-use approval-runs replay --sn [--webhook ] [--source-corp ] [--target-corp ]", + "seal-use approval-runs replay --sn --channel hose-outbound [--target-corp ] [--dry-run]", + "seal-use approval-runs replay --channel hose-outbound [--target-corp ] [--dry-run]", "seal-use approval-runs replay --limit [--status ] [--source-corp ] [--target-corp ]" ], options: [ { flag: "", description: "Approval run record ID" }, { flag: "--sn ", description: "Lookup approval record by source document SN" }, + { flag: "--channel ", description: "Replay channel: webhook (default) or hose-outbound (Hosecloud official outbound)" }, + { flag: "--message-id ", description: "Explicit Hose outbound messageId override" }, + { flag: "--rejection-num ", description: "Target specific rejection iteration (0, 1, 2, ...)" }, { flag: "--limit ", description: "Batch replay latest N records" }, { flag: "--status ", description: "Filter records by status" }, { flag: "--webhook ", description: "Target Webhook integration" }, @@ -747,6 +752,14 @@ export const HELP_REGISTRY: AreaHelp[] = [ name: "hosecloud sync", summary: "Synchronize HoseCloud rules and definitions", usage: ["seal-use deploy hosecloud sync [--corp ]"] + }, + { + name: "hosecloud test-outbound", + summary: "向合思出站 (outbound) 接口推送测试/重放消息以模拟工作流触发(要求 assisted 模式)", + usage: [ + "seal-use deploy hosecloud test-outbound [--sign-key ] --flow-id --message-id [--dry-run] [--corp ]", + "seal-use deploy hosecloud test-outbound [--sign-key ] --sn --message-id [--dry-run] [--corp ]" + ] } ] }, diff --git a/src/cli/parser.ts b/src/cli/parser.ts index 65c7b06..cd08e17 100644 --- a/src/cli/parser.ts +++ b/src/cli/parser.ts @@ -27,9 +27,9 @@ export const BOOLEAN_FLAGS = new Set([ "completed-only", "completedOnly", "confirm", "count", "disable-attachment-cache", "disableAttachmentCache", "download", "downloads", "dry-run", "dryRun", "elevate-hose", "enabled", "exclude-deleted", "extract", "extract-expenses", "extractExpenses", "fail-on-flips", "flow", "force", "full", "has-input", "has-output", "help", - "hose", "hose-sso", "hoseSso", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged", + "hose", "hose-outbound", "hose-sso", "hoseOutbound", "hoseSso", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged", "includeBridge", "includeSimulation", "includeUnchanged", "local", "no-attachments", "no-flow", - "no-wait", "noWait", "overwrite", "plain", "publish", "quiet", + "no-wait", "noWait", "outbound", "overwrite", "plain", "publish", "quiet", "r", "recode", "refresh", "refresh-if-missing", "reveal", "rotate-secret", "rotateSecret", "save", "silent", "silent-save", "simulation", "skip-expense-extraction", "skip-extract", "skip-invoice-generation", "skipExpenseExtraction", "skipExtract", "skipInvoiceGeneration", "snippet-only", "snippetOnly", "sso", "strict", @@ -41,27 +41,27 @@ export const BOOLEAN_FLAGS = new Set([ export const VALUE_FLAGS = new Set([ "access-token", "accessToken", "app-key", "app-security", "appKey", "appSecurity", "base-url", "batch", "batch-id", "batchId", "business-codes", "businessCodes", - "code", "concurrency", "content", "content-file", "content-hints", "content-type", "contentFile", - "contentType", "context-chars", "contextLines", "corp", "corp-id", "corpId", "date", + "channel", "code", "concurrency", "content", "content-file", "content-hints", "content-type", "contentFile", + "contentType", "context-chars", "contextLines", "corp", "corp-id", "corpId", "corporation-id", "corporationId", "date", "dedupe-by", "dedupeBy", "default", "departmentId", "dept", "desc", "description", "description-file", "descriptionFile", "dir", "doc-id-prefix", "doc-id-suffix", "docIdPrefix", "docIdSuffix", "document-id", "document-sn", "document-sns", "document-type", "documentId", "documentLimit", "documentSn", "documentType", "domain", "enable", "end", "end-date", "end-time", "endDate", "endTime", "env", "environment", "expire", "expires-in", "expiresIn", "fields", "file", "file-id", "file-name", "flow-concurrency", - "flow-ids", "flow-status-list", "flowIds", "flowStatusList", "format", "from", + "flow-id", "flow-ids", "flow-status-list", "flowId", "flowIds", "flowStatusList", "format", "from", "from-link", "host", "humanResult", "id", "input", "integration", "json", "json-path", "key-id", "keyId", "keyword", "level", "limit", "lines", "link", "linter", "manual-status", "manualApprovalStatus", "manualStatus", - "max-chars", "max-preview-chars", "maxChars", "maxResults", "max-results", "metadata", "metadata-key", "min-score", "minScore", "mode", + "max-chars", "max-preview-chars", "maxChars", "maxResults", "max-results", "message-id", "messageId", "metadata", "metadata-key", "min-score", "minScore", "mode", "max-runs", "month", - "n", "name", "name-contains", "note", "observation-id", "observation-types", "o", "offset", "out", + "n", "name", "name-contains", "node-id", "nodeId", "note", "observation-id", "observation-types", "o", "offset", "out", "out-dir", "outDir", "outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file", "outputFile", "p", "package-id", "package-ids", "packageId", "packageIds", "path", "phone", "policyId", "poll-interval", "pollInterval", "port", "prod", "prod-corp", "prodCorp", "purpose", "q", "query", - "record-id", "record-ids", "recordId", "recordIds", "reject-node", "rejectNode", + "record-id", "record-ids", "recordId", "recordIds", "reject-node", "rejectNode", "rejection-num", "rejectionNum", "reviewed-by", "reviewedBy", "report-id", "repo", "request-ids", "requestIds", "result-url", "resultUrl", "reuse-window", @@ -88,10 +88,10 @@ export const KNOWN_FLAGS = new Set([ "V", "access-token", "accessToken", "add", "all", "app-key", "app-security", "appKey", "appSecurity", "as-hose", "attachments", "auto", "auto-login", "autoLogin", "base-url", "batch", "batch-id", "batchId", - "bg-save", "business-codes", "businessCodes", "changelog", "check", "check-only", + "bg-save", "business-codes", "businessCodes", "channel", "changelog", "check", "check-only", "code", "completed-only", "completedOnly", "concurrency", "confirm", "content", "content-file", "content-hints", "content-type", "contentFile", "contentType", "context-chars", "contextLines", "corp", - "corp-id", "corpId", "count", "date", "dedupe-by", "dedupeBy", + "corp-id", "corpId", "corporation-id", "corporationId", "count", "date", "dedupe-by", "dedupeBy", "default", "departmentId", "dept", "desc", "description", "description-file", "descriptionFile", "dir", "disable-attachment-cache", "disableAttachmentCache", "doc-id-prefix", "doc-id-suffix", "docIdPrefix", "docIdSuffix", "document-id", "document-sn", "document-sns", "document-type", @@ -99,24 +99,24 @@ export const KNOWN_FLAGS = new Set([ "downloads", "dry-run", "dryRun", "elevate-hose", "enable", "enabled", "end", "end-date", "end-time", "endDate", "endTime", "env", "environment", "exclude-deleted", "extract", "extract-expenses", "extractExpenses", "expire", "expires-in", "expiresIn", "f", "fail-on-flips", - "fields", "file", "file-id", "file-name", "flow", "flow-concurrency", "flow-ids", "flow-status-list", - "flowIds", "flowStatusList", "force", "format", "from", "from-link", - "full", "h", "has-input", "has-output", "help", "hose", "hose-sso", "hoseSso", + "fields", "file", "file-id", "file-name", "flow", "flow-concurrency", "flow-id", "flow-ids", "flow-status-list", + "flowId", "flowIds", "flowStatusList", "force", "format", "from", "from-link", + "full", "h", "has-input", "has-output", "help", "hose", "hose-outbound", "hose-sso", "hoseOutbound", "hoseSso", "host", "humanResult", "id", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged", "includeBridge", "includeSimulation", "includeUnchanged", "input", "integration", "json", "json-path", "key-id", "keyId", "keyword", "level", "limit", "lines", "link", "linter", "local", "manual-status", "manualApprovalStatus", "manualStatus", - "max-chars", "max-preview-chars", "maxChars", "maxResults", "max-results", "metadata", "metadata-key", "min-score", "minScore", "mode", + "max-chars", "max-preview-chars", "maxChars", "maxResults", "max-results", "message-id", "messageId", "metadata", "metadata-key", "min-score", "minScore", "mode", "max-runs", "month", - "n", "name", "name-contains", "no-attachments", "no-flow", "no-wait", "noWait", - "note", "observation-id", "observation-types", "o", "offset", "out", "out-dir", "outDir", + "n", "name", "name-contains", "no-attachments", "no-flow", "no-wait", "noWait", "node-id", "nodeId", + "note", "observation-id", "observation-types", "o", "offset", "out", "out-dir", "outDir", "outbound", "outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file", "outputFile", "overwrite", "p", "package-id", "package-ids", "packageId", "packageIds", "path", "phone", "plain", "policyId", "poll-interval", "pollInterval", "port", "prod", "prod-corp", "prodCorp", "publish", "purpose", "q", "query", "quiet", "r", "recode", "record-id", "record-ids", - "recordId", "recordIds", "refresh", "refresh-if-missing", "reject-node", "rejectNode", "repo", + "recordId", "recordIds", "refresh", "refresh-if-missing", "reject-node", "rejectNode", "rejection-num", "rejectionNum", "repo", "report-id", "request-ids", "requestIds", "result-url", "resultUrl", "reuse-window", "reuseWindow", "reviewed-by", "reviewedBy", diff --git a/src/domains/seal/api.ts b/src/domains/seal/api.ts index c6dca8b..d169380 100644 --- a/src/domains/seal/api.ts +++ b/src/domains/seal/api.ts @@ -842,6 +842,24 @@ export async function syncHosecloudOutbound( return json.data ?? json; } +export async function postHosecloudOutbound( + client: KyInstance, + signKey: string, + payload: { + flowId: string; + nodeId: string; + messageId: string; + rejectionNum: number; + corporationId: string; + } +): Promise<{ success?: boolean; message?: string; [key: string]: unknown }> { + const response = await client.post(`api/hosecloud/outbound?config_id=${encodeURIComponent(signKey)}`, { + json: payload + }); + const json = (await response.json().catch(() => ({}))) as { data?: unknown }; + return (json.data ?? json) as { success?: boolean; message?: string; [key: string]: unknown }; +} + export async function uploadMaterialPackage( client: KyInstance, params: { fileName: string; fileBuffer: Uint8Array } diff --git a/src/domains/seal/capabilities/deploy.ts b/src/domains/seal/capabilities/deploy.ts index fbbab81..eeb36ee 100644 --- a/src/domains/seal/capabilities/deploy.ts +++ b/src/domains/seal/capabilities/deploy.ts @@ -3,7 +3,9 @@ import type { KyInstance } from "ky"; import { randomBytes } from "node:crypto"; import * as api from "../api.js"; import { probeHoseDomain } from "../../../core/auth/hose.js"; +import { safetyBlocked, validationError } from "../../../core/errors.js"; import { + type ApprovalRun, type HosecloudConfigInput } from "../types.js"; import type { @@ -217,5 +219,184 @@ export const deployCapabilities = [ result }; } + }, + { + name: "sealDeployHosecloudTestOutbound", + description: "向合思出站 (outbound) 接口推送测试/重放消息以模拟工作流触发,强制要求目标集成必须为 assisted 模式", + parameters: z.object({ + signKey: z.string().optional().describe("合思集成 sign-key(若企业仅有一个合思配置可自动识别)"), + flowId: z.string().optional().describe("合思单据/流程 ID (flowId / sourceDocumentId)"), + sn: z.string().optional().describe("合思单号 (sourceDocumentSN,若未提供 flowId 可自动解析)"), + messageId: z.string().describe("合思真实的 messageId(合思开放平台消息凭证,必须提供真实有效值以供拉取单据)"), + nodeId: z.string().optional().default("FLOW:测试模拟节点_禁止流转").describe("合思流程节点 ID(默认填入中文阻断标识)"), + rejectionNum: z.number().int().optional().default(0).describe("驳回/重提次数(默认 0)"), + corporationId: z.string().optional().describe("合思企业 ID(若未提供则取自集成配置)"), + dryRun: z.boolean().optional().default(false).describe("是否仅预览请求载荷与安全检查而不实际推送") + }), + handler: async ( + client: KyInstance, + params: { + signKey?: string; + flowId?: string; + sn?: string; + messageId: string; + nodeId?: string; + rejectionNum?: number; + corporationId?: string; + dryRun?: boolean; + }, + context: CapabilityContext + ) => { + const config = await api.getApprovalStylePreferences(client); + const hoseConfigs = (config.integrations ?? []).filter((i: any) => i.type === "hosecloud"); + if (hoseConfigs.length === 0) { + throw new Error( + `当前企业 (${context.corp.name}) 尚未添加合思发布配置。\n` + + `👉 请先运行配置命令:seal-use deploy hosecloud configure --json '{...}' --corp ${context.corp.id}` + ); + } + + let integration: any; + if (params.signKey) { + integration = hoseConfigs.find((i: any) => i.signKey === params.signKey); + if (!integration) { + throw validationError( + `未找到 signKey 为「${params.signKey}」的合思集成配置。可用 signKey: ${hoseConfigs.map((i: any) => i.signKey).join(", ")}` + ); + } + } else if (hoseConfigs.length === 1) { + integration = hoseConfigs[0]; + } else { + const list = hoseConfigs.map((i: any) => `"${i.outboundName ?? "SealAI 审批"}" (signKey: ${i.signKey})`).join(", "); + throw validationError( + `当前企业存在多个合思集成 [${list}],请通过 --sign-key 指定目标集成配置。` + ); + } + + // 1. 严格安全门禁检查:强制要求目标集成必须为 assisted 模式 + const mode = integration.mode ?? "assisted"; + if (mode !== "assisted") { + throw safetyBlocked( + `安全阻断:目标合思配置「${integration.outboundName ?? integration.signKey}」当前为「${mode}」模式,非 assisted(辅助审核)模式。为防止自动向合思回写审批动作影响生产/线上流程,严禁在此模式下测试出站通道。`, + `请先在目标企业将模式调整为 assisted 模式后重试:seal-use deploy hosecloud configure --json '{"signKey":"${integration.signKey}","mode":"assisted"}' --corp ${context.corp.id}` + ); + } + + // 2. 消息凭证校验 + const messageId = params.messageId?.trim(); + if (!messageId) { + throw validationError( + "缺少必需参数 --message-id。合思开放平台出站协议要求使用真实有效的 messageId 换取单据上下文,请从合思出站请求日志中提取提供。" + ); + } + + // 3. 解析 flowId + let flowId = params.flowId?.trim(); + const sn = params.sn?.trim(); + if (!flowId && sn) { + try { + const existing = await api.listApprovalRuns(client, { + search: sn, + sourceDocumentSN: sn, + limit: 5 + }); + const match = (existing.records || []).find( + (r) => r.sourceDocumentSN === sn || r.sourceDocumentId === sn + ); + if (match?.sourceDocumentId) { + flowId = match.sourceDocumentId; + } + } catch { + // 忽略 + } + if (!flowId && sn.startsWith("ID01")) { + flowId = sn; + } + } + + if (!flowId) { + throw validationError( + "缺少必需参数 --flow-id(合思单据/流程 ID)。若已存在该单的历史运行记录,也可通过 --sn <单号> 自动解析。" + ); + } + + // 4. 解析 corporationId + const corporationId = params.corporationId?.trim() || integration.corporationId; + if (!corporationId) { + throw validationError( + "缺少 corporationId,且当前合思集成未保存有效 corporationId,请通过 --corporation-id 参数显式提供。" + ); + } + + const nodeId = params.nodeId?.trim() || "FLOW:测试模拟节点_禁止流转"; + const rejectionNum = params.rejectionNum ?? 0; + + const sealUrl = (context.corp.seal.url ?? `https://${context.corp.id.toLowerCase()}.sealai.cc`).replace(/\/+$/, ""); + const webhookUrl = `${sealUrl}/api/hosecloud/outbound?config_id=${encodeURIComponent(integration.signKey)}`; + + const payload = { + flowId, + nodeId, + messageId, + rejectionNum, + corporationId + }; + + if (params.dryRun) { + return { + preview: true, + url: webhookUrl, + targetCorp: context.corp.id, + targetIntegration: { + signKey: integration.signKey, + outboundName: integration.outboundName, + mode: integration.mode + }, + safetyCheck: { + mode: "assisted", + passed: true, + note: "目标企业出站模式为 assisted,AI 绝不会向合思回写审批动作;且默认 nodeId 包含中文阻断标记,双重安全保障。" + }, + payload + }; + } + + const response = await api.postHosecloudOutbound(client, integration.signKey, payload); + + // 等待后台队列消费 (2秒) + await new Promise((r) => setTimeout(r, 2000)); + let createdRecord: ApprovalRun | undefined; + try { + const runs = await api.listApprovalRuns(client, { + limit: 5, + search: flowId + }); + createdRecord = (runs.records || []).find( + (r) => r.sourceDocumentId === flowId || r.sourceDocumentSN === flowId + ); + } catch { + // 非阻塞 + } + + console.error(`✓ 已成功向合思出站通道推送测试消息 (flowId: ${flowId}, signKey: ${integration.signKey})`); + if (createdRecord) { + console.error(`✓ 异步消费成功!已在【${context.corp.name}】生成审核记录: ${createdRecord.id} (任务模式: ${createdRecord.taskMode})`); + console.error(`👉 查看审核详情: seal-use approval-runs get ${createdRecord.id} --corp ${context.corp.id}`); + } else { + console.error(`ℹ️ 消息已入队正在异步消费,可在几秒后刷新后台页面或查询: seal-use approval-runs list --corp ${context.corp.id}`); + } + + return { + success: true, + targetCorp: context.corp.id, + signKey: integration.signKey, + mode: integration.mode, + payload, + response, + recordId: createdRecord?.id, + recordStatus: createdRecord?.status, + taskMode: createdRecord?.taskMode + }; + } } ]; diff --git a/src/domains/seal/capabilities/index.ts b/src/domains/seal/capabilities/index.ts index 0ce5782..0bd7621 100644 --- a/src/domains/seal/capabilities/index.ts +++ b/src/domains/seal/capabilities/index.ts @@ -135,6 +135,7 @@ export const SEAL_MUTATING_CAPABILITIES: ReadonlySet = new Set([ "sealDelegationRevoke", "sealDeployHosecloudConfigure", "sealDeployHosecloudSync", + "sealDeployHosecloudTestOutbound", "sealInsightRecordAnalyze", "sealPreferenceDecisionUpdate", "sealPreferenceThinkingDepthPoliciesRemove", diff --git a/src/domains/seal/hose-outbound-replay.test.ts b/src/domains/seal/hose-outbound-replay.test.ts new file mode 100644 index 0000000..fb24ad8 --- /dev/null +++ b/src/domains/seal/hose-outbound-replay.test.ts @@ -0,0 +1,201 @@ +import { describe, expect, test } from "bun:test"; +import { + selectMatchingOutboundLog, + validateHoseOutboundReplaySafety, + type HoseOutboundLogItem +} from "./hose-outbound-replay.js"; +import type { CorpConfig } from "../../core/config/types.js"; + +const mockLogs: HoseOutboundLogItem[] = [ + { + id: "log-callback-3", + name: "全自动模式审批_财务部门", + type: "CALLBACK", + state: "SUCCESS", + createTime: 1789461868758, + request: { + action: "accept", + flowId: "ID01Wah1FQ9faf", + nodeId: "FLOW:355474724:884326991", + comment: "AI建议【通过】\n查看详情:https://test.sealai.cc/approval-result/01a0a43c-521b-778c-b11b-238c8496dfec" + } + }, + { + id: "log-invoking-3", + name: "全自动模式审批_财务部门", + type: "INVOKING", + state: "SUCCESS", + createTime: 1789461809348, + nodeName: "财务部门", + request: { + flowId: "ID01Wah1FQ9faf", + nodeId: "FLOW:355474724:884326991", + messageId: "ID01Wh05v0In3F", + rejectionNum: 3, + corporationId: "ID01lwQSjf93Bl" + } + }, + { + id: "log-callback-2", + name: "全自动报销审批. - 完成回调", + type: "CALLBACK", + state: "SUCCESS", + createTime: 1789112525311, + request: { + action: "refuse", + flowId: "ID01Wah1FQ9faf", + nodeId: "FLOW:215172549:1248083206", + comment: "AI建议【驳回】\n查看详情:https://test.sealai.cc/approval-result/01a08f69-ad6f-76b8-8c81-81190544150d" + } + }, + { + id: "log-invoking-2", + name: "全自动报销审批.", + type: "INVOKING", + state: "SUCCESS", + createTime: 1789112460936, + nodeName: "财务部门", + request: { + flowId: "ID01Wah1FQ9faf", + nodeId: "FLOW:215172549:1248083206", + messageId: "ID01WahQ3gbhMP", + rejectionNum: 2, + corporationId: "ID01lwQSjf93Bl" + } + } +]; + +const mockSourceCorp: CorpConfig = { + id: "prod-corp", + name: "生产企业", + environment: "production", + seal: { + url: "https://prod.sealai.cc", + endpoints: { approvalStylePreferences: "api/v1/system/preferences/approval-style" } + }, + source: { + type: "hose", + domain: "https://app.ekuaibao.com", + appKey: "key-123", + appSecurity: "sec-456", + staffId: "staff-1", + corpId: "corp-1" + }, + auth: { refreshTtl: 300 }, + testCorpId: "test-corp" +}; + +const mockTargetCorp: CorpConfig = { + id: "test-corp", + name: "测试企业", + environment: "test", + seal: { + url: "https://test.sealai.cc", + endpoints: { approvalStylePreferences: "api/v1/system/preferences/approval-style" } + }, + source: { + type: "seal", + token: "token-abc", + sealUrl: "https://test.sealai.cc", + expiresIn: 3600, + staffId: "seal" + }, + auth: { refreshTtl: 300 }, + prodCorpId: "prod-corp" +}; + +describe("selectMatchingOutboundLog", () => { + test("defaults to the latest invoking log when no options given", () => { + const selected = selectMatchingOutboundLog(mockLogs); + expect(selected).toBeDefined(); + expect(selected?.id).toBe("log-invoking-3"); + expect(selected?.request?.messageId).toBe("ID01Wh05v0In3F"); + }); + + test("matches by explicit messageId", () => { + const selected = selectMatchingOutboundLog(mockLogs, { messageId: "ID01WahQ3gbhMP" }); + expect(selected).toBeDefined(); + expect(selected?.id).toBe("log-invoking-2"); + expect(selected?.request?.rejectionNum).toBe(2); + }); + + test("matches by recordId reverse lookup via CALLBACK comment", () => { + const selected = selectMatchingOutboundLog(mockLogs, { + recordId: "01a08f69-ad6f-76b8-8c81-81190544150d" + }); + expect(selected).toBeDefined(); + expect(selected?.id).toBe("log-invoking-2"); + expect(selected?.request?.messageId).toBe("ID01WahQ3gbhMP"); + }); + + test("matches by rejectionNum", () => { + const selected = selectMatchingOutboundLog(mockLogs, { rejectionNum: 2 }); + expect(selected).toBeDefined(); + expect(selected?.request?.messageId).toBe("ID01WahQ3gbhMP"); + }); + + test("returns undefined if no invoking logs exist", () => { + const emptyLogs: HoseOutboundLogItem[] = [ + { id: "1", name: "cb", type: "CALLBACK", state: "OK", createTime: 123 } + ]; + expect(selectMatchingOutboundLog(emptyLogs)).toBeUndefined(); + }); +}); + +describe("validateHoseOutboundReplaySafety", () => { + test("passes when source and target are paired and target is assisted", () => { + expect(() => + validateHoseOutboundReplaySafety( + mockSourceCorp, + mockTargetCorp, + { mode: "assisted", outboundName: "测试通道", signKey: "key-1" } + ) + ).not.toThrow(); + }); + + test("blocks when source and target are NOT paired", () => { + const unpairedTarget = { ...mockTargetCorp, prodCorpId: "other-prod" }; + const unpairedSource = { ...mockSourceCorp, testCorpId: "other-test" }; + expect(() => + validateHoseOutboundReplaySafety( + unpairedSource, + unpairedTarget, + { mode: "assisted", signKey: "k" } + ) + ).toThrow(/未配置双向测试绑定关系/); + }); + + test("blocks when target is production", () => { + const prodTarget = { ...mockTargetCorp, environment: "production" as const }; + expect(() => + validateHoseOutboundReplaySafety( + mockSourceCorp, + prodTarget, + { mode: "assisted", signKey: "k" } + ) + ).toThrow(/标记为正式生产环境/); + }); + + test("blocks when target mode is NOT assisted", () => { + expect(() => + validateHoseOutboundReplaySafety( + mockSourceCorp, + mockTargetCorp, + { mode: "fully_automatic", signKey: "k" } + ) + ).toThrow(/非 assisted(辅助审核)模式/); + }); + + test("allows force override for unpaired tenants", () => { + const unpairedTarget = { ...mockTargetCorp, prodCorpId: "other-prod" }; + const unpairedSource = { ...mockSourceCorp, testCorpId: "other-test" }; + expect(() => + validateHoseOutboundReplaySafety( + unpairedSource, + unpairedTarget, + { mode: "assisted", signKey: "k" }, + true + ) + ).not.toThrow(); + }); +}); diff --git a/src/domains/seal/hose-outbound-replay.ts b/src/domains/seal/hose-outbound-replay.ts new file mode 100644 index 0000000..97e8f53 --- /dev/null +++ b/src/domains/seal/hose-outbound-replay.ts @@ -0,0 +1,431 @@ +import type { KyInstance } from "ky"; +import type { CorpConfig } from "../../core/config/types.js"; +import { safetyBlocked, validationError } from "../../core/errors.js"; +import { createHoseCloseClient } from "../hose/close/client.js"; +import * as api from "./api.js"; +import type { ApprovalRun } from "./types.js"; + +export interface HoseOutboundLogItem { + id: string; + name: string; + type: "INVOKING" | "CALLBACK" | string; + state: string; + flowId?: { + id: string; + form?: { + code?: string; + }; + }; + nodeName?: string; + createTime: number; + messageType?: string; + request?: { + flowId?: string; + nodeId?: string; + messageId?: string; + rejectionNum?: number; + corporationId?: string; + action?: string; + comment?: string; + signKey?: string; + [key: string]: unknown; + }; + response?: unknown; +} + +export interface HoseOutboundReplayOptions { + sourceCorp: CorpConfig; + targetCorp: CorpConfig; + sourceClient?: KyInstance; + targetClient: KyInstance; + sn?: string; + recordId?: string; + flowId?: string; + messageId?: string; + nodeId?: string; + corporationId?: string; + rejectionNum?: number; + targetSignKey?: string; + dryRun?: boolean; + force?: boolean; +} + +/** + * Fetch historical outbound message logs from Hosecloud's CloseAPI for a given document SN. + */ +export async function fetchHoseOutboundLogs( + sourceCorp: CorpConfig, + sn: string +): Promise { + if (sourceCorp.source.type !== "hose") { + throw validationError( + `源企业「${sourceCorp.name}」非合思(hose)租户,无法通过合思 CloseAPI 查询出站消息日志。` + ); + } + + const client = await createHoseCloseClient(sourceCorp); + const corpId = sourceCorp.source.corpId; + + const response = (await client + .post("api/outbound/v1/message/messageLog", { + searchParams: { + messageType: "flow", + corpId + }, + json: { + limit: { start: 0, count: 20 }, + orderBy: [{ value: "createTime", order: "DESC" }], + select: "id,name,flowId(id, form(code)),nodeName,type,request,response,state,createTime,messageType", + filterBy: `(flowId.form.code==("${sn}"))` + } + }) + .json()) as { items?: HoseOutboundLogItem[] }; + + return response.items ?? []; +} + +/** + * Select the best matching INVOKING log from a list of outbound message logs. + */ +export function selectMatchingOutboundLog( + logs: HoseOutboundLogItem[], + options: { + messageId?: string; + recordId?: string; + recordCreatedAt?: number; + rejectionNum?: number; + } = {} +): HoseOutboundLogItem | undefined { + const invokingLogs = logs.filter((item) => item.type === "INVOKING"); + if (invokingLogs.length === 0) { + return undefined; + } + + // 1. Explicit messageId match + if (options.messageId) { + return invokingLogs.find((item) => item.request?.messageId === options.messageId); + } + + // 2. Exact recordId match via CALLBACK link/comment + if (options.recordId) { + const callbackWithRecordId = logs.find( + (item) => + item.type === "CALLBACK" && + typeof item.request?.comment === "string" && + item.request.comment.includes(options.recordId!) + ); + if (callbackWithRecordId) { + // Find the invoking event right before this callback + const priorInvoking = invokingLogs.find( + (item) => item.createTime <= callbackWithRecordId.createTime + ); + if (priorInvoking) { + return priorInvoking; + } + } + + // Fallback: match by timestamp delta (< 60s) + if (options.recordCreatedAt) { + const closestByTime = invokingLogs + .filter((item) => item.createTime <= options.recordCreatedAt! + 1000) + .sort( + (a, b) => + Math.abs(options.recordCreatedAt! - a.createTime) - + Math.abs(options.recordCreatedAt! - b.createTime) + )[0]; + if (closestByTime) { + return closestByTime; + } + } + } + + // 3. Match by rejectionNum if provided + if (options.rejectionNum !== undefined) { + const matchRejection = invokingLogs.find( + (item) => item.request?.rejectionNum === options.rejectionNum + ); + if (matchRejection) { + return matchRejection; + } + } + + // 4. Default: latest invoking log + return invokingLogs[0]; +} + +/** + * Validate security preconditions for Hose outbound replay. + */ +export function validateHoseOutboundReplaySafety( + sourceCorp: CorpConfig, + targetCorp: CorpConfig, + targetIntegration: { mode?: string; outboundName?: string; signKey?: string }, + force = false +): void { + // 1. Double-binding guard: prevent accidental cross-tenant execution outside paired sandbox + const isPaired = + sourceCorp.testCorpId === targetCorp.id || + targetCorp.prodCorpId === sourceCorp.id || + sourceCorp.id === targetCorp.id; + + if (!isPaired && !force) { + throw safetyBlocked( + `安全阻断:源企业「${sourceCorp.name}」(${sourceCorp.id}) 与目标企业「${targetCorp.name}」(${targetCorp.id}) 未配置双向测试绑定关系 (testCorpId / prodCorpId)。\n` + + `出站重放具备高仿真性,仅允许在绑定的生产-测试企业对之间执行。如确需跨租户测试,请添加 --force 参数。`, + `请检查企业配置 ~/.config/seal-use/enterprises/ 或添加 --force` + ); + } + + // 2. Production target guard + if (targetCorp.environment === "production" && !force) { + throw safetyBlocked( + `安全阻断:目标企业「${targetCorp.name}」标记为正式生产环境 (production)。\n` + + `为防止测试消息污染生产审批流,严禁向生产企业重发出站报文。请通过 --target-corp 指定测试企业。`, + `seal-use approval-runs replay --target-corp ...` + ); + } + + // 3. Mode guard: target Hose integration MUST be assisted + const mode = targetIntegration.mode ?? "assisted"; + if (mode !== "assisted") { + throw safetyBlocked( + `安全阻断:目标测试企业「${targetCorp.name}」的合思配置「${targetIntegration.outboundName ?? targetIntegration.signKey}」当前为「${mode}」模式,非 assisted(辅助审核)模式。\n` + + `为防止自动向合思回写审批动作影响流程,严禁在非 assisted 模式下重放出站单据。`, + `请先将目标企业的合思配置调整为 assisted 模式后重试:seal-use deploy hosecloud configure --json '{"signKey":"${targetIntegration.signKey}","mode":"assisted"}' --corp ${targetCorp.id}` + ); + } +} + +/** + * Main execution handler for Hose outbound replay. + */ +export async function executeHoseOutboundReplay(options: HoseOutboundReplayOptions) { + const { sourceCorp, targetCorp, targetClient, dryRun, force } = options; + + // 1. Get target corp's Hose integrations + const targetConfig = await api.getApprovalStylePreferences( + targetClient, + targetCorp.seal?.endpoints?.approvalStylePreferences + ); + const hoseConfigs: Array<{ + type: string; + signKey?: string; + outboundName?: string; + mode?: string; + corporationId?: string; + [key: string]: unknown; + }> = (targetConfig.integrations ?? []).filter((i: any) => i.type === "hosecloud"); + if (hoseConfigs.length === 0) { + throw validationError( + `目标测试企业「${targetCorp.name}」未配置任何合思出站发布通道。请先运行:seal-use deploy hosecloud configure --corp ${targetCorp.id}` + ); + } + + const foundIntegration = options.targetSignKey + ? hoseConfigs.find((i) => i.signKey === options.targetSignKey) + : hoseConfigs[0]; + + if (!foundIntegration || !foundIntegration.signKey) { + if (options.targetSignKey) { + throw validationError( + `在目标企业中未找到 signKey 为「${options.targetSignKey}」的合思配置。可用配置: ${hoseConfigs.map((i) => i.signKey).filter(Boolean).join(", ")}` + ); + } + throw validationError( + `目标测试企业「${targetCorp.name}」未配置有效的合思 signKey。` + ); + } + + const targetIntegration = { + ...foundIntegration, + signKey: foundIntegration.signKey + }; + + // 2. Validate safety constraints + validateHoseOutboundReplaySafety(sourceCorp, targetCorp, targetIntegration, force); + + // 3. Resolve document SN & record details + let sn = options.sn?.trim(); + let sourceRecord: ApprovalRun | undefined; + + if (options.recordId) { + if (options.sourceClient) { + try { + sourceRecord = await api.getApprovalRun(options.sourceClient, options.recordId); + if (sourceRecord?.sourceDocumentSN) { + sn = sourceRecord.sourceDocumentSN; + } + } catch { + // continue + } + } + } + + if (!sn && !options.messageId) { + throw validationError( + "缺少必需参数:请提供单号 (--sn ) 或运行记录 ID (),以便自动从合思检索出站消息日志。" + ); + } + + // 4. Retrieve or match outbound log + let selectedLog: HoseOutboundLogItem | undefined; + if (!options.messageId && sn) { + console.error(`ℹ️ 正在通过合思 CloseAPI 检索单据「${sn}」的历史出站消息日志...`); + const logs = await fetchHoseOutboundLogs(sourceCorp, sn); + const recordCreatedAt = + typeof sourceRecord?.createdAt === "number" + ? sourceRecord.createdAt + : typeof sourceRecord?.createdAt === "string" + ? Date.parse(sourceRecord.createdAt) + : undefined; + selectedLog = selectMatchingOutboundLog(logs, { + recordId: options.recordId, + recordCreatedAt: Number.isNaN(recordCreatedAt) ? undefined : recordCreatedAt, + rejectionNum: options.rejectionNum + }); + + if (!selectedLog || !selectedLog.request?.messageId) { + throw validationError( + `在合思出站日志中未找到单据「${sn}」的有效出站记录 (type: INVOKING)。\n` + + `请确认该单据在合思审批流中是否触发过出站消息(EBot节点),或显式提供 --message-id 参数。` + ); + } + } + + // 5. Construct payload + const flowId = + options.flowId?.trim() ?? + selectedLog?.request?.flowId ?? + selectedLog?.flowId?.id ?? + sourceRecord?.sourceDocumentId ?? + (sn?.startsWith("ID01") ? sn : undefined); + + if (!flowId) { + throw validationError( + `未能解析出单据「${sn}」的合思流程实例 ID (flowId)。请确认单据信息或显式提供 flowId。` + ); + } + + const messageId = options.messageId?.trim() ?? selectedLog?.request?.messageId; + if (!messageId) { + throw validationError("未能获取到有效 messageId。"); + } + + const rejectionNum = + options.rejectionNum ?? selectedLog?.request?.rejectionNum ?? 0; + + const corporationId = + options.corporationId?.trim() ?? + selectedLog?.request?.corporationId ?? + (sourceCorp.source as any)?.corpId ?? + targetIntegration.corporationId; + + // Crucial: Chinese mock nodeId causes Hose to return HTTP 412 on callback, creating an indestructible safety gate + const nodeId = options.nodeId?.trim() || "FLOW:测试模拟节点_禁止流转"; + + const targetSealUrl = ( + targetCorp.seal.url ?? `https://${targetCorp.id.toLowerCase()}.sealai.cc` + ).replace(/\/+$/, ""); + const targetWebhookUrl = `${targetSealUrl}/api/hosecloud/outbound?config_id=${encodeURIComponent(targetIntegration.signKey)}`; + + const payload = { + flowId, + nodeId, + messageId, + rejectionNum, + corporationId + }; + + // 6. Dry run preview + if (dryRun) { + return { + preview: true, + channel: "hose-outbound", + sourceCorp: { + id: sourceCorp.id, + name: sourceCorp.name, + environment: sourceCorp.environment + }, + targetCorp: { + id: targetCorp.id, + name: targetCorp.name, + environment: targetCorp.environment + }, + targetIntegration: { + signKey: targetIntegration.signKey, + outboundName: targetIntegration.outboundName, + mode: targetIntegration.mode + }, + matchedLog: selectedLog + ? { + logId: selectedLog.id, + nodeName: selectedLog.nodeName, + createTime: selectedLog.createTime, + messageId: selectedLog.request?.messageId, + rejectionNum: selectedLog.request?.rejectionNum + } + : undefined, + safetyGuards: { + pairedBinding: true, + targetModeAssisted: true, + nodeId412Blocked: true + }, + targetUrl: targetWebhookUrl, + payload + }; + } + + // 7. Live execution + const response = await api.postHosecloudOutbound( + targetClient, + targetIntegration.signKey, + payload + ); + + console.error(`✓ 成功从合思出站日志匹配消息 (messageId: ${messageId}, 轮次: ${rejectionNum})`); + console.error(`✓ 已向测试企业「${targetCorp.name}」出站网关推送重放报文 (nodeId: ${nodeId})`); + + // Wait 2.5s for worker queue consumption + await new Promise((r) => setTimeout(r, 2500)); + let createdRecord: ApprovalRun | undefined; + try { + const runs = await api.listApprovalRuns(targetClient, { + limit: 5, + search: flowId + }); + createdRecord = (runs.records || []).find( + (r) => r.sourceDocumentId === flowId || r.sourceDocumentSN === sn + ); + } catch { + // non-blocking + } + + if (createdRecord) { + console.error(`✓ 异步消费成功!已在【${targetCorp.name}】生成审核记录: ${createdRecord.id} (任务模式: ${createdRecord.taskMode})`); + console.error(`👉 查看审核详情: seal-use approval-runs get ${createdRecord.id} --corp ${targetCorp.id}`); + } else { + console.error(`ℹ️ 消息已入队正在异步消费,可稍后在测试后台页面刷新查看。`); + } + + return { + success: true, + channel: "hose-outbound", + sourceCorp: { + id: sourceCorp.id, + name: sourceCorp.name + }, + targetCorp: { + id: targetCorp.id, + name: targetCorp.name + }, + targetSignKey: targetIntegration.signKey, + mode: targetIntegration.mode, + matchedMessageId: messageId, + rejectionNum, + payload, + response, + recordId: createdRecord?.id, + recordStatus: createdRecord?.status, + taskMode: createdRecord?.taskMode + }; +}