Fix outbound confirmation and verification safety

This commit is contained in:
gitea committed 2026-10-12 00:13:22 +08:00
1 parent b17bd09194
commit 67a461452c
20 files changed
+313 -74

No files matched your search

@@ -124,10 +124,10 @@ When diagnosing a bad case or verifying rule fixes, replay the historic run's st
seal-use webhook replay <recordId> --dry-run --corp <corpId>
# 执行重放,生成全新审批实例(支持自动附加单号后缀防重)
seal-use webhook replay <recordId> [--webhook <idOrName>] [--sn-suffix '-retest'] --corp <corpId>
seal-use webhook replay <recordId> [--webhook <idOrName>] [--sn-suffix '-retest'] --corp <corpId> --yes
# 跨企业提取:从生产企业提取单据并推送至测试企业 Webhook 进行回归验证
seal-use webhook replay <recordId> --source-corp <prodCorpId> --corp <testCorpId>
seal-use webhook replay <recordId> --source-corp <prodCorpId> --corp <testCorpId> --yes
```
## Output Discipline
+4 -4
View File
@@ -145,15 +145,15 @@ seal-use webhook delete <idOrName> [--yes|--dry-run] [--corp <corpId>]
seal-use webhook resource-pack export [--limit <n>] [--status <status>] [--output <file.zip>] [--to-downloads] [--corp <corpId>]
seal-use webhook resource-pack preview <资源包.zip|信息表.xlsx> [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--corp <corpId>]
seal-use webhook resource-pack push <资源包.zip|信息表.xlsx> [--webhook <idOrName>] [--corp <corpId>]
seal-use webhook replay [<recordId>] [--sn <documentSN>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--sn-suffix <str>] [--channel webhook|hose-outbound] [--rejection-num <n>] [--message-id <msgId>] [--flow-id <flowId>] [--dry-run] [--force] [--corp <corpId>]
seal-use approval-runs replay --sn <sn> [--channel hose-outbound] [--rejection-num <n>] [--message-id <msgId>] [--flow-id <flowId>] [--target-corp <corpId>] [--dry-run] [--corp <corpId>]
seal-use webhook replay [<recordId>] [--sn <documentSN>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--sn-suffix <str>] [--channel webhook|hose-outbound] [--rejection-num <n>] [--message-id <msgId>] [--flow-id <flowId>] [--dry-run] [--yes|--confirm] [--force] [--corp <corpId>]
seal-use approval-runs replay --sn <sn> [--channel hose-outbound] [--rejection-num <n>] [--message-id <msgId>] [--flow-id <flowId>] [--target-corp <corpId>] [--dry-run] [--yes|--confirm] [--corp <corpId>]
seal-use deploy hosecloud requirements [--corp <corpId>]
seal-use deploy hosecloud list [--corp <corpId>]
seal-use deploy hosecloud get <sign-key> [--corp <corpId>]
seal-use deploy hosecloud status [--corp <corpId>]
seal-use deploy hosecloud configure --json '{...}' [--dry-run] [--corp <corpId>]
seal-use deploy hosecloud sync [<sign-key>] [--auto] [--corp <corpId>]
seal-use deploy hosecloud test-outbound [--sign-key <key>] --flow-id <flowId> --message-id <msgId> [--sn <sn>] [--rejection-num <n>] [--dry-run] [--corp <corpId>]
seal-use deploy hosecloud test-outbound [--sign-key <key>] --flow-id <flowId> --message-id <msgId> [--sn <sn>] [--rejection-num <n>] [--dry-run] [--yes|--confirm] [--corp <corpId>]
seal-use preference get [--corp <corpId>]
seal-use preference decision update --json '{"explicitApprove":"..."}' [--dry-run] [--corp <corpId>]
seal-use preference thinking-depth set --default <medium|high> [--dry-run] [--corp <corpId>]
@@ -346,7 +346,7 @@ Webhook integrations:
- `seal-use webhook resource-pack export [--limit <n>] [--status <status>] [--output <file.zip>] [--to-downloads] --corp <corpId>` (将线上审核记录打包导出为标准 Webhook 资源包,支持按条数、状态或指定单据 ID 筛选)
- `seal-use webhook resource-pack preview <资源包.zip|信息表.xlsx> [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] --corp <corpId>`
- `seal-use webhook resource-pack push <资源包.zip|信息表.xlsx> [--webhook <idOrName>] --corp <corpId>` (别名 `pack`,旧名 `material-pack` 兼容支持)
- `seal-use webhook replay [<recordId>] [--sn <documentSN>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--sn-suffix <str>] [--dry-run] [--force] [--corp <corpId>]` (通用单据重放:从历史审批单据汲取结构化表单与明细,清洗规范化字段类型,支持单条或批量重放到目标企业的 Webhook 触发审批。默认阻止向未授权生产环境重放以防污染数据,提供 `--force` 显式覆盖支持)
- `seal-use webhook replay [<recordId>] [--sn <documentSN>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--sn-suffix <str>] [--dry-run] [--yes|--confirm] [--force] [--corp <corpId>]` (通用单据重放:从历史审批单据汲取结构化表单与明细,清洗规范化字段类型,支持单条或批量重放到目标企业的 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.
@@ -79,10 +79,13 @@ seal-use deploy hosecloud get [<signKey>] --corp <corpId>
# 7. 检查发布与多平台集成状态
seal-use deploy hosecloud status --corp <corpId>
# 8. 测试/重放出站请求 (要求 assisted 模式,强制中文 nodeId 阻断安全门禁)
seal-use deploy hosecloud test-outbound [--sign-key <key>] --flow-id <flowId> --message-id <msgId> [--sn <sn>] [--dry-run] --corp <corpId>
# 8. 测试/重放出站请求 (要求 assisted 模式,默认使用中文 nodeId 阻断标记)
seal-use deploy hosecloud test-outbound [--sign-key <key>] --flow-id <flowId> --message-id <msgId> [--sn <sn>] [--dry-run] [--yes|--confirm] --corp <corpId>
```
实际推送必须带 `--yes` 或 `--confirm`;`--dry-run` 可直接预览。自定义 `nodeId` 时,预览中的 `nodeId412Blocked` 不再声明默认标记的阻断保障。
出站响应未明确返回关联 `recordId` 时,结果为 `consumptionVerified: false`(推送已接受,消费尚未确认),不会用同单据的历史记录误报本次消费成功。
---
## 4. 关键配置参数定义
@@ -185,10 +185,10 @@ flowchart TD
seal-use corps replay-test <prodCorpId> --sn '<单据号>' --confirm
# 跨企业通用重放
seal-use webhook replay --limit 5 --status failed --prod-corp <prodCorpId> --test-corp <testCorpId>
seal-use webhook replay --limit 5 --status failed --prod-corp <prodCorpId> --test-corp <testCorpId> --yes
# 未绑定测试企业 / 明确需要重放到生产企业(必须显式指定 --force 覆盖生产保护拦截)
seal-use webhook replay <recordId> --force
seal-use webhook replay <recordId> --force --yes
```
> **生产环境直接重放说明**:若企业未配置独立测试租户,用户确实需要直接在生产环境重放验证时,系统支持通过 `--force` 显式放行。执行前请确认生产 Webhook 通道的回调地址(若有)不会影响外部下游生产系统。
@@ -199,13 +199,13 @@ flowchart TD
seal-use approval-runs replay --sn <SN> --channel hose-outbound --corp <prodCorpId> --dry-run
# 正式执行(自动推送到绑定的测试企业,并在测试企业异步生成 AI 审核记录)
seal-use approval-runs replay --sn <SN> --channel hose-outbound --corp <prodCorpId>
seal-use approval-runs replay --sn <SN> --channel hose-outbound --corp <prodCorpId> --yes
# 精准匹配指定驳回重提轮次
seal-use approval-runs replay --sn <SN> --channel hose-outbound --rejection-num 1 --corp <prodCorpId>
seal-use approval-runs replay --sn <SN> --channel hose-outbound --rejection-num 1 --corp <prodCorpId> --yes
# 底层直接推送出站调试消息(仅限 assisted 模式)
seal-use deploy hosecloud test-outbound --flow-id <flowId> --message-id <msgId> --corp <testCorpId>
seal-use deploy hosecloud test-outbound --flow-id <flowId> --message-id <msgId> --corp <testCorpId> --yes
```
> **专属安全红线契约**:
> 1. **双向绑定**:必须在已绑定的生产-测试企业对之间执行;严禁跨越非关联租户(未带 `--force` 时直接报 Exit 14 阻断)。
+2 -1
View File
@@ -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(未实际推送)。`);
+2 -1
View File
@@ -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)
);
+62 -1
View File
@@ -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);
}
});
});
+4 -1
View File
@@ -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) {
+17 -11
View File
@@ -435,9 +435,9 @@ export const HELP_REGISTRY: AreaHelp[] = [
{
name: "replay",
usage: [
"seal-use webhook replay <recordId> [--webhook <idOrName>] [--sn-suffix <str>] [--dry-run] [--corp <corpId>]",
"seal-use webhook replay --sn <documentSN> [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>]",
"seal-use webhook replay --limit <n> [--status <status>] [--source-corp <corpId>] [--target-corp <corpId>]"
"seal-use webhook replay <recordId> [--webhook <idOrName>] [--sn-suffix <str>] [--dry-run] [--yes|--confirm] [--corp <corpId>]",
"seal-use webhook replay --sn <documentSN> [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--yes|--confirm]",
"seal-use webhook replay --limit <n> [--status <status>] [--source-corp <corpId>] [--target-corp <corpId>] [--yes|--confirm]"
],
options: [
{ flag: "<recordId>", description: "Approval run record ID to replay" },
@@ -450,6 +450,7 @@ export const HELP_REGISTRY: AreaHelp[] = [
{ flag: "--sn-suffix <str>", description: "Optional suffix appended to documentSN and documentId" },
{ flag: "--sn-prefix <str>", 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 <recordId> [--webhook <idOrName>] [--sn-suffix <str>] [--dry-run] [--corp <corpId>]",
"seal-use approval-runs replay --sn <documentSN> [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>]",
"seal-use approval-runs replay --sn <documentSN> --channel hose-outbound [--sign-key <key>] [--target-corp <corpId>] [--dry-run]",
"seal-use approval-runs replay <recordId> --channel hose-outbound [--sign-key <key>] [--target-corp <corpId>] [--dry-run]",
"seal-use approval-runs replay --limit <n> [--status <status>] [--source-corp <corpId>] [--target-corp <corpId>]"
"seal-use approval-runs replay <recordId> [--webhook <idOrName>] [--sn-suffix <str>] [--dry-run] [--yes|--confirm] [--corp <corpId>]",
"seal-use approval-runs replay --sn <documentSN> [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--yes|--confirm]",
"seal-use approval-runs replay --sn <documentSN> --channel hose-outbound [--sign-key <key>] [--target-corp <corpId>] [--dry-run] [--yes|--confirm]",
"seal-use approval-runs replay <recordId> --channel hose-outbound [--sign-key <key>] [--target-corp <corpId>] [--dry-run] [--yes|--confirm]",
"seal-use approval-runs replay --limit <n> [--status <status>] [--source-corp <corpId>] [--target-corp <corpId>] [--yes|--confirm]"
],
options: [
{ flag: "<recordId>", description: "Approval run record ID" },
@@ -601,7 +602,8 @@ export const HELP_REGISTRY: AreaHelp[] = [
{ flag: "--source-corp <corpId>", description: "Source enterprise where records reside" },
{ flag: "--target-corp <corpId>", description: "Target enterprise where records are pushed" },
{ flag: "--sn-suffix <str>", 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 <key>] --flow-id <id> --message-id <msgId> [--dry-run] [--corp <corpId>]",
"seal-use deploy hosecloud test-outbound [--sign-key <key>] --sn <SN> --message-id <msgId> [--dry-run] [--corp <corpId>]"
"seal-use deploy hosecloud test-outbound [--sign-key <key>] --flow-id <id> --message-id <msgId> [--dry-run] [--yes|--confirm] [--corp <corpId>]",
"seal-use deploy hosecloud test-outbound [--sign-key <key>] --sn <SN> --message-id <msgId> [--dry-run] [--yes|--confirm] [--corp <corpId>]"
],
options: [
{ flag: "--dry-run", description: "Preview the outbound payload without sending" },
{ flag: "--yes, --confirm", description: "Required for live outbound push" }
]
}
]
+13
View File
@@ -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
+1 -1
View File
@@ -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;
+4
View File
@@ -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);
});
});
+9 -3
View File
@@ -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;
}
+9 -2
View File
@@ -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
+4 -1
View File
@@ -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
});
}
},
@@ -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(
+19 -5
View File
@@ -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
+99 -17
View File
@@ -212,10 +212,12 @@ describe("resolveCorporationId", () => {
});
describe("pushOutboundAndVerify", () => {
function fakeClient(records: Array<Record<string, unknown>>): KyInstance {
function fakeClient(records: Array<Record<string, unknown>>, 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");
});
});
+30 -16
View File
@@ -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<string | undefined>): 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<ReturnType<typeof api.postHosecloudOutbound>>; 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 };
+9 -1
View File
@@ -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,