Split corps command by domain

This commit is contained in:
gitea committed 2026-09-22 14:25:06 +08:00
1 parent 1987b45336
commit f5be38d112
7 files changed
+2034 -2333

No files matched your search

+16 -2152
View File
File diff suppressed because it is too large. Load diff
+155
View File
@@ -0,0 +1,155 @@
import { updateCorpConfig } from "../../../core/config/loader.js";
import { selectCorp } from "../../helpers.js";
import { confirmationRequired, usageError } from "../../errors.js";
import { booleanOption, stringOption } from "../../parser.js";
import { printJson } from "../../printer.js";
import type { ParsedArgs } from "../../types.js";
export async function handleCorpBindings(
action: string | undefined,
maybeName: string | undefined,
args: ParsedArgs
): Promise<boolean> {
if (action === "bind-test") {
let prodId: string | undefined;
let testId: string | undefined;
if (maybeName && args.command[3]) {
prodId = maybeName;
testId = args.command[3];
} else if (maybeName) {
const corpOption = stringOption(args.options.corp);
const testCorpOption = stringOption(args.options["test-corp"]) ?? stringOption(args.options.testCorp);
if (corpOption) {
prodId = corpOption;
testId = maybeName;
} else if (testCorpOption) {
prodId = maybeName;
testId = testCorpOption;
}
}
if (!prodId || !testId) {
throw usageError(
"Usage: seal-use corps bind-test <prodCorpId> <testCorpId> [--confirm] [--force]\n" +
" or: seal-use corps bind-test <testCorpId> --corp <prodCorpId> [--confirm] [--force]"
);
}
const prodCorp = selectCorp(prodId);
const testCorp = selectCorp(testId);
if (prodCorp.id === testCorp.id) {
throw usageError(`Cannot bind enterprise '${prodCorp.id}' to itself.`);
}
if (prodCorp.prodCorpId && prodCorp.prodCorpId !== testCorp.id) {
throw usageError(
`Cannot use '${prodCorp.id}' as a production enterprise because it is already registered as a test enterprise for '${prodCorp.prodCorpId}'. Multi-tier chaining is not permitted.`
);
}
if (testCorp.testCorpId && testCorp.testCorpId !== prodCorp.id) {
throw usageError(
`Cannot bind '${testCorp.id}' as a test enterprise because it already has a bound test enterprise '${testCorp.testCorpId}'. Multi-tier chaining is not permitted.`
);
}
const force = booleanOption(args.options.force) === true;
if (
(prodCorp.testCorpId && prodCorp.testCorpId !== testCorp.id) ||
(testCorp.prodCorpId && testCorp.prodCorpId !== prodCorp.id)
) {
if (!force) {
throw confirmationRequired(
`Enterprise binding conflict: production enterprise '${prodCorp.id}' is bound to '${prodCorp.testCorpId ?? "none"}', and test enterprise '${testCorp.id}' is bound to '${testCorp.prodCorpId ?? "none"}'. Overwriting an existing binding requires --force and --confirm.`,
`seal-use corps bind-test ${prodCorp.id} ${testCorp.id} --confirm --force`
);
}
}
const confirmed = booleanOption(args.options.confirm) === true || booleanOption(args.options.yes) === true;
if (!confirmed) {
const forceFlag = force ? " --force" : "";
throw confirmationRequired(
`Refusing to bind test enterprise '${testCorp.name}' (${testCorp.id}) to production enterprise '${prodCorp.name}' (${prodCorp.id}) without --confirm. Enterprise binding establishes 1-to-1 sync pairing and marks '${testCorp.id}' as a test environment.`,
`seal-use corps bind-test ${prodCorp.id} ${testCorp.id} --confirm${forceFlag}`
);
}
if (prodCorp.testCorpId && prodCorp.testCorpId !== testCorp.id) {
try {
updateCorpConfig(prodCorp.testCorpId, { prodCorpId: undefined });
} catch {}
}
if (testCorp.prodCorpId && testCorp.prodCorpId !== prodCorp.id) {
try {
updateCorpConfig(testCorp.prodCorpId, { testCorpId: undefined });
} catch {}
}
const updatedProd = updateCorpConfig(prodCorp.id, {
environment: "production",
testCorpId: testCorp.id
});
const updatedTest = updateCorpConfig(testCorp.id, {
environment: "test",
prodCorpId: prodCorp.id
});
printJson({
success: true,
productionEnterprise: {
id: updatedProd.id,
name: updatedProd.name,
environment: updatedProd.environment,
testCorpId: updatedProd.testCorpId
},
testEnterprise: {
id: updatedTest.id,
name: updatedTest.name,
environment: updatedTest.environment,
prodCorpId: updatedTest.prodCorpId
}
});
return true;
}
if (action === "unbind-test") {
const targetId = maybeName ?? stringOption(args.options.corp);
const corp = selectCorp(targetId);
if (!corp.testCorpId && !corp.prodCorpId) {
printJson({
unbound: false,
message: `Enterprise '${corp.name}' (${corp.id}) does not have an active test enterprise binding.`
});
return true;
}
const prodId = corp.testCorpId ? corp.id : corp.prodCorpId!;
const testId = corp.testCorpId ? corp.testCorpId : corp.id;
const confirmed = booleanOption(args.options.confirm) === true || booleanOption(args.options.yes) === true;
if (!confirmed) {
throw confirmationRequired(
`Refusing to unbind production enterprise '${prodId}' and test enterprise '${testId}' without --confirm.`,
`seal-use corps unbind-test ${corp.id} --confirm`
);
}
updateCorpConfig(prodId, { testCorpId: undefined });
try {
updateCorpConfig(testId, { prodCorpId: undefined });
} catch {}
printJson({
success: true,
unboundProduction: prodId,
unboundTest: testId
});
return true;
}
return false;
}
+739
View File
@@ -0,0 +1,739 @@
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import {
assertHoseAssistTenantMatches,
exchangeHoseAssistLink,
fetchHoseOpenApiKeysFromLink,
fetchHoseRoleDefGroups,
fetchHoseRoleStaffs,
fetchHoseStaffDetails,
maskHoseSecurity,
parseHoseAssistLink,
probeHoseDomain,
resolveHoseAssistLinkDetails,
type HoseOpenApiKey
} from "../../../core/auth/hose.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";
import { CliError } from "../../errors.js";
import { selectCorp } from "../../helpers.js";
import {
booleanOption,
jsonObject,
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";
export async function handleCorpOnboarding(
action: string | undefined,
maybeName: string | undefined,
args: ParsedArgs
): Promise<boolean> {
if (action === "probe-hose") {
await probeHoseCorp(jsonObject(args.json));
return true;
}
if (action === "hose-staffs") {
await queryHoseStaffs(jsonObject(args.json));
return true;
}
if (action === "add-hose-persistent" || action === "add-hose") {
if (action === "add-hose") {
console.error("⚠️ Notice: 'add-hose' is a compatibility alias; use 'add-hose-persistent' for durable Hose credentials.");
}
const jsonPayload = jsonObject(args.json);
const merged = {
...jsonPayload,
...(args.options.staffName ? { staffName: stringOption(args.options.staffName) } : {}),
...(args.options["staff-name"] ? { staffName: stringOption(args.options["staff-name"]) } : {}),
...(args.options.staffPhone ? { staffPhone: stringOption(args.options.staffPhone) } : {}),
...(args.options["staff-phone"] ? { staffPhone: stringOption(args.options["staff-phone"]) } : {}),
...(args.options.name ? { name: stringOption(args.options.name) } : {}),
...(args.options.domain ? { domain: stringOption(args.options.domain) } : {}),
...(args.options.corpId ? { corpId: stringOption(args.options.corpId) } : {}),
...(args.options["corp-id"] ? { corpId: stringOption(args.options["corp-id"]) } : {}),
...(args.options.appKey ? { appKey: stringOption(args.options.appKey) } : {}),
...(args.options["app-key"] ? { appKey: stringOption(args.options["app-key"]) } : {}),
...(args.options.appSecurity ? { appSecurity: stringOption(args.options.appSecurity) } : {}),
...(args.options["app-security"] ? { appSecurity: stringOption(args.options["app-security"]) } : {}),
...(args.options.force !== undefined ? { force: booleanOption(args.options.force) } : {}),
...(args.options.overwrite !== undefined ? { overwrite: booleanOption(args.options.overwrite) } : {})
};
await addHoseCorp(merged);
return true;
}
if (action === "add-hose-web-session") {
const jsonPayload = jsonObject(args.json);
const merged = {
...jsonPayload,
...(args.options.name ? { name: stringOption(args.options.name) } : {}),
...(args.options.domain ? { baseUrl: stringOption(args.options.domain) } : {}),
...(args.options["base-url"] ? { baseUrl: stringOption(args.options["base-url"]) } : {}),
...(args.options.corpId ? { corpId: stringOption(args.options.corpId) } : {}),
...(args.options["corp-id"] ? { corpId: stringOption(args.options["corp-id"]) } : {}),
...(args.options.staffId ? { staffId: stringOption(args.options.staffId) } : {}),
...(args.options["staff-id"] ? { staffId: stringOption(args.options["staff-id"]) } : {}),
...(args.options.accessToken ? { accessToken: stringOption(args.options.accessToken) } : {}),
...(args.options["access-token"] ? { accessToken: stringOption(args.options["access-token"]) } : {}),
...(args.options.overwrite !== undefined ? { overwrite: booleanOption(args.options.overwrite) } : {}),
...(args.options["dry-run"] !== undefined ? { dryRun: booleanOption(args.options["dry-run"]) } : {})
};
await addHoseWebSessionCorp(merged);
return true;
}
if (action === "add-seal-bearer" || action === "add-seal") {
if (action === "add-seal") {
console.error("⚠️ Notice: 'add-seal' is a compatibility alias; use 'add-seal-bearer' for Seal Bearer credentials.");
}
const jsonPayload = jsonObject(args.json);
const merged = {
...jsonPayload,
...(args.options.name ? { name: stringOption(args.options.name) } : {}),
...(args.options.token ? { token: stringOption(args.options.token) } : {}),
...(args.options.sealUrl ? { sealUrl: stringOption(args.options.sealUrl) } : {}),
...(args.options.url ? { sealUrl: stringOption(args.options.url) } : {}),
...(args.options.force !== undefined ? { force: booleanOption(args.options.force) } : {}),
...(args.options.overwrite !== undefined ? { overwrite: booleanOption(args.options.overwrite) } : {})
};
await addSealCorp(merged);
return true;
}
if (action === "add-link") {
const link = maybeName ?? stringOption(args.options.link) ?? stringOption(args.options.url);
if (!link) {
throw new Error("Usage: seal-use corps add-link <url> [--name <customName>] [--elevate-hose] [--overwrite]");
}
const dryRun = booleanOption(args.options["dry-run"]) === true || booleanOption(args.options.dryRun) === true;
const legacyAsHose = booleanOption(args.options["as-hose"]) === true || booleanOption(args.options.hose) === true;
const elevateHose = booleanOption(args.options["elevate-hose"]) === true || legacyAsHose;
if (legacyAsHose && !booleanOption(args.options["elevate-hose"])) {
console.error("⚠️ Notice: '--as-hose' is deprecated; use '--elevate-hose' to request Hose credential elevation.");
}
if (elevateHose) {
const winner = scoreAssistLink(link)[0];
if (winner?.kind === "seal-delegate") {
throw new Error("Option --elevate-hose cannot be used with a Seal native delegate link. Seal delegate links directly authenticate to Seal.");
}
await addLinkAsHoseCorp(
link,
stringOption(args.options.name),
booleanOption(args.options.overwrite) === true,
booleanOption(args.options.force) === true,
dryRun,
{
appKey: stringOption(args.options["app-key"]) ?? stringOption(args.options.appKey),
keyId: stringOption(args.options["key-id"]) ?? stringOption(args.options.keyId)
}
);
return true;
}
await addLinkCorp(link, stringOption(args.options.name), booleanOption(args.options.overwrite) === true, dryRun);
return true;
}
if (action === "extract-keys" || action === "extract-key" || action === "extract-hose-keys" || action === "hose-extract-keys") {
const link = maybeName ?? stringOption(args.options.link) ?? stringOption(args.options.url);
if (!link) {
throw new Error("Usage: seal-use corps hose-extract-keys <url> [--reveal] [--save] [--app-key <key>] [--key-id <id>] [--name <customName>] [--overwrite]");
}
await extractKeysFromLinkAction(link, {
reveal: booleanOption(args.options.reveal) === true || booleanOption(args.options.r) === true || booleanOption(args.options.plain) === true,
save: booleanOption(args.options.save) === true || booleanOption(args.options.add) === true,
name: stringOption(args.options.name),
overwrite: booleanOption(args.options.overwrite) === true,
force: booleanOption(args.options.force) === true,
appKey: stringOption(args.options["app-key"]) ?? stringOption(args.options.appKey),
keyId: stringOption(args.options["key-id"]) ?? stringOption(args.options.keyId)
});
return true;
}
if (action === "keys" || action === "hose-keys") {
const target = maybeName ?? stringOption(args.options.link) ?? stringOption(args.options.url) ?? stringOption(args.options.corp);
const reveal = booleanOption(args.options.reveal) === true || booleanOption(args.options.r) === true || booleanOption(args.options.plain) === true;
if (target && (target.startsWith("http://") || target.startsWith("https://"))) {
await extractKeysFromLinkAction(target, {
reveal,
save: booleanOption(args.options.save) === true || booleanOption(args.options.add) === true,
name: stringOption(args.options.name),
overwrite: booleanOption(args.options.overwrite) === true,
force: booleanOption(args.options.force) === true,
appKey: stringOption(args.options["app-key"]) ?? stringOption(args.options.appKey),
keyId: stringOption(args.options["key-id"]) ?? stringOption(args.options.keyId)
});
return true;
}
await showCorpKeysAction(target, { reveal });
return true;
}
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,
expiresIn: optionalNumber(input, "expiresIn"),
expiresAt: optionalString(input, "expiresAt"),
staffId: suppliedStaffId ?? details.staffId,
sealUrl: session.sealUrl,
remote: identity,
overwrite: input.overwrite === true
});
}
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
});
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 }
);
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 });
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
});
}
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`);
console.error(dryRun
? `ℹ️ [合思子域提权] 已选定合思 OpenAPI 凭据 (appKey: ${selectedKey.appKey}, 应用: "${selectedKey.name || "未命名应用"}"),正在生成预览...`
: `ℹ️ [合思子域提权] 已选定合思 OpenAPI 凭据 (appKey: ${selectedKey.appKey}, 应用: "${selectedKey.name || "未命名应用"}"),正在初始化为长期合思标准配置...`);
if (dryRun) {
printJson({
dryRun: true,
kind: "hose",
provider: "hose",
corpId: result.corpId,
corpName: result.corpName,
baseUrl: result.baseUrl,
staffId: result.staffId,
selectedKey: {
id: selectedKey.id,
name: selectedKey.name || "-",
appKey: selectedKey.appKey,
appSecurity: maskHoseSecurity(selectedKey.appSecurity),
active: selectedKey.active
}
});
return;
}
await addHoseCorp({ domain: result.baseUrl, appKey: selectedKey.appKey, appSecurity: selectedKey.appSecurity, corpId: result.corpId, name: name ?? result.corpName, staffId: result.staffId, overwrite, force });
}
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;
if (options.save) {
const selectedKey = selectHoseOpenApiKey(result.keys, result.corpId, { appKey: options.appKey, keyId: options.keyId }, `seal-use corps hose-extract-keys "<url>" --save`);
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 });
return;
}
if (!reveal) console.error("ℹ️ [合思子域提权] 成功提取合思 (Hose) OpenAPI 密钥。接入密码默认脱敏,附加 --reveal (或 -r) 可查看完整 appSecurity 明文;附加 --save 可将临时会话提权并持久化为标准合思企业。\n");
else console.error("⚠️ [合思子域提权] 正在以明文展示合思 (Hose) appSecurity 接入密码,请妥善保管敏感凭据。\n");
printJson({
provider: "hose",
capability: "privilege-elevation",
corpId: result.corpId,
corpName: result.corpName ?? result.corpId,
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
}))
});
}
export async function showCorpKeysAction(targetCorpId: string | undefined, options: { reveal?: boolean }) {
const corp = selectCorp(targetCorpId);
const reveal = options.reveal === true;
if (corp.source.type !== "hose") {
throw new CliError(`【合思子域专享能力】当前企业「${corp.name}」(id: ${corp.id}) 为原生 Seal (${corp.source.type}) 租户,非合思 (Hose/合思云/易快报) 渠道企业。\n` +
"OpenAPI 密钥查询与提权能力专属于合思生态租户(用于从合思协助链接或合思凭据中提取开发者密钥提升权限等级),非合思渠道企业不支持此能力。", 2);
}
const appKey = corp.source.appKey ?? corp.source.key;
const appSecurity = corp.source.appSecurity ?? corp.source.password;
if (!reveal) console.error("💡 [合思子域] 接入密码默认脱敏,附加 --reveal (或 -r) 可查看完整 appSecurity 明文。\n");
else console.error("⚠️ [合思子域] 正在以明文展示合思 appSecurity 接入密码,请妥善保管敏感凭据。\n");
printJson({
provider: "hose",
capability: "privilege-elevation",
corpId: corp.id,
corpName: corp.name,
domain: corp.source.domain,
staffId: corp.source.staffId,
appKey: appKey ?? "-",
appSecurity: appSecurity ? (reveal ? appSecurity : maskHoseSecurity(appSecurity)) : "-",
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> };
}
+224
View File
@@ -0,0 +1,224 @@
import {
findCorpConfigFile,
loadCorpConfigs,
loadGlobalConfig,
saveGlobalConfig,
updateCorpConfig
} from "../../../core/config/loader.js";
import { filterCorpsFuzzy } from "../../../core/search/fuzzy.js";
import { sortCorpsByUsageAndRecency } from "../../../core/stats/usage-tracker.js";
import type { CorpEnvironment } from "../../../core/config/types.js";
import { selectCorp } from "../../helpers.js";
import { confirmationRequired, usageError } from "../../errors.js";
import { booleanOption, numberOption, optionalString, stringOption } from "../../parser.js";
import { printJson } from "../../printer.js";
import type { ParsedArgs } from "../../types.js";
import { formatSafeSourceDetail, resolveCorpSealUrl } from "./shared.js";
export async function handleCorpOverview(
action: string | undefined,
maybeName: string | undefined,
args: ParsedArgs
): Promise<boolean> {
if (!action || action === "list" || action === "search" || action === "find") {
const rawQuery = (
maybeName ?? stringOption(args.options.query) ?? stringOption(args.options.q)
)?.trim();
const isStrict = booleanOption(args.options.strict) === true;
const envFilter = (
stringOption(args.options.env) ?? stringOption(args.options.environment)
)?.trim().toLowerCase();
if ((action === "search" || action === "find") && !rawQuery && !envFilter) {
throw usageError("Usage: seal-use corps search <query> [--env <production|test>] [--strict]");
}
const corpId = stringOption(args.options.corp);
const allCorps = loadCorpConfigs();
const globalConfig = loadGlobalConfig();
const currentCorpId = corpId ?? (
globalConfig.stateful
? globalConfig.defaultCorpId ?? allCorps[0]?.id
: undefined
);
let filtered = allCorps;
if (envFilter) {
filtered = filtered.filter((item) => (item.environment ?? "production").toLowerCase() === envFilter);
}
if (rawQuery) {
filtered = filterCorpsFuzzy(filtered, rawQuery, { strict: isStrict });
}
if (allCorps.length === 0) {
console.error("提示:当前未检测到企业配置。你可以使用 seal-use corps add-hose-persistent、add-hose-web-session 或 add-seal-bearer 添加企业,或运行 seal-use help 查看说明。");
} else if (isStrict && filtered.length === 0 && (action === "search" || action === "find") && rawQuery) {
console.error(`提示:未在严格模式下匹配到企业 "${rawQuery}"。可以尝试省略 --strict 进行智能软搜索。`);
}
// Search results are already ranked by match confidence. Usage sorting is
// useful for an unfiltered list, but would otherwise discard relevance
// ordering for a query.
const sorted = rawQuery ? filtered : sortCorpsByUsageAndRecency(filtered, currentCorpId);
const isList = !action || action === "list";
const isAll = booleanOption(args.options.all) === true;
const limitOpt = numberOption(args.options.limit);
const defaultLimit = 10;
const effectiveLimit = limitOpt !== undefined
? Math.max(1, limitOpt)
: (isList && !isAll ? defaultLimit : undefined);
let displayList = sorted;
if (effectiveLimit !== undefined && sorted.length > effectiveLimit) {
displayList = sorted.slice(0, effectiveLimit);
if (isList && !isAll && limitOpt === undefined) {
console.error(
`ℹ️ 当前共有 ${sorted.length} 家企业,已按最近 7 天使用频次展示前 ${effectiveLimit} 家。\n` +
`👉 查看全部请添加: seal-use corps list --all\n` +
`👉 检索指定企业请使用: seal-use corps search <keyword>`
);
}
}
printJson(displayList.map((item) => ({
id: item.id,
name: item.name,
environment: item.environment ?? "production",
sourceType: item.source.type,
provider: (item.source as any).provider ?? item.source.type,
staffId: item.source.staffId,
testCorpId: item.testCorpId,
prodCorpId: item.prodCorpId,
current: item.id === currentCorpId
})));
return true;
}
if (action === "get" || action === "show") {
const targetCorpId = maybeName ?? stringOption(args.options.corp);
if (!targetCorpId) {
throw usageError("Usage: seal-use corps get <corpId>");
}
const corp = selectCorp(targetCorpId);
const configFile = findCorpConfigFile(corp.id);
const sealUrl = resolveCorpSealUrl(corp);
printJson({
id: corp.id,
name: corp.name,
environment: corp.environment ?? "production",
configFile,
seal: {
url: sealUrl,
tenantSlug: corp.seal.tenantSlug ?? (corp.source as any).tenantSlug,
customHeaderNames: corp.seal.headers ? Object.keys(corp.seal.headers) : [],
customCookieNames: corp.seal.cookies ? Object.keys(corp.seal.cookies) : [],
endpoints: corp.seal.endpoints
},
source: formatSafeSourceDetail(corp.source),
relations: {
testCorpId: corp.testCorpId,
prodCorpId: corp.prodCorpId
},
auth: {
refreshTtl: corp.auth.refreshTtl
}
});
return true;
}
if (action === "current") {
const corp = selectCorp(stringOption(args.options.corp));
printJson({
id: corp.id,
name: corp.name,
environment: corp.environment ?? "production",
sourceType: corp.source.type,
provider: (corp.source as any).provider ?? corp.source.type,
staffId: corp.source.staffId,
testCorpId: corp.testCorpId,
prodCorpId: corp.prodCorpId
});
return true;
}
if (action === "mark" || action === "mark-test" || action === "mark-prod") {
const corpId = maybeName ?? stringOption(args.options.corp);
if (!corpId) {
throw usageError("Usage: seal-use corps mark <corpId> --env <production|test> [--confirm]");
}
const corp = selectCorp(corpId);
const targetEnv = (
action === "mark-test"
? "test"
: action === "mark-prod"
? "production"
: (stringOption(args.options.env) ?? stringOption(args.options.environment))
) as CorpEnvironment | undefined;
if (targetEnv !== "production" && targetEnv !== "test") {
throw usageError("Usage: seal-use corps mark <corpId> --env <production|test> [--confirm]");
}
const confirmed = booleanOption(args.options.confirm) === true || booleanOption(args.options.yes) === true;
if (!confirmed) {
throw confirmationRequired(
`Refusing to change environment tag of enterprise '${corp.name}' (${corp.id}) to '${targetEnv}' without --confirm. Marking alters synchronization safety guards.`,
`seal-use corps mark ${corp.id} --env ${targetEnv} --confirm`
);
}
const updated = updateCorpConfig(corp.id, { environment: targetEnv });
printJson({
id: updated.id,
name: updated.name,
environment: updated.environment,
testCorpId: updated.testCorpId,
prodCorpId: updated.prodCorpId
});
return true;
}
if (action === "rename") {
const targetCorpId = maybeName ?? stringOption(args.options.corp) ?? stringOption(args.options.id);
const newName = stringOption(args.options.name) ?? stringOption(args.options.to) ??
(args.command[3] && !args.command[3].startsWith("-") ? args.command[3] : undefined);
if (!targetCorpId || !newName) {
throw new Error("Usage: seal-use corps rename <corpId> --name <newName>");
}
const corp = selectCorp(targetCorpId);
const updated = updateCorpConfig(corp.id, { name: newName });
printJson({
success: true,
id: updated.id,
name: updated.name,
previousName: corp.name
});
return true;
}
if (action === "switch") {
const corpId = maybeName;
if (!corpId) throw new Error("Usage: seal-use corps switch <corpId>");
const globalConfig = loadGlobalConfig();
if (!globalConfig.stateful) {
throw new Error(
"Cannot switch the default enterprise while stateless mode is enabled. " +
"Use `seal-use config mode stateful` first."
);
}
const corp = selectCorp(corpId);
saveGlobalConfig({ ...globalConfig, stateful: true, defaultCorpId: corp.id });
printJson({
current: true,
id: corp.id,
name: corp.name
});
return true;
}
return false;
}
+82
View File
@@ -0,0 +1,82 @@
import { defaultSealUrl } from "../../../core/auth/hose.js";
import type { CorpConfig, SealSource } from "../../../core/config/types.js";
// ---------------------------------------------------------------------------
// Helpers & Sanitizers
// ---------------------------------------------------------------------------
export function maskSecret(value: string | undefined): string | undefined {
if (!value) return undefined;
if (value.length <= 8) return "****";
return `${value.slice(0, 4)}...${value.slice(-4)}`;
}
export function resolveCorpSealUrl(corp: CorpConfig): string | undefined {
if (corp.source.type === "hose") {
return defaultSealUrl(corp, corp.source);
}
return corp.seal.url ?? corp.source.sealUrl;
}
export function formatSafeSourceDetail(source: SealSource) {
if (source.type === "hose") {
const key = source.appKey ?? source.key;
return {
type: "hose",
provider: source.provider ?? "hosecloud",
domain: source.domain,
corpId: source.corpId,
staffId: source.staffId,
appKey: maskSecret(key),
hasAppSecurity: Boolean(source.appSecurity ?? source.password),
hasCloseToken: Boolean(source.closeToken),
closeTokenExpiresIn: source.closeToken ? source.expiresIn : undefined,
closeTokenExpiresAt: source.closeToken ? source.expiresAt : undefined,
credentialMode: source.closeToken ? "web-session" : "persistent",
sealUrl: source.sealUrl
};
}
if (source.type === "seal") {
return {
type: "seal",
provider: source.provider ?? "seal",
tenantId: source.tenantId,
tenantSlug: source.tenantSlug,
tenantName: source.tenantName,
providerUserId: source.providerUserId,
staffId: source.staffId,
corpId: source.corpId,
sealUrl: source.sealUrl,
hasToken: Boolean(source.token),
tokenMasked: maskSecret(source.token),
expiresIn: source.expiresIn,
expiresAt: source.expiresAt
};
}
throw new Error(`Unsupported enterprise source type: ${(source as { type: string }).type}`);
}
export function maskCellphone(phone: string | undefined | null): string {
if (!phone) return "未绑定手机";
const cleaned = phone.trim();
if (cleaned.length === 11) {
return `${cleaned.slice(0, 3)}****${cleaned.slice(7)}`;
}
if (cleaned.length >= 7) {
return `${cleaned.slice(0, 3)}****${cleaned.slice(-4)}`;
}
if (cleaned.length > 4) {
return `${cleaned.slice(0, 2)}****${cleaned.slice(-2)}`;
}
return cleaned;
}
export function formatUtcTimestampSeconds(timestampMs: number): string {
return new Date(timestampMs).toISOString().replace(/\.\d{3}Z$/, "Z");
}
export function stringValue(value: unknown): string | undefined {
return typeof value === "string" && value ? value : undefined;
}
+637
View File
@@ -0,0 +1,637 @@
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 { executeApprovalRunsReplay, type ReplayRecordsQuery } from "../../../domains/seal/webhook-replay.js";
import { selectCorp } from "../../helpers.js";
import { CliError, confirmationRequired, usageError } from "../../errors.js";
import { booleanOption, numberOption, stringOption } from "../../parser.js";
import { printJson } from "../../printer.js";
import type { ParsedArgs } from "../../types.js";
export async function handleCorpSync(
action: string | undefined,
maybeName: string | undefined,
args: ParsedArgs
): Promise<boolean> {
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 dryRun = booleanOption(args.options["dry-run"]) === true || booleanOption(args.options.dryRun) === 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
}
});
return true;
}
const confirmed = booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true;
if (!confirmed) {
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.`,
`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
}
});
return true;
}
if (action === "replay-test") {
const targetCorpId = maybeName ?? stringOption(args.options.corp) ?? stringOption(args.options.prodCorp) ?? stringOption(args.options["prod-corp"]);
const prodCorp = selectCorp(targetCorpId);
const force = booleanOption(args.options.force) === true;
const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]);
const confirmed = booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true;
let testCorp: CorpConfig;
if (!prodCorp.testCorpId) {
if (!force) {
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,\n` +
`or add '--force' (or use 'seal-use webhook replay <recordId> --force') if you explicitly intend to replay directly within production.`
);
}
testCorp = prodCorp;
} else {
testCorp = selectCorp(prodCorp.testCorpId);
if (testCorp.environment !== "test" && !force) {
throw new Error(
`Target enterprise '${testCorp.name}' (${testCorp.id}) is marked as '${testCorp.environment}', NOT 'test'. Aborting replay to protect non-test environments (use --force to override).`
);
}
}
if (!dryRun && !confirmed) {
throw confirmationRequired(
"Refusing to replay approval records without --confirm. Use --dry-run to preview the payload without sending it.",
`seal-use corps replay-test ${targetCorpId ?? "<prodCorpId>"} --confirm`
);
}
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 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 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 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,
sourceClient: prodClient,
targetClient: testClient,
sourceCorp: prodCorp,
targetCorp: testCorp,
webhookSelector: selector,
snPrefix,
snSuffix,
docIdPrefix,
docIdSuffix,
dryRun
});
if (dryRun) {
console.error(`[corps-replay-test] 预览模式:已成功从 ${prodCorp.name} 提取单据并转换为 Webhook Payload(未实际推送)。`);
console.log(JSON.stringify(result, null, 2));
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 通道"})`);
}
} 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);
}
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 };
}