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

+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> };
}