Move enterprise workflows into domains

This commit is contained in:
gitea committed 2026-09-22 15:10:04 +08:00
1 parent f5be38d112
commit 9094f4907a
10 files changed
+1432 -1234

No files matched your search

+191 -491
View File
@@ -1,35 +1,19 @@
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { maskHoseSecurity } from "../../../core/auth/hose.js";
import { scoreAssistLink } from "../../../core/auth/delegate.js";
import { onboardSealBearer } from "../../../domains/seal/onboarding.js";
import { onboardAssistanceLink } from "../../../domains/enterprise/onboarding.js";
import {
assertHoseAssistTenantMatches,
exchangeHoseAssistLink,
fetchHoseOpenApiKeysFromLink,
fetchHoseRoleDefGroups,
fetchHoseRoleStaffs,
fetchHoseStaffDetails,
maskHoseSecurity,
parseHoseAssistLink,
probeHoseDomain,
resolveHoseAssistLinkDetails,
type HoseOpenApiKey
} from "../../../core/auth/hose.js";
listHoseStaffs,
onboardHosePersistent,
onboardHoseWebSession,
probeHoseEnterprise
} from "../../../domains/hose/onboarding.js";
import {
exchangeSealDelegateLink,
parseSealDelegateLink,
previewSealDelegateLink,
scoreAssistLink
} from "../../../core/auth/delegate.js";
import { clearCorpTokenCache } from "../../../core/auth/token-store.js";
import { createSealClientForUrl } from "../../../core/http/factory.js";
import { resolveSealCustomHeaders } from "../../../core/http/request-headers.js";
import { resolveWritableEnterprisesDir } from "../../../core/config/loader.js";
import {
SealCookieMapSchema,
SealHeaderMapSchema
} from "../../../core/config/types.js";
import type { CorpConfig } from "../../../core/config/types.js";
import { getMe } from "../../../domains/seal/api.js";
import { resolveLiveSealEnterpriseConfig } from "../../../domains/seal/source.js";
elevateHoseLink,
extractHoseKeysFromLink,
formatHoseKeyForOutput,
HoseKeySelectionError
} from "../../../domains/hose/keys.js";
import { CliError } from "../../errors.js";
import { selectCorp } from "../../helpers.js";
import {
@@ -38,13 +22,11 @@ import {
optionalNumber,
optionalString,
requiredString,
requiredStringAlias,
safeFileName,
stringOption
} from "../../parser.js";
import { printJson } from "../../printer.js";
import type { ParsedArgs } from "../../types.js";
import { formatUtcTimestampSeconds, maskCellphone, stringValue } from "./shared.js";
import { maskCellphone } from "./shared.js";
export async function handleCorpOnboarding(
action: string | undefined,
@@ -52,12 +34,48 @@ export async function handleCorpOnboarding(
args: ParsedArgs
): Promise<boolean> {
if (action === "probe-hose") {
await probeHoseCorp(jsonObject(args.json));
const input = jsonObject(args.json);
const result = await probeHoseEnterprise({
appKey: requiredString(input, "appKey"),
appSecurity: requiredString(input, "appSecurity"),
domain: optionalString(input, "domain")
});
printJson({
domain: result.domain,
corpId: result.corpId,
name: result.corpName ?? result.corpId,
roleCount: result.roleCount,
roleGroups: result.roleGroups
});
return true;
}
if (action === "hose-staffs") {
await queryHoseStaffs(jsonObject(args.json));
const input = jsonObject(args.json);
const result = await listHoseStaffs({
appKey: requiredString(input, "appKey"),
appSecurity: requiredString(input, "appSecurity"),
domain: optionalString(input, "domain"),
role: optionalString(input, "role"),
roleDefId: optionalString(input, "roleDefId")
});
printJson({
domain: result.domain,
corpId: result.corpId,
corpName: result.corpName,
roleId: result.roleId,
roleName: result.roleName,
count: result.staffs.length,
staffs: result.staffs.map((staff) => ({
id: staff.id,
name: staff.name,
cellphone: maskCellphone(staff.cellphone),
active: staff.active,
authState: staff.authState,
userId: staff.userId,
email: staff.email
}))
});
return true;
}
@@ -83,7 +101,20 @@ export async function handleCorpOnboarding(
...(args.options.force !== undefined ? { force: booleanOption(args.options.force) } : {}),
...(args.options.overwrite !== undefined ? { overwrite: booleanOption(args.options.overwrite) } : {})
};
await addHoseCorp(merged);
const result = await onboardHosePersistent({
...merged,
appKey: requiredString(merged, "appKey"),
appSecurity: requiredString(merged, "appSecurity")
});
printJson({
id: result.config.id,
name: result.config.name,
corpId: result.config.source.type === "hose" ? result.config.source.corpId : undefined,
domain: result.domain,
staffId: result.staffId,
verified: result.verified,
path: result.path
});
return true;
}
@@ -103,7 +134,35 @@ export async function handleCorpOnboarding(
...(args.options.overwrite !== undefined ? { overwrite: booleanOption(args.options.overwrite) } : {}),
...(args.options["dry-run"] !== undefined ? { dryRun: booleanOption(args.options["dry-run"]) } : {})
};
await addHoseWebSessionCorp(merged);
const dryRun = merged.dryRun === true;
const input = merged as Parameters<typeof onboardHoseWebSession>[0] & { dryRun?: boolean };
const result = await onboardHoseWebSession({
...input,
persist: !dryRun
});
if (dryRun) {
printJson({
dryRun: true,
kind: "hose-web-session",
corpId: result.session.corpId,
sealUrl: result.session.sealUrl,
tenant: result.identity.tenant,
user: result.identity.user,
staffId: result.staffId,
expiresIn: result.session.expiresIn
});
} else {
printJson({
id: result.config.id,
name: result.config.name,
tenantId: result.identity.tenant.id,
tenantSlug: result.config.seal.tenantSlug,
sourceType: "hose",
credentialMode: "web-session",
verified: true,
path: result.path
});
}
return true;
}
@@ -197,376 +256,91 @@ export async function handleCorpOnboarding(
return false;
}
async function probeHoseCorp(input: Record<string, unknown>) {
const appKey = requiredString(input, "appKey");
const appSecurity = requiredString(input, "appSecurity");
const probe = await probeHoseDomain(appKey, appSecurity, optionalString(input, "domain"));
const roleGroups = await fetchHoseRoleDefGroups(probe.domain, probe.openapiToken).catch(() => []);
printJson({
domain: probe.domain,
corpId: probe.corpId,
name: probe.corpName ?? probe.corpId,
roleCount: roleGroups.reduce((acc, g) => acc + g.roleDefs.length, 0),
roleGroups: roleGroups.map((g) => ({
id: g.id,
name: g.name,
roleDefs: g.roleDefs.map((r) => ({ id: r.id, name: r.name, sourceType: r.sourceType }))
}))
});
}
async function queryHoseStaffs(input: Record<string, unknown>) {
const appKey = requiredString(input, "appKey");
const appSecurity = requiredString(input, "appSecurity");
const roleQuery = optionalString(input, "role") ?? optionalString(input, "roleDefId") ?? "admin";
const probe = await probeHoseDomain(appKey, appSecurity, optionalString(input, "domain"));
const roleGroups = await fetchHoseRoleDefGroups(probe.domain, probe.openapiToken);
let targetRoleDefId: string | undefined;
let targetRoleName: string | undefined;
// 1. Direct match by id
for (const group of roleGroups) {
for (const role of group.roleDefs) {
if (role.id === roleQuery || role.id === `${probe.corpId}:${roleQuery}`) {
targetRoleDefId = role.id;
targetRoleName = role.name;
break;
}
}
if (targetRoleDefId) break;
}
// 2. Admin match default
if (!targetRoleDefId && (roleQuery === "admin" || roleQuery === "主管理员")) {
for (const group of roleGroups) {
for (const role of group.roleDefs) {
if (role.id.endsWith(":admin") || role.name === "主管理员") {
targetRoleDefId = role.id;
targetRoleName = role.name;
break;
}
}
if (targetRoleDefId) break;
}
}
// 3. Match by role name substring
if (!targetRoleDefId) {
for (const group of roleGroups) {
for (const role of group.roleDefs) {
if (role.name.toLowerCase().includes(roleQuery.toLowerCase())) {
targetRoleDefId = role.id;
targetRoleName = role.name;
break;
}
}
if (targetRoleDefId) break;
}
}
if (!targetRoleDefId) {
throw new Error(`Role not found matching query: '${roleQuery}'. Run 'seal-use corps probe-hose' to view all available roles.`);
}
const roleStaffs = await fetchHoseRoleStaffs(probe.domain, probe.openapiToken, targetRoleDefId);
const staffDetails = await fetchHoseStaffDetails(probe.domain, probe.openapiToken, roleStaffs.staffs);
printJson({
domain: probe.domain,
corpId: probe.corpId,
corpName: probe.corpName ?? probe.corpId,
roleId: targetRoleDefId,
roleName: targetRoleName,
count: staffDetails.length,
staffs: staffDetails.map((staff) => ({
id: staff.id,
name: staff.name,
cellphone: maskCellphone(staff.cellphone),
active: staff.active,
authState: staff.authState,
userId: staff.userId,
email: staff.email
}))
});
}
async function addHoseCorp(input: Record<string, unknown>) {
const nameInput = optionalString(input, "name");
const appKey = requiredString(input, "appKey");
const appSecurity = requiredString(input, "appSecurity");
const explicitDomain = optionalString(input, "domain");
const explicitStaffId = optionalString(input, "staffId") ?? optionalString(input, "proxyStaffBizId");
const staffName = optionalString(input, "staffName");
const staffPhone = optionalString(input, "staffPhone");
const roleQuery = optionalString(input, "role") ?? "admin";
const force = input.force === true;
const verify = force || input.verify === false ? false : true;
let domain = explicitDomain;
let corpId = optionalString(input, "corpId") ?? optionalString(input, "corporationId");
let corpName = nameInput;
let openapiToken: string | undefined;
if (!domain || !corpId || !explicitStaffId) {
const probe = await probeHoseDomain(appKey, appSecurity, explicitDomain);
domain = probe.domain;
corpId = corpId ?? probe.corpId;
corpName = corpName ?? probe.corpName;
openapiToken = probe.openapiToken;
}
let finalStaffId = explicitStaffId;
if (!finalStaffId && openapiToken && domain) {
const roleGroups = await fetchHoseRoleDefGroups(domain, openapiToken).catch(() => []);
let targetRoleId: string | undefined;
for (const group of roleGroups) {
for (const role of group.roleDefs) {
if (role.id.endsWith(`:${roleQuery}`) || role.name === roleQuery || role.id === roleQuery) {
targetRoleId = role.id;
break;
}
}
if (targetRoleId) break;
}
if (!targetRoleId) {
targetRoleId = roleGroups.find((group) => group.roleDefs.some((role) => role.id.endsWith(":admin")))
?.roleDefs.find((role) => role.id.endsWith(":admin"))?.id;
}
if (targetRoleId) {
const roleStaffs = await fetchHoseRoleStaffs(domain, openapiToken, targetRoleId).catch(() => ({ staffs: [] }));
const staffDetails = await fetchHoseStaffDetails(domain, openapiToken, roleStaffs.staffs).catch(() => []);
if (staffName || staffPhone) {
const matches = staffDetails.filter((staff) => {
if (staffName && staff.name !== staffName && !staff.name.includes(staffName)) return false;
if (staffPhone && (!staff.cellphone || !staff.cellphone.includes(staffPhone))) return false;
return true;
});
if (matches.length === 1 && matches[0]) {
finalStaffId = matches[0].id;
} else if (matches.length > 1) {
throw new Error(`Multiple staff members matched '${staffName ?? staffPhone}': ${matches.map((m) => `${m.name}(${m.id})`).join(", ")}. Please specify exact staffId.`);
} else {
throw new Error(`No staff member found matching '${staffName ?? staffPhone}' under role ${targetRoleId}. Run 'seal-use corps hose-staffs' to view candidates.`);
}
} else if (!force) {
const candidateLines = staffDetails.map((staff, idx) => ` [${idx + 1}] ${staff.name} (${maskCellphone(staff.cellphone)})`).join("\n");
throw new Error(
`Missing required parameter: staffId. 当前企业共配置了 ${staffDetails.length} 位管理员账号(手机号已脱敏):\n\n${candidateLines}\n\n` +
`👉 请指定要作为审计身份绑定的管理员:\n` +
` • 按姓名选择:追加 --staffName <姓名>(支持关键字,如: --staffName 谢子豪)\n` +
` • 按手机选择:追加 --staffPhone <手机号>(支持手机后4位,如: --staffPhone 5678)\n` +
` • 或传 force:true / --force 自动使用默认首位管理员。`
);
} else {
finalStaffId = staffDetails.find((staff) => staff.active)?.id ?? staffDetails[0]?.id;
}
}
}
if (!finalStaffId) {
if (!verify && explicitStaffId) finalStaffId = explicitStaffId;
else throw new Error("Missing required parameter: staffId (or proxyStaffBizId). Run 'seal-use corps hose-staffs' to discover available administrators.");
}
const id = optionalString(input, "id") ?? corpId;
let name = nameInput ?? corpName ?? corpId;
const sealUrl = optionalString(input, "sealUrl") ?? `https://${corpId.toLowerCase()}.sealai.cc`;
const config: CorpConfig = {
id,
name,
environment: "production",
seal: {
url: sealUrl,
endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" }
},
source: {
type: "hose",
domain: domain!,
appKey,
appSecurity,
corpId: corpId!,
staffId: finalStaffId
},
auth: { refreshTtl: 300 }
};
if (verify) {
clearCorpTokenCache(id);
const live = await resolveLiveSealEnterpriseConfig(config);
if ((!nameInput || nameInput === corpId) && live.tenantName && live.tenantName !== corpId) {
name = live.tenantName;
config.name = live.tenantName;
}
}
const enterprisesDir = resolveWritableEnterprisesDir();
mkdirSync(enterprisesDir, { recursive: true, mode: 0o700 });
const file = join(enterprisesDir, `${safeFileName(id)}.json`);
if (existsSync(file) && input.overwrite !== true) {
throw new Error(`Enterprise config already exists: ${file}。如需覆盖已有配置,请在命令行追加 --overwrite 或在 JSON 参数中添加 "overwrite": true。`);
}
writeFileSync(file, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
printJson({ id, name, corpId, domain, staffId: finalStaffId, verified: verify, path: file });
}
async function addSealCorp(input: Record<string, unknown>) {
const token = requiredString(input, "token");
const sealUrl = (optionalString(input, "sealUrl") ?? optionalString(input, "url") ?? "").replace(/\/+$/, "");
if (!sealUrl) throw new Error("Missing required JSON field: sealUrl");
const expiresIn = optionalNumber(input, "expiresIn") ?? 30 * 24 * 60 * 60;
const verify = input.force === true || input.verify === false ? false : true;
const custom = sealCustomHeadersFromInput(input);
const remote = verify ? await resolveSealWhoami(sealUrl, token, resolveSealCustomHeaders(custom)) : undefined;
writeSealCorpConfig(input, { token, sealUrl, expiresIn, verify, remote, custom });
}
async function addHoseWebSessionCorp(input: Record<string, unknown>) {
const accessToken = requiredStringAlias(input, ["accessToken", "accesstoken"]);
const corpId = requiredStringAlias(input, ["corpId", "ekbCorpId", "corporationId"]);
const baseUrl = optionalString(input, "baseUrl") ?? optionalString(input, "domain");
const suppliedStaffId = optionalString(input, "staffId");
const details = await resolveHoseAssistLinkDetails({ corpId, accessToken, baseUrl });
const session = await exchangeHoseAssistLink({ corpId, accessToken, baseUrl });
const me = await getMe(createSealClientForUrl(session.sealUrl, session.token));
const identity = { user: me.user as unknown as Record<string, unknown>, tenant: me.tenant as unknown as Record<string, unknown> };
assertHoseAssistTenantMatches(session.corpId, identity.tenant);
if (input.dryRun === true) {
printJson({
dryRun: true,
kind: "hose-web-session",
corpId: session.corpId,
sealUrl: session.sealUrl,
tenant: identity.tenant,
user: identity.user,
staffId: suppliedStaffId ?? details.staffId,
expiresIn: session.expiresIn
});
return;
}
writeHoseWebSessionConfig({
id: session.corpId,
corpId: session.corpId,
name: optionalString(input, "name") ?? details.corpName,
provider: "hosecloud",
domain: details.baseUrl,
closeToken: accessToken,
const result = await onboardSealBearer({
...input,
token,
sealUrl,
expiresIn: optionalNumber(input, "expiresIn"),
expiresAt: optionalString(input, "expiresAt"),
staffId: suppliedStaffId ?? details.staffId,
sealUrl: session.sealUrl,
remote: identity,
overwrite: input.overwrite === true
id: optionalString(input, "id"),
name: optionalString(input, "name"),
tenantSlug: optionalString(input, "tenantSlug"),
tenantId: optionalString(input, "tenantId"),
tenantName: optionalString(input, "tenantName"),
corpId: optionalString(input, "corpId"),
staffId: optionalString(input, "staffId"),
provider: optionalString(input, "provider"),
force: input.force === true,
verify: input.verify === false,
overwrite: input.overwrite === true,
headers: input.headers,
cookies: input.cookies
});
printJson({
id: result.config.id,
name: result.config.name,
tenantId: result.tenantId,
tenantSlug: result.tenantSlug,
verified: result.verified,
path: result.path
});
}
function sealCustomHeadersFromInput(input: Record<string, unknown>) {
// Validates extra headers/cookies up front so a malformed name fails here
// rather than on the next config load.
return {
headers: SealHeaderMapSchema.parse(input.headers),
cookies: SealCookieMapSchema.parse(input.cookies)
};
}
async function addLinkCorp(link: string, name: string | undefined, overwrite: boolean, dryRun = false) {
// Classify the incoming link by score. The highest-scoring scorer decides
// which exchange path to take. This lets one command consume both Seal
// native delegate links (*/delegate?token=...) and Hose assistance links
// (*/web/thirdparty.html) without the caller having to know which they got.
const winner = scoreAssistLink(link)[0];
if (!winner || winner.score < 50) {
throw new Error(
`Unrecognized assistance/delegate link. Expected either a Seal native delegate link ` +
`(https://<tenant>.sealai.cc/delegate?token=...) or a Hose assistance link ` +
`(https://<corp>.ekuaibao.com/web/thirdparty.html?accessToken=...&ekbCorpId=...). ` +
`Top score: ${winner ? winner.kind + "=" + winner.score : "none"}.`
);
}
if (winner.kind === "seal-delegate") {
if (dryRun) {
const preview = await previewSealDelegateLink(link);
const parsed = parseSealDelegateLink(link);
printJson({
dryRun: true,
kind: "seal-delegate",
sealUrl: parsed.sealUrl,
tenant: { id: preview.tenantId, name: preview.tenantName },
user: { id: preview.userId, name: preview.userName },
delegationId: preview.delegationId
});
const result = await onboardAssistanceLink(link, { name, overwrite, dryRun });
if (result.kind === "seal-delegate") {
if (result.dryRun) {
printJson(result);
return;
}
// Seal native delegate link: exchange directly against the Seal tenant.
console.error(`ℹ️ [Seal 委托链接] 识别为 Seal 原生委托链接 (${winner.reason}),正在交换临时会话...`);
const session = await exchangeSealDelegateLink(link);
const identity = { user: session.user, tenant: session.tenant };
const tenantSlug = typeof session.tenant.tenantSlug === "string" && session.tenant.tenantSlug ? session.tenant.tenantSlug : undefined;
const tenantId = typeof session.tenant.id === "string" && session.tenant.id ? session.tenant.id : undefined;
const corpId = tenantSlug ?? tenantId ?? "seal-delegate";
writeSealCorpConfig(
{ id: corpId, corpId, name, provider: "seal", overwrite },
{ token: session.token, sealUrl: session.sealUrl, expiresIn: session.expiresIn, verify: true, remote: identity }
);
printJson({
id: result.saved.config.id,
name: result.saved.config.name,
tenantId: result.saved.tenantId,
tenantSlug: result.saved.tenantSlug,
verified: true,
path: result.saved.path
});
return;
}
// Default: Hose assistance link. Keep the Hose web-session source and its
// CloseAPI token; the Seal bearer is only a runtime SSO session.
const hoseLink = parseHoseAssistLink(link);
const details = await resolveHoseAssistLinkDetails(hoseLink);
const session = await exchangeHoseAssistLink(hoseLink);
const me = await getMe(createSealClientForUrl(session.sealUrl, session.token));
const identity = { user: me.user as unknown as Record<string, unknown>, tenant: me.tenant as unknown as Record<string, unknown> };
assertHoseAssistTenantMatches(session.corpId, identity.tenant);
if (dryRun) {
printJson({ dryRun: true, kind: "hose", corpId: session.corpId, sealUrl: session.sealUrl, tenant: identity.tenant, user: identity.user, staffId: details.staffId });
if (result.dryRun) {
printJson({
dryRun: true,
kind: "hose",
corpId: result.result.session.corpId,
sealUrl: result.result.session.sealUrl,
tenant: result.result.identity.tenant,
user: result.result.identity.user,
staffId: result.result.staffId
});
return;
}
writeHoseWebSessionConfig({
id: session.corpId,
corpId: session.corpId,
name: name ?? details.corpName,
provider: "hosecloud",
domain: details.baseUrl,
closeToken: hoseLink.accessToken,
staffId: details.staffId,
sealUrl: session.sealUrl,
remote: identity,
overwrite
printJson({
id: result.result.config.id,
name: result.result.config.name,
tenantId: result.result.identity.tenant.id,
tenantSlug: result.result.config.seal.tenantSlug,
sourceType: "hose",
credentialMode: "web-session",
verified: true,
path: result.result.path
});
}
function selectHoseOpenApiKey(keys: HoseOpenApiKey[], corpId: string, selection: { appKey?: string; keyId?: string }, contextCmd: string): HoseOpenApiKey {
if (keys.length === 0) {
throw new Error(`[合思子域提权] 未能从协助链接中提取到合思企业 [${corpId}] 的 OpenAPI 密钥凭据。\n` +
`💡 说明:此能力专属于合思 (Hose) 子域,用于将临时会话提权为标准 OpenAPI 开发者接入。需要企业管理员已在合思开放平台创建应用并生成 appKey/appSecurity。`);
}
if (selection.keyId || selection.appKey) {
const matched = keys.find((key) => (selection.keyId && key.id === selection.keyId) || (selection.appKey && key.appKey === selection.appKey));
if (!matched) {
console.error(`\n❌ 未找到指定的合思 OpenAPI 密钥 (${selection.appKey ?? selection.keyId})。`);
console.error(`ℹ️ 该合思企业当前存在以下 ${keys.length} 套候选密钥:`);
for (const key of keys) console.error(` • "${key.name || "未命名应用"}" (appKey: ${key.appKey}, keyId: ${key.id}, 状态: ${key.active ? "🟢 启用" : "⚪ 停用"})`);
throw new CliError("指定的合思密钥不存在,请从上述候选列表中选择正确的 appKey 或 keyId。", 2, `${contextCmd} --app-key ${keys[0]!.appKey}`);
}
return matched;
}
if (keys.length === 1) return keys[0]!;
// Multiple keys exist and user did not specify which one
console.error(`\nℹ️ [合思子域提权] 合思企业 [${corpId}] 存在多套 (${keys.length} 套) OpenAPI 应用密钥凭据:`);
for (let i = 0; i < keys.length; i++) {
const key = keys[i]!;
console.error(` [${i + 1}] "${key.name || "未命名应用"}" (appKey: ${key.appKey}, keyId: ${key.id}, 状态: ${key.active ? "🟢 启用" : "⚪ 停用"})`);
}
console.error("\n👉 为确保权限提权绑定正确的业务应用,请显式指定要使用的密钥套件:");
console.error(" 在命令后追加 --app-key <key> 或 --key-id <id> 参数。\n");
throw new CliError(`合思企业 [${corpId}] 存在多套 OpenAPI 密钥,必须指定 --app-key 或 --key-id 明确选择要绑定的密钥。`, 2, `${contextCmd} --app-key ${keys[0]!.appKey}`);
}
async function addLinkAsHoseCorp(link: string, name: string | undefined, overwrite: boolean, force = false, dryRun = false, selection?: { appKey?: string; keyId?: string }) {
console.error("ℹ️ [合思子域提权] 正在通过合思协助链接提取 OpenAPI 开发者密钥并提升企业权限等级...");
const result = await fetchHoseOpenApiKeysFromLink(link);
const selectedKey = selectHoseOpenApiKey(result.keys, result.corpId, selection ?? {}, `seal-use corps add-link "<url>" --elevate-hose`);
let elevated;
try {
elevated = await elevateHoseLink({ link, name, overwrite, force, dryRun, ...(selection ?? {}) });
} catch (error) {
if (error instanceof HoseKeySelectionError) throw new CliError(error.message, 2, error.nextAction);
throw error;
}
const { result, selectedKey } = elevated;
console.error(dryRun
? `ℹ️ [合思子域提权] 已选定合思 OpenAPI 凭据 (appKey: ${selectedKey.appKey}, 应用: "${selectedKey.name || "未命名应用"}"),正在生成预览...`
: `ℹ️ [合思子域提权] 已选定合思 OpenAPI 凭据 (appKey: ${selectedKey.appKey}, 应用: "${selectedKey.name || "未命名应用"}"),正在初始化为长期合思标准配置...`);
@@ -589,16 +363,41 @@ async function addLinkAsHoseCorp(link: string, name: string | undefined, overwri
});
return;
}
await addHoseCorp({ domain: result.baseUrl, appKey: selectedKey.appKey, appSecurity: selectedKey.appSecurity, corpId: result.corpId, name: name ?? result.corpName, staffId: result.staffId, overwrite, force });
const saved = elevated.saved;
if (!saved) throw new Error("Hose elevation completed without a saved enterprise configuration");
printJson({
id: saved.config.id,
name: saved.config.name,
corpId: result.corpId,
domain: saved.domain,
staffId: saved.staffId,
verified: saved.verified,
path: saved.path
});
}
export async function extractKeysFromLinkAction(link: string, options: { reveal?: boolean; save?: boolean; name?: string; overwrite?: boolean; force?: boolean; appKey?: string; keyId?: string }) {
const result = await fetchHoseOpenApiKeysFromLink(link);
const reveal = options.reveal === true;
let extracted;
try {
extracted = await extractHoseKeysFromLink({ link, ...options });
} catch (error) {
if (error instanceof HoseKeySelectionError) throw new CliError(error.message, 2, error.nextAction);
throw error;
}
const { result } = extracted;
const reveal = extracted.reveal;
if (options.save) {
const selectedKey = selectHoseOpenApiKey(result.keys, result.corpId, { appKey: options.appKey, keyId: options.keyId }, `seal-use corps hose-extract-keys "<url>" --save`);
const selectedKey = extracted.selectedKey!;
console.error(`ℹ️ [合思子域提权] 正在将选定的合思 OpenAPI 密钥 (appKey: ${selectedKey.appKey}, 应用: "${selectedKey.name || "未命名应用"}") 保存为标准合思企业配置...`);
await addHoseCorp({ domain: result.baseUrl, appKey: selectedKey.appKey, appSecurity: selectedKey.appSecurity, corpId: result.corpId, name: options.name ?? result.corpName, staffId: result.staffId, overwrite: options.overwrite, force: options.force });
printJson({
id: extracted.saved!.config.id,
name: extracted.saved!.config.name,
corpId: result.corpId,
domain: extracted.saved!.domain,
staffId: extracted.saved!.staffId,
verified: extracted.saved!.verified,
path: extracted.saved!.path
});
return;
}
if (!reveal) console.error("ℹ️ [合思子域提权] 成功提取合思 (Hose) OpenAPI 密钥。接入密码默认脱敏,附加 --reveal (或 -r) 可查看完整 appSecurity 明文;附加 --save 可将临时会话提权并持久化为标准合思企业。\n");
@@ -611,15 +410,7 @@ export async function extractKeysFromLinkAction(link: string, options: { reveal?
baseUrl: result.baseUrl,
staffId: result.staffId,
keyCount: result.keys.length,
keys: result.keys.map((key) => ({
id: key.id,
name: key.name || "-",
appKey: key.appKey,
appSecurity: reveal ? key.appSecurity : maskHoseSecurity(key.appSecurity),
active: key.active,
createTime: key.createTime,
updateTime: key.updateTime
}))
keys: result.keys.map((key) => formatHoseKeyForOutput(key, reveal))
});
}
@@ -646,94 +437,3 @@ export async function showCorpKeysAction(targetCorpId: string | undefined, optio
active: true
});
}
type RemoteSealIdentity = { user: Record<string, unknown>; tenant: Record<string, unknown> };
function writeSealCorpConfig(input: Record<string, unknown>, auth: { token: string; sealUrl: string; expiresIn: number; expiresAt?: string; verify: boolean; remote?: RemoteSealIdentity; custom?: { headers?: Record<string, string>; cookies?: Record<string, string> } }) {
const { token, sealUrl, expiresIn, verify, remote } = auth;
const expiresAt = auth.expiresAt ?? formatUtcTimestampSeconds(Date.now() + expiresIn * 1000);
const custom = auth.custom ?? sealCustomHeadersFromInput(input);
const remoteUser = remote?.user;
const remoteTenant = remote?.tenant;
const tenantSlug = optionalString(input, "tenantSlug") ?? stringValue(remoteTenant?.tenantSlug);
const tenantId = optionalString(input, "tenantId") ?? stringValue(remoteTenant?.id);
const tenantName = optionalString(input, "tenantName") ?? stringValue(remoteTenant?.name);
const id = optionalString(input, "id") ?? tenantSlug ?? tenantId;
if (!id) throw new Error("Missing required JSON field: id. Seal whoami did not return tenantSlug or tenantId.");
const staffId = optionalString(input, "staffId") ?? stringValue(remoteUser?.providerUserId) ?? stringValue(remoteUser?.id) ?? "seal";
const provider = optionalString(input, "provider") ?? stringValue(remoteUser?.provider) ?? stringValue((remoteTenant as any)?.providerConfig?.provider);
const corpId = optionalString(input, "corpId") ?? tenantSlug ?? tenantId ?? id;
const config: CorpConfig = {
id,
name: optionalString(input, "name") ?? tenantName ?? id,
environment: "production",
seal: {
url: sealUrl,
tenantSlug,
headers: custom.headers,
cookies: custom.cookies,
endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" }
},
source: {
type: "seal",
token,
sealUrl,
expiresIn,
expiresAt,
staffId,
corpId,
tenantId,
tenantSlug,
tenantName,
providerUserId: stringValue(remoteUser?.providerUserId),
provider
},
auth: { refreshTtl: 300 }
};
const enterprisesDir = resolveWritableEnterprisesDir();
mkdirSync(enterprisesDir, { recursive: true, mode: 0o700 });
const file = join(enterprisesDir, `${safeFileName(id)}.json`);
if (existsSync(file) && input.overwrite !== true) throw new Error(`Enterprise config already exists: ${file}. Pass "overwrite": true to replace it.`);
writeFileSync(file, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
printJson({ id, name: config.name, tenantId, tenantSlug, verified: verify, path: file });
}
function writeHoseWebSessionConfig(input: { id: string; corpId: string; name?: string; provider: string; domain: string; closeToken: string; expiresIn?: number; expiresAt?: string; staffId: string; sealUrl: string; remote: RemoteSealIdentity; overwrite: boolean }) {
const remoteTenant = input.remote.tenant;
const tenantSlug = stringValue(remoteTenant.tenantSlug) ?? input.corpId;
const tenantId = stringValue(remoteTenant.id);
const tenantName = stringValue(remoteTenant.name);
const config: CorpConfig = {
id: input.id,
name: input.name ?? tenantName ?? input.id,
environment: "production",
seal: {
url: input.sealUrl,
tenantSlug,
endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" }
},
source: {
type: "hose",
provider: input.provider,
domain: input.domain,
closeToken: input.closeToken,
...(input.expiresIn !== undefined ? { expiresIn: input.expiresIn } : {}),
...(input.expiresAt ? { expiresAt: input.expiresAt } : {}),
staffId: input.staffId,
corpId: input.corpId,
sealUrl: input.sealUrl
},
auth: { refreshTtl: 300 }
};
const enterprisesDir = resolveWritableEnterprisesDir();
mkdirSync(enterprisesDir, { recursive: true, mode: 0o700 });
const file = join(enterprisesDir, `${safeFileName(input.id)}.json`);
if (existsSync(file) && !input.overwrite) throw new Error(`Enterprise config already exists: ${file}. Pass "overwrite": true to replace it.`);
writeFileSync(file, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
printJson({ id: config.id, name: config.name, tenantId, tenantSlug, sourceType: "hose", credentialMode: "web-session", verified: true, path: file });
}
async function resolveSealWhoami(sealUrl: string, token: string, customHeaders: Record<string, string> = {}) {
const me = await getMe(createSealClientForUrl(sealUrl, token, customHeaders));
return { user: (me.user ?? {}) as Record<string, unknown>, tenant: (me.tenant ?? {}) as Record<string, unknown> };
}
+33 -535
View File
@@ -1,14 +1,6 @@
import { randomBytes } from "node:crypto";
import type { KyInstance } from "ky";
import { createSealClient } from "../../../core/http/factory.js";
import type { CorpConfig } from "../../../core/config/types.js";
import * as api from "../../../domains/seal/api.js";
import {
computeNextSyncIteration,
formatSyncVersionName,
saveRuleMappingSnapshot
} from "../../../domains/seal/rule-mapping.js";
import { savePublishedRuleVersionSnapshot } from "../../../domains/seal/rule-version-snapshot.js";
import { syncTestEnterprise, buildTestHosecloudOutboundName } from "../../../domains/seal/test-sync.js";
import { executeApprovalRunsReplay, type ReplayRecordsQuery } from "../../../domains/seal/webhook-replay.js";
import { selectCorp } from "../../helpers.js";
import { CliError, confirmationRequired, usageError } from "../../errors.js";
@@ -16,6 +8,8 @@ import { booleanOption, numberOption, stringOption } from "../../parser.js";
import { printJson } from "../../printer.js";
import type { ParsedArgs } from "../../types.js";
export { buildTestHosecloudOutboundName } from "../../../domains/seal/test-sync.js";
export async function handleCorpSync(
action: string | undefined,
maybeName: string | undefined,
@@ -24,371 +18,36 @@ export async function handleCorpSync(
if (action === "sync-test") {
const targetCorpId = maybeName ?? stringOption(args.options.corp);
const prodCorp = selectCorp(targetCorpId);
if (!prodCorp.testCorpId) {
throw usageError(
`Production enterprise '${prodCorp.name}' (${prodCorp.id}) has no bound test enterprise.\n` +
`Run 'seal-use corps bind-test ${prodCorp.id} <testCorpId> --confirm' first to establish a verified 1-to-1 association.`
);
}
const testCorp = selectCorp(prodCorp.testCorpId);
if (testCorp.environment !== "test") {
throw new Error(
`Target enterprise '${testCorp.name}' (${testCorp.id}) is marked as '${testCorp.environment}', NOT 'test'. Aborting sync to protect non-test environments.`
);
}
const prodClient = await createSealClient(prodCorp);
const testClient = await createSealClient(testCorp);
const [
prodPref,
testPref,
prodRules,
testRules,
prodVersions,
testVersions,
prodDocsRes,
testDocsRes
] = await Promise.all([
api.getApprovalStylePreferences(prodClient, prodCorp.seal.endpoints.approvalStylePreferences),
api.getApprovalStylePreferences(testClient, testCorp.seal.endpoints.approvalStylePreferences),
api.listApprovalRules(prodClient),
api.listApprovalRules(testClient),
api.listApprovalRuleVersions(prodClient),
api.listApprovalRuleVersions(testClient),
listAllApprovalDocuments(prodClient),
listAllApprovalDocuments(testClient)
]);
const prodDocs = (prodDocsRes.articles || []).filter((d) => !d.isDeleted);
const testDocs = (testDocsRes.articles || []).filter((d) => !d.isDeleted);
const testDocsByTitle = new Map(testDocs.map((d) => [d.title.trim(), d]));
const docsToCreate = [];
const docsToUpdate = [];
const prodTitles = new Set(prodDocs.map((d) => d.title.trim()));
for (const prodDoc of prodDocs) {
const title = prodDoc.title.trim();
const existing = testDocsByTitle.get(title);
if (!existing) {
docsToCreate.push(prodDoc);
continue;
}
const contentChanged = existing.content !== prodDoc.content;
const purposeChanged = (existing.purpose ?? "") !== (prodDoc.purpose ?? "");
const enabledChanged = existing.enabled !== prodDoc.enabled;
const contentTypeChanged = existing.contentType !== prodDoc.contentType;
const statusChanged = (existing.status ?? "") !== (prodDoc.status ?? "");
const scenariosChanged = JSON.stringify([...(existing.scenarios ?? [])].sort()) !==
JSON.stringify([...(prodDoc.scenarios ?? [])].sort());
const tagsChanged = JSON.stringify([...(existing.tags ?? [])].sort()) !==
JSON.stringify([...(prodDoc.tags ?? [])].sort());
if (contentChanged || purposeChanged || enabledChanged || contentTypeChanged || statusChanged || scenariosChanged || tagsChanged) {
docsToUpdate.push({
testId: existing.id,
prodDoc,
reasons: [
...(contentChanged ? ["content"] : []),
...(purposeChanged ? ["purpose"] : []),
...(enabledChanged ? ["enabled"] : []),
...(contentTypeChanged ? ["contentType"] : []),
...(statusChanged ? ["status"] : []),
...(scenariosChanged ? ["scenarios"] : []),
...(tagsChanged ? ["tags"] : [])
]
});
}
}
const docsToDelete = testDocs.filter((td) => !prodTitles.has(td.title.trim()));
const sortedProdVersions = [...prodVersions].sort((a, b) => b.versionNumber - a.versionNumber);
const latestProd = sortedProdVersions[0];
const prodVersionNumber = latestProd?.versionNumber;
const sortedTestVersions = [...testVersions].sort((a, b) => b.versionNumber - a.versionNumber);
const targetTestExpectedVersionNumber = (sortedTestVersions[0]?.versionNumber ?? 0) + 1;
const nextIteration = computeNextSyncIteration(prodCorp.name, prodVersionNumber, testVersions);
const customVersionName = stringOption(args.options["version-name"]) ?? stringOption(args.options.versionName);
const versionName = customVersionName ?? formatSyncVersionName(
prodCorp.name,
prodVersionNumber,
nextIteration,
targetTestExpectedVersionNumber
);
const updatedTestPref = {
...testPref,
tone: prodPref.tone,
language: prodPref.language,
detailLevel: prodPref.detailLevel,
outputFormat: prodPref.outputFormat,
examples: prodPref.examples ?? [],
prohibitedPhrases: prodPref.prohibitedPhrases ?? [],
customInstructions: prodPref.customInstructions,
decisionPreferences: prodPref.decisionPreferences,
thinkingDepthPreference: prodPref.thinkingDepthPreference
};
const versionName = stringOption(args.options["version-name"]) ?? stringOption(args.options.versionName);
const dryRun = booleanOption(args.options["dry-run"]) === true || booleanOption(args.options.dryRun) === true;
const confirmed = booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true;
if (dryRun) {
printJson({
dryRun: true,
source: {
id: prodCorp.id,
name: prodCorp.name,
environment: prodCorp.environment,
latestPublishedVersion: latestProd ? {
versionNumber: latestProd.versionNumber,
versionName: latestProd.versionName
} : null,
documentsCount: prodDocs.length
},
target: {
id: testCorp.id,
name: testCorp.name,
environment: testCorp.environment
},
versionMappingPlan: {
sourceProdVersionNumber: prodVersionNumber ?? null,
sourceProdVersionName: latestProd?.versionName ?? null,
targetTestExpectedVersionNumber,
targetTestPublishVersionName: versionName,
iteration: nextIteration
},
preferencesDiff: {
decisionPreferences: {
before: testPref.decisionPreferences,
after: prodPref.decisionPreferences
},
thinkingDepthPreference: {
before: testPref.thinkingDepthPreference,
after: prodPref.thinkingDepthPreference
}
},
rulesPlan: {
sourceDraftRuleCount: prodRules.rules.length,
targetExistingDraftRuleCount: testRules.rules.length,
toDeleteCount: testRules.rules.length,
toCreateCount: prodRules.rules.length,
rulesToSync: prodRules.rules.map((r, idx) => ({
index: idx + 1,
sourceRuleId: r.id,
sourceRuleCode: r.code ?? idx + 1,
expectedTargetCode: `rule-${idx + 1}`,
description: r.description,
scope: r.scope,
strictness: r.strictness
}))
},
documentsPlan: {
sourceDocumentCount: prodDocs.length,
targetExistingDocumentCount: testDocs.length,
toCreateCount: docsToCreate.length,
toCreate: docsToCreate.map((d) => ({
title: d.title,
purpose: d.purpose,
contentType: d.contentType,
scenarios: d.scenarios
})),
toUpdateCount: docsToUpdate.length,
toUpdate: docsToUpdate.map((d) => ({
targetDocumentId: d.testId,
title: d.prodDoc.title,
reasons: d.reasons
})),
toDeleteCount: docsToDelete.length,
toDelete: docsToDelete.map((d) => ({
targetDocumentId: d.id,
title: d.title
}))
},
publishingPlan: {
targetCorpId: testCorp.id,
publishVersionName: versionName,
publishTarget: "test"
},
hosecloudSyncPlan: buildHosecloudSyncPlan(prodCorp, prodPref),
productionGuarantees: {
prodRulesStayDraft: true,
prodVersionPublished: false
}
});
printJson(await syncTestEnterprise(prodCorp, testCorp, { versionName, dryRun: true }));
return true;
}
const confirmed = booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true;
if (!confirmed) {
const preview = await syncTestEnterprise(prodCorp, testCorp, { versionName, execute: false }) as {
rulesPlan: { sourceDraftRuleCount: number };
documentsPlan: { sourceDocumentCount: number };
};
throw confirmationRequired(
`Refusing to overwrite test enterprise '${testCorp.name}' (${testCorp.id}) with preferences, ${prodRules.rules.length} draft rules, and ${prodDocs.length} knowledge documents from production enterprise '${prodCorp.name}' (${prodCorp.id}) without --yes. This will replace test draft rules, synchronize knowledge documents, and publish a new version on the test enterprise.`,
`Refusing to overwrite test enterprise '${testCorp.name}' (${testCorp.id}) with preferences, ${preview.rulesPlan.sourceDraftRuleCount} draft rules, and ${preview.documentsPlan.sourceDocumentCount} knowledge documents from production enterprise '${prodCorp.name}' (${prodCorp.id}) without --yes. This will replace test draft rules, synchronize knowledge documents, and publish a new version on the test enterprise.`,
`seal-use corps sync-test ${prodCorp.id} --yes`
);
}
// 1. Update style & decision preferences in test enterprise
await api.updateApprovalStylePreferences(testClient, updatedTestPref, testCorp.seal.endpoints.approvalStylePreferences);
// 2. Synchronize knowledge documents in test enterprise (full coverage, delete redundant test documents)
const deletedDocs: Array<{ id: string; title: string }> = [];
for (const doc of docsToDelete) {
await api.deleteApprovalDocument(testClient, doc.id);
deletedDocs.push({ id: doc.id, title: doc.title });
}
const updatedDocs: Array<{ id: string; title: string; reasons: string[] }> = [];
for (const item of docsToUpdate) {
await api.updateApprovalDocument(testClient, item.testId, {
title: item.prodDoc.title,
purpose: item.prodDoc.purpose,
content: item.prodDoc.content,
contentType: item.prodDoc.contentType,
status: item.prodDoc.status,
enabled: item.prodDoc.enabled,
scenarios: item.prodDoc.scenarios && item.prodDoc.scenarios.length > 0 ? item.prodDoc.scenarios : ["audit"],
tags: item.prodDoc.tags
});
updatedDocs.push({ id: item.testId, title: item.prodDoc.title, reasons: item.reasons });
}
const createdDocs: Array<{ id: string; title: string }> = [];
for (const doc of docsToCreate) {
const created = await api.createApprovalDocument(testClient, {
title: doc.title,
purpose: doc.purpose,
content: doc.content,
contentType: doc.contentType,
status: doc.status,
enabled: doc.enabled,
scenarios: doc.scenarios && doc.scenarios.length > 0 ? doc.scenarios : ["audit"],
tags: doc.tags
});
createdDocs.push({ id: created.id, title: created.title });
}
// 3. Clear old draft rules in test enterprise
for (const rule of testRules.rules) {
await api.deleteApprovalRule(testClient, rule.id);
}
// 4. Create new draft rules in test enterprise
const createdRules: any[] = [];
for (const rule of prodRules.rules) {
const created = await api.createApprovalRule(testClient, {
description: rule.description,
scope: rule.scope,
strictness: rule.strictness
});
createdRules.push(created);
}
// 5. Batch recode rules in test enterprise
const recodeResult = await api.recodeApprovalRules(testClient) as { ok: boolean; status: number };
if (!recodeResult.ok) {
throw new Error(`Failed to recode test approval rules: HTTP ${recodeResult.status}`);
}
// 6. Sync HoseCloud integrations before publishing the test version. This
// keeps a Hose configuration failure from leaving a newly published
// version behind, although the overall multi-request operation remains
// non-transactional.
const hosecloudSync = await syncHosecloudIntegrationsToTest(prodCorp, testCorp, prodClient, testClient);
// 7. Publish new version in test enterprise
const published = await api.publishApprovalRuleVersion(testClient, versionName);
try {
savePublishedRuleVersionSnapshot(testCorp.id, published.version, createdRules);
} catch {}
const publishedRules = published.version.rules ?? [];
const ruleMapping = prodRules.rules.map((prodRule, idx) => {
const testDraft = createdRules[idx];
const publishedRule = publishedRules[idx];
return {
index: idx + 1,
sourceRuleId: prodRule.id,
sourceRuleCode: prodRule.code ?? idx + 1,
targetRuleId: testDraft?.id ?? "",
targetRuleCode: publishedRule?.code ?? `rule-${idx + 1}`,
description: prodRule.description,
scope: prodRule.scope,
strictness: prodRule.strictness
};
});
const versionMapping = {
sourceProdVersionNumber: prodVersionNumber ?? null,
sourceProdVersionName: latestProd?.versionName ?? null,
targetTestVersionNumber: published.version.versionNumber,
targetTestVersionName: published.version.versionName ?? null
};
let mappingSavedTo: string | undefined;
try {
mappingSavedTo = saveRuleMappingSnapshot({
syncedAt: new Date().toISOString(),
source: {
id: prodCorp.id,
name: prodCorp.name,
latestPublishedVersionNumber: prodVersionNumber ?? null,
latestPublishedVersionName: latestProd?.versionName ?? null
},
target: {
id: testCorp.id,
name: testCorp.name,
publishedVersionNumber: published.version.versionNumber,
publishedVersionName: published.version.versionName,
rulesCount: published.rulesCount
},
versionMapping,
ruleMapping
});
} catch {}
printJson({
success: true,
syncedAt: new Date().toISOString(),
source: {
id: prodCorp.id,
name: prodCorp.name,
environment: prodCorp.environment,
latestPublishedVersion: latestProd ? {
versionNumber: latestProd.versionNumber,
versionName: latestProd.versionName
} : null,
draftRulesCount: prodRules.rules.length,
documentsCount: prodDocs.length
},
target: {
id: testCorp.id,
name: testCorp.name,
environment: testCorp.environment,
deletedDraftRulesCount: testRules.rules.length,
createdDraftRulesCount: createdRules.length,
publishedVersion: {
id: published.version.id,
versionNumber: published.version.versionNumber,
versionName: published.version.versionName,
rulesCount: published.rulesCount
}
},
documents: {
sourceCount: prodDocs.length,
targetExistingCount: testDocs.length,
createdCount: createdDocs.length,
created: createdDocs,
updatedCount: updatedDocs.length,
updated: updatedDocs,
deletedCount: deletedDocs.length,
deleted: deletedDocs
},
versionMapping,
ruleMapping,
...(mappingSavedTo ? { mappingSavedTo } : {}),
hosecloudSync,
productionGuarantees: {
prodRulesStayDraft: true,
prodVersionPublished: false
}
});
printJson(await syncTestEnterprise(prodCorp, testCorp, { versionName, execute: true }));
return true;
}
@@ -417,7 +76,6 @@ export async function handleCorpSync(
);
}
}
if (!dryRun && !confirmed) {
throw confirmationRequired(
"Refusing to replay approval records without --confirm. Use --dry-run to preview the payload without sending it.",
@@ -427,23 +85,23 @@ export async function handleCorpSync(
const recordId = stringOption(args.options.recordId) ?? stringOption(args.options["record-id"]) ?? stringOption(args.options.id);
const recordIdsRaw = stringOption(args.options.recordIds) ?? stringOption(args.options["record-ids"]);
const recordIds = recordIdsRaw ? recordIdsRaw.split(",").map((s) => s.trim()).filter(Boolean) : undefined;
const recordIds = recordIdsRaw ? recordIdsRaw.split(",").map((value) => value.trim()).filter(Boolean) : undefined;
const sn = stringOption(args.options.sn) ?? stringOption(args.options.documentSn) ?? stringOption(args.options["document-sn"]);
const snsRaw = stringOption(args.options.sns) ?? stringOption(args.options["document-sns"]);
const sns = snsRaw ? snsRaw.split(",").map((s) => s.trim()).filter(Boolean) : undefined;
const sns = snsRaw ? snsRaw.split(",").map((value) => value.trim()).filter(Boolean) : undefined;
const limit = numberOption(args.options.limit) ?? (!recordId && !recordIds && !sn && !sns ? 1 : undefined);
const status = stringOption(args.options.status);
const startDate = stringOption(args.options.startDate) ?? stringOption(args.options["start-date"]);
const endDate = stringOption(args.options.endDate) ?? stringOption(args.options["end-date"]);
const query: ReplayRecordsQuery = {
recordId,
recordIds,
sn,
sns,
limit,
status: stringOption(args.options.status),
startDate: stringOption(args.options.startDate) ?? stringOption(args.options["start-date"]),
endDate: stringOption(args.options.endDate) ?? stringOption(args.options["end-date"])
};
const prodClient = await createSealClient(prodCorp);
const testClient = prodCorp.id === testCorp.id ? prodClient : await createSealClient(testCorp);
const selector = stringOption(args.options.webhook) ?? stringOption(args.options.selector);
const snSuffix = stringOption(args.options.snSuffix) ?? stringOption(args.options["sn-suffix"]);
const snPrefix = stringOption(args.options.snPrefix) ?? stringOption(args.options["sn-prefix"]);
const docIdSuffix = stringOption(args.options.docIdSuffix) ?? stringOption(args.options["doc-id-suffix"]);
const docIdPrefix = stringOption(args.options.docIdPrefix) ?? stringOption(args.options["doc-id-prefix"]);
const query: ReplayRecordsQuery = { recordId, recordIds, sn, sns, limit, status, startDate, endDate };
console.error(`[corps-replay-test] 正式企业「${prodCorp.name}」(${prodCorp.id}) -> 测试企业「${testCorp.name}」(${testCorp.id})`);
const result = await executeApprovalRunsReplay({
query,
@@ -451,187 +109,27 @@ export async function handleCorpSync(
targetClient: testClient,
sourceCorp: prodCorp,
targetCorp: testCorp,
webhookSelector: selector,
snPrefix,
snSuffix,
docIdPrefix,
docIdSuffix,
webhookSelector: stringOption(args.options.webhook) ?? stringOption(args.options.selector),
snPrefix: stringOption(args.options.snPrefix) ?? stringOption(args.options["sn-prefix"]),
snSuffix: stringOption(args.options.snSuffix) ?? stringOption(args.options["sn-suffix"]),
docIdPrefix: stringOption(args.options.docIdPrefix) ?? stringOption(args.options["doc-id-prefix"]),
docIdSuffix: stringOption(args.options.docIdSuffix) ?? stringOption(args.options["doc-id-suffix"]),
dryRun
});
if (dryRun) {
console.error(`[corps-replay-test] 预览模式:已成功从 ${prodCorp.name} 提取单据并转换为 Webhook Payload(未实际推送)。`);
console.log(JSON.stringify(result, null, 2));
printJson(result);
return true;
}
if (result.success) {
if (result.totalCount === 1 && result.replayedDocument) {
console.error(`🟢 成功重放单据「${result.replayedDocument.documentSN}」至 ${testCorp.name} (${result.targetWebhook?.name ?? "Webhook 通道"})`);
} else {
console.error(`🟢 成功重放 ${result.successCount} 条单据(来自「${prodCorp.name}」)至「${testCorp.name}」(${result.targetWebhook?.name ?? "Webhook 通道"})`);
}
console.error(`🟢 成功重放 ${result.successCount} 条单据(来自「${prodCorp.name}」)至「${testCorp.name}」(${result.targetWebhook?.name ?? "Webhook 通道"})`);
} else {
console.error(`🔴 单据重放部分或全部失败(成功 ${result.successCount} 条,失败 ${result.failureCount} 条)至「${testCorp.name}」`);
}
console.error(`👉 Next action: seal-use approval-runs list --corp ${testCorp.id} --limit ${result.totalCount}`);
console.log(JSON.stringify(result, null, 2));
if (!result.success) {
throw new CliError(`Approval record replay failed: ${result.failureCount} record(s) failed.`, 1);
}
printJson(result);
if (!result.success) throw new CliError(`Approval record replay failed: ${result.failureCount} record(s) failed.`, 1);
return true;
}
return false;
}
async function listAllApprovalDocuments(client: KyInstance) {
const pageSize = 100;
const documents: Awaited<ReturnType<typeof api.listApprovalDocuments>>["articles"] = [];
let offset = 0;
while (true) {
const page = await api.listApprovalDocuments(client, { offset, limit: pageSize });
documents.push(...page.articles);
offset += page.articles.length;
if (page.articles.length === 0 || page.articles.length < pageSize) break;
if (page.total !== undefined && offset >= page.total) break;
}
return { articles: documents, total: documents.length };
}
/**
* Build the outboundName for a test-env hosecloud integration.
* Format: {企业名前7字}(Seal测) — capped at 13 chars total.
*/
export function buildTestHosecloudOutboundName(corpName: string): string {
const suffix = "(Seal测)";
// "(Seal测)" is 7 chars; leave 6 chars for the corp name prefix.
const maxPrefix = 13 - suffix.length;
const prefix = [...corpName].slice(0, maxPrefix).join("");
return prefix + suffix;
}
/**
* Sync hosecloud integrations from the production Seal enterprise into the
* test Seal enterprise. Rules:
* - Only runs when prodCorp.source.type === "hose" (credentials available locally)
* - outboundName: buildTestHosecloudOutboundName(prodCorp.name)
* - mode: always "assisted"
* - apiKey/apiSecret: from prodCorp.source.appKey / appSecurity
* - apiOrigin/customApiUrl: copied verbatim from the production integration config
* - signKey: existing test integration keeps its key; new ones get a fresh random key
* - Does NOT call syncHosecloudOutbound (no sync to 合思)
*/
interface HosecloudSyncResult {
skipped: boolean;
reason?: string;
synced?: Array<{ signKey: string; outboundName: string; corporationId: string; action: "created" | "updated" }>;
}
function buildHosecloudSyncPlan(prodCorp: CorpConfig, prodPref: any) {
if (prodCorp.source.type !== "hose") {
return {
sourceType: prodCorp.source.type,
skipped: true,
reason: "prod source is not hose; no hosecloud credentials available"
};
}
const rawHose = (prodPref.integrations ?? []).filter((i: any) => i.type === "hosecloud");
const seen = new Set<string>();
const distinct = rawHose.filter((i: any) => {
const cid = i.corporationId ?? prodCorp.id;
if (seen.has(cid)) return false;
seen.add(cid);
return true;
});
return {
sourceType: "hose",
outboundName: buildTestHosecloudOutboundName(prodCorp.name),
targetMode: "assisted",
integrationsCount: distinct.length,
integrations: distinct.map((i: any) => ({
corporationId: i.corporationId,
apiOrigin: i.apiOrigin,
customApiUrl: i.customApiUrl
}))
};
}
async function syncHosecloudIntegrationsToTest(
prodCorp: CorpConfig,
testCorp: CorpConfig,
prodClient: KyInstance,
testClient: KyInstance
): Promise<HosecloudSyncResult> {
if (prodCorp.source.type !== "hose") {
return { skipped: true, reason: "prod source is not hose; no hosecloud credentials available" };
}
const appKey = (prodCorp.source.appKey ?? prodCorp.source.key)?.trim();
const appSecurity = (prodCorp.source.appSecurity ?? prodCorp.source.password)?.trim();
if (!appKey || !appSecurity) {
return { skipped: true, reason: "prod hose source missing appKey/appSecurity (or key/password)" };
}
const [prodPref, testPref] = await Promise.all([
api.getApprovalStylePreferences(prodClient, prodCorp.seal.endpoints.approvalStylePreferences),
api.getApprovalStylePreferences(testClient, testCorp.seal.endpoints.approvalStylePreferences)
]);
const prodIntegrations: any[] = (prodPref.integrations ?? []).filter((i: any) => i.type === "hosecloud");
if (prodIntegrations.length === 0) {
return { skipped: true, reason: "prod Seal enterprise has no hosecloud integrations configured" };
}
// Deduplicate prod integrations by corporationId:
// Production enterprises may have multiple integrations (e.g. "assisted" + "fully_automatic")
// with the same corporationId. For the test environment, exactly one assisted integration per
// corporationId is needed.
const seenCorpIds = new Set<string>();
const distinctProdIntegrations: any[] = [];
for (const item of prodIntegrations) {
const cid = item.corporationId ?? prodCorp.id;
if (!seenCorpIds.has(cid)) {
seenCorpIds.add(cid);
distinctProdIntegrations.push({ ...item, corporationId: cid });
}
}
const testIntegrations: any[] = testPref.integrations ?? [];
const testByCorpId = new Map<string, any>(
testIntegrations.filter((i: any) => i.type === "hosecloud").map((i: any) => [i.corporationId, i])
);
const outboundName = buildTestHosecloudOutboundName(prodCorp.name);
const synced: HosecloudSyncResult["synced"] = [];
const nextHosecloudIntegrations: any[] = distinctProdIntegrations.map((prodInt: any) => {
const existing = testByCorpId.get(prodInt.corporationId);
const signKey = existing?.signKey ?? randomBytes(6).toString("hex");
synced!.push({
signKey,
outboundName,
corporationId: prodInt.corporationId,
action: existing ? "updated" : "created"
});
return {
type: "hosecloud",
signKey,
outboundName,
mode: "assisted",
apiKey: appKey,
apiSecret: appSecurity,
apiOrigin: prodInt.apiOrigin,
...(prodInt.customApiUrl ? { customApiUrl: prodInt.customApiUrl } : {}),
corporationId: prodInt.corporationId
};
});
// Merge: keep non-hosecloud entries + newly built hosecloud entries
const otherIntegrations = testIntegrations.filter((i: any) => i.type !== "hosecloud");
await api.updateApprovalStylePreferences(
testClient,
{ ...testPref, integrations: [...otherIntegrations, ...nextHosecloudIntegrations] },
testCorp.seal.endpoints.approvalStylePreferences
);
return { skipped: false, synced };
}