Compare commits

..
9 Commits
Author SHA1 Message Date
yunyingk f4147cec58 Merge pull request #216 from yunyingk/codex/release-v0.11.5
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
Release v0.11.5: Automated release bump
2026-10-10 16:04:38 +08:00
gitea aed3a10958 Release v0.11.5: Automated release bump 2026-10-10 16:03:41 +08:00
yunyingk 7af7be4925 Merge pull request #215 from yunyingk/mac15/hosecloud-test-outbound
Add Hose outbound replay with CloseAPI log matching and safety guards
2026-10-10 16:02:52 +08:00
gitea 152f96ec78 Update agent skill docs for Hose outbound replay and test-outbound 2026-10-10 16:01:27 +08:00
gitea 2fc88e208c Add Hose outbound replay with CloseAPI log matching and safety guards 2026-10-10 15:58:06 +08:00
yunyingk 042d223704 Merge pull request #214 from yunyingk/mac15/unify-expire-duration-parsing
Unify assistance link duration parsing with hour floor and stderr hints
2026-10-10 15:10:24 +08:00
gitea 0296c2bff2 Unify assistance link duration parsing with hour floor and stderr hints 2026-10-10 15:09:11 +08:00
yunyingk c094980ae5 Merge pull request #213 from yunyingk/mac15/support-delegation-expire-config
Add configurable expiration for Seal and Hose assistance links
2026-10-10 14:59:43 +08:00
gitea 932957ea08 Add configurable expiration for Seal and Hose assistance links 2026-10-10 14:58:30 +08:00
23 changed files with 1448 additions and 55 deletions

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.11.4",
"version": "0.11.5",
"description": "Seal Use tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
"author": {
"name": "yingqing"
+12
View File
@@ -7,6 +7,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [0.11.5] - 2026-10-10
### Added
- Merge pull request #215 from yunyingk/mac15/hosecloud-test-outbound
- Update agent skill docs for Hose outbound replay and test-outbound
- Add Hose outbound replay with CloseAPI log matching and safety guards
- Merge pull request #214 from yunyingk/mac15/unify-expire-duration-parsing
- Unify assistance link duration parsing with hour floor and stderr hints
- Merge pull request #213 from yunyingk/mac15/support-delegation-expire-config
- Add configurable expiration for Seal and Hose assistance links
## [0.11.4] - 2026-10-10
### Added
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.11.4",
"version": "0.11.5",
"private": true,
"description": "Seal tenant operations toolkit: approval-run diagnosis, rule remediation, Hose/合思 auth, plus a CLI and an optional MCP server.",
"license": "MIT",
+3 -3
View File
@@ -1,9 +1,9 @@
---
name: seal-use
description: "v0.11.4: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
description: "v0.11.5: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
metadata:
version: 0.11.4
short-description: Seal tenant and Hose approval automation (v0.11.4)
version: 0.11.5
short-description: Seal tenant and Hose approval automation (v0.11.5)
---
# Seal Use
+3 -1
View File
@@ -145,13 +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>] [--dry-run] [--force] [--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 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 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>]
@@ -78,6 +78,9 @@ 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>
```
---
@@ -192,6 +192,26 @@ flowchart TD
```
> **生产环境直接重放说明**:若企业未配置独立测试租户,用户确实需要直接在生产环境重放验证时,系统支持通过 `--force` 显式放行。执行前请确认生产 Webhook 通道的回调地址(若有)不会影响外部下游生产系统。
- **方式 D:合思出站通道高仿重放 (Hose Outbound Replay,单据/附件仿真专属)**:
基于合思出站(EBot Outbound Webhook)官方通道的仿真重放。通过合思管理后台 CloseAPI 自动抓取历史出站日志中真实有效的 `messageId`、`flowId` 与 `rejectionNum`,并向测试环境出站网关推送;Seal 会依据真实 `messageId` 从合思开放平台拉取完整单据字段与全量二进制附件(发票、合同等),仿真度极高:
```bash
# 预览重放(自动从合思 CloseAPI 检索日志、提取真实 messageId 并做安全检查,不实际推送)
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 --rejection-num 1 --corp <prodCorpId>
# 底层直接推送出站调试消息(仅限 assisted 模式)
seal-use deploy hosecloud test-outbound --flow-id <flowId> --message-id <msgId> --corp <testCorpId>
```
> **专属安全红线契约**:
> 1. **双向绑定**:必须在已绑定的生产-测试企业对之间执行;严禁跨越非关联租户(未带 `--force` 时直接报 Exit 14 阻断)。
> 2. **锁死 assisted 模式**:目标测试环境的合思配置必须为 `assisted` 辅助模式,否则直接触发 Exit 14 安全阻断。
> 3. **中文 nodeId 物理阻断**:出站报文中注入中文标记 `nodeId: "FLOW:测试模拟节点_禁止流转"`。因为合思辅助审核也会调用审批回调,篡改后合思在回调时必定返回 `HTTP 200 { code: 412, message: "当前的审批节点不为:..." }` 物理级阻断,双重保障生产单据绝不会被意外流转或修改。
3. **轮询并检查判定结果**:
```bash
# 查看状态与进度
+1 -1
View File
@@ -70,7 +70,7 @@ describe("CLI version & help handling", () => {
expect(result.stdout).toContain("seal-use webhook get|find <idOrName>");
expect(result.stdout).toContain("seal-use webhook add --name <name> --result-url <url>");
expect(result.stdout).toContain("seal-use corps add-link <url>");
expect(result.stdout).toContain("seal-use auth link [--note <note>] [--corp <corpId>]");
expect(result.stdout).toContain("seal-use auth link [--note <note>] [--expire <duration>] [--corp <corpId>]");
expect(result.stdout).toContain("[--secret <secret>|--rotate-secret]");
});
+153
View File
@@ -93,6 +93,83 @@ describe("auth links", () => {
expect(parsed.expiresAt).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\+08:00$/);
});
test("supports --expire 7d for native Seal link and passes expiresInHours: 168", async () => {
const root = mkdtempSync(join(tmpdir(), "seal-use-auth-link-expire-"));
const enterprises = join(root, "enterprises");
tempDirs.push(root);
mkdirSync(enterprises, { recursive: true });
process.env.SEAL_USE_ENTERPRISES_DIR = enterprises;
process.env.SEAL_USE_CONFIG_FILE = join(root, "config.json");
process.env.SEAL_USE_TOKEN_STORE = join(root, "tokens.json");
process.env.SEAL_USE_USAGE_FILE = join(root, "usage.json");
writeFileSync(
join(enterprises, "native-seal.json"),
JSON.stringify({
id: "native-seal",
name: "原生 Seal 企业",
environment: "production",
seal: { url: "https://native.seal.test", tenantSlug: "native-seal" },
source: {
type: "seal",
token: "seal-token",
sealUrl: "https://native.seal.test",
expiresIn: 3600,
corpId: "native-corp",
staffId: "native-staff"
},
auth: { refreshTtl: 300 }
})
);
let recordedPayload: any = null;
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const requestUrl = typeof input === "string"
? input
: input instanceof URL
? input.toString()
: input.url;
const url = new URL(requestUrl);
if (url.pathname === "/api/v1/delegation/create") {
if (input instanceof Request) {
recordedPayload = await input.clone().json();
} else if (init?.body) {
recordedPayload = JSON.parse(String(init.body));
}
return new Response(JSON.stringify({
data: {
id: "delegation-7d",
token: "delegation-token-7d",
link: "https://native.seal.test/delegation?token=delegation-token-7d"
}
}), { status: 200, headers: { "content-type": "application/json" } });
}
return new Response(JSON.stringify({ error: `Unexpected request: ${url.pathname}` }), {
status: 404,
headers: { "content-type": "application/json" }
});
}) as typeof fetch;
const result = await runCli(["auth", "link", "--corp", "native-seal", "--expire", "7d"]);
expect(result.isError).toBe(false);
expect(recordedPayload).toMatchObject({
expiresInHours: 168
});
// Test fractional duration: floors to 1h and prints stderr guidance
const floorResult = await runCli(["auth", "link", "--corp", "native-seal", "--expire", "90m"]);
expect(floorResult.isError).toBe(false);
expect(recordedPayload).toMatchObject({
expiresInHours: 1
});
expect(floorResult.stderr).toContain("已自动向下取整为 1 小时 (1h)");
// Test reject exceeding 7 days (168 hours)
const invalidResult = await runCli(["auth", "link", "--corp", "native-seal", "--expire", "8d"]);
expect(invalidResult.isError).toBe(true);
expect(invalidResult.exitCode).toBe(2);
});
test("formats hose-link with corp metadata, link, and Beijing ISO expiry without url field", async () => {
const root = mkdtempSync(join(tmpdir(), "seal-use-auth-hose-link-"));
const enterprises = join(root, "enterprises");
@@ -164,6 +241,82 @@ describe("auth links", () => {
expect(parsed.expiresAt).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\+08:00$/);
});
test("supports --expire 7d for hose-link and converts to 604800 seconds", async () => {
const root = mkdtempSync(join(tmpdir(), "seal-use-auth-hose-link-7d-"));
const enterprises = join(root, "enterprises");
tempDirs.push(root);
mkdirSync(enterprises, { recursive: true });
process.env.SEAL_USE_ENTERPRISES_DIR = enterprises;
process.env.SEAL_USE_CONFIG_FILE = join(root, "config.json");
process.env.SEAL_USE_TOKEN_STORE = join(root, "tokens.json");
process.env.SEAL_USE_USAGE_FILE = join(root, "usage.json");
writeFileSync(
join(enterprises, "hose-corp.json"),
JSON.stringify({
id: "hose-corp",
name: "合思测试企业",
environment: "production",
seal: { url: "https://hose-corp.sealai.cc" },
source: {
type: "hose",
domain: "https://app.ekuaibao.com",
appKey: "key-1",
appSecurity: "sec-1",
corpId: "HOSE-CORP",
staffId: "HOSE-CORP:STAFF-1"
},
auth: { refreshTtl: 300 }
})
);
let recordedHoseBody: any = null;
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const requestUrl = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
const url = new URL(requestUrl);
if (url.pathname === "/api/openapi/v1/auth/getAccessToken") {
return new Response(
JSON.stringify({
value: { accessToken: "test-openapi-token", expireTime: 7200 }
}),
{ status: 200, headers: { "content-type": "application/json" } }
);
}
if (url.pathname === "/api/openapi/v1.1/provisional/getProvisionalAuth") {
if (input instanceof Request) {
recordedHoseBody = await input.clone().json();
} else if (init?.body) {
recordedHoseBody = JSON.parse(String(init.body));
}
return new Response(
JSON.stringify({
value: {
message: "https://app.ekuaibao.com/web/thirdparty.html?accessToken=provisional-token-7d"
}
}),
{ status: 200, headers: { "content-type": "application/json" } }
);
}
return new Response(JSON.stringify({ error: `Unexpected request: ${url.pathname}` }), {
status: 404,
headers: { "content-type": "application/json" }
});
}) as typeof fetch;
const result = await runCli(["auth", "hose-link", "--corp", "hose-corp", "--expire", "7d"]);
expect(result.isError).toBe(false);
expect(recordedHoseBody).toMatchObject({
expireDate: 604800
});
const result2 = await runCli(["auth", "hose-link", "--corp", "hose-corp", "--expire", "2"]);
expect(result2.isError).toBe(false);
expect(recordedHoseBody).toMatchObject({
expireDate: 7200
});
expect(result2.stderr).toContain("已按 2 小时 (7200s) 自动换算");
});
test("runs auth check and hidden aliases (status, diagnose, test)", async () => {
const root = mkdtempSync(join(tmpdir(), "seal-use-auth-check-"));
const enterprises = join(root, "enterprises");
+17 -10
View File
@@ -5,7 +5,12 @@ import type { CorpConfig } from "../../core/config/types.js";
import { createSealClient, createSealClientForUrl } from "../../core/http/factory.js";
import { resolveSealCustomHeaders } from "../../core/http/request-headers.js";
import { createDelegation, getMe } from "../../domains/seal/api.js";
import { booleanOption, numberOption, stringOption } from "../parser.js";
import {
booleanOption,
parseDelegationExpireHours,
parseHoseExpireSeconds,
stringOption
} from "../parser.js";
import { outputOptions, printJson, redactSensitiveText } from "../printer.js";
import type { ParsedArgs } from "../types.js";
import { runCapability, runCapabilityResult } from "../helpers.js";
@@ -40,11 +45,13 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
if ((action === "seal-link" || action === "link" || (action === "hose-link" && corp?.source?.type === "seal")) && fromLink) {
const note = stringOption(args.options.note);
const expireOption = args.options.expire ?? args.options["expires-in"] ?? args.options.expiresIn;
const expiresInHours = parseDelegationExpireHours(expireOption, 24);
const session = await exchangeHoseAssistLink(fromLink);
const client = createSealClientForUrl(session.sealUrl, session.token);
const me = await getMe(client);
assertHoseAssistTenantMatches(session.corpId, me.tenant as unknown as Record<string, unknown>);
const delegation = await createDelegation(client, { note });
const delegation = await createDelegation(client, { note, expiresInHours });
printJson({
tenant: {
@@ -60,7 +67,8 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
isAdmin: me.user.isAdmin
},
delegation,
expiresIn: session.expiresIn
expiresIn: session.expiresIn,
expiresAt: formatBeijingIso(Date.now() + expiresInHours * 3600 * 1000)
});
return;
}
@@ -90,18 +98,20 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
}
const note = stringOption(args.options.note) ?? "CLI generated provisional access link";
const expireOption = args.options.expire ?? args.options["expires-in"] ?? args.options.expiresIn;
const expiresInHours = parseDelegationExpireHours(expireOption, 24);
const delegation = await runCapabilityResult(
"sealDelegationCreate",
client,
corp,
{ note }
{ note, expiresInHours }
);
if (action === "hose-link") {
console.error(`👉 提示: 企业「${corp.name}」源类型为 Seal 原生测试环境,已自动为您生成委托免登直达链接。`);
}
const delegationRecord = delegation as Record<string, unknown>;
const staffName = "staffName" in corp.source && typeof corp.source.staffName === "string" ? corp.source.staffName : undefined;
const expiresAt = formatBeijingIso(Date.now() + 86400 * 1000);
const expiresAt = formatBeijingIso(Date.now() + expiresInHours * 3600 * 1000);
printJson({
id: delegationRecord.id,
corpId: corp.source.corpId ?? corp.id,
@@ -116,11 +126,8 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
}
if (action === "hose-link") {
const rawExpire = args.options.expire;
const expiresIn = rawExpire !== undefined ? numberOption(rawExpire) : 7200;
if (expiresIn === undefined || expiresIn <= 0) {
throw new Error(`Invalid --expire: ${String(rawExpire)}. Must be a positive number of seconds (e.g. --expire 7200 or --expire 86400).`);
}
const rawExpire = args.options.expire ?? args.options["expires-in"] ?? args.options.expiresIn;
const expiresIn = parseHoseExpireSeconds(rawExpire, 7200);
const force =
booleanOption(args.options.force) === true ||
booleanOption(args.options.refresh) === true ||
+32 -2
View File
@@ -2,7 +2,7 @@ import { readFileSync } from "node:fs";
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { runCapability } from "../helpers.js";
import { booleanOption, jsonObject, stringOption } from "../parser.js";
import { booleanOption, jsonObject, numberOption, stringOption } from "../parser.js";
import { outputOptions } from "../printer.js";
import type { ParsedArgs } from "../types.js";
import * as api from "../../domains/seal/api.js";
@@ -166,5 +166,35 @@ export async function handleDeployCommand(
return;
}
throw new Error(`Unknown deploy hosecloud action: ${action ?? ""}. Available: requirements, list, get, status, configure, sync.`);
if (action === "test-outbound" || action === "outbound-test") {
const signKey = target ?? stringOption(args.options.signKey) ?? stringOption(args.options["sign-key"]);
const flowId = stringOption(args.options.flowId) ?? stringOption(args.options["flow-id"]);
const sn = stringOption(args.options.sn) ?? stringOption(args.options.sourceDocumentSN);
const messageId = stringOption(args.options.messageId) ?? stringOption(args.options["message-id"]);
const nodeId = stringOption(args.options.nodeId) ?? stringOption(args.options["node-id"]);
const rejectionNum = numberOption(args.options.rejectionNum) ?? numberOption(args.options["rejection-num"]);
const corporationId = stringOption(args.options.corporationId) ?? stringOption(args.options["corporation-id"]);
const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]);
await runCapability(
"sealDeployHosecloudTestOutbound",
client,
corp,
{
signKey,
flowId,
sn,
messageId,
nodeId,
rejectionNum,
corporationId,
dryRun
},
outputOptions(args.options)
);
return;
}
throw new Error(`Unknown deploy hosecloud action: ${action ?? ""}. Available: requirements, list, get, status, configure, sync, test-outbound.`);
}
+11 -3
View File
@@ -2,7 +2,7 @@ import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { confirmationRequired } from "../errors.js";
import { runCapability } from "../helpers.js";
import { booleanOption, stringOption } from "../parser.js";
import { booleanOption, parseDelegationExpireHours, stringOption } from "../parser.js";
import { outputOptions } from "../printer.js";
import type { ParsedArgs } from "../types.js";
@@ -73,9 +73,17 @@ export async function handleUsersCommand(
if (action === "delegation" || action === "impersonate") {
const userIdOrPhone = maybeName ?? stringOption(args.options.userId) ?? stringOption(args.options.phone);
if (!userIdOrPhone) throw new Error("Usage: seal-use users delegation <userIdOrPhone> [--note <note>]");
if (!userIdOrPhone) throw new Error("Usage: seal-use users delegation <userIdOrPhone> [--note <note>] [--expire <duration>]");
const note = stringOption(args.options.note);
await runCapability("sealUserDelegationCreate", client, corp, { userIdOrPhone, note }, outputOptions(args.options));
const expireOption = args.options.expire ?? args.options["expires-in"] ?? args.options.expiresIn;
const expiresInHours = parseDelegationExpireHours(expireOption, 24);
await runCapability(
"sealUserDelegationCreate",
client,
corp,
{ userIdOrPhone, note, expiresInHours },
outputOptions(args.options)
);
return;
}
+57
View File
@@ -513,4 +513,61 @@ describe("seal-use webhook replay CLI", () => {
const parsed = JSON.parse(forceResult.stdout);
expect(parsed.targetCorp.id).toBe("prod-corp-target");
});
test("approval-runs replay --channel hose-outbound executes dry-run preview with safety guards", async () => {
setupMockEnv();
const mockHoseIntegrations = [
{
type: "hosecloud",
signKey: "sign-key-xyz",
outboundName: "测试出站通道",
mode: "assisted",
corporationId: "corp-id-123"
}
];
globalThis.fetch = (async (input: RequestInfo | URL) => {
const requestUrl =
typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
if (
requestUrl.includes("api/v1/system/preferences/approval-style") ||
requestUrl.includes("api/v1/agent/ai-approval/config")
) {
return new Response(
JSON.stringify({
data: { integrations: mockHoseIntegrations }
}),
{ status: 200, headers: { "Content-Type": "application/json" } }
);
}
return new Response("Not found", { status: 404 });
}) as any;
const result = await runCli([
"approval-runs",
"replay",
"--sn",
"S26002992",
"--channel",
"hose-outbound",
"--message-id",
"ID01Wh05v0In3F",
"--flow-id",
"ID01Wah1FQ9faf",
"--dry-run"
]);
expect(result.isError).toBe(false);
expect(result.exitCode).toBe(0);
const parsed = JSON.parse(result.stdout);
expect(parsed.preview).toBe(true);
expect(parsed.channel).toBe("hose-outbound");
expect(parsed.payload.messageId).toBe("ID01Wh05v0In3F");
expect(parsed.payload.nodeId).toBe("FLOW:测试模拟节点_禁止流转");
expect(parsed.safetyGuards.targetModeAssisted).toBe(true);
expect(parsed.safetyGuards.nodeId412Blocked).toBe(true);
});
});
+37
View File
@@ -12,6 +12,7 @@ import {
resolveReplayCorpPair,
type ReplayRecordsQuery
} from "../../domains/seal/webhook-replay.js";
import { executeHoseOutboundReplay } from "../../domains/seal/hose-outbound-replay.js";
import {
checkWebhookReadiness,
exportApprovalRunsToResourcePack,
@@ -148,6 +149,42 @@ export async function handleWebhookCommand(
const docIdPrefix = stringOption(args.options.docIdPrefix) ?? stringOption(args.options["doc-id-prefix"]);
const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]);
const channel =
stringOption(args.options.channel) ??
(booleanOption(args.options["hose-outbound"]) || booleanOption(args.options.outbound) ? "hose-outbound" : undefined);
if (channel === "hose-outbound" || channel === "outbound") {
const flowId = stringOption(args.options.flowId) ?? stringOption(args.options["flow-id"]);
const messageId = stringOption(args.options.messageId) ?? stringOption(args.options["message-id"]);
const nodeId = stringOption(args.options.nodeId) ?? stringOption(args.options["node-id"]);
const corporationId = stringOption(args.options.corporationId) ?? stringOption(args.options["corporation-id"]);
const rejectionNum = numberOption(args.options.rejectionNum) ?? numberOption(args.options["rejection-num"]);
const targetSignKey =
stringOption(args.options.signKey) ??
stringOption(args.options["sign-key"]) ??
stringOption(args.options.webhook);
const result = await executeHoseOutboundReplay({
sourceCorp,
targetCorp,
sourceClient,
targetClient,
sn,
recordId,
flowId,
messageId,
nodeId,
corporationId,
rejectionNum,
targetSignKey,
dryRun,
force
});
printJson(result, outputOptions(args.options));
return;
}
const query: ReplayRecordsQuery = {
recordId,
recordIds,
+23 -5
View File
@@ -584,11 +584,16 @@ export const HELP_REGISTRY: AreaHelp[] = [
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 [--target-corp <corpId>] [--dry-run]",
"seal-use approval-runs replay <recordId> --channel hose-outbound [--target-corp <corpId>] [--dry-run]",
"seal-use approval-runs replay --limit <n> [--status <status>] [--source-corp <corpId>] [--target-corp <corpId>]"
],
options: [
{ flag: "<recordId>", description: "Approval run record ID" },
{ flag: "--sn <sn>", description: "Lookup approval record by source document SN" },
{ flag: "--channel <webhook|hose-outbound>", description: "Replay channel: webhook (default) or hose-outbound (Hosecloud official outbound)" },
{ flag: "--message-id <msgId>", description: "Explicit Hose outbound messageId override" },
{ flag: "--rejection-num <n>", description: "Target specific rejection iteration (0, 1, 2, ...)" },
{ flag: "--limit <n>", description: "Batch replay latest N records" },
{ flag: "--status <status>", description: "Filter records by status" },
{ flag: "--webhook <idOrName>", description: "Target Webhook integration" },
@@ -747,6 +752,14 @@ export const HELP_REGISTRY: AreaHelp[] = [
name: "hosecloud sync",
summary: "Synchronize HoseCloud rules and definitions",
usage: ["seal-use deploy hosecloud sync <sign-key> [--corp <corpId>]"]
},
{
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>]"
]
}
]
},
@@ -835,11 +848,12 @@ export const HELP_REGISTRY: AreaHelp[] = [
name: "link",
summary: "【Seal 审核后台】生成免密登录/委托访问直达链接",
usage: [
"seal-use auth link [--note <note>] [--corp <corpId>]",
"seal-use auth link --from-link <url> [--note <note>]"
"seal-use auth link [--note <note>] [--expire <duration>] [--corp <corpId>]",
"seal-use auth link --from-link <url> [--note <note>] [--expire <duration>]"
],
options: [
{ flag: "--note <note>", description: "委托授权备注说明(如:演示测试、外部审计)" },
{ flag: "--expire, --expires-in <duration>", description: "委托授权有效期,推荐 '7d' 或 '24h'(最大 7 天,兼容秒数并自动向下取整)" },
{ flag: "--from-link <url>", description: "直接由合思协助链接换取 Seal 委托直达链接" }
],
description:
@@ -859,9 +873,9 @@ export const HELP_REGISTRY: AreaHelp[] = [
{
name: "hose-link",
summary: "【合思外部主站】生成免密登录/第三方协助入口链接",
usage: ["seal-use auth hose-link [--corp <corpId>] [--expire 7200] [--force]"],
usage: ["seal-use auth hose-link [--corp <corpId>] [--expire <duration>] [--force]"],
options: [
{ flag: "--expire <seconds>", description: "链接有效时间(秒),默认 7200,支持如 86400(1天)" },
{ flag: "--expire, --expires-in <duration>", description: "链接有效时间,推荐 '7d' 或 '2h'(默认 2h,兼容秒数如 7200)" },
{ flag: "--force, --refresh, -f", description: "强制向合思 OpenAPI 申请全新临时凭证" }
],
description:
@@ -912,7 +926,11 @@ export const HELP_REGISTRY: AreaHelp[] = [
{
name: "delegation",
summary: "Create delegation token for a specific user",
usage: ["seal-use users delegation <userIdOrPhone|name> [--note <note>] [--corp <corpId>]"]
usage: ["seal-use users delegation <userIdOrPhone|name> [--note <note>] [--expire <duration>] [--corp <corpId>]"],
options: [
{ flag: "--note <note>", description: "委托授权备注说明" },
{ flag: "--expire, --expires-in <duration>", description: "委托授权有效期,推荐 '7d' 或 '24h'(最大 7 天,兼容秒数并自动向下取整)" }
]
},
{
name: "reset-password",
+41
View File
@@ -7,6 +7,8 @@ import {
KNOWN_FLAGS,
numberOption,
parseArgs,
parseDelegationExpireHours,
parseHoseExpireSeconds,
splitOption,
stringOption,
VALUE_FLAGS
@@ -116,6 +118,45 @@ describe("option helpers", () => {
expect(splitOption("")).toBeUndefined();
expect(splitOption(true)).toBeUndefined();
});
test("parseDelegationExpireHours parses days, hours, rounds down with stderr notice, and clamps to 1..168", () => {
expect(parseDelegationExpireHours(undefined)).toBe(24);
expect(parseDelegationExpireHours("7d")).toBe(168);
expect(parseDelegationExpireHours("1d")).toBe(24);
expect(parseDelegationExpireHours("24h")).toBe(24);
expect(parseDelegationExpireHours("2h")).toBe(2);
expect(parseDelegationExpireHours("168")).toBe(168);
expect(parseDelegationExpireHours(168)).toBe(168);
expect(parseDelegationExpireHours("86400")).toBe(24);
expect(parseDelegationExpireHours("7200s")).toBe(2);
// Floor fractional hours and clamp minimum to 1h
expect(parseDelegationExpireHours("90m")).toBe(1);
expect(parseDelegationExpireHours("1.5h")).toBe(1);
expect(parseDelegationExpireHours("30m")).toBe(1);
expect(parseDelegationExpireHours("1800s")).toBe(1);
expect(() => parseDelegationExpireHours("8d")).toThrow("最多为 7 天 (168h)");
expect(() => parseDelegationExpireHours("0h")).toThrow("必须为大于 0 的有效时长");
expect(() => parseDelegationExpireHours("invalid")).toThrow("必须为有效时长格式");
});
test("parseHoseExpireSeconds parses days, hours, minutes, raw seconds, and converts unitless small numbers to hours", () => {
expect(parseHoseExpireSeconds(undefined)).toBe(7200);
expect(parseHoseExpireSeconds("7200")).toBe(7200);
expect(parseHoseExpireSeconds(7200)).toBe(7200);
expect(parseHoseExpireSeconds("2h")).toBe(7200);
expect(parseHoseExpireSeconds("7d")).toBe(604800);
expect(parseHoseExpireSeconds("30m")).toBe(1800);
// Unitless small numbers (<= 168) convert to hours automatically
expect(parseHoseExpireSeconds(2)).toBe(7200);
expect(parseHoseExpireSeconds("2")).toBe(7200);
expect(parseHoseExpireSeconds("24")).toBe(86400);
expect(() => parseHoseExpireSeconds("0s")).toThrow("必须为大于 0 的有效时长");
expect(() => parseHoseExpireSeconds("invalid")).toThrow("必须为有效时长");
});
});
describe("flag registry cross-check", () => {
+174 -19
View File
@@ -27,9 +27,9 @@ export const BOOLEAN_FLAGS = new Set([
"completed-only", "completedOnly", "confirm", "count", "disable-attachment-cache", "disableAttachmentCache",
"download", "downloads", "dry-run", "dryRun", "elevate-hose", "enabled",
"exclude-deleted", "extract", "extract-expenses", "extractExpenses", "fail-on-flips", "flow", "force", "full", "has-input", "has-output", "help",
"hose", "hose-sso", "hoseSso", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged",
"hose", "hose-outbound", "hose-sso", "hoseOutbound", "hoseSso", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged",
"includeBridge", "includeSimulation", "includeUnchanged", "local", "no-attachments", "no-flow",
"no-wait", "noWait", "overwrite", "plain", "publish", "quiet",
"no-wait", "noWait", "outbound", "overwrite", "plain", "publish", "quiet",
"r", "recode", "refresh", "refresh-if-missing", "reveal", "rotate-secret", "rotateSecret",
"save", "silent", "silent-save", "simulation", "skip-expense-extraction", "skip-extract", "skip-invoice-generation",
"skipExpenseExtraction", "skipExtract", "skipInvoiceGeneration", "snippet-only", "snippetOnly", "sso", "strict",
@@ -41,27 +41,27 @@ export const BOOLEAN_FLAGS = new Set([
export const VALUE_FLAGS = new Set([
"access-token", "accessToken", "app-key", "app-security", "appKey", "appSecurity",
"base-url", "batch", "batch-id", "batchId", "business-codes", "businessCodes",
"code", "concurrency", "content", "content-file", "content-hints", "content-type", "contentFile",
"contentType", "context-chars", "contextLines", "corp", "corp-id", "corpId", "date",
"channel", "code", "concurrency", "content", "content-file", "content-hints", "content-type", "contentFile",
"contentType", "context-chars", "contextLines", "corp", "corp-id", "corpId", "corporation-id", "corporationId", "date",
"dedupe-by", "dedupeBy", "default", "departmentId", "dept", "desc",
"description", "description-file", "descriptionFile", "dir", "doc-id-prefix", "doc-id-suffix",
"docIdPrefix", "docIdSuffix", "document-id", "document-sn", "document-sns", "document-type",
"documentId", "documentLimit", "documentSn", "documentType", "domain", "enable",
"end", "end-date", "end-time", "endDate", "endTime", "env",
"environment", "expire", "expiresIn", "fields", "file", "file-id", "file-name", "flow-concurrency",
"flow-ids", "flow-status-list", "flowIds", "flowStatusList", "format", "from",
"environment", "expire", "expires-in", "expiresIn", "fields", "file", "file-id", "file-name", "flow-concurrency",
"flow-id", "flow-ids", "flow-status-list", "flowId", "flowIds", "flowStatusList", "format", "from",
"from-link", "host", "humanResult", "id", "input", "integration",
"json", "json-path", "key-id", "keyId", "keyword", "level", "limit",
"lines", "link", "linter", "manual-status", "manualApprovalStatus", "manualStatus",
"max-chars", "max-preview-chars", "maxChars", "maxResults", "max-results", "metadata", "metadata-key", "min-score", "minScore", "mode",
"max-chars", "max-preview-chars", "maxChars", "maxResults", "max-results", "message-id", "messageId", "metadata", "metadata-key", "min-score", "minScore", "mode",
"max-runs",
"month",
"n", "name", "name-contains", "note", "observation-id", "observation-types", "o", "offset", "out",
"n", "name", "name-contains", "node-id", "nodeId", "note", "observation-id", "observation-types", "o", "offset", "out",
"out-dir", "outDir", "outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file",
"outputFile", "p", "package-id", "package-ids", "packageId", "packageIds",
"path", "phone", "policyId", "poll-interval", "pollInterval", "port",
"prod", "prod-corp", "prodCorp", "purpose", "q", "query",
"record-id", "record-ids", "recordId", "recordIds", "reject-node", "rejectNode",
"record-id", "record-ids", "recordId", "recordIds", "reject-node", "rejectNode", "rejection-num", "rejectionNum",
"reviewed-by", "reviewedBy",
"report-id",
"repo", "request-ids", "requestIds", "result-url", "resultUrl", "reuse-window",
@@ -88,35 +88,35 @@ export const KNOWN_FLAGS = new Set([
"V", "access-token", "accessToken", "add", "all", "app-key",
"app-security", "appKey", "appSecurity", "as-hose", "attachments", "auto",
"auto-login", "autoLogin", "base-url", "batch", "batch-id", "batchId",
"bg-save", "business-codes", "businessCodes", "changelog", "check", "check-only",
"bg-save", "business-codes", "businessCodes", "channel", "changelog", "check", "check-only",
"code", "completed-only", "completedOnly", "concurrency", "confirm", "content",
"content-file", "content-hints", "content-type", "contentFile", "contentType", "context-chars", "contextLines", "corp",
"corp-id", "corpId", "count", "date", "dedupe-by", "dedupeBy",
"corp-id", "corpId", "corporation-id", "corporationId", "count", "date", "dedupe-by", "dedupeBy",
"default", "departmentId", "dept", "desc", "description", "description-file",
"descriptionFile", "dir", "disable-attachment-cache", "disableAttachmentCache", "doc-id-prefix", "doc-id-suffix",
"docIdPrefix", "docIdSuffix", "document-id", "document-sn", "document-sns", "document-type",
"documentId", "documentLimit", "documentSn", "documentType", "domain", "download",
"downloads", "dry-run", "dryRun", "elevate-hose", "enable", "enabled",
"end", "end-date", "end-time", "endDate", "endTime", "env",
"environment", "exclude-deleted", "extract", "extract-expenses", "extractExpenses", "expire", "expiresIn", "f", "fail-on-flips",
"fields", "file", "file-id", "file-name", "flow", "flow-concurrency", "flow-ids", "flow-status-list",
"flowIds", "flowStatusList", "force", "format", "from", "from-link",
"full", "h", "has-input", "has-output", "help", "hose", "hose-sso", "hoseSso",
"environment", "exclude-deleted", "extract", "extract-expenses", "extractExpenses", "expire", "expires-in", "expiresIn", "f", "fail-on-flips",
"fields", "file", "file-id", "file-name", "flow", "flow-concurrency", "flow-id", "flow-ids", "flow-status-list",
"flowId", "flowIds", "flowStatusList", "force", "format", "from", "from-link",
"full", "h", "has-input", "has-output", "help", "hose", "hose-outbound", "hose-sso", "hoseOutbound", "hoseSso",
"host", "humanResult", "id", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged",
"includeBridge", "includeSimulation", "includeUnchanged", "input", "integration", "json",
"json-path", "key-id", "keyId", "keyword", "level", "limit", "lines",
"link", "linter", "local", "manual-status", "manualApprovalStatus", "manualStatus",
"max-chars", "max-preview-chars", "maxChars", "maxResults", "max-results", "metadata", "metadata-key", "min-score", "minScore", "mode",
"max-chars", "max-preview-chars", "maxChars", "maxResults", "max-results", "message-id", "messageId", "metadata", "metadata-key", "min-score", "minScore", "mode",
"max-runs",
"month",
"n", "name", "name-contains", "no-attachments", "no-flow", "no-wait", "noWait",
"note", "observation-id", "observation-types", "o", "offset", "out", "out-dir", "outDir",
"n", "name", "name-contains", "no-attachments", "no-flow", "no-wait", "noWait", "node-id", "nodeId",
"note", "observation-id", "observation-types", "o", "offset", "out", "out-dir", "outDir", "outbound",
"outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file", "outputFile", "overwrite",
"p", "package-id", "package-ids", "packageId", "packageIds", "path",
"phone", "plain", "policyId", "poll-interval", "pollInterval", "port",
"prod", "prod-corp", "prodCorp", "publish", "purpose", "q",
"query", "quiet", "r", "recode", "record-id", "record-ids",
"recordId", "recordIds", "refresh", "refresh-if-missing", "reject-node", "rejectNode", "repo",
"recordId", "recordIds", "refresh", "refresh-if-missing", "reject-node", "rejectNode", "rejection-num", "rejectionNum", "repo",
"report-id",
"request-ids", "requestIds", "result-url", "resultUrl", "reuse-window", "reuseWindow",
"reviewed-by", "reviewedBy",
@@ -436,3 +436,158 @@ export function materialPackFilePolicyOptions(
allowedExtensions
};
}
export function parseDelegationExpireHours(
value: string | boolean | number | undefined,
defaultHours = 24
): number {
if (value === undefined || value === null || value === "") {
return defaultHours;
}
let rawHours: number;
let isFractionalOrTruncated = false;
if (typeof value === "number") {
if (!Number.isFinite(value) || value <= 0) {
throw usageError(`Invalid --expire: ${value}。必须为大于 0 的有效时长,推荐使用 '7d' 或 '24h'。`);
}
if (value > 168) {
rawHours = value / 3600;
if (value % 3600 !== 0) isFractionalOrTruncated = true;
} else {
rawHours = value;
if (!Number.isInteger(value)) isFractionalOrTruncated = true;
}
} else if (typeof value === "string") {
const trimmed = value.trim();
const match = trimmed.match(
/^(\d+(?:\.\d+)?)\s*(d|day|days|h|hr|hrs|hour|hours|m|min|mins|minute|minutes|s|sec|secs|second|seconds)?$/i
);
if (!match || !match[1]) {
throw usageError(
`Invalid --expire: '${value}'。必须为有效时长格式,推荐使用 '7d' 或 '24h'(支持 d/h/m/s 及秒数)。`
);
}
const val = parseFloat(match[1]);
if (!Number.isFinite(val) || val <= 0) {
throw usageError(`Invalid --expire: '${value}'。必须为大于 0 的有效时长,推荐使用 '7d' 或 '24h'。`);
}
const unit = (match[2] ?? "").toLowerCase();
if (!unit) {
if (val > 168) {
rawHours = val / 3600;
if (val % 3600 !== 0) isFractionalOrTruncated = true;
} else {
rawHours = val;
if (!Number.isInteger(val)) isFractionalOrTruncated = true;
}
} else if (unit.startsWith("d")) {
rawHours = val * 24;
if (!Number.isInteger(rawHours)) isFractionalOrTruncated = true;
} else if (unit.startsWith("h")) {
rawHours = val;
if (!Number.isInteger(rawHours)) isFractionalOrTruncated = true;
} else if (unit.startsWith("m")) {
rawHours = val / 60;
if (val % 60 !== 0) isFractionalOrTruncated = true;
} else if (unit.startsWith("s")) {
rawHours = val / 3600;
if (val % 3600 !== 0) isFractionalOrTruncated = true;
} else {
rawHours = val;
}
} else {
throw usageError(`Invalid --expire: ${String(value)}。`);
}
if (rawHours > 168) {
throw usageError(
`Invalid --expire: 计算得 ${rawHours > 168.1 ? Math.floor(rawHours) : rawHours} 小时。Seal delegation 授权有效期最多为 7 天 (168h)。建议使用 --expire 7d。`
);
}
let finalHours = Math.floor(rawHours);
if (finalHours < 1) {
finalHours = 1;
console.error(
`👉 提示: Seal 协助链接按整小时生效(最少 1 小时),输入值 ${String(value)} 已自动保底设置为 1 小时 (1h)。建议后续使用 --expire 1h。`
);
return finalHours;
}
if (isFractionalOrTruncated) {
console.error(
`👉 提示: Seal 协助链接按整小时生效,输入值 ${String(value)} 已自动向下取整为 ${finalHours} 小时 (${finalHours}h)。建议后续使用 --expire ${finalHours}h 或 --expire 7d。`
);
}
return finalHours;
}
export function parseHoseExpireSeconds(
value: string | boolean | number | undefined,
defaultSeconds = 7200
): number {
if (value === undefined || value === null || value === "") {
return defaultSeconds;
}
let seconds: number;
if (typeof value === "number") {
if (!Number.isFinite(value) || value <= 0) {
throw usageError(`Invalid --expire: ${value}。必须为大于 0 的有效时长。`);
}
if (value <= 168) {
seconds = Math.round(value * 3600);
console.error(
`👉 提示: 检测到未加单位的数值 ${value},已按 ${value} 小时 (${seconds}s) 自动换算。建议明确使用 --expire ${value}h。`
);
} else {
seconds = Math.round(value);
}
} else if (typeof value === "string") {
const trimmed = value.trim();
const match = trimmed.match(
/^(\d+(?:\.\d+)?)\s*(d|day|days|h|hr|hrs|hour|hours|m|min|mins|minute|minutes|s|sec|secs|second|seconds)?$/i
);
if (!match || !match[1]) {
throw usageError(
`Invalid --expire: '${value}'。必须为有效时长,推荐使用 '7d' 或 '2h'(支持 d/h/m/s 及秒数)。`
);
}
const val = parseFloat(match[1]);
if (!Number.isFinite(val) || val <= 0) {
throw usageError(`Invalid --expire: '${value}'。必须为大于 0 的有效时长。`);
}
const unit = (match[2] ?? "").toLowerCase();
if (!unit) {
if (val <= 168) {
seconds = Math.round(val * 3600);
console.error(
`👉 提示: 检测到未加单位的数值 ${value},已按 ${val} 小时 (${seconds}s) 自动换算。建议明确使用 --expire ${val}h。`
);
} else {
seconds = Math.round(val);
}
} else if (unit.startsWith("d")) {
seconds = Math.round(val * 86400);
} else if (unit.startsWith("h")) {
seconds = Math.round(val * 3600);
} else if (unit.startsWith("m")) {
seconds = Math.round(val * 60);
} else if (unit.startsWith("s")) {
seconds = Math.round(val);
} else {
seconds = Math.round(val);
}
} else {
throw usageError(`Invalid --expire: ${String(value)}。`);
}
if (seconds <= 0) {
throw usageError(`Invalid --expire: 计算得 ${seconds} 秒。必须为大于 0 的有效时长。`);
}
return seconds;
}
+24 -4
View File
@@ -842,6 +842,24 @@ export async function syncHosecloudOutbound(
return json.data ?? json;
}
export async function postHosecloudOutbound(
client: KyInstance,
signKey: string,
payload: {
flowId: string;
nodeId: string;
messageId: string;
rejectionNum: number;
corporationId: string;
}
): Promise<{ success?: boolean; message?: string; [key: string]: unknown }> {
const response = await client.post(`api/hosecloud/outbound?config_id=${encodeURIComponent(signKey)}`, {
json: payload
});
const json = (await response.json().catch(() => ({}))) as { data?: unknown };
return (json.data ?? json) as { success?: boolean; message?: string; [key: string]: unknown };
}
export async function uploadMaterialPackage(
client: KyInstance,
params: { fileName: string; fileBuffer: Uint8Array }
@@ -882,7 +900,7 @@ export async function listDelegations(client: KyInstance): Promise<SealDelegatio
export async function createDelegation(
client: KyInstance,
params?: { note?: string }
params?: { note?: string; expiresInHours?: number }
): Promise<SealDelegationCreateResult> {
return unwrap(
await client.post("api/v1/delegation/create", { json: params ?? {} }),
@@ -1162,7 +1180,7 @@ export async function loginWithPhonePassword(
export async function createDelegationForUser(
client: KyInstance,
params: { userIdOrPhone: string; note?: string },
params: { userIdOrPhone: string; note?: string; expiresInHours?: number },
createClientForToken: (token: string) => Promise<KyInstance>,
corp?: CorpConfig
): Promise<{
@@ -1249,7 +1267,8 @@ export async function createDelegationForUser(
if (targetUserSealToken) {
const userClient = await createClientForToken(targetUserSealToken);
const delegation = await createDelegation(userClient, {
note: params.note ?? `Delegation generated by admin for ${user.name}`
note: params.note ?? `Delegation generated by admin for ${user.name}`,
expiresInHours: params.expiresInHours
});
return {
@@ -1287,7 +1306,8 @@ export async function createDelegationForUser(
const userClient = await createClientForToken(token);
const delegation = await createDelegation(userClient, {
note: params.note ?? `Delegation generated by admin for ${user.name}`
note: params.note ?? `Delegation generated by admin for ${user.name}`,
expiresInHours: params.expiresInHours
});
return {
+181
View File
@@ -3,7 +3,9 @@ import type { KyInstance } from "ky";
import { randomBytes } from "node:crypto";
import * as api from "../api.js";
import { probeHoseDomain } from "../../../core/auth/hose.js";
import { safetyBlocked, validationError } from "../../../core/errors.js";
import {
type ApprovalRun,
type HosecloudConfigInput
} from "../types.js";
import type {
@@ -217,5 +219,184 @@ export const deployCapabilities = [
result
};
}
},
{
name: "sealDeployHosecloudTestOutbound",
description: "向合思出站 (outbound) 接口推送测试/重放消息以模拟工作流触发,强制要求目标集成必须为 assisted 模式",
parameters: z.object({
signKey: z.string().optional().describe("合思集成 sign-key(若企业仅有一个合思配置可自动识别)"),
flowId: z.string().optional().describe("合思单据/流程 ID (flowId / sourceDocumentId)"),
sn: z.string().optional().describe("合思单号 (sourceDocumentSN,若未提供 flowId 可自动解析)"),
messageId: z.string().describe("合思真实的 messageId(合思开放平台消息凭证,必须提供真实有效值以供拉取单据)"),
nodeId: z.string().optional().default("FLOW:测试模拟节点_禁止流转").describe("合思流程节点 ID(默认填入中文阻断标识)"),
rejectionNum: z.number().int().optional().default(0).describe("驳回/重提次数(默认 0)"),
corporationId: z.string().optional().describe("合思企业 ID(若未提供则取自集成配置)"),
dryRun: z.boolean().optional().default(false).describe("是否仅预览请求载荷与安全检查而不实际推送")
}),
handler: async (
client: KyInstance,
params: {
signKey?: string;
flowId?: string;
sn?: string;
messageId: string;
nodeId?: string;
rejectionNum?: number;
corporationId?: string;
dryRun?: boolean;
},
context: CapabilityContext
) => {
const config = await api.getApprovalStylePreferences(client);
const hoseConfigs = (config.integrations ?? []).filter((i: any) => i.type === "hosecloud");
if (hoseConfigs.length === 0) {
throw new Error(
`当前企业 (${context.corp.name}) 尚未添加合思发布配置。\n` +
`👉 请先运行配置命令:seal-use deploy hosecloud configure --json '{...}' --corp ${context.corp.id}`
);
}
let integration: any;
if (params.signKey) {
integration = hoseConfigs.find((i: any) => i.signKey === params.signKey);
if (!integration) {
throw validationError(
`未找到 signKey 为「${params.signKey}」的合思集成配置。可用 signKey: ${hoseConfigs.map((i: any) => i.signKey).join(", ")}`
);
}
} else if (hoseConfigs.length === 1) {
integration = hoseConfigs[0];
} else {
const list = hoseConfigs.map((i: any) => `"${i.outboundName ?? "SealAI 审批"}" (signKey: ${i.signKey})`).join(", ");
throw validationError(
`当前企业存在多个合思集成 [${list}],请通过 --sign-key 指定目标集成配置。`
);
}
// 1. 严格安全门禁检查:强制要求目标集成必须为 assisted 模式
const mode = integration.mode ?? "assisted";
if (mode !== "assisted") {
throw safetyBlocked(
`安全阻断:目标合思配置「${integration.outboundName ?? integration.signKey}」当前为「${mode}」模式,非 assisted(辅助审核)模式。为防止自动向合思回写审批动作影响生产/线上流程,严禁在此模式下测试出站通道。`,
`请先在目标企业将模式调整为 assisted 模式后重试:seal-use deploy hosecloud configure --json '{"signKey":"${integration.signKey}","mode":"assisted"}' --corp ${context.corp.id}`
);
}
// 2. 消息凭证校验
const messageId = params.messageId?.trim();
if (!messageId) {
throw validationError(
"缺少必需参数 --message-id。合思开放平台出站协议要求使用真实有效的 messageId 换取单据上下文,请从合思出站请求日志中提取提供。"
);
}
// 3. 解析 flowId
let flowId = params.flowId?.trim();
const sn = params.sn?.trim();
if (!flowId && sn) {
try {
const existing = await api.listApprovalRuns(client, {
search: sn,
sourceDocumentSN: sn,
limit: 5
});
const match = (existing.records || []).find(
(r) => r.sourceDocumentSN === sn || r.sourceDocumentId === sn
);
if (match?.sourceDocumentId) {
flowId = match.sourceDocumentId;
}
} catch {
// 忽略
}
if (!flowId && sn.startsWith("ID01")) {
flowId = sn;
}
}
if (!flowId) {
throw validationError(
"缺少必需参数 --flow-id(合思单据/流程 ID)。若已存在该单的历史运行记录,也可通过 --sn <单号> 自动解析。"
);
}
// 4. 解析 corporationId
const corporationId = params.corporationId?.trim() || integration.corporationId;
if (!corporationId) {
throw validationError(
"缺少 corporationId,且当前合思集成未保存有效 corporationId,请通过 --corporation-id 参数显式提供。"
);
}
const nodeId = params.nodeId?.trim() || "FLOW:测试模拟节点_禁止流转";
const rejectionNum = params.rejectionNum ?? 0;
const sealUrl = (context.corp.seal.url ?? `https://${context.corp.id.toLowerCase()}.sealai.cc`).replace(/\/+$/, "");
const webhookUrl = `${sealUrl}/api/hosecloud/outbound?config_id=${encodeURIComponent(integration.signKey)}`;
const payload = {
flowId,
nodeId,
messageId,
rejectionNum,
corporationId
};
if (params.dryRun) {
return {
preview: true,
url: webhookUrl,
targetCorp: context.corp.id,
targetIntegration: {
signKey: integration.signKey,
outboundName: integration.outboundName,
mode: integration.mode
},
safetyCheck: {
mode: "assisted",
passed: true,
note: "目标企业出站模式为 assisted,AI 绝不会向合思回写审批动作;且默认 nodeId 包含中文阻断标记,双重安全保障。"
},
payload
};
}
const response = await api.postHosecloudOutbound(client, integration.signKey, payload);
// 等待后台队列消费 (2秒)
await new Promise((r) => setTimeout(r, 2000));
let createdRecord: ApprovalRun | undefined;
try {
const runs = await api.listApprovalRuns(client, {
limit: 5,
search: flowId
});
createdRecord = (runs.records || []).find(
(r) => r.sourceDocumentId === flowId || r.sourceDocumentSN === flowId
);
} catch {
// 非阻塞
}
console.error(`✓ 已成功向合思出站通道推送测试消息 (flowId: ${flowId}, signKey: ${integration.signKey})`);
if (createdRecord) {
console.error(`✓ 异步消费成功!已在【${context.corp.name}】生成审核记录: ${createdRecord.id} (任务模式: ${createdRecord.taskMode})`);
console.error(`👉 查看审核详情: seal-use approval-runs get ${createdRecord.id} --corp ${context.corp.id}`);
} else {
console.error(`ℹ️ 消息已入队正在异步消费,可在几秒后刷新后台页面或查询: seal-use approval-runs list --corp ${context.corp.id}`);
}
return {
success: true,
targetCorp: context.corp.id,
signKey: integration.signKey,
mode: integration.mode,
payload,
response,
recordId: createdRecord?.id,
recordStatus: createdRecord?.status,
taskMode: createdRecord?.taskMode
};
}
}
];
+21 -5
View File
@@ -29,10 +29,19 @@ export const identityCapabilities = [
name: "sealDelegationCreate",
description: "创建新的 Seal 授权链接 (Delegation)",
parameters: z.object({
note: z.string().optional().describe("授权链接的备注或说明信息")
note: z.string().optional().describe("授权链接的备注或说明信息"),
expiresInHours: z
.number()
.int()
.min(1)
.max(168)
.optional()
.describe("授权链接有效期小时数(1~168 小时,即最大 7 天,默认 24 小时)")
}),
handler: async (client: KyInstance, params: { note?: string }) =>
api.createDelegation(client, params)
handler: async (
client: KyInstance,
params: { note?: string; expiresInHours?: number }
) => api.createDelegation(client, params)
},
{
name: "sealDelegationRevoke",
@@ -107,11 +116,18 @@ export const identityCapabilities = [
description: "为指定 Seal 用户(按用户ID、手机号或姓名)重置密码登录并生成其专属授权链接 (Delegation)",
parameters: z.object({
userIdOrPhone: z.string().describe("目标用户 ID、手机号或姓名"),
note: z.string().optional().describe("授权链接备注信息")
note: z.string().optional().describe("授权链接备注信息"),
expiresInHours: z
.number()
.int()
.min(1)
.max(168)
.optional()
.describe("授权链接有效期小时数(1~168 小时,即最大 7 天,默认 24 小时)")
}),
handler: async (
client: KyInstance,
params: { userIdOrPhone: string; note?: string },
params: { userIdOrPhone: string; note?: string; expiresInHours?: number },
context: CapabilityContext
) =>
api.createDelegationForUser(
+1
View File
@@ -135,6 +135,7 @@ export const SEAL_MUTATING_CAPABILITIES: ReadonlySet<string> = new Set([
"sealDelegationRevoke",
"sealDeployHosecloudConfigure",
"sealDeployHosecloudSync",
"sealDeployHosecloudTestOutbound",
"sealInsightRecordAnalyze",
"sealPreferenceDecisionUpdate",
"sealPreferenceThinkingDepthPoliciesRemove",
@@ -0,0 +1,201 @@
import { describe, expect, test } from "bun:test";
import {
selectMatchingOutboundLog,
validateHoseOutboundReplaySafety,
type HoseOutboundLogItem
} from "./hose-outbound-replay.js";
import type { CorpConfig } from "../../core/config/types.js";
const mockLogs: HoseOutboundLogItem[] = [
{
id: "log-callback-3",
name: "全自动模式审批_财务部门",
type: "CALLBACK",
state: "SUCCESS",
createTime: 1789461868758,
request: {
action: "accept",
flowId: "ID01Wah1FQ9faf",
nodeId: "FLOW:355474724:884326991",
comment: "AI建议【通过】\n查看详情:https://test.sealai.cc/approval-result/01a0a43c-521b-778c-b11b-238c8496dfec"
}
},
{
id: "log-invoking-3",
name: "全自动模式审批_财务部门",
type: "INVOKING",
state: "SUCCESS",
createTime: 1789461809348,
nodeName: "财务部门",
request: {
flowId: "ID01Wah1FQ9faf",
nodeId: "FLOW:355474724:884326991",
messageId: "ID01Wh05v0In3F",
rejectionNum: 3,
corporationId: "ID01lwQSjf93Bl"
}
},
{
id: "log-callback-2",
name: "全自动报销审批. - 完成回调",
type: "CALLBACK",
state: "SUCCESS",
createTime: 1789112525311,
request: {
action: "refuse",
flowId: "ID01Wah1FQ9faf",
nodeId: "FLOW:215172549:1248083206",
comment: "AI建议【驳回】\n查看详情:https://test.sealai.cc/approval-result/01a08f69-ad6f-76b8-8c81-81190544150d"
}
},
{
id: "log-invoking-2",
name: "全自动报销审批.",
type: "INVOKING",
state: "SUCCESS",
createTime: 1789112460936,
nodeName: "财务部门",
request: {
flowId: "ID01Wah1FQ9faf",
nodeId: "FLOW:215172549:1248083206",
messageId: "ID01WahQ3gbhMP",
rejectionNum: 2,
corporationId: "ID01lwQSjf93Bl"
}
}
];
const mockSourceCorp: CorpConfig = {
id: "prod-corp",
name: "生产企业",
environment: "production",
seal: {
url: "https://prod.sealai.cc",
endpoints: { approvalStylePreferences: "api/v1/system/preferences/approval-style" }
},
source: {
type: "hose",
domain: "https://app.ekuaibao.com",
appKey: "key-123",
appSecurity: "sec-456",
staffId: "staff-1",
corpId: "corp-1"
},
auth: { refreshTtl: 300 },
testCorpId: "test-corp"
};
const mockTargetCorp: CorpConfig = {
id: "test-corp",
name: "测试企业",
environment: "test",
seal: {
url: "https://test.sealai.cc",
endpoints: { approvalStylePreferences: "api/v1/system/preferences/approval-style" }
},
source: {
type: "seal",
token: "token-abc",
sealUrl: "https://test.sealai.cc",
expiresIn: 3600,
staffId: "seal"
},
auth: { refreshTtl: 300 },
prodCorpId: "prod-corp"
};
describe("selectMatchingOutboundLog", () => {
test("defaults to the latest invoking log when no options given", () => {
const selected = selectMatchingOutboundLog(mockLogs);
expect(selected).toBeDefined();
expect(selected?.id).toBe("log-invoking-3");
expect(selected?.request?.messageId).toBe("ID01Wh05v0In3F");
});
test("matches by explicit messageId", () => {
const selected = selectMatchingOutboundLog(mockLogs, { messageId: "ID01WahQ3gbhMP" });
expect(selected).toBeDefined();
expect(selected?.id).toBe("log-invoking-2");
expect(selected?.request?.rejectionNum).toBe(2);
});
test("matches by recordId reverse lookup via CALLBACK comment", () => {
const selected = selectMatchingOutboundLog(mockLogs, {
recordId: "01a08f69-ad6f-76b8-8c81-81190544150d"
});
expect(selected).toBeDefined();
expect(selected?.id).toBe("log-invoking-2");
expect(selected?.request?.messageId).toBe("ID01WahQ3gbhMP");
});
test("matches by rejectionNum", () => {
const selected = selectMatchingOutboundLog(mockLogs, { rejectionNum: 2 });
expect(selected).toBeDefined();
expect(selected?.request?.messageId).toBe("ID01WahQ3gbhMP");
});
test("returns undefined if no invoking logs exist", () => {
const emptyLogs: HoseOutboundLogItem[] = [
{ id: "1", name: "cb", type: "CALLBACK", state: "OK", createTime: 123 }
];
expect(selectMatchingOutboundLog(emptyLogs)).toBeUndefined();
});
});
describe("validateHoseOutboundReplaySafety", () => {
test("passes when source and target are paired and target is assisted", () => {
expect(() =>
validateHoseOutboundReplaySafety(
mockSourceCorp,
mockTargetCorp,
{ mode: "assisted", outboundName: "测试通道", signKey: "key-1" }
)
).not.toThrow();
});
test("blocks when source and target are NOT paired", () => {
const unpairedTarget = { ...mockTargetCorp, prodCorpId: "other-prod" };
const unpairedSource = { ...mockSourceCorp, testCorpId: "other-test" };
expect(() =>
validateHoseOutboundReplaySafety(
unpairedSource,
unpairedTarget,
{ mode: "assisted", signKey: "k" }
)
).toThrow(/未配置双向测试绑定关系/);
});
test("blocks when target is production", () => {
const prodTarget = { ...mockTargetCorp, environment: "production" as const };
expect(() =>
validateHoseOutboundReplaySafety(
mockSourceCorp,
prodTarget,
{ mode: "assisted", signKey: "k" }
)
).toThrow(/标记为正式生产环境/);
});
test("blocks when target mode is NOT assisted", () => {
expect(() =>
validateHoseOutboundReplaySafety(
mockSourceCorp,
mockTargetCorp,
{ mode: "fully_automatic", signKey: "k" }
)
).toThrow(/非 assisted(辅助审核)模式/);
});
test("allows force override for unpaired tenants", () => {
const unpairedTarget = { ...mockTargetCorp, prodCorpId: "other-prod" };
const unpairedSource = { ...mockSourceCorp, testCorpId: "other-test" };
expect(() =>
validateHoseOutboundReplaySafety(
unpairedSource,
unpairedTarget,
{ mode: "assisted", signKey: "k" },
true
)
).not.toThrow();
});
});
+431
View File
@@ -0,0 +1,431 @@
import type { KyInstance } from "ky";
import type { CorpConfig } from "../../core/config/types.js";
import { safetyBlocked, validationError } from "../../core/errors.js";
import { createHoseCloseClient } from "../hose/close/client.js";
import * as api from "./api.js";
import type { ApprovalRun } from "./types.js";
export interface HoseOutboundLogItem {
id: string;
name: string;
type: "INVOKING" | "CALLBACK" | string;
state: string;
flowId?: {
id: string;
form?: {
code?: string;
};
};
nodeName?: string;
createTime: number;
messageType?: string;
request?: {
flowId?: string;
nodeId?: string;
messageId?: string;
rejectionNum?: number;
corporationId?: string;
action?: string;
comment?: string;
signKey?: string;
[key: string]: unknown;
};
response?: unknown;
}
export interface HoseOutboundReplayOptions {
sourceCorp: CorpConfig;
targetCorp: CorpConfig;
sourceClient?: KyInstance;
targetClient: KyInstance;
sn?: string;
recordId?: string;
flowId?: string;
messageId?: string;
nodeId?: string;
corporationId?: string;
rejectionNum?: number;
targetSignKey?: string;
dryRun?: boolean;
force?: boolean;
}
/**
* Fetch historical outbound message logs from Hosecloud's CloseAPI for a given document SN.
*/
export async function fetchHoseOutboundLogs(
sourceCorp: CorpConfig,
sn: string
): Promise<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.
*/
export function selectMatchingOutboundLog(
logs: HoseOutboundLogItem[],
options: {
messageId?: string;
recordId?: string;
recordCreatedAt?: number;
rejectionNum?: number;
} = {}
): HoseOutboundLogItem | undefined {
const invokingLogs = logs.filter((item) => item.type === "INVOKING");
if (invokingLogs.length === 0) {
return undefined;
}
// 1. Explicit messageId match
if (options.messageId) {
return invokingLogs.find((item) => item.request?.messageId === options.messageId);
}
// 2. Exact recordId match via CALLBACK link/comment
if (options.recordId) {
const callbackWithRecordId = logs.find(
(item) =>
item.type === "CALLBACK" &&
typeof item.request?.comment === "string" &&
item.request.comment.includes(options.recordId!)
);
if (callbackWithRecordId) {
// Find the invoking event right before this callback
const priorInvoking = invokingLogs.find(
(item) => item.createTime <= callbackWithRecordId.createTime
);
if (priorInvoking) {
return priorInvoking;
}
}
// Fallback: match by timestamp delta (< 60s)
if (options.recordCreatedAt) {
const closestByTime = invokingLogs
.filter((item) => item.createTime <= options.recordCreatedAt! + 1000)
.sort(
(a, b) =>
Math.abs(options.recordCreatedAt! - a.createTime) -
Math.abs(options.recordCreatedAt! - b.createTime)
)[0];
if (closestByTime) {
return closestByTime;
}
}
}
// 3. Match by rejectionNum if provided
if (options.rejectionNum !== undefined) {
const matchRejection = invokingLogs.find(
(item) => item.request?.rejectionNum === options.rejectionNum
);
if (matchRejection) {
return matchRejection;
}
}
// 4. Default: latest invoking log
return invokingLogs[0];
}
/**
* Validate security preconditions for Hose outbound replay.
*/
export function validateHoseOutboundReplaySafety(
sourceCorp: CorpConfig,
targetCorp: CorpConfig,
targetIntegration: { mode?: string; outboundName?: string; signKey?: string },
force = false
): void {
// 1. Double-binding guard: prevent accidental cross-tenant execution outside paired sandbox
const isPaired =
sourceCorp.testCorpId === targetCorp.id ||
targetCorp.prodCorpId === sourceCorp.id ||
sourceCorp.id === targetCorp.id;
if (!isPaired && !force) {
throw safetyBlocked(
`安全阻断:源企业「${sourceCorp.name}」(${sourceCorp.id}) 与目标企业「${targetCorp.name}」(${targetCorp.id}) 未配置双向测试绑定关系 (testCorpId / prodCorpId)。\n` +
`出站重放具备高仿真性,仅允许在绑定的生产-测试企业对之间执行。如确需跨租户测试,请添加 --force 参数。`,
`请检查企业配置 ~/.config/seal-use/enterprises/ 或添加 --force`
);
}
// 2. Production target guard
if (targetCorp.environment === "production" && !force) {
throw safetyBlocked(
`安全阻断:目标企业「${targetCorp.name}」标记为正式生产环境 (production)。\n` +
`为防止测试消息污染生产审批流,严禁向生产企业重发出站报文。请通过 --target-corp 指定测试企业。`,
`seal-use approval-runs replay --target-corp <testCorpId> ...`
);
}
// 3. Mode guard: target Hose integration MUST be assisted
const mode = targetIntegration.mode ?? "assisted";
if (mode !== "assisted") {
throw safetyBlocked(
`安全阻断:目标测试企业「${targetCorp.name}」的合思配置「${targetIntegration.outboundName ?? targetIntegration.signKey}」当前为「${mode}」模式,非 assisted(辅助审核)模式。\n` +
`为防止自动向合思回写审批动作影响流程,严禁在非 assisted 模式下重放出站单据。`,
`请先将目标企业的合思配置调整为 assisted 模式后重试:seal-use deploy hosecloud configure --json '{"signKey":"${targetIntegration.signKey}","mode":"assisted"}' --corp ${targetCorp.id}`
);
}
}
/**
* Main execution handler for Hose outbound replay.
*/
export async function executeHoseOutboundReplay(options: HoseOutboundReplayOptions) {
const { sourceCorp, targetCorp, targetClient, dryRun, force } = options;
// 1. Get target corp's Hose integrations
const targetConfig = await api.getApprovalStylePreferences(
targetClient,
targetCorp.seal?.endpoints?.approvalStylePreferences
);
const hoseConfigs: Array<{
type: string;
signKey?: string;
outboundName?: string;
mode?: string;
corporationId?: string;
[key: string]: unknown;
}> = (targetConfig.integrations ?? []).filter((i: any) => i.type === "hosecloud");
if (hoseConfigs.length === 0) {
throw validationError(
`目标测试企业「${targetCorp.name}」未配置任何合思出站发布通道。请先运行:seal-use deploy hosecloud configure --corp ${targetCorp.id}`
);
}
const foundIntegration = options.targetSignKey
? hoseConfigs.find((i) => i.signKey === options.targetSignKey)
: hoseConfigs[0];
if (!foundIntegration || !foundIntegration.signKey) {
if (options.targetSignKey) {
throw validationError(
`在目标企业中未找到 signKey 为「${options.targetSignKey}」的合思配置。可用配置: ${hoseConfigs.map((i) => i.signKey).filter(Boolean).join(", ")}`
);
}
throw validationError(
`目标测试企业「${targetCorp.name}」未配置有效的合思 signKey。`
);
}
const targetIntegration = {
...foundIntegration,
signKey: foundIntegration.signKey
};
// 2. Validate safety constraints
validateHoseOutboundReplaySafety(sourceCorp, targetCorp, targetIntegration, force);
// 3. Resolve document SN & record details
let sn = options.sn?.trim();
let sourceRecord: ApprovalRun | undefined;
if (options.recordId) {
if (options.sourceClient) {
try {
sourceRecord = await api.getApprovalRun(options.sourceClient, options.recordId);
if (sourceRecord?.sourceDocumentSN) {
sn = sourceRecord.sourceDocumentSN;
}
} catch {
// continue
}
}
}
if (!sn && !options.messageId) {
throw validationError(
"缺少必需参数:请提供单号 (--sn <SN>) 或运行记录 ID (<recordId>),以便自动从合思检索出站消息日志。"
);
}
// 4. Retrieve or match outbound log
let selectedLog: HoseOutboundLogItem | undefined;
if (!options.messageId && sn) {
console.error(`ℹ️ 正在通过合思 CloseAPI 检索单据「${sn}」的历史出站消息日志...`);
const logs = await fetchHoseOutboundLogs(sourceCorp, sn);
const recordCreatedAt =
typeof sourceRecord?.createdAt === "number"
? sourceRecord.createdAt
: typeof sourceRecord?.createdAt === "string"
? Date.parse(sourceRecord.createdAt)
: undefined;
selectedLog = selectMatchingOutboundLog(logs, {
recordId: options.recordId,
recordCreatedAt: Number.isNaN(recordCreatedAt) ? undefined : recordCreatedAt,
rejectionNum: options.rejectionNum
});
if (!selectedLog || !selectedLog.request?.messageId) {
throw validationError(
`在合思出站日志中未找到单据「${sn}」的有效出站记录 (type: INVOKING)。\n` +
`请确认该单据在合思审批流中是否触发过出站消息(EBot节点),或显式提供 --message-id 参数。`
);
}
}
// 5. Construct payload
const flowId =
options.flowId?.trim() ??
selectedLog?.request?.flowId ??
selectedLog?.flowId?.id ??
sourceRecord?.sourceDocumentId ??
(sn?.startsWith("ID01") ? sn : undefined);
if (!flowId) {
throw validationError(
`未能解析出单据「${sn}」的合思流程实例 ID (flowId)。请确认单据信息或显式提供 flowId。`
);
}
const messageId = options.messageId?.trim() ?? selectedLog?.request?.messageId;
if (!messageId) {
throw validationError("未能获取到有效 messageId。");
}
const rejectionNum =
options.rejectionNum ?? selectedLog?.request?.rejectionNum ?? 0;
const corporationId =
options.corporationId?.trim() ??
selectedLog?.request?.corporationId ??
(sourceCorp.source as any)?.corpId ??
targetIntegration.corporationId;
// Crucial: Chinese mock nodeId causes Hose to return HTTP 412 on callback, creating an indestructible safety gate
const nodeId = options.nodeId?.trim() || "FLOW:测试模拟节点_禁止流转";
const targetSealUrl = (
targetCorp.seal.url ?? `https://${targetCorp.id.toLowerCase()}.sealai.cc`
).replace(/\/+$/, "");
const targetWebhookUrl = `${targetSealUrl}/api/hosecloud/outbound?config_id=${encodeURIComponent(targetIntegration.signKey)}`;
const payload = {
flowId,
nodeId,
messageId,
rejectionNum,
corporationId
};
// 6. Dry run preview
if (dryRun) {
return {
preview: true,
channel: "hose-outbound",
sourceCorp: {
id: sourceCorp.id,
name: sourceCorp.name,
environment: sourceCorp.environment
},
targetCorp: {
id: targetCorp.id,
name: targetCorp.name,
environment: targetCorp.environment
},
targetIntegration: {
signKey: targetIntegration.signKey,
outboundName: targetIntegration.outboundName,
mode: targetIntegration.mode
},
matchedLog: selectedLog
? {
logId: selectedLog.id,
nodeName: selectedLog.nodeName,
createTime: selectedLog.createTime,
messageId: selectedLog.request?.messageId,
rejectionNum: selectedLog.request?.rejectionNum
}
: undefined,
safetyGuards: {
pairedBinding: true,
targetModeAssisted: true,
nodeId412Blocked: true
},
targetUrl: targetWebhookUrl,
payload
};
}
// 7. Live execution
const response = await api.postHosecloudOutbound(
targetClient,
targetIntegration.signKey,
payload
);
console.error(`✓ 成功从合思出站日志匹配消息 (messageId: ${messageId}, 轮次: ${rejectionNum})`);
console.error(`✓ 已向测试企业「${targetCorp.name}」出站网关推送重放报文 (nodeId: ${nodeId})`);
// Wait 2.5s for worker queue consumption
await new Promise((r) => setTimeout(r, 2500));
let createdRecord: ApprovalRun | undefined;
try {
const runs = await api.listApprovalRuns(targetClient, {
limit: 5,
search: flowId
});
createdRecord = (runs.records || []).find(
(r) => r.sourceDocumentId === flowId || r.sourceDocumentSN === sn
);
} catch {
// non-blocking
}
if (createdRecord) {
console.error(`✓ 异步消费成功!已在【${targetCorp.name}】生成审核记录: ${createdRecord.id} (任务模式: ${createdRecord.taskMode})`);
console.error(`👉 查看审核详情: seal-use approval-runs get ${createdRecord.id} --corp ${targetCorp.id}`);
} else {
console.error(`ℹ️ 消息已入队正在异步消费,可稍后在测试后台页面刷新查看。`);
}
return {
success: true,
channel: "hose-outbound",
sourceCorp: {
id: sourceCorp.id,
name: sourceCorp.name
},
targetCorp: {
id: targetCorp.id,
name: targetCorp.name
},
targetSignKey: targetIntegration.signKey,
mode: targetIntegration.mode,
matchedMessageId: messageId,
rejectionNum,
payload,
response,
recordId: createdRecord?.id,
recordStatus: createdRecord?.status,
taskMode: createdRecord?.taskMode
};
}