From 67a461452c8832323fa2058d356feb53319031a7 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Mon, 12 Oct 2026 00:13:22 +0800 Subject: [PATCH] Fix outbound confirmation and verification safety --- .../references/approval-run-lightweight.md | 4 +- skills/seal-use/references/cli.md | 8 +- .../references/hose-enterprise-deploy.md | 7 +- .../references/staging-simulation-workflow.md | 10 +- src/cli/commands/corps/sync.ts | 3 +- src/cli/commands/deploy.ts | 3 +- src/cli/commands/webhook-replay.test.ts | 63 +++++++++- src/cli/commands/webhook.ts | 5 +- src/cli/help.ts | 28 +++-- src/cli/parser.test.ts | 13 ++ src/cli/parser.ts | 2 +- src/core/duration.test.ts | 4 + src/core/duration.ts | 12 +- src/domains/seal/capabilities/deploy.ts | 11 +- src/domains/seal/capabilities/webhook.ts | 5 +- src/domains/seal/hose-outbound-replay.test.ts | 13 ++ src/domains/seal/hose-outbound-replay.ts | 24 +++- src/domains/seal/outbound-push.test.ts | 116 +++++++++++++++--- src/domains/seal/outbound-push.ts | 46 ++++--- src/domains/seal/webhook-replay.ts | 10 +- 20 files changed, 313 insertions(+), 74 deletions(-) diff --git a/skills/seal-use/references/approval-run-lightweight.md b/skills/seal-use/references/approval-run-lightweight.md index 28f300f..c40bd65 100644 --- a/skills/seal-use/references/approval-run-lightweight.md +++ b/skills/seal-use/references/approval-run-lightweight.md @@ -124,10 +124,10 @@ When diagnosing a bad case or verifying rule fixes, replay the historic run's st seal-use webhook replay --dry-run --corp # 执行重放,生成全新审批实例(支持自动附加单号后缀防重) -seal-use webhook replay [--webhook ] [--sn-suffix '-retest'] --corp +seal-use webhook replay [--webhook ] [--sn-suffix '-retest'] --corp --yes # 跨企业提取:从生产企业提取单据并推送至测试企业 Webhook 进行回归验证 -seal-use webhook replay --source-corp --corp +seal-use webhook replay --source-corp --corp --yes ``` ## Output Discipline diff --git a/skills/seal-use/references/cli.md b/skills/seal-use/references/cli.md index fb39f80..1f0483b 100644 --- a/skills/seal-use/references/cli.md +++ b/skills/seal-use/references/cli.md @@ -145,15 +145,15 @@ seal-use webhook delete [--yes|--dry-run] [--corp ] seal-use webhook resource-pack export [--limit ] [--status ] [--output ] [--to-downloads] [--corp ] seal-use webhook resource-pack preview <资源包.zip|信息表.xlsx> [--min-file-size ] [--max-file-size ] [--allowed-extensions <.pdf,.xlsx,...>] [--corp ] seal-use webhook resource-pack push <资源包.zip|信息表.xlsx> [--webhook ] [--corp ] -seal-use webhook replay [] [--sn ] [--limit ] [--status ] [--webhook ] [--source-corp ] [--target-corp ] [--sn-suffix ] [--channel webhook|hose-outbound] [--rejection-num ] [--message-id ] [--flow-id ] [--dry-run] [--force] [--corp ] -seal-use approval-runs replay --sn [--channel hose-outbound] [--rejection-num ] [--message-id ] [--flow-id ] [--target-corp ] [--dry-run] [--corp ] +seal-use webhook replay [] [--sn ] [--limit ] [--status ] [--webhook ] [--source-corp ] [--target-corp ] [--sn-suffix ] [--channel webhook|hose-outbound] [--rejection-num ] [--message-id ] [--flow-id ] [--dry-run] [--yes|--confirm] [--force] [--corp ] +seal-use approval-runs replay --sn [--channel hose-outbound] [--rejection-num ] [--message-id ] [--flow-id ] [--target-corp ] [--dry-run] [--yes|--confirm] [--corp ] seal-use deploy hosecloud requirements [--corp ] seal-use deploy hosecloud list [--corp ] seal-use deploy hosecloud get [--corp ] seal-use deploy hosecloud status [--corp ] seal-use deploy hosecloud configure --json '{...}' [--dry-run] [--corp ] seal-use deploy hosecloud sync [] [--auto] [--corp ] -seal-use deploy hosecloud test-outbound [--sign-key ] --flow-id --message-id [--sn ] [--rejection-num ] [--dry-run] [--corp ] +seal-use deploy hosecloud test-outbound [--sign-key ] --flow-id --message-id [--sn ] [--rejection-num ] [--dry-run] [--yes|--confirm] [--corp ] seal-use preference get [--corp ] seal-use preference decision update --json '{"explicitApprove":"..."}' [--dry-run] [--corp ] seal-use preference thinking-depth set --default [--dry-run] [--corp ] @@ -346,7 +346,7 @@ Webhook integrations: - `seal-use webhook resource-pack export [--limit ] [--status ] [--output ] [--to-downloads] --corp ` (将线上审核记录打包导出为标准 Webhook 资源包,支持按条数、状态或指定单据 ID 筛选) - `seal-use webhook resource-pack preview <资源包.zip|信息表.xlsx> [--min-file-size ] [--max-file-size ] [--allowed-extensions <.pdf,.xlsx,...>] --corp ` - `seal-use webhook resource-pack push <资源包.zip|信息表.xlsx> [--webhook ] --corp ` (别名 `pack`,旧名 `material-pack` 兼容支持) -- `seal-use webhook replay [] [--sn ] [--limit ] [--status ] [--webhook ] [--source-corp ] [--target-corp ] [--sn-suffix ] [--dry-run] [--force] [--corp ]` (通用单据重放:从历史审批单据汲取结构化表单与明细,清洗规范化字段类型,支持单条或批量重放到目标企业的 Webhook 触发审批。默认阻止向未授权生产环境重放以防污染数据,提供 `--force` 显式覆盖支持) +- `seal-use webhook replay [] [--sn ] [--limit ] [--status ] [--webhook ] [--source-corp ] [--target-corp ] [--sn-suffix ] [--dry-run] [--yes|--confirm] [--force] [--corp ]` (通用单据重放:从历史审批单据汲取结构化表单与明细,清洗规范化字段类型,支持单条或批量重放到目标企业的 Webhook 触发审批。实际重放要求 `--yes` 或 `--confirm`;默认阻止向未授权生产环境重放以防污染数据,提供 `--force` 显式覆盖支持) Webhook writes read the current AI approval config and POST the merged full config back to `api/v1/agent/ai-approval/config`, preserving non-Webhook integrations. List/get mask `secret` by default; add returns the generated secret once. Each Webhook can also store a mutable `materialPackFilePolicy` with `minFileSizeBytes`, optional `maxFileSizeBytes`, and `allowedExtensions`. Update is a patch: omitted policy fields are retained; `allowedExtensions` replaces the complete list; `--clear-max-file-size` removes the upper bound. diff --git a/skills/seal-use/references/hose-enterprise-deploy.md b/skills/seal-use/references/hose-enterprise-deploy.md index 154f212..4be5aeb 100644 --- a/skills/seal-use/references/hose-enterprise-deploy.md +++ b/skills/seal-use/references/hose-enterprise-deploy.md @@ -79,10 +79,13 @@ seal-use deploy hosecloud get [] --corp # 7. 检查发布与多平台集成状态 seal-use deploy hosecloud status --corp -# 8. 测试/重放出站请求 (要求 assisted 模式,强制中文 nodeId 阻断安全门禁) -seal-use deploy hosecloud test-outbound [--sign-key ] --flow-id --message-id [--sn ] [--dry-run] --corp +# 8. 测试/重放出站请求 (要求 assisted 模式,默认使用中文 nodeId 阻断标记) +seal-use deploy hosecloud test-outbound [--sign-key ] --flow-id --message-id [--sn ] [--dry-run] [--yes|--confirm] --corp ``` +实际推送必须带 `--yes` 或 `--confirm`;`--dry-run` 可直接预览。自定义 `nodeId` 时,预览中的 `nodeId412Blocked` 不再声明默认标记的阻断保障。 +出站响应未明确返回关联 `recordId` 时,结果为 `consumptionVerified: false`(推送已接受,消费尚未确认),不会用同单据的历史记录误报本次消费成功。 + --- ## 4. 关键配置参数定义 diff --git a/skills/seal-use/references/staging-simulation-workflow.md b/skills/seal-use/references/staging-simulation-workflow.md index af46350..99dbfc7 100644 --- a/skills/seal-use/references/staging-simulation-workflow.md +++ b/skills/seal-use/references/staging-simulation-workflow.md @@ -185,10 +185,10 @@ flowchart TD seal-use corps replay-test --sn '<单据号>' --confirm # 跨企业通用重放 - seal-use webhook replay --limit 5 --status failed --prod-corp --test-corp + seal-use webhook replay --limit 5 --status failed --prod-corp --test-corp --yes # 未绑定测试企业 / 明确需要重放到生产企业(必须显式指定 --force 覆盖生产保护拦截) - seal-use webhook replay --force + seal-use webhook replay --force --yes ``` > **生产环境直接重放说明**:若企业未配置独立测试租户,用户确实需要直接在生产环境重放验证时,系统支持通过 `--force` 显式放行。执行前请确认生产 Webhook 通道的回调地址(若有)不会影响外部下游生产系统。 @@ -199,13 +199,13 @@ flowchart TD seal-use approval-runs replay --sn --channel hose-outbound --corp --dry-run # 正式执行(自动推送到绑定的测试企业,并在测试企业异步生成 AI 审核记录) - seal-use approval-runs replay --sn --channel hose-outbound --corp + seal-use approval-runs replay --sn --channel hose-outbound --corp --yes # 精准匹配指定驳回重提轮次 - seal-use approval-runs replay --sn --channel hose-outbound --rejection-num 1 --corp + seal-use approval-runs replay --sn --channel hose-outbound --rejection-num 1 --corp --yes # 底层直接推送出站调试消息(仅限 assisted 模式) - seal-use deploy hosecloud test-outbound --flow-id --message-id --corp + seal-use deploy hosecloud test-outbound --flow-id --message-id --corp --yes ``` > **专属安全红线契约**: > 1. **双向绑定**:必须在已绑定的生产-测试企业对之间执行;严禁跨越非关联租户(未带 `--force` 时直接报 Exit 14 阻断)。 diff --git a/src/cli/commands/corps/sync.ts b/src/cli/commands/corps/sync.ts index 9cc1708..71f298b 100644 --- a/src/cli/commands/corps/sync.ts +++ b/src/cli/commands/corps/sync.ts @@ -126,7 +126,8 @@ export async function handleCorpSync( snSuffix: stringOption(args.options.snSuffix) ?? stringOption(args.options["sn-suffix"]), docIdPrefix: stringOption(args.options.docIdPrefix) ?? stringOption(args.options["doc-id-prefix"]), docIdSuffix: stringOption(args.options.docIdSuffix) ?? stringOption(args.options["doc-id-suffix"]), - dryRun + dryRun, + confirm: confirmed }); if (dryRun) { console.error(`[corps-replay-test] 预览模式:已成功从 ${prodCorp.name} 提取单据并转换为 Webhook Payload(未实际推送)。`); diff --git a/src/cli/commands/deploy.ts b/src/cli/commands/deploy.ts index 940f180..cfbfcf3 100644 --- a/src/cli/commands/deploy.ts +++ b/src/cli/commands/deploy.ts @@ -189,7 +189,8 @@ export async function handleDeployCommand( nodeId, rejectionNum, corporationId, - dryRun + dryRun, + confirm: booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true }, outputOptions(args.options) ); diff --git a/src/cli/commands/webhook-replay.test.ts b/src/cli/commands/webhook-replay.test.ts index c05d505..e089027 100644 --- a/src/cli/commands/webhook-replay.test.ts +++ b/src/cli/commands/webhook-replay.test.ts @@ -288,7 +288,7 @@ describe("seal-use webhook replay CLI", () => { return new Response("Not found", { status: 404 }); }) as any; - const result = await runCli(["webhook", "replay", "run-001"]); + const result = await runCli(["webhook", "replay", "run-001", "--yes"]); expect(result.isError).toBe(false); expect(result.exitCode).toBe(0); @@ -569,5 +569,66 @@ describe("seal-use webhook replay CLI", () => { expect(parsed.safetyGuards.targetModeAssisted).toBe(true); expect(parsed.safetyGuards.nodeId412Blocked).toBe(true); }); + + test("webhook replay requires confirmation before provisioning or pushing", async () => { + setupMockEnv(); + let mutations = 0; + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + const method = init?.method ?? (input instanceof Request ? input.method : "GET"); + if (method !== "GET") mutations++; + return new Response(JSON.stringify({ data: mockApprovalRun }), { + status: 200, headers: { "Content-Type": "application/json" } + }); + }) as typeof fetch; + const result = await runCli(["approval-runs", "replay", "run-001"]); + expect(result.exitCode).toBe(10); + expect(result.stderr).toContain("--yes or --confirm"); + expect(mutations).toBe(0); + }); + + test("outbound CLI gates both entry points and passes either confirmation flag", async () => { + setupMockEnv(); + let pushes = 0; + globalThis.fetch = (async (input: RequestInfo | URL) => { + const requestUrl = input instanceof Request ? input.url : input.toString(); + if (requestUrl.includes("/api/hosecloud/outbound")) { + pushes++; + return new Response(JSON.stringify({ data: { success: true } }), { + status: 200, headers: { "Content-Type": "application/json" } + }); + } + return new Response(JSON.stringify({ data: { integrations: [{ + type: "hosecloud", signKey: "key", mode: "assisted", corporationId: "corp" + }] } }), { status: 200, headers: { "Content-Type": "application/json" } }); + }) as typeof fetch; + for (const command of [ + ["approval-runs", "replay", "--sn", "SN", "--channel", "hose-outbound"], + ["deploy", "hosecloud", "test-outbound"] + ]) { + const args = [...command, "--flow-id", "flow", "--message-id", "message"]; + for (const flags of [[], ["--yes=false"], ["--force"]]) { + const before = pushes; + const result = await runCli([...args, ...flags]); + expect(result.exitCode).toBe(10); + expect(pushes).toBe(before); + } + for (const flag of ["--yes", "--confirm"]) { + const before = pushes; + const result = await runCli([...args, flag]); + expect(result.exitCode).toBe(0); + expect(pushes).toBe(before + 1); + const parsed = JSON.parse(result.stdout); + expect(parsed.consumptionVerified).toBe(false); + expect(parsed.recordId).toBeUndefined(); + } + + const before = pushes; + const preview = await runCli([...args, "--node-id", "FLOW:real-node", "--dry-run"]); + expect(preview.exitCode).toBe(0); + expect(pushes).toBe(before); + const parsed = JSON.parse(preview.stdout); + expect((parsed.safetyGuards ?? parsed.safetyCheck).nodeId412Blocked).toBe(false); + } + }); }); diff --git a/src/cli/commands/webhook.ts b/src/cli/commands/webhook.ts index c6724f4..94059cf 100644 --- a/src/cli/commands/webhook.ts +++ b/src/cli/commands/webhook.ts @@ -148,6 +148,7 @@ export async function handleWebhookCommand( const docIdSuffix = stringOption(args.options.docIdSuffix) ?? stringOption(args.options["doc-id-suffix"]); const docIdPrefix = stringOption(args.options.docIdPrefix) ?? stringOption(args.options["doc-id-prefix"]); const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]); + const confirm = booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true; const channel = stringOption(args.options.channel) ?? @@ -178,6 +179,7 @@ export async function handleWebhookCommand( rejectionNum, targetSignKey, dryRun, + confirm, force }); @@ -207,7 +209,8 @@ export async function handleWebhookCommand( snSuffix, docIdPrefix, docIdSuffix, - dryRun + dryRun, + confirm }); if (dryRun) { diff --git a/src/cli/help.ts b/src/cli/help.ts index 9e6c277..f40df4f 100644 --- a/src/cli/help.ts +++ b/src/cli/help.ts @@ -435,9 +435,9 @@ export const HELP_REGISTRY: AreaHelp[] = [ { name: "replay", usage: [ - "seal-use webhook replay [--webhook ] [--sn-suffix ] [--dry-run] [--corp ]", - "seal-use webhook replay --sn [--webhook ] [--source-corp ] [--target-corp ]", - "seal-use webhook replay --limit [--status ] [--source-corp ] [--target-corp ]" + "seal-use webhook replay [--webhook ] [--sn-suffix ] [--dry-run] [--yes|--confirm] [--corp ]", + "seal-use webhook replay --sn [--webhook ] [--source-corp ] [--target-corp ] [--yes|--confirm]", + "seal-use webhook replay --limit [--status ] [--source-corp ] [--target-corp ] [--yes|--confirm]" ], options: [ { flag: "", description: "Approval run record ID to replay" }, @@ -450,6 +450,7 @@ export const HELP_REGISTRY: AreaHelp[] = [ { flag: "--sn-suffix ", description: "Optional suffix appended to documentSN and documentId" }, { flag: "--sn-prefix ", description: "Optional prefix prepended to documentSN and documentId" }, { flag: "--dry-run", description: "Generate and output Webhook payload JSON without sending HTTP request" }, + { flag: "--yes, --confirm", description: "Required for live replay; --force only overrides the environment guard" }, { flag: "--force", description: "Allow replaying to a production enterprise" } ], description: "Extracts structured form fields from historical approval records (Webhook or Hose source), sanitizes field types, and pushes documents to the target Webhook channel. Automatically infers 1-to-1 bound test/production enterprise pairs." @@ -582,11 +583,11 @@ export const HELP_REGISTRY: AreaHelp[] = [ name: "replay", summary: "Replay approval run record into a Webhook integration", 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 [--sign-key ] [--target-corp ] [--dry-run]", - "seal-use approval-runs replay --channel hose-outbound [--sign-key ] [--target-corp ] [--dry-run]", - "seal-use approval-runs replay --limit [--status ] [--source-corp ] [--target-corp ]" + "seal-use approval-runs replay [--webhook ] [--sn-suffix ] [--dry-run] [--yes|--confirm] [--corp ]", + "seal-use approval-runs replay --sn [--webhook ] [--source-corp ] [--target-corp ] [--yes|--confirm]", + "seal-use approval-runs replay --sn --channel hose-outbound [--sign-key ] [--target-corp ] [--dry-run] [--yes|--confirm]", + "seal-use approval-runs replay --channel hose-outbound [--sign-key ] [--target-corp ] [--dry-run] [--yes|--confirm]", + "seal-use approval-runs replay --limit [--status ] [--source-corp ] [--target-corp ] [--yes|--confirm]" ], options: [ { flag: "", description: "Approval run record ID" }, @@ -601,7 +602,8 @@ export const HELP_REGISTRY: AreaHelp[] = [ { flag: "--source-corp ", description: "Source enterprise where records reside" }, { flag: "--target-corp ", description: "Target enterprise where records are pushed" }, { flag: "--sn-suffix ", description: "Optional suffix appended to documentSN" }, - { flag: "--dry-run", description: "Preview payload without sending" } + { flag: "--dry-run", description: "Preview payload without sending" }, + { flag: "--yes, --confirm", description: "Required for live replay; --force only overrides environment and pairing guards" } ] } ] @@ -758,8 +760,12 @@ export const HELP_REGISTRY: AreaHelp[] = [ 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 ]" + "seal-use deploy hosecloud test-outbound [--sign-key ] --flow-id --message-id [--dry-run] [--yes|--confirm] [--corp ]", + "seal-use deploy hosecloud test-outbound [--sign-key ] --sn --message-id [--dry-run] [--yes|--confirm] [--corp ]" + ], + options: [ + { flag: "--dry-run", description: "Preview the outbound payload without sending" }, + { flag: "--yes, --confirm", description: "Required for live outbound push" } ] } ] diff --git a/src/cli/parser.test.ts b/src/cli/parser.test.ts index 5348da8..f5a7948 100644 --- a/src/cli/parser.test.ts +++ b/src/cli/parser.test.ts @@ -158,6 +158,19 @@ describe("option helpers", () => { expect(() => parseHoseExpireSeconds("invalid")).toThrow("必须为有效时长"); }); + test("overflowing --expire literals are usage errors before reaching auth", () => { + for (const parse of [parseDelegationExpireHours, parseHoseExpireSeconds]) { + for (const literal of ["9".repeat(309), "9".repeat(309) + "s", "9".repeat(308) + "d"]) { + expect(() => parse(literal)).toThrow(); + try { + parse(literal); + } catch (error) { + expect((error as { exitCode: number }).exitCode).toBe(2); + } + } + } + }); + test("both --expire flags read a unitless literal the same way", () => { // Regression: the two parsers used to each carry their own copy of the // unitless heuristic, so `--expire 300` meant 5 minutes on one path and diff --git a/src/cli/parser.ts b/src/cli/parser.ts index 5a246a9..f1118a8 100644 --- a/src/cli/parser.ts +++ b/src/cli/parser.ts @@ -533,7 +533,7 @@ export function parseHoseExpireSeconds( } const seconds = Math.round(expireSeconds(token)); - if (seconds <= 0) { + if (!Number.isFinite(seconds) || seconds <= 0) { throw usageError(`Invalid --expire: 计算得 ${seconds} 秒。必须为大于 0 的有效时长。`); } return seconds; diff --git a/src/core/duration.test.ts b/src/core/duration.test.ts index 3651060..c3f0d2f 100644 --- a/src/core/duration.test.ts +++ b/src/core/duration.test.ts @@ -26,6 +26,8 @@ describe("tokenizeDuration", () => { expect(tokenizeDuration("5parsecs")).toBeUndefined(); expect(tokenizeDuration(Number.NaN)).toBeUndefined(); expect(tokenizeDuration(true as unknown as string)).toBeUndefined(); + expect(tokenizeDuration("9".repeat(309))).toBeUndefined(); + expect(tokenizeDuration("9".repeat(309) + "s")).toBeUndefined(); }); }); @@ -71,5 +73,7 @@ describe("parseDurationMs", () => { test("falls back rather than failing a batch over a bad poll interval", () => { expect(parseDurationMs("soon")).toBe(600_000); expect(parseDurationMs("soon", 1000)).toBe(1000); + expect(parseDurationMs("9".repeat(309) + "s", 1000)).toBe(1000); + expect(parseDurationMs("9".repeat(308) + "d", 1000)).toBe(1000); }); }); diff --git a/src/core/duration.ts b/src/core/duration.ts index 26e518b..3a904cf 100644 --- a/src/core/duration.ts +++ b/src/core/duration.ts @@ -74,9 +74,14 @@ export function tokenizeDuration( return undefined; } + const magnitude = parseFloat(match[1]); + if (!Number.isFinite(magnitude)) { + return undefined; + } + const rawUnit = match[2]?.toLowerCase(); if (!rawUnit) { - return { value: parseFloat(match[1]), unit: undefined }; + return { value: magnitude, unit: undefined }; } const unit = UNIT_ALIASES[rawUnit]; @@ -86,7 +91,7 @@ export function tokenizeDuration( if (options.units && !options.units.includes(unit)) { return undefined; } - return { value: parseFloat(match[1]), unit }; + return { value: magnitude, unit }; } /** @@ -135,5 +140,6 @@ export function parseDurationMs(duration: string, fallbackMs = DEFAULT_DURATION_ if (!token || token.value < 0) { return fallbackMs; } - return Math.round(durationSeconds(token, "s") * 1000); + const milliseconds = Math.round(durationSeconds(token, "s") * 1000); + return Number.isFinite(milliseconds) ? milliseconds : fallbackMs; } diff --git a/src/domains/seal/capabilities/deploy.ts b/src/domains/seal/capabilities/deploy.ts index 2aeac2d..a484570 100644 --- a/src/domains/seal/capabilities/deploy.ts +++ b/src/domains/seal/capabilities/deploy.ts @@ -239,7 +239,8 @@ export const deployCapabilities = [ nodeId: z.string().optional().default(BLOCKING_NODE_ID).describe("合思流程节点 ID(默认填入中文阻断标识)"), rejectionNum: z.number().int().optional().default(0).describe("驳回/重提次数(默认 0)"), corporationId: z.string().optional().describe("合思企业 ID(若未提供则取自集成配置)"), - dryRun: z.boolean().optional().default(false).describe("是否仅预览请求载荷与安全检查而不实际推送") + dryRun: z.boolean().optional().default(false).describe("是否仅预览请求载荷与安全检查而不实际推送"), + confirm: z.boolean().optional().describe("明确确认实际推送;CLI 使用 --yes 或 --confirm") }), handler: async ( client: KyInstance, @@ -252,6 +253,7 @@ export const deployCapabilities = [ rejectionNum?: number; corporationId?: string; dryRun?: boolean; + confirm?: boolean; }, context: CapabilityContext ) => { @@ -332,7 +334,10 @@ export const deployCapabilities = [ safetyCheck: { mode: "assisted", passed: true, - note: "目标企业出站模式为 assisted,AI 绝不会向合思回写审批动作;且默认 nodeId 包含中文阻断标记,双重安全保障。" + nodeId412Blocked: payload.nodeId === BLOCKING_NODE_ID, + note: payload.nodeId === BLOCKING_NODE_ID + ? "目标企业出站模式为 assisted;使用默认中文 nodeId 阻断标记。" + : "目标企业出站模式为 assisted;自定义 nodeId 未验证具备 HTTP 412 阻断保障。" }, payload }; @@ -344,6 +349,7 @@ export const deployCapabilities = [ payload, flowId, sn, + confirm: params.confirm, corpName: context.corp.name, corpId: context.corp.id, pushedMessages: [ @@ -358,6 +364,7 @@ export const deployCapabilities = [ mode: integration.mode, payload, response, + consumptionVerified: createdRecord !== undefined, recordId: createdRecord?.id, recordStatus: createdRecord?.status, taskMode: createdRecord?.taskMode diff --git a/src/domains/seal/capabilities/webhook.ts b/src/domains/seal/capabilities/webhook.ts index 5ea4fca..48fc466 100644 --- a/src/domains/seal/capabilities/webhook.ts +++ b/src/domains/seal/capabilities/webhook.ts @@ -239,6 +239,7 @@ export const webhookCapabilities = [ snPrefix: z.string().optional().describe("重放单号前缀"), snSuffix: z.string().optional().describe("重放单号后缀"), dryRun: z.boolean().optional().describe("是否仅执行预检转换而不实际推送 (默认 false)"), + confirm: z.boolean().optional().describe("明确确认实际重放;CLI 使用 --yes 或 --confirm"), force: z.boolean().optional().describe("若目标为生产环境,强制执行重放") }), handler: async ( @@ -254,6 +255,7 @@ export const webhookCapabilities = [ snPrefix?: string; snSuffix?: string; dryRun?: boolean; + confirm?: boolean; force?: boolean; }, context: CapabilityContext @@ -299,7 +301,8 @@ export const webhookCapabilities = [ webhookSelector: params.webhook, snPrefix: params.snPrefix, snSuffix: params.snSuffix, - dryRun: params.dryRun + dryRun: params.dryRun, + confirm: params.confirm }); } }, diff --git a/src/domains/seal/hose-outbound-replay.test.ts b/src/domains/seal/hose-outbound-replay.test.ts index 3ab0a6a..bb74c22 100644 --- a/src/domains/seal/hose-outbound-replay.test.ts +++ b/src/domains/seal/hose-outbound-replay.test.ts @@ -143,6 +143,19 @@ describe("selectMatchingOutboundLog", () => { }); describe("validateHoseOutboundReplaySafety", () => { + test("reports the actual guards overridden by force", () => { + const guards = validateHoseOutboundReplaySafety( + { ...mockSourceCorp, testCorpId: undefined }, + { ...mockTargetCorp, prodCorpId: undefined, environment: "production" }, + { mode: "assisted", signKey: "key" }, + true + ); + expect(guards.pairedBinding).toBe(false); + expect(guards.targetNonProduction).toBe(false); + expect(guards.targetModeAssisted).toBe(true); + expect(guards.overriddenGuards).toEqual(["pairedBinding", "targetNonProduction"]); + }); + test("passes when source and target are paired and target is assisted", () => { expect(() => validateHoseOutboundReplaySafety( diff --git a/src/domains/seal/hose-outbound-replay.ts b/src/domains/seal/hose-outbound-replay.ts index 5d29bfb..6f3745c 100644 --- a/src/domains/seal/hose-outbound-replay.ts +++ b/src/domains/seal/hose-outbound-replay.ts @@ -5,6 +5,7 @@ import { fetchHoseOutboundLogs, type HoseOutboundLogItem } from "../hose/close/o import * as api from "./api.js"; import { assertAssistedIntegration, + BLOCKING_NODE_ID, buildOutboundPayload, buildOutboundWebhookUrl, flowIdFromDocumentSn, @@ -32,6 +33,7 @@ export interface HoseOutboundReplayOptions { rejectionNum?: number; targetSignKey?: string; dryRun?: boolean; + confirm?: boolean; force?: boolean; } @@ -116,7 +118,7 @@ export function validateHoseOutboundReplaySafety( 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 || @@ -143,6 +145,17 @@ export function validateHoseOutboundReplaySafety( corpName: targetCorp.name, corpId: targetCorp.id }); + + const targetNonProduction = targetCorp.environment !== "production"; + return { + pairedBinding: isPaired, + targetNonProduction, + targetModeAssisted: true, + overriddenGuards: [ + ...(!isPaired ? ["pairedBinding"] : []), + ...(!targetNonProduction ? ["targetNonProduction"] : []) + ] + }; } /** @@ -164,7 +177,7 @@ export async function executeHoseOutboundReplay(options: HoseOutboundReplayOptio }); // 2. Validate safety constraints - validateHoseOutboundReplaySafety(sourceCorp, targetCorp, targetIntegration, force); + const safetyGuards = validateHoseOutboundReplaySafety(sourceCorp, targetCorp, targetIntegration, force); // 3. Resolve document SN & record details let sn = options.sn?.trim(); @@ -279,9 +292,8 @@ export async function executeHoseOutboundReplay(options: HoseOutboundReplayOptio } : undefined, safetyGuards: { - pairedBinding: true, - targetModeAssisted: true, - nodeId412Blocked: true + ...safetyGuards, + nodeId412Blocked: payload.nodeId === BLOCKING_NODE_ID }, targetUrl: targetWebhookUrl, payload @@ -295,6 +307,7 @@ export async function executeHoseOutboundReplay(options: HoseOutboundReplayOptio payload, flowId, sn, + confirm: options.confirm, corpName: targetCorp.name, corpId: targetCorp.id, pushedMessages: [ @@ -320,6 +333,7 @@ export async function executeHoseOutboundReplay(options: HoseOutboundReplayOptio rejectionNum: payload.rejectionNum, payload, response, + consumptionVerified: createdRecord !== undefined, recordId: createdRecord?.id, recordStatus: createdRecord?.status, taskMode: createdRecord?.taskMode diff --git a/src/domains/seal/outbound-push.test.ts b/src/domains/seal/outbound-push.test.ts index cf61b86..ad9cdf8 100644 --- a/src/domains/seal/outbound-push.test.ts +++ b/src/domains/seal/outbound-push.test.ts @@ -212,10 +212,12 @@ describe("resolveCorporationId", () => { }); describe("pushOutboundAndVerify", () => { - function fakeClient(records: Array>): KyInstance { + function fakeClient(records: Array>, recordId?: string): KyInstance { return { - post: async () => ({ json: async () => ({ data: { success: true } }) }), - get: async () => ({ json: async () => ({ data: { records } }) }) + post: async () => ({ json: async () => ({ data: { success: true, recordId } }) }), + get: async (path: string) => ({ json: async () => ({ + data: path === "api/v1/approvals" ? { records } : records.find((record) => path.endsWith(`/${record.id}`)) + }) }) } as unknown as KyInstance; } @@ -227,7 +229,7 @@ describe("pushOutboundAndVerify", () => { const { response, createdRecord } = await pushOutboundAndVerify({ client: fakeClient([ { id: "run-9", sourceDocumentId: "ID01abc", status: "pending", taskMode: "auto" } - ]), + ], "run-9"), signKey: "key-1", payload: buildOutboundPayload({ flowId: "ID01abc", @@ -239,13 +241,14 @@ describe("pushOutboundAndVerify", () => { corpName: "目标企业", corpId: "target-corp", pushedMessages: ["✓ pushed"], - verifyWaitMs: 0 + verifyWaitMs: 0, + confirm: true }); - expect(response).toEqual({ success: true }); + expect(response).toEqual({ success: true, recordId: "run-9" }); expect(createdRecord?.id).toBe("run-9"); expect(lines[0]).toBe("✓ pushed"); - expect(lines.join("\n")).toContain("已在【目标企业】生成审核记录: run-9"); + expect(lines.join("\n")).toContain("已确认本次推送关联【目标企业】审核记录: run-9"); expect(lines.join("\n")).toContain("seal-use approval-runs get run-9 --corp target-corp"); } finally { console.error = originalError; @@ -258,7 +261,7 @@ describe("pushOutboundAndVerify", () => { console.error = (line: string) => lines.push(line); try { const { createdRecord } = await pushOutboundAndVerify({ - client: fakeClient([{ id: "run-s", sourceDocumentSN: "BX999" }]), + client: fakeClient([{ id: "run-s", sourceDocumentSN: "BX999" }], "run-s"), signKey: "key-1", payload: buildOutboundPayload({ flowId: "ID01abc", @@ -269,7 +272,8 @@ describe("pushOutboundAndVerify", () => { sn: "BX999", corpName: "目标企业", corpId: "target-corp", - verifyWaitMs: 0 + verifyWaitMs: 0, + confirm: true }); expect(createdRecord?.id).toBe("run-s"); } finally { @@ -290,10 +294,11 @@ describe("pushOutboundAndVerify", () => { flowId: "ID01abc", corpName: "目标企业", corpId: "target-corp", - verifyWaitMs: 0 + verifyWaitMs: 0, + confirm: true }); expect(createdRecord).toBeUndefined(); - expect(queued.join("\n")).toContain("消息已入队正在异步消费"); + expect(queued.join("\n")).toContain("推送已接受,异步消费尚未确认"); expect(queued.join("\n")).toContain("seal-use approval-runs list --corp target-corp"); } finally { console.error = originalError; @@ -309,7 +314,7 @@ describe("pushOutboundAndVerify", () => { console.error = (line: string) => lines.push(line); try { const { createdRecord } = await pushOutboundAndVerify({ - client: fakeClient([{ id: "unrelated-old-run" }]), + client: fakeClient([{ id: "unrelated-old-run" }], "unrelated-old-run"), signKey: "key-1", payload: buildOutboundPayload({ flowId: "ID01abc", @@ -319,11 +324,12 @@ describe("pushOutboundAndVerify", () => { flowId: "ID01abc", corpName: "目标企业", corpId: "target-corp", - verifyWaitMs: 0 + verifyWaitMs: 0, + confirm: true }); expect(createdRecord).toBeUndefined(); - expect(lines.join("\n")).toContain("消息已入队正在异步消费"); + expect(lines.join("\n")).toContain("推送已接受,异步消费尚未确认"); expect(lines.join("\n")).not.toContain("unrelated-old-run"); } finally { console.error = originalError; @@ -335,7 +341,7 @@ describe("pushOutboundAndVerify", () => { console.error = () => {}; try { const client = { - post: async () => ({ json: async () => ({ data: { success: true } }) }), + post: async () => ({ json: async () => ({ data: { success: true, recordId: "run-9" } }) }), get: async () => { throw new Error("502 Bad Gateway"); } @@ -352,13 +358,89 @@ describe("pushOutboundAndVerify", () => { flowId: "f", corpName: "目标企业", corpId: "target-corp", - verifyWaitMs: 0 + verifyWaitMs: 0, + confirm: true }); - expect(response).toEqual({ success: true }); + expect(response).toEqual({ success: true, recordId: "run-9" }); expect(createdRecord).toBeUndefined(); } finally { console.error = originalError; } }); + + test("requires explicit confirmation before any push", async () => { + let pushed = false; + const client = { + post: async () => { pushed = true; throw new Error("unexpected push"); } + } as unknown as KyInstance; + for (const confirm of [undefined, false]) { + await expect(pushOutboundAndVerify({ + client, + signKey: "key-1", + payload: buildOutboundPayload({ flowId: "f", messageId: "m", corporationId: "c" }), + flowId: "f", + corpName: "目标企业", + corpId: "target-corp", + confirm + })).rejects.toMatchObject({ exitCode: 10 }); + } + expect(pushed).toBe(false); + }); + + test("never attributes old or concurrent runs without a recordId from the push", async () => { + let queried = false; + const client = { + post: async () => ({ json: async () => ({ data: { success: true } }) }), + get: async () => { + queried = true; + return { json: async () => ({ data: { records: [ + { id: "old-run", sourceDocumentId: "f", status: "failed", createdAt: "2025-01-01T00:00:00Z" }, + { id: "concurrent-run", sourceDocumentId: "f", createdAt: Date.now() } + ] } }) }; + } + } as unknown as KyInstance; + const result = await pushOutboundAndVerify({ + client, + signKey: "key-1", + payload: buildOutboundPayload({ flowId: "f", messageId: "m", corporationId: "c" }), + flowId: "f", + corpName: "目标企业", + corpId: "target-corp", + confirm: true, + verifyWaitMs: 0 + }); + expect(result.createdRecord).toBeUndefined(); + expect(queried).toBe(false); + }); + + test("rejects a mismatched flow even when its SN matches", async () => { + const result = await pushOutboundAndVerify({ + client: fakeClient([{ id: "wrong-run", sourceDocumentId: "other-flow", sourceDocumentSN: "SN" }], "wrong-run"), + signKey: "key-1", + payload: buildOutboundPayload({ flowId: "f", messageId: "m", corporationId: "c" }), + flowId: "f", + sn: "SN", + corpName: "目标企业", + corpId: "target-corp", + confirm: true, + verifyWaitMs: 0 + }); + expect(result.createdRecord).toBeUndefined(); + }); + + test("a rejected push is a domain failure rather than an accepted message", async () => { + const client = { + post: async () => ({ json: async () => ({ data: { success: false, message: "rejected" } }) }) + } as unknown as KyInstance; + await expect(pushOutboundAndVerify({ + client, + signKey: "key-1", + payload: buildOutboundPayload({ flowId: "f", messageId: "m", corporationId: "c" }), + flowId: "f", + corpName: "目标企业", + corpId: "target-corp", + confirm: true + })).rejects.toThrow("合思出站推送失败:rejected"); + }); }); diff --git a/src/domains/seal/outbound-push.ts b/src/domains/seal/outbound-push.ts index af2900c..46b21b3 100644 --- a/src/domains/seal/outbound-push.ts +++ b/src/domains/seal/outbound-push.ts @@ -1,5 +1,5 @@ import type { KyInstance } from "ky"; -import { safetyBlocked, validationError } from "../../core/errors.js"; +import { confirmationRequired, safetyBlocked, validationError } from "../../core/errors.js"; import type { CorpConfig } from "../../core/config/types.js"; import * as api from "./api.js"; import type { ApprovalIntegration, ApprovalRun, ApprovalStylePreferences } from "./types.js"; @@ -153,6 +153,8 @@ export function resolveCorporationId(candidates: Array): str * Push the payload, then poll approval runs to report whether the queue * consumed it. The poll is advisory: a miss only downgrades the message to * "queued", it never fails the push that already succeeded. + * Only a recordId returned by this push can associate a run with this message; + * finding the same document in a list also finds historical or concurrent runs. */ export async function pushOutboundAndVerify(options: { client: KyInstance; @@ -160,6 +162,7 @@ export async function pushOutboundAndVerify(options: { payload: OutboundPayload; flowId: string; sn?: string; + confirm?: boolean; corpName: string; corpId: string; /** Channel-specific success lines logged right after the push lands. */ @@ -169,36 +172,47 @@ export async function pushOutboundAndVerify(options: { }): Promise<{ response: Awaited>; createdRecord?: ApprovalRun }> { const { client, signKey, payload, flowId, sn, corpName, corpId } = options; + if (options.confirm !== true) { + throw confirmationRequired( + "Refusing to push an outbound test/replay message without --yes or --confirm. Use --dry-run to preview first.", + "seal-use help deploy hosecloud test-outbound" + ); + } + const response = await api.postHosecloudOutbound(client, signKey, payload); + if (response.success === false) { + throw new Error(`合思出站推送失败:${response.message ?? "上游拒绝请求"}`); + } for (const line of options.pushedMessages ?? []) { console.error(line); } - await new Promise((resolve) => setTimeout(resolve, options.verifyWaitMs ?? OUTBOUND_VERIFY_WAIT_MS)); - // `sn` is optional: callers that only know the flowId leave it undefined, and // an undefined needle must never match a record whose SN is absent — that // would report an unrelated run as the one this push just created. const snNeedle = sn?.trim() || undefined; - let createdRecord: ApprovalRun | undefined; - try { - const runs = await api.listApprovalRuns(client, { limit: 5, search: flowId }); - createdRecord = (runs.records || []).find( - (record) => - record.sourceDocumentId === flowId || - record.sourceDocumentSN === flowId || - (snNeedle !== undefined && record.sourceDocumentSN === snNeedle) - ); - } catch { - // Non-blocking: the run may not exist yet even when the push succeeded. + const recordId = typeof response.recordId === "string" ? response.recordId.trim() : undefined; + if (recordId) { + await new Promise((resolve) => setTimeout(resolve, options.verifyWaitMs ?? OUTBOUND_VERIFY_WAIT_MS)); + try { + const record = await api.getApprovalRun(client, recordId); + const sameDocument = record.sourceDocumentId === flowId || + (!record.sourceDocumentId && (record.sourceDocumentSN === flowId || + (snNeedle !== undefined && record.sourceDocumentSN === snNeedle))); + if (record.id === recordId && sameDocument) { + createdRecord = record; + } + } catch { + // Non-blocking: the run may not exist yet even when the push succeeded. + } } if (createdRecord) { - console.error(`✓ 异步消费成功!已在【${corpName}】生成审核记录: ${createdRecord.id} (任务模式: ${createdRecord.taskMode})`); + console.error(`✓ 已确认本次推送关联【${corpName}】审核记录: ${createdRecord.id} (任务模式: ${createdRecord.taskMode})`); console.error(`👉 查看审核详情: seal-use approval-runs get ${createdRecord.id} --corp ${corpId}`); } else { - console.error(`ℹ️ 消息已入队正在异步消费,可稍后执行: seal-use approval-runs list --corp ${corpId}`); + console.error(`ℹ️ 推送已接受,异步消费尚未确认,可稍后执行: seal-use approval-runs list --corp ${corpId}`); } return { response, createdRecord }; diff --git a/src/domains/seal/webhook-replay.ts b/src/domains/seal/webhook-replay.ts index 38673eb..014e9df 100644 --- a/src/domains/seal/webhook-replay.ts +++ b/src/domains/seal/webhook-replay.ts @@ -2,7 +2,7 @@ import type { KyInstance } from "ky"; import type { ApprovalRun, WebhookIntegration } from "./types.js"; import type { MaterialField } from "./material-pack/types.js"; import { webhookHeaders } from "./material-pack/signature.js"; -import { CliError, validationError } from "../../core/errors.js"; +import { CliError, confirmationRequired, validationError } from "../../core/errors.js"; import type { CorpConfig } from "../../core/config/types.js"; import { resolveSealCustomHeaders } from "../../core/http/request-headers.js"; import * as api from "./api.js"; @@ -341,6 +341,7 @@ export interface ReplayApprovalRunsOptions { docIdPrefix?: string; docIdSuffix?: string; dryRun?: boolean; + confirm?: boolean; fetchFn?: typeof fetch; } @@ -536,6 +537,13 @@ export async function executeApprovalRunsReplay( }; } + if (options.confirm !== true) { + throw confirmationRequired( + "Refusing to replay approval records without --yes or --confirm. Use --dry-run to preview first.", + `seal-use approval-runs replay ${runs[0]!.id} --source-corp ${sourceCorp.id} --target-corp ${targetCorp.id} --dry-run` + ); + } + const integration = await ensureTestWebhookIntegration(targetClient, targetCorp, webhookSelector); const targetWebhook = { id: integration.id,