Add shared outbound-push module for Hose deploy and replay

The deploy capability and the cross-tenant replay each carried their own
copy of the same outbound pipeline: integration selection, the assisted-only
gate, payload/URL construction, and push-then-verify. A change to the wire
contract could drift into one path and not the other.

Move the shared parts into domains/seal/outbound-push.ts and return the raw
CloseAPI messageLog query to the hose domain (domains/hose/close/outbound.ts),
leaving only the replay-specific log matching on the seal side. The
production-target guard is now one implementation (replay-safety.ts) shared
by the corp-pair resolver and the channel validator; both call sites are
kept deliberately as defense in depth.

Behavior note: replay used to silently pick the first integration when the
target had several and no --sign-key was given. It now errors and lists the
available signKeys, matching what deploy already did — pushing a message to
the wrong outbound channel should not depend on array order.
This commit is contained in:
gitea committed 2026-10-11 19:33:19 +08:00
1 parent f4147cec58
commit df44791779
10 files changed
+774 -270

No files matched your search

+7 -6
View File
@@ -6,6 +6,7 @@ import { booleanOption, jsonObject, numberOption, stringOption } from "../parser
import { outputOptions } from "../printer.js";
import type { ParsedArgs } from "../types.js";
import * as api from "../../domains/seal/api.js";
import { listHoseIntegrations } from "../../domains/seal/outbound-push.js";
import { CliError } from "../errors.js";
export async function handleDeployCommand(
@@ -68,7 +69,7 @@ export async function handleDeployCommand(
const signKey = target ?? stringOption(args.options.signKey) ?? stringOption(args.options["sign-key"]);
if (!signKey) {
const config = await api.getApprovalStylePreferences(client);
const hoseConfigs = (config.integrations ?? []).filter((i: any) => i.type === "hosecloud");
const hoseConfigs = listHoseIntegrations(config);
if (hoseConfigs.length === 0) {
throw new Error(
`当前企业 (${corp.name}) 尚未添加合思发布配置。\n` +
@@ -78,9 +79,9 @@ export async function handleDeployCommand(
console.error(`Usage: seal-use deploy hosecloud get <sign-key> [--corp ${corp.id}]\n`);
console.error(`ℹ️ 当前企业发现以下可用的合思配置卡片:`);
for (const item of hoseConfigs) {
const name = (item as any).outboundName ?? "SealAI 审批";
const name = item.outboundName ?? "SealAI 审批";
const key = item.signKey;
const origin = (item as any).apiOrigin ?? "production";
const origin = item.apiOrigin ?? "production";
console.error(` • "${name}" (signKey: ${key}, 环境: ${origin})`);
console.error(` 👉 查看命令: seal-use deploy hosecloud get ${key} --corp ${corp.id}\n`);
}
@@ -122,7 +123,7 @@ export async function handleDeployCommand(
if (!signKey) {
const config = await api.getApprovalStylePreferences(client);
const hoseConfigs = (config.integrations ?? []).filter((i: any) => i.type === "hosecloud");
const hoseConfigs = listHoseIntegrations(config);
if (hoseConfigs.length === 0) {
throw new Error(
@@ -142,9 +143,9 @@ export async function handleDeployCommand(
console.error(`Usage: seal-use deploy hosecloud sync <sign-key> [--corp ${corp.id}]\n`);
console.error(`ℹ️ 当前企业发现以下可用的合思配置卡片:`);
for (const item of hoseConfigs) {
const name = (item as any).outboundName ?? "SealAI 审批";
const name = item.outboundName ?? "SealAI 审批";
const key = item.signKey;
const origin = (item as any).apiOrigin ?? "production";
const origin = item.apiOrigin ?? "production";
console.error(` • "${name}" (signKey: ${key}, 环境: ${origin})`);
console.error(` 👉 同步命令: seal-use deploy hosecloud sync ${key} --corp ${corp.id}\n`);
}
+1
View File
@@ -1,3 +1,4 @@
export * from "./types.js";
export * from "./client.js";
export * from "./api.js";
export * from "./outbound.js";
+80
View File
@@ -0,0 +1,80 @@
import type { KyInstance } from "ky";
import { validationError } from "../../../core/errors.js";
import type { CorpConfig } from "../../../core/config/types.js";
import { createHoseCloseClient } from "./client.js";
/**
* A single row of the CloseAPI outbound message log. The `request` payload is
* the EBot push body, so its fields mirror Seal's `/api/hosecloud/outbound`
* contract (flowId / nodeId / messageId / rejectionNum / corporationId).
*/
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;
}
/**
* Query CloseAPI's outbound message log for one document SN (flowId.form.code).
*/
export async function searchOutboundMessageLogs(
client: KyInstance,
corpId: string,
sn: string
): Promise<HoseOutboundLogItem[]> {
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 ?? [];
}
/**
* Fetch historical outbound message logs from Hosecloud's CloseAPI for a given document SN.
*/
export async function fetchHoseOutboundLogs(
sourceCorp: CorpConfig,
sn: string
): Promise<HoseOutboundLogItem[]> {
if (sourceCorp.source.type !== "hose") {
throw validationError(
`源企业「${sourceCorp.name}」非合思(hose)租户,无法通过合思 CloseAPI 查询出站消息日志。`
);
}
const client = await createHoseCloseClient(sourceCorp);
return searchOutboundMessageLogs(client, sourceCorp.source.corpId, sn);
}
+52 -87
View File
@@ -3,11 +3,19 @@ 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 { validationError } from "../../../core/errors.js";
import { type HosecloudConfigInput } from "../types.js";
import {
type ApprovalRun,
type HosecloudConfigInput
} from "../types.js";
assertAssistedIntegration,
BLOCKING_NODE_ID,
buildOutboundPayload,
buildOutboundWebhookUrl,
flowIdFromDocumentSn,
listHoseIntegrations,
pushOutboundAndVerify,
resolveCorporationId,
selectHoseIntegration
} from "../outbound-push.js";
import type {
CapabilityContext
} from "./helpers.js";
@@ -46,7 +54,7 @@ export const deployCapabilities = [
parameters: z.object({}),
handler: async (client: KyInstance) => {
const config = await api.getApprovalStylePreferences(client);
const integrations = (config.integrations ?? []).filter((item: any) => item.type === "hosecloud");
const integrations = listHoseIntegrations(config);
return {
count: integrations.length,
integrations: integrations.map(redactIntegrationSecrets)
@@ -61,8 +69,8 @@ export const deployCapabilities = [
}),
handler: async (client: KyInstance, params: { signKey: string }) => {
const config = await api.getApprovalStylePreferences(client);
const integration = (config.integrations ?? []).find(
(item: any) => item.type === "hosecloud" && item.signKey === params.signKey
const integration = listHoseIntegrations(config).find(
(item) => item.signKey === params.signKey
);
if (!integration) {
throw new Error(`未找到合思配置:${params.signKey}`);
@@ -77,7 +85,7 @@ export const deployCapabilities = [
handler: async (client: KyInstance) => {
const status = await api.getSimulationIntegrationStatus(client);
const config = await api.getApprovalStylePreferences(client);
const integrations = (config.integrations ?? []).filter((item: any) => item.type === "hosecloud");
const integrations = listHoseIntegrations(config);
return {
status,
integrations: integrations.map(redactIntegrationSecrets)
@@ -194,20 +202,20 @@ export const deployCapabilities = [
}),
handler: async (client: KyInstance, params: { signKey: string }, context: CapabilityContext) => {
const config = await api.getApprovalStylePreferences(client);
const integration = (config.integrations ?? []).find(
(item: any) => item.type === "hosecloud" && item.signKey === params.signKey
const integration = listHoseIntegrations(config).find(
(item) => item.signKey === params.signKey
);
if (!integration) {
throw new Error(`未找到合思配置:${params.signKey}`);
}
const sealUrl = (context.corp.seal.url ?? `https://${context.corp.id.toLowerCase()}.sealai.cc`).replace(/\/+$/, "");
const messageName = (integration as any).outboundName ?? "SealAI 审批";
const messageName = integration.outboundName ?? "SealAI 审批";
const result = await api.syncHosecloudOutbound(client, {
signKey: params.signKey,
webhookUrl: `${sealUrl}/api/hosecloud/outbound?config_id=${encodeURIComponent(params.signKey)}`,
webhookUrl: buildOutboundWebhookUrl(context.corp, params.signKey),
completionWebhookUrl: `${sealUrl}/api/hosecloud/flow/completion?config_id=${encodeURIComponent(params.signKey)}`,
messageName,
mode: (integration as any).mode ?? "assisted"
mode: integration.mode ?? "assisted"
});
console.error(`✓ 同步成功!出站消息已在合思开放平台创建/更新: "${messageName}"`);
@@ -228,7 +236,7 @@ export const deployCapabilities = [
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(默认填入中文阻断标识)"),
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("是否仅预览请求载荷与安全检查而不实际推送")
@@ -248,39 +256,18 @@ export const deployCapabilities = [
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 指定目标集成配置。`
);
}
const integration = selectHoseIntegration({
integrations: listHoseIntegrations(config),
signKey: params.signKey,
corpName: context.corp.name,
corpId: context.corp.id
});
// 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}`
);
}
assertAssistedIntegration(integration, {
corpName: context.corp.name,
corpId: context.corp.id
});
// 2. 消息凭证校验
const messageId = params.messageId?.trim();
@@ -309,8 +296,8 @@ export const deployCapabilities = [
} catch {
// 忽略
}
if (!flowId && sn.startsWith("ID01")) {
flowId = sn;
if (!flowId) {
flowId = flowIdFromDocumentSn(sn);
}
}
@@ -321,26 +308,16 @@ export const deployCapabilities = [
}
// 4. 解析 corporationId
const corporationId = params.corporationId?.trim() || integration.corporationId;
if (!corporationId) {
throw validationError(
"缺少 corporationId,且当前合思集成未保存有效 corporationId,请通过 --corporation-id 参数显式提供。"
);
}
const corporationId = resolveCorporationId([params.corporationId, integration.corporationId]);
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 = {
const payload = buildOutboundPayload({
flowId,
nodeId,
messageId,
rejectionNum,
nodeId: params.nodeId,
rejectionNum: params.rejectionNum,
corporationId
};
});
const webhookUrl = buildOutboundWebhookUrl(context.corp, integration.signKey!);
if (params.dryRun) {
return {
@@ -361,30 +338,18 @@ export const deployCapabilities = [
};
}
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}`);
}
const { response, createdRecord } = await pushOutboundAndVerify({
client,
signKey: integration.signKey!,
payload,
flowId,
sn,
corpName: context.corp.name,
corpId: context.corp.id,
pushedMessages: [
`✓ 已成功向合思出站通道推送测试消息 (flowId: ${flowId}, signKey: ${integration.signKey})`
]
});
return {
success: true,
@@ -173,7 +173,7 @@ describe("validateHoseOutboundReplaySafety", () => {
prodTarget,
{ mode: "assisted", signKey: "k" }
)
).toThrow(/标记为正式生产环境/);
).toThrow(/标记为生产正式环境/);
});
test("blocks when target mode is NOT assisted", () => {
+64 -168
View File
@@ -1,37 +1,22 @@
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 { fetchHoseOutboundLogs, type HoseOutboundLogItem } from "../hose/close/outbound.js";
import * as api from "./api.js";
import {
assertAssistedIntegration,
buildOutboundPayload,
buildOutboundWebhookUrl,
flowIdFromDocumentSn,
listHoseIntegrations,
pushOutboundAndVerify,
resolveCorporationId,
selectHoseIntegration
} from "./outbound-push.js";
import { assertNonProductionReplayTarget } from "./replay-safety.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 type { HoseOutboundLogItem } from "../hose/close/outbound.js";
export interface HoseOutboundReplayOptions {
sourceCorp: CorpConfig;
@@ -50,42 +35,12 @@ export interface HoseOutboundReplayOptions {
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<HoseOutboundLogItem[]> {
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.
*
* This is the replay channel's own matching policy — it maps a Seal approval
* record back onto the Hose outbound event that produced it, so it stays here
* rather than in the shared push module.
*/
export function selectMatchingOutboundLog(
logs: HoseOutboundLogItem[],
@@ -177,23 +132,17 @@ export function validateHoseOutboundReplaySafety(
}
// 2. Production target guard
if (targetCorp.environment === "production" && !force) {
throw safetyBlocked(
`安全阻断:目标企业「${targetCorp.name}」标记为正式生产环境 (production)。\n` +
`为防止测试消息污染生产审批流,严禁向生产企业重发出站报文。请通过 --target-corp 指定测试企业。`,
`seal-use approval-runs replay --target-corp <testCorpId> ...`
);
}
assertNonProductionReplayTarget(targetCorp, {
force,
action: "重放出站报文",
nextAction: `seal-use webhook replay --channel hose-outbound --target-corp <testCorpId> --source-corp ${sourceCorp.id}`
});
// 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}`
);
}
assertAssistedIntegration(targetIntegration, {
corpName: targetCorp.name,
corpId: targetCorp.id
});
}
/**
@@ -202,44 +151,17 @@ export function validateHoseOutboundReplaySafety(
export async function executeHoseOutboundReplay(options: HoseOutboundReplayOptions) {
const { sourceCorp, targetCorp, targetClient, dryRun, force } = options;
// 1. Get target corp's Hose integrations
// 1. Resolve the target's hose integration (ambiguous lists are an error, not a guess)
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
};
const targetIntegration = selectHoseIntegration({
integrations: listHoseIntegrations(targetConfig),
signKey: options.targetSignKey,
corpName: targetCorp.name,
corpId: targetCorp.id
});
// 2. Validate safety constraints
validateHoseOutboundReplaySafety(sourceCorp, targetCorp, targetIntegration, force);
@@ -294,11 +216,11 @@ export async function executeHoseOutboundReplay(options: HoseOutboundReplayOptio
// 5. Construct payload
const flowId =
options.flowId?.trim() ??
selectedLog?.request?.flowId ??
selectedLog?.flowId?.id ??
sourceRecord?.sourceDocumentId ??
(sn?.startsWith("ID01") ? sn : undefined);
options.flowId?.trim() ||
selectedLog?.request?.flowId ||
selectedLog?.flowId?.id ||
sourceRecord?.sourceDocumentId ||
flowIdFromDocumentSn(sn);
if (!flowId) {
throw validationError(
@@ -306,35 +228,26 @@ export async function executeHoseOutboundReplay(options: HoseOutboundReplayOptio
);
}
const messageId = options.messageId?.trim() ?? selectedLog?.request?.messageId;
const messageId = options.messageId?.trim() || selectedLog?.request?.messageId;
if (!messageId) {
throw validationError("未能获取到有效 messageId。");
}
const rejectionNum =
options.rejectionNum ?? selectedLog?.request?.rejectionNum ?? 0;
const corporationId = resolveCorporationId([
options.corporationId,
selectedLog?.request?.corporationId,
sourceCorp.source.type === "hose" ? sourceCorp.source.corpId : undefined,
targetIntegration.corporationId
]);
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 = {
const payload = buildOutboundPayload({
flowId,
nodeId,
messageId,
rejectionNum,
nodeId: options.nodeId,
rejectionNum: options.rejectionNum ?? selectedLog?.request?.rejectionNum,
corporationId
};
});
const targetWebhookUrl = buildOutboundWebhookUrl(targetCorp, targetIntegration.signKey!);
// 6. Dry run preview
if (dryRun) {
@@ -376,36 +289,19 @@ export async function executeHoseOutboundReplay(options: HoseOutboundReplayOptio
}
// 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(`ℹ️ 消息已入队正在异步消费,可稍后在测试后台页面刷新查看。`);
}
const { response, createdRecord } = await pushOutboundAndVerify({
client: targetClient,
signKey: targetIntegration.signKey!,
payload,
flowId,
sn,
corpName: targetCorp.name,
corpId: targetCorp.id,
pushedMessages: [
`✓ 成功从合思出站日志匹配消息 (messageId: ${messageId}, 轮次: ${payload.rejectionNum})`,
`✓ 已向测试企业「${targetCorp.name}」出站网关推送重放报文 (nodeId: ${payload.nodeId})`
]
});
return {
success: true,
@@ -421,7 +317,7 @@ export async function executeHoseOutboundReplay(options: HoseOutboundReplayOptio
targetSignKey: targetIntegration.signKey,
mode: targetIntegration.mode,
matchedMessageId: messageId,
rejectionNum,
rejectionNum: payload.rejectionNum,
payload,
response,
recordId: createdRecord?.id,
+334
View File
@@ -0,0 +1,334 @@
import { describe, expect, test } from "bun:test";
import type { KyInstance } from "ky";
import type { CorpConfig } from "../../core/config/types.js";
import type { ApprovalIntegration, ApprovalStylePreferences } from "./types.js";
import {
assertAssistedIntegration,
BLOCKING_NODE_ID,
buildOutboundPayload,
buildOutboundWebhookUrl,
flowIdFromDocumentSn,
listHoseIntegrations,
pushOutboundAndVerify,
resolveCorporationId,
selectHoseIntegration
} from "./outbound-push.js";
function corp(overrides: Partial<CorpConfig> = {}): CorpConfig {
return {
id: "test-corp",
name: "测试企业",
environment: "test",
seal: { url: "https://test.sealai.cc" },
source: { type: "seal", token: "t", sealUrl: "https://test.sealai.cc" },
auth: { refreshTtl: 300 },
...overrides
} as CorpConfig;
}
function integration(overrides: Partial<ApprovalIntegration> = {}): ApprovalIntegration {
return { type: "hosecloud", signKey: "key-1", ...overrides };
}
function preferences(items: ApprovalIntegration[]): ApprovalStylePreferences {
return { integrations: items } as ApprovalStylePreferences;
}
describe("listHoseIntegrations", () => {
test("keeps only hosecloud entries and tolerates a missing list", () => {
const items = listHoseIntegrations(
preferences([
integration({ signKey: "a" }),
{ type: "webhook", signKey: "b" } as ApprovalIntegration
])
);
expect(items.map((item) => item.signKey)).toEqual(["a"]);
expect(listHoseIntegrations({} as ApprovalStylePreferences)).toEqual([]);
});
});
describe("selectHoseIntegration", () => {
const corpName = "目标企业";
const corpId = "target-corp";
test("uses the only integration when no signKey is given", () => {
const selected = selectHoseIntegration({
integrations: [integration()],
corpName,
corpId
});
expect(selected.signKey).toBe("key-1");
});
test("resolves an explicit signKey", () => {
const selected = selectHoseIntegration({
integrations: [integration({ signKey: "a" }), integration({ signKey: "b" })],
signKey: "b",
corpName,
corpId
});
expect(selected.signKey).toBe("b");
});
test("refuses to guess when several integrations exist and none was named", () => {
expect(() =>
selectHoseIntegration({
integrations: [integration({ signKey: "a" }), integration({ signKey: "b" })],
corpName,
corpId
})
).toThrow(/请通过 --sign-key 指定目标集成配置/);
});
test("errors when the configured list is empty", () => {
expect(() => selectHoseIntegration({ integrations: [], corpName, corpId })).toThrow(
/未配置任何合思出站发布通道/
);
});
test("errors when the named signKey is unknown, listing what exists", () => {
expect(() =>
selectHoseIntegration({
integrations: [integration({ signKey: "a" })],
signKey: "nope",
corpName,
corpId
})
).toThrow(/可用 signKey: a/);
});
test("rejects an integration that never saved a signKey", () => {
expect(() =>
selectHoseIntegration({
integrations: [integration({ signKey: undefined })],
corpName,
corpId
})
).toThrow(/未保存 signKey/);
});
});
describe("assertAssistedIntegration", () => {
const options = { corpName: "目标企业", corpId: "target-corp" };
test("passes for assisted and for an unset mode (defaults to assisted)", () => {
expect(() => assertAssistedIntegration(integration({ mode: "assisted" }), options)).not.toThrow();
expect(() => assertAssistedIntegration(integration({ mode: undefined }), options)).not.toThrow();
});
test("blocks every non-assisted mode with an exit-14 safety error", () => {
for (const mode of ["fully_automatic", "semi_automatic"]) {
let thrown: unknown;
try {
assertAssistedIntegration(integration({ mode }), options);
} catch (error) {
thrown = error;
}
expect(thrown).toBeInstanceOf(Error);
expect((thrown as { exitCode?: number }).exitCode).toBe(14);
expect((thrown as Error).message).toContain("非 assisted(辅助审核)模式");
}
});
test("next action tells the operator exactly how to flip the mode back", () => {
try {
assertAssistedIntegration(integration({ mode: "fully_automatic" }), options);
throw new Error("expected a block");
} catch (error) {
expect((error as { nextAction?: string }).nextAction).toContain(
`"mode":"assisted"`
);
expect((error as { nextAction?: string }).nextAction).toContain("--corp target-corp");
}
});
});
describe("payload and url builders", () => {
test("defaults nodeId to the blocking marker and rejectionNum to 0", () => {
const payload = buildOutboundPayload({
flowId: "ID01abc",
messageId: "msg-1",
corporationId: "corp-1"
});
expect(payload).toEqual({
flowId: "ID01abc",
nodeId: BLOCKING_NODE_ID,
messageId: "msg-1",
rejectionNum: 0,
corporationId: "corp-1"
});
});
test("an explicit nodeId wins only when non-blank after trimming", () => {
expect(
buildOutboundPayload({
flowId: "f",
messageId: "m",
corporationId: "c",
nodeId: "FLOW:custom"
}).nodeId
).toBe("FLOW:custom");
expect(
buildOutboundPayload({
flowId: "f",
messageId: "m",
corporationId: "c",
nodeId: " "
}).nodeId
).toBe(BLOCKING_NODE_ID);
});
test("webhook url falls back to the corp subdomain and strips trailing slashes", () => {
expect(buildOutboundWebhookUrl(corp(), "key-1")).toBe(
"https://test.sealai.cc/api/hosecloud/outbound?config_id=key-1"
);
expect(
buildOutboundWebhookUrl(corp({ seal: { url: "https://custom.example/" } as CorpConfig["seal"] }), "a/b")
).toBe("https://custom.example/api/hosecloud/outbound?config_id=a%2Fb");
expect(buildOutboundWebhookUrl(corp({ seal: {} as CorpConfig["seal"] }), "k")).toBe(
"https://test-corp.sealai.cc/api/hosecloud/outbound?config_id=k"
);
});
});
describe("flowIdFromDocumentSn", () => {
test("only ID01-prefixed SNs double as a flowId", () => {
expect(flowIdFromDocumentSn("ID01Wah1FQ9faf")).toBe("ID01Wah1FQ9faf");
expect(flowIdFromDocumentSn("BX9990001")).toBeUndefined();
expect(flowIdFromDocumentSn(undefined)).toBeUndefined();
});
});
describe("resolveCorporationId", () => {
test("takes the first non-blank candidate", () => {
expect(resolveCorporationId([undefined, "", " ", "ID01x", "ID01y"])).toBe("ID01x");
});
test("fails with an actionable message when nothing is available", () => {
expect(() => resolveCorporationId([undefined, "", " "])).toThrow(
/请通过 --corporation-id 参数显式提供/
);
});
});
describe("pushOutboundAndVerify", () => {
function fakeClient(records: Array<Record<string, unknown>>): KyInstance {
return {
post: async () => ({ json: async () => ({ data: { success: true } }) }),
get: async () => ({ json: async () => ({ data: { records } }) })
} as unknown as KyInstance;
}
test("reports the created run when the queue consumed the push", async () => {
const lines: string[] = [];
const originalError = console.error;
console.error = (line: string) => lines.push(line);
try {
const { response, createdRecord } = await pushOutboundAndVerify({
client: fakeClient([
{ id: "run-9", sourceDocumentId: "ID01abc", status: "pending", taskMode: "auto" }
]),
signKey: "key-1",
payload: buildOutboundPayload({
flowId: "ID01abc",
messageId: "msg-1",
corporationId: "c"
}),
flowId: "ID01abc",
sn: "BX999",
corpName: "目标企业",
corpId: "target-corp",
pushedMessages: ["✓ pushed"],
verifyWaitMs: 0
});
expect(response).toEqual({ success: true });
expect(createdRecord?.id).toBe("run-9");
expect(lines[0]).toBe("✓ pushed");
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;
}
});
test("matches on SN when flowId is not yet on the record, and downgrades to queued", async () => {
const lines: string[] = [];
const originalError = console.error;
console.error = (line: string) => lines.push(line);
try {
const { createdRecord } = await pushOutboundAndVerify({
client: fakeClient([{ id: "run-s", sourceDocumentSN: "BX999" }]),
signKey: "key-1",
payload: buildOutboundPayload({
flowId: "ID01abc",
messageId: "msg-1",
corporationId: "c"
}),
flowId: "ID01abc",
sn: "BX999",
corpName: "目标企业",
corpId: "target-corp",
verifyWaitMs: 0
});
expect(createdRecord?.id).toBe("run-s");
} finally {
console.error = originalError;
}
const queued: string[] = [];
console.error = (line: string) => queued.push(line);
try {
const { createdRecord } = await pushOutboundAndVerify({
client: fakeClient([]),
signKey: "key-1",
payload: buildOutboundPayload({
flowId: "ID01abc",
messageId: "msg-1",
corporationId: "c"
}),
flowId: "ID01abc",
corpName: "目标企业",
corpId: "target-corp",
verifyWaitMs: 0
});
expect(createdRecord).toBeUndefined();
expect(queued.join("\n")).toContain("消息已入队正在异步消费");
expect(queued.join("\n")).toContain("seal-use approval-runs list --corp target-corp");
} finally {
console.error = originalError;
}
});
test("a failing poll never turns a successful push into an error", async () => {
const originalError = console.error;
console.error = () => {};
try {
const client = {
post: async () => ({ json: async () => ({ data: { success: true } }) }),
get: async () => {
throw new Error("502 Bad Gateway");
}
} as unknown as KyInstance;
const { response, createdRecord } = await pushOutboundAndVerify({
client,
signKey: "key-1",
payload: buildOutboundPayload({
flowId: "f",
messageId: "m",
corporationId: "c"
}),
flowId: "f",
corpName: "目标企业",
corpId: "target-corp",
verifyWaitMs: 0
});
expect(response).toEqual({ success: true });
expect(createdRecord).toBeUndefined();
} finally {
console.error = originalError;
}
});
});
+200
View File
@@ -0,0 +1,200 @@
import type { KyInstance } from "ky";
import { 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";
/**
* Shared primitives for pushing a test/replay message into Seal's
* `/api/hosecloud/outbound` gateway. Two callers need them and they must stay
* in lockstep because they build the exact same wire payload:
* - `capabilities/deploy.ts` → `sealDeployHosecloudTestOutbound` (single tenant)
* - `hose-outbound-replay.ts` → `webhook replay --channel hose-outbound` (cross tenant)
*
* Anything that describes the outbound contract (payload shape, blocking nodeId,
* integration selection, the assisted-only gate) lives here so a change to the
* protocol can't drift into one path and not the other.
*/
/**
* Chinese mock nodeId: Hose rejects the callback with HTTP 412 for this node,
* which is what keeps a pushed message from advancing a real approval flow.
*/
export const BLOCKING_NODE_ID = "FLOW:测试模拟节点_禁止流转";
/** Long enough for the worker queue to consume the push before we look for the run. */
const OUTBOUND_VERIFY_WAIT_MS = 2_500;
export interface OutboundPayload {
flowId: string;
nodeId: string;
messageId: string;
rejectionNum: number;
corporationId: string;
}
export function listHoseIntegrations(
preferences: Pick<ApprovalStylePreferences, "integrations">
): ApprovalIntegration[] {
return (preferences.integrations ?? []).filter((item) => item.type === "hosecloud");
}
/**
* Pick the hose integration a push should target. An explicit signKey must
* match; without one, an ambiguous list is an error rather than a guess —
* pushing to the wrong outbound channel is not something to default silently.
*/
export function selectHoseIntegration(options: {
integrations: ApprovalIntegration[];
signKey?: string;
corpName: string;
corpId: string;
}): ApprovalIntegration {
const { integrations, corpName, corpId } = options;
if (integrations.length === 0) {
throw validationError(
`企业「${corpName}」未配置任何合思出站发布通道。\n` +
`请先运行:seal-use deploy hosecloud configure --json '{...}' --corp ${corpId}`
);
}
if (options.signKey) {
const found = integrations.find((item) => item.signKey === options.signKey);
if (!found) {
throw validationError(
`未找到 signKey 为「${options.signKey}」的合思配置。可用 signKey: ` +
`${integrations.map((item) => item.signKey).filter(Boolean).join(", ")}`
);
}
return requireSignKey(found, corpName);
}
if (integrations.length > 1) {
const list = integrations
.map((item) => `"${item.outboundName ?? "SealAI 审批"}" (signKey: ${item.signKey})`)
.join(", ");
throw validationError(
`企业「${corpName}」存在多个合思集成 [${list}],请通过 --sign-key 指定目标集成配置。`
);
}
return requireSignKey(integrations[0]!, corpName);
}
function requireSignKey(integration: ApprovalIntegration, corpName: string): ApprovalIntegration {
if (!integration.signKey) {
throw validationError(`企业「${corpName}」的合思出站配置未保存 signKey,请重新执行 configure。`);
}
return integration;
}
/**
* Every push must target an `assisted` integration: any other mode lets the
* result callback write approval actions back into the flow autonomously.
*/
export function assertAssistedIntegration(
integration: Pick<ApprovalIntegration, "signKey" | "outboundName" | "mode">,
options: { corpName: string; corpId: string }
): void {
const mode = integration.mode ?? "assisted";
if (mode === "assisted") {
return;
}
throw safetyBlocked(
`安全阻断:企业「${options.corpName}」的合思配置「${integration.outboundName ?? integration.signKey}」` +
`当前为「${mode}」模式,非 assisted(辅助审核)模式。\n` +
`为防止自动向合思回写审批动作影响审批流程,严禁在非 assisted 模式下推送出站报文。`,
`seal-use deploy hosecloud configure --json '{"signKey":"${integration.signKey}","mode":"assisted"}' --corp ${options.corpId}`
);
}
export function buildOutboundWebhookUrl(corp: CorpConfig, signKey: string): string {
const sealUrl = (corp.seal.url ?? `https://${corp.id.toLowerCase()}.sealai.cc`).replace(/\/+$/, "");
return `${sealUrl}/api/hosecloud/outbound?config_id=${encodeURIComponent(signKey)}`;
}
export function buildOutboundPayload(options: {
flowId: string;
messageId: string;
nodeId?: string;
rejectionNum?: number;
corporationId: string;
}): OutboundPayload {
return {
flowId: options.flowId,
nodeId: options.nodeId?.trim() || BLOCKING_NODE_ID,
messageId: options.messageId,
rejectionNum: options.rejectionNum ?? 0,
corporationId: options.corporationId
};
}
/**
* Hose document SNs double as flowIds only when they carry the ID01 prefix;
* any other SN needs a lookup to resolve the flow instance.
*/
export function flowIdFromDocumentSn(sn: string | undefined): string | undefined {
return sn?.startsWith("ID01") ? sn : undefined;
}
export function resolveCorporationId(candidates: Array<string | undefined>): string {
const found = candidates.map((value) => value?.trim()).find((value) => value);
if (!found) {
throw validationError(
"缺少 corporationId,且当前合思集成未保存有效 corporationId,请通过 --corporation-id 参数显式提供。"
);
}
return found;
}
/**
* 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.
*/
export async function pushOutboundAndVerify(options: {
client: KyInstance;
signKey: string;
payload: OutboundPayload;
flowId: string;
sn?: string;
corpName: string;
corpId: string;
/** Channel-specific success lines logged right after the push lands. */
pushedMessages?: string[];
/** Queue-drain wait before polling; injectable so tests don't sleep. */
verifyWaitMs?: number;
}): Promise<{ response: Awaited<ReturnType<typeof api.postHosecloudOutbound>>; createdRecord?: ApprovalRun }> {
const { client, signKey, payload, flowId, sn, corpName, corpId } = options;
const response = await api.postHosecloudOutbound(client, signKey, payload);
for (const line of options.pushedMessages ?? []) {
console.error(line);
}
await new Promise((resolve) => setTimeout(resolve, options.verifyWaitMs ?? OUTBOUND_VERIFY_WAIT_MS));
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 === sn ||
record.sourceDocumentSN === flowId
);
} 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(`👉 查看审核详情: seal-use approval-runs get ${createdRecord.id} --corp ${corpId}`);
} else {
console.error(`ℹ️ 消息已入队正在异步消费,可稍后执行: seal-use approval-runs list --corp ${corpId}`);
}
return { response, createdRecord };
}
+28
View File
@@ -0,0 +1,28 @@
import { safetyBlocked } from "../../core/errors.js";
import type { CorpConfig } from "../../core/config/types.js";
/**
* Shared environment guard for every replay channel: test traffic must never
* land in a production tenant. Both the corp-pair resolver and the individual
* channel executors call it — the redundancy is deliberate, so a channel that
* is invoked without going through `resolveReplayCorpPair` is still blocked.
*/
export function assertNonProductionReplayTarget(
targetCorp: CorpConfig,
options: {
force?: boolean;
/** What is being forbidden, e.g. `重放单据` — used verbatim in the message. */
action: string;
nextAction: string;
}
): void {
if (targetCorp.environment !== "production" || options.force) {
return;
}
throw safetyBlocked(
`安全阻断:目标企业「${targetCorp.name}」(${targetCorp.id}) 标记为生产正式环境 (production)。\n` +
`为防止测试数据污染生产审批流,禁止向生产环境${options.action}。请指定测试企业 (--target-corp <testCorpId>),或在确有需要时添加 --force。`,
options.nextAction
);
}
+7 -8
View File
@@ -2,10 +2,11 @@ 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, safetyBlocked, validationError } from "../../core/errors.js";
import { CliError, 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";
import { assertNonProductionReplayTarget } from "./replay-safety.js";
export const ALLOWED_WEBHOOK_FIELD_TYPES = new Set([
"TEXT",
@@ -273,13 +274,11 @@ export function resolveReplayCorpPair(
}
// Safety guard: prevent pushing replay test records to production
if (targetCorp.environment === "production" && !force) {
throw safetyBlocked(
`目标企业「${targetCorp.name}」(${targetCorp.id}) 标记为生产正式环境 (production)。\n` +
`为防止测试单据污染生产审批流,禁止向生产环境重放单据。请指定测试企业 (--target-corp <testCorpId>),或在确有需要时添加 --force。`,
`seal-use webhook replay --target-corp <testCorpId>${sourceCorp.id !== targetCorp.id ? ` --source-corp ${sourceCorp.id}` : ""}`
);
}
assertNonProductionReplayTarget(targetCorp, {
force,
action: "重放单据",
nextAction: `seal-use webhook replay --target-corp <testCorpId>${sourceCorp.id !== targetCorp.id ? ` --source-corp ${sourceCorp.id}` : ""}`
});
return { sourceCorp, targetCorp };
}