- Sync hosecloud integrations from prod to test during corps sync-test
- Format outboundName as {corpNamePrefix}(Seal测) capped at 13 chars
- Force assisted mode and reuse existing credentials and apiOrigin
- Skip outbound sync to Hosecloud to preserve production approval flows
- Add unit and integration tests covering naming, mode, and idempotency
1254 lines
44 KiB
TypeScript
1254 lines
44 KiB
TypeScript
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
|
|
import { randomBytes } from "node:crypto";
|
|
import { join } from "node:path";
|
|
import {
|
|
assertHoseAssistTenantMatches,
|
|
exchangeHoseAssistLink,
|
|
fetchHoseRoleDefGroups,
|
|
fetchHoseRoleStaffs,
|
|
fetchHoseStaffDetails,
|
|
probeHoseDomain
|
|
} from "../../core/auth/hose.js";
|
|
import { clearCorpTokenCache } from "../../core/auth/token-store.js";
|
|
import { createSealClient, createSealClientForUrl } from "../../core/http/factory.js";
|
|
import { resolveSealCustomHeaders } from "../../core/http/request-headers.js";
|
|
import {
|
|
loadCorpConfigs,
|
|
loadGlobalConfig,
|
|
resolveWritableEnterprisesDir,
|
|
saveGlobalConfig,
|
|
updateCorpConfig
|
|
} from "../../core/config/loader.js";
|
|
import { SealCookieMapSchema, SealHeaderMapSchema } from "../../core/config/types.js";
|
|
import type { CorpConfig, CorpEnvironment } from "../../core/config/types.js";
|
|
import * as api from "../../domains/seal/api.js";
|
|
import { getMe } from "../../domains/seal/api.js";
|
|
import {
|
|
computeNextSyncIteration,
|
|
formatSyncVersionName,
|
|
saveRuleMappingSnapshot
|
|
} from "../../domains/seal/rule-mapping.js";
|
|
import { resolveLiveSealEnterpriseConfig } from "../../domains/seal/source.js";
|
|
import { selectCorp } from "../helpers.js";
|
|
import { confirmationRequired, usageError } from "../errors.js";
|
|
import {
|
|
inferCorpIdFromStaffId,
|
|
booleanOption,
|
|
jsonObject,
|
|
optionalNumber,
|
|
optionalString,
|
|
requiredString,
|
|
requiredStringAlias,
|
|
safeFileName,
|
|
stringOption
|
|
} from "../parser.js";
|
|
import { printJson } from "../printer.js";
|
|
import type { ParsedArgs } from "../types.js";
|
|
|
|
export async function handleCorpsCommand(action: string | undefined, maybeName: string | undefined, args: ParsedArgs) {
|
|
if (action === "list") {
|
|
const corpId = stringOption(args.options.corp);
|
|
const corps = loadCorpConfigs();
|
|
const globalConfig = loadGlobalConfig();
|
|
const currentCorpId = corpId ?? (
|
|
globalConfig.stateful
|
|
? globalConfig.defaultCorpId ?? corps[0]?.id
|
|
: undefined
|
|
);
|
|
if (corps.length === 0) {
|
|
console.error("提示:当前未检测到企业配置。你可以使用 seal-use corps add-hose 或 seal-use corps add-seal 添加企业,或运行 seal-use help 查看说明。");
|
|
}
|
|
printJson(corps.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,
|
|
testCorpId: item.testCorpId,
|
|
prodCorpId: item.prodCorpId,
|
|
current: item.id === currentCorpId
|
|
})));
|
|
return;
|
|
}
|
|
|
|
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,
|
|
testCorpId: corp.testCorpId,
|
|
prodCorpId: corp.prodCorpId
|
|
});
|
|
return;
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
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).catch(() => ({} as any)),
|
|
api.getApprovalStylePreferences(testClient, testCorp.seal.endpoints.approvalStylePreferences).catch(() => ({} as any)),
|
|
api.listApprovalRules(prodClient),
|
|
api.listApprovalRules(testClient),
|
|
api.listApprovalRuleVersions(prodClient).catch(() => []),
|
|
api.listApprovalRuleVersions(testClient).catch(() => []),
|
|
api.listApprovalDocuments(prodClient, { limit: 100 }).catch(() => ({ articles: [] })),
|
|
api.listApprovalDocuments(testClient, { limit: 100 }).catch(() => ({ articles: [] }))
|
|
]);
|
|
|
|
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);
|
|
} else {
|
|
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: prodCorp.source.type === "hose" ? {
|
|
sourceType: "hose",
|
|
outboundName: buildTestHosecloudOutboundName(prodCorp.name),
|
|
targetMode: "assisted",
|
|
integrationsCount: (prodPref.integrations ?? []).filter((i: any) => i.type === "hosecloud").length,
|
|
integrations: (prodPref.integrations ?? [])
|
|
.filter((i: any) => i.type === "hosecloud")
|
|
.map((i: any) => ({
|
|
corporationId: i.corporationId,
|
|
apiOrigin: i.apiOrigin,
|
|
customApiUrl: i.customApiUrl
|
|
}))
|
|
} : {
|
|
sourceType: prodCorp.source.type,
|
|
skipped: true,
|
|
reason: "prod source is not hose; no hosecloud credentials available"
|
|
},
|
|
productionGuarantees: {
|
|
prodRulesStayDraft: true,
|
|
prodVersionPublished: false
|
|
}
|
|
});
|
|
return;
|
|
}
|
|
|
|
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
|
|
await api.recodeApprovalRules(testClient).catch(() => undefined);
|
|
|
|
// 6. Publish new version in test enterprise
|
|
const published = await api.publishApprovalRuleVersion(testClient, versionName);
|
|
|
|
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 {}
|
|
|
|
// 7. Sync hosecloud integrations from prod to test (hose-source corps only)
|
|
const hosecloudSync = await syncHosecloudIntegrationsToTest(prodCorp, testCorp, prodClient, testClient).catch(
|
|
(err) => ({ skipped: true, reason: `error: ${err?.message ?? String(err)}` } as HosecloudSyncResult)
|
|
);
|
|
|
|
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;
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
if (action === "probe-hose") {
|
|
await probeHoseCorp(jsonObject(args.json));
|
|
return;
|
|
}
|
|
|
|
if (action === "hose-staffs") {
|
|
await queryHoseStaffs(jsonObject(args.json));
|
|
return;
|
|
}
|
|
|
|
if (action === "add-hose") {
|
|
await addHoseCorp(jsonObject(args.json));
|
|
return;
|
|
}
|
|
|
|
if (action === "add-seal") {
|
|
await addSealCorp(jsonObject(args.json));
|
|
return;
|
|
}
|
|
|
|
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 <https://.../web/thirdparty.html?...> [--name <customName>] [--overwrite]"
|
|
);
|
|
}
|
|
await addLinkCorp(link, stringOption(args.options.name), booleanOption(args.options.overwrite) === true);
|
|
return;
|
|
}
|
|
|
|
throw new Error(`Unknown corps command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Hosecloud integration sync helpers
|
|
// ---------------------------------------------------------------------------
|
|
|
|
/**
|
|
* Build the outboundName for a test-env hosecloud integration.
|
|
* Format: {企业名前7字}(Seal测) — capped at 13 chars total.
|
|
*/
|
|
export function buildTestHosecloudOutboundName(corpName: string): string {
|
|
// "(Seal测)" is 7 chars; leave 6 chars for the corp name prefix.
|
|
const suffix = "(Seal测)"
|
|
const maxPrefix = 13 - suffix.length // 6
|
|
const prefix = [...corpName].slice(0, maxPrefix).join("")
|
|
return prefix + suffix
|
|
}
|
|
|
|
interface HosecloudSyncResult {
|
|
skipped: boolean
|
|
reason?: string
|
|
synced?: Array<{ signKey: string; outboundName: string; corporationId: string; action: "created" | "updated" }>
|
|
}
|
|
|
|
/**
|
|
* 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 合思)
|
|
*/
|
|
async function syncHosecloudIntegrationsToTest(
|
|
prodCorp: import("../../core/config/types.js").CorpConfig,
|
|
testCorp: import("../../core/config/types.js").CorpConfig,
|
|
prodClient: import("ky").KyInstance,
|
|
testClient: import("ky").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 as any).appKey as string | undefined
|
|
const appSecurity = (prodCorp.source as any).appSecurity as string | undefined
|
|
if (!appKey || !appSecurity) {
|
|
return { skipped: true, reason: "prod hose source missing appKey/appSecurity" }
|
|
}
|
|
|
|
const [prodPref, testPref] = await Promise.all([
|
|
api.getApprovalStylePreferences(prodClient, prodCorp.seal.endpoints.approvalStylePreferences).catch(() => ({} as any)),
|
|
api.getApprovalStylePreferences(testClient, testCorp.seal.endpoints.approvalStylePreferences).catch(() => ({} as any))
|
|
])
|
|
|
|
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" }
|
|
}
|
|
|
|
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[] = prodIntegrations.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")
|
|
const nextConfig = {
|
|
...testPref,
|
|
integrations: [...otherIntegrations, ...nextHosecloudIntegrations]
|
|
}
|
|
await api.updateApprovalStylePreferences(testClient, nextConfig, testCorp.seal.endpoints.approvalStylePreferences)
|
|
|
|
return { skipped: false, synced }
|
|
}
|
|
|
|
async function probeHoseCorp(input: Record<string, unknown>) {
|
|
const appKey = requiredString(input, "appKey");
|
|
const appSecurity = requiredString(input, "appSecurity");
|
|
const explicitDomain = optionalString(input, "domain");
|
|
|
|
const probe = await probeHoseDomain(appKey, appSecurity, explicitDomain);
|
|
const roleGroups = await fetchHoseRoleDefGroups(probe.domain, probe.openapiToken).catch(() => []);
|
|
|
|
const totalRoles = roleGroups.reduce((acc, g) => acc + g.roleDefs.length, 0);
|
|
|
|
printJson({
|
|
domain: probe.domain,
|
|
corpId: probe.corpId,
|
|
name: probe.corpName ?? probe.corpId,
|
|
roleCount: totalRoles,
|
|
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 explicitDomain = optionalString(input, "domain");
|
|
const roleQuery = optionalString(input, "role") ?? optionalString(input, "roleDefId") ?? "admin";
|
|
|
|
const probe = await probeHoseDomain(appKey, appSecurity, explicitDomain);
|
|
const roleGroups = await fetchHoseRoleDefGroups(probe.domain, probe.openapiToken);
|
|
|
|
let targetRoleDefId: string | undefined;
|
|
let targetRoleName: string | undefined;
|
|
|
|
// 1. Direct match by id
|
|
for (const g of roleGroups) {
|
|
for (const r of g.roleDefs) {
|
|
if (r.id === roleQuery || r.id === `${probe.corpId}:${roleQuery}`) {
|
|
targetRoleDefId = r.id;
|
|
targetRoleName = r.name;
|
|
break;
|
|
}
|
|
}
|
|
if (targetRoleDefId) break;
|
|
}
|
|
|
|
// 2. Admin match default
|
|
if (!targetRoleDefId && (roleQuery === "admin" || roleQuery === "主管理员")) {
|
|
for (const g of roleGroups) {
|
|
for (const r of g.roleDefs) {
|
|
if (r.id.endsWith(":admin") || r.name === "主管理员") {
|
|
targetRoleDefId = r.id;
|
|
targetRoleName = r.name;
|
|
break;
|
|
}
|
|
}
|
|
if (targetRoleDefId) break;
|
|
}
|
|
}
|
|
|
|
// 3. Match by role name substring
|
|
if (!targetRoleDefId) {
|
|
for (const g of roleGroups) {
|
|
for (const r of g.roleDefs) {
|
|
if (r.name.toLowerCase().includes(roleQuery.toLowerCase())) {
|
|
targetRoleDefId = r.id;
|
|
targetRoleName = r.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((s) => ({
|
|
id: s.id,
|
|
name: s.name,
|
|
cellphone: s.cellphone,
|
|
active: s.active,
|
|
authState: s.authState,
|
|
userId: s.userId,
|
|
email: s.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 g of roleGroups) {
|
|
for (const r of g.roleDefs) {
|
|
if (r.id.endsWith(`:${roleQuery}`) || r.name === roleQuery || r.id === roleQuery) {
|
|
targetRoleId = r.id;
|
|
break;
|
|
}
|
|
}
|
|
if (targetRoleId) break;
|
|
}
|
|
if (!targetRoleId) {
|
|
targetRoleId = roleGroups
|
|
.find((g) => g.roleDefs.some((r) => r.id.endsWith(":admin")))
|
|
?.roleDefs.find((r) => r.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((s) => {
|
|
if (staffName && s.name !== staffName && !s.name.includes(staffName)) return false;
|
|
if (staffPhone && (!s.cellphone || !s.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 candidates = staffDetails
|
|
.map((s) => `${s.name} (${s.cellphone || "no-phone"}, id: ${s.id}, active: ${s.active})`)
|
|
.join("\n - ");
|
|
throw new Error(
|
|
`Missing required parameter: staffId. Found ${staffDetails.length} candidate administrators:\n - ${candidates}\n` +
|
|
`Please specify 'staffId', 'staffName', or 'staffPhone' to explicitly select an account (or pass force:true to bypass).`
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
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;
|
|
const name = 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);
|
|
await resolveLiveSealEnterpriseConfig(config);
|
|
}
|
|
|
|
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,
|
|
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 });
|
|
}
|
|
|
|
// Validates extra headers/cookies up front so a malformed name fails here
|
|
// rather than on the next config load.
|
|
function sealCustomHeadersFromInput(input: Record<string, unknown>) {
|
|
return {
|
|
headers: SealHeaderMapSchema.parse(input.headers),
|
|
cookies: SealCookieMapSchema.parse(input.cookies)
|
|
};
|
|
}
|
|
|
|
async function addLinkCorp(link: string, name: string | undefined, overwrite: boolean) {
|
|
const session = await exchangeHoseAssistLink(link);
|
|
const client = createSealClientForUrl(session.sealUrl, session.token);
|
|
const me = await getMe(client);
|
|
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);
|
|
writeSealCorpConfig(
|
|
{
|
|
id: session.corpId,
|
|
corpId: session.corpId,
|
|
name,
|
|
provider: "hosecloud",
|
|
overwrite
|
|
},
|
|
{
|
|
token: session.token,
|
|
sealUrl: session.sealUrl,
|
|
expiresIn: session.expiresIn,
|
|
verify: true,
|
|
remote: identity
|
|
}
|
|
);
|
|
}
|
|
|
|
type RemoteSealIdentity = {
|
|
user: Record<string, unknown>;
|
|
tenant: Record<string, unknown>;
|
|
};
|
|
|
|
function writeSealCorpConfig(
|
|
input: Record<string, unknown>,
|
|
auth: {
|
|
token: string;
|
|
sealUrl: string;
|
|
expiresIn: number;
|
|
verify: boolean;
|
|
remote?: RemoteSealIdentity;
|
|
custom?: { headers?: Record<string, string>; cookies?: Record<string, string> };
|
|
}
|
|
) {
|
|
const { token, sealUrl, expiresIn, verify, remote } = auth;
|
|
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,
|
|
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
|
|
});
|
|
}
|
|
|
|
async function resolveHoseCorporation(domain: string, appKey: string, appSecurity: string) {
|
|
const response = await fetch(`${domain.replace(/\/+$/, "")}/api/openapi/v1/auth/getAccessToken`, {
|
|
method: "POST",
|
|
headers: {
|
|
"content-type": "application/json"
|
|
},
|
|
body: JSON.stringify({
|
|
appKey,
|
|
appSecurity
|
|
})
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const body = await response.text().catch(() => "");
|
|
throw new Error(`Hose login failed: ${response.status}${body ? ` ${body}` : ""}`);
|
|
}
|
|
|
|
const data = (await response.json()) as {
|
|
value?: {
|
|
corporationId?: string;
|
|
corporation?: {
|
|
id?: string;
|
|
name?: string;
|
|
};
|
|
};
|
|
};
|
|
const corporationId = data.value?.corporationId ?? data.value?.corporation?.id;
|
|
return corporationId
|
|
? {
|
|
id: corporationId,
|
|
name: data.value?.corporation?.name
|
|
}
|
|
: undefined;
|
|
}
|
|
|
|
async function resolveSealWhoami(sealUrl: string, token: string, customHeaders: Record<string, string> = {}) {
|
|
const json = await getJson(`${sealUrl}/api/v1/auth/me`, {
|
|
...customHeaders,
|
|
authorization: `Bearer ${token}`
|
|
});
|
|
const data = objectValue(json.data);
|
|
return {
|
|
user: objectValue(data.user ?? json.user),
|
|
tenant: objectValue(data.tenant ?? json.tenant)
|
|
};
|
|
}
|
|
|
|
async function getJson(url: string, headers: Record<string, string> = {}): Promise<Record<string, unknown>> {
|
|
const response = await fetch(url, {
|
|
headers
|
|
});
|
|
const body = await response.text();
|
|
if (!response.ok) {
|
|
throw new Error(`${response.status} ${body}`);
|
|
}
|
|
const json = JSON.parse(body) as unknown;
|
|
return objectValue(json);
|
|
}
|
|
|
|
function objectValue(value: unknown): Record<string, unknown> {
|
|
return value && typeof value === "object" && !Array.isArray(value)
|
|
? (value as Record<string, unknown>)
|
|
: {};
|
|
}
|
|
|
|
function stringValue(value: unknown): string | undefined {
|
|
return typeof value === "string" && value ? value : undefined;
|
|
}
|