import { existsSync, readFileSync, readdirSync } from "node:fs"; import { homedir } from "node:os"; import { join } from "node:path"; import { AuthenticationError } from "../errors.js"; import { CorpConfig, CorpConfigSchema } from "../config/types.js"; import { saveCorpConfig, resolveWritableEnterprisesDir } from "../config/loader.js"; import { resolveCorpCluster } from "../http/unity-client.js"; import { DEFAULT_EKB_BASE_URL, HoseOpenApiKeyItem, canRefreshCorpAccessToken, fetchHoseOpenApiAccessToken, fetchHoseProvisionalAuth, fetchHoseRoleDefGroups, fetchHoseRoleStaffs, fetchHoseStaffDetails, fetchOpenApiKeysBySession, formatBeijingIso, getCorpOpenApiCredentials, hasOpenApiPersistentCredentials, normalizeBaseUrl, probeHoseDomain, selectOpenApiKey, } from "./openapi-v1.js"; import { importCredentials, invalidateCorpSubdomainTokenCaches, parseExpiresInSeconds, } from "./link-import.js"; import { refreshSingleCorpAccessToken } from "./login.js"; export interface OnboardHosePersistentParams { id?: string; name?: string; appKey: string; appSecurity: string; domain?: string; baseUrl?: string; corpId?: string; staffId?: string; staffName?: string; staffPhone?: string; role?: string; force?: boolean; overwrite?: boolean; enterprisesDir?: string; } /** * 通过开放平台持久化密钥 (appKey + appSecurity) 自动探测域名、管理员并导入企业配置 */ export async function onboardHosePersistent( input: OnboardHosePersistentParams ): Promise { const explicitDomain = input.domain || input.baseUrl; const probe = await probeHoseDomain(input.appKey, input.appSecurity, explicitDomain); const domain = probe.domain; const corpId = input.corpId || probe.corpId; let corpName = input.name || probe.corpName; let staffId = input.staffId; let staffName = input.staffName; const targetDir = input.enterprisesDir || resolveWritableEnterprisesDir(); const targetFile = join(targetDir, `${input.id || corpId}.json`); if (input.overwrite === false && existsSync(targetFile)) { throw new AuthenticationError(`企业 [${input.id || corpId}] 配置文件已存在。若要更新覆盖,请附加 --overwrite 参数。`); } if (!staffId) { const roleQuery = input.role ?? "admin"; const roleGroups = await fetchHoseRoleDefGroups(domain, probe.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, probe.openapiToken, targetRoleId).catch(() => ({ staffs: [] })); const staffDetails = await fetchHoseStaffDetails(domain, probe.openapiToken, roleStaffs.staffs).catch(() => []); if (input.staffName || input.staffPhone) { const matches = staffDetails.filter((staff) => { if (input.staffName && staff.name !== input.staffName && !staff.name.includes(input.staffName)) return false; if (input.staffPhone && (!staff.cellphone || !staff.cellphone.includes(input.staffPhone))) return false; return true; }); if (matches.length === 1 && matches[0]) { staffId = matches[0].id; staffName = matches[0].name; } else if (matches.length > 1) { throw new AuthenticationError( `匹配到多位管理员候选人 (${matches.map((s) => `${s.name}[${s.id}]`).join(", ")}),请通过 --staff-id 精确指定。` ); } else { throw new AuthenticationError( `未找到匹配 '${input.staffName ?? input.staffPhone}' 的管理员,请检查姓名/手机号或显式指定 --staff-id。` ); } } else { const activeStaffs = staffDetails.filter((s) => s.active); if (staffDetails.length === 1 && staffDetails[0]) { staffId = staffDetails[0].id; staffName = staffDetails[0].name; } else if (activeStaffs.length === 1 && activeStaffs[0]) { staffId = activeStaffs[0].id; staffName = activeStaffs[0].name; } else if (input.force && (activeStaffs[0] || staffDetails[0])) { const picked = activeStaffs[0] ?? staffDetails[0]!; staffId = picked.id; staffName = picked.name; } else if (staffDetails.length > 1) { const candidates = staffDetails.map((s) => ({ id: s.id, name: s.name, cellphone: s.cellphone ? s.cellphone.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2") : undefined, active: s.active, })); throw new AuthenticationError( `检测到多位主管理员候选人,请通过 --staff-id、--staff-name 指定,或追加 --force 自动选择第一位在职管理员: ${JSON.stringify(candidates)}` ); } } } } if (!staffId) { throw new AuthenticationError( "缺少员工工号 (staffId),且未能从主管理员角色自动发现,请通过 --staff-id 显式指定。" ); } const normalizedStaffId = staffId.includes(":") ? staffId : `${corpId}:${staffId}`; // 使用 getProvisionalAuth 签发初始会话并走 importCredentials 完整探测企业全称与 Session 元数据 const provisional = await fetchHoseProvisionalAuth({ baseUrl: domain, openapiToken: probe.openapiToken, corpId, staffId: normalizedStaffId, expiresIn: 7200, }); const imported = await importCredentials({ accessToken: provisional.token, corpId, staffId: normalizedStaffId, name: corpName, baseUrl: domain, source: "openapi", enterprisesDir: input.enterprisesDir, overwrite: true, appKey: input.appKey, appSecurity: input.appSecurity, autoElevate: false, }); if (staffName && !imported.staffName) { imported.staffName = staffName; saveCorpConfig(imported, input.enterprisesDir); } return imported; } export interface SyncFromSealUseOptions { filter?: string; sealEnterprisesDir?: string; enterprisesDir?: string; verify?: boolean; overwrite?: boolean; } export interface SyncFromSealUseItemResult { corpId: string; name: string; appKey: string; domain: string; staffId: string; action: "merged" | "created" | "skipped"; } export async function syncOpenApiFromSealUse( options: SyncFromSealUseOptions = {} ): Promise<{ sealDir: string; targetDir: string; items: SyncFromSealUseItemResult[]; }> { const sealDir = options.sealEnterprisesDir || process.env.SEAL_USE_ENTERPRISES_DIR?.trim() || join(homedir(), ".config", "seal-use", "enterprises"); const targetDir = options.enterprisesDir || resolveWritableEnterprisesDir(); if (!existsSync(sealDir)) { throw new AuthenticationError(`未找到 seal-use 企业配置目录: ${sealDir}`); } const files = readdirSync(sealDir).filter((f) => f.endsWith(".json") && !f.startsWith("example.")); const kw = options.filter?.trim().toLowerCase(); const items: SyncFromSealUseItemResult[] = []; for (const file of files) { try { const raw = JSON.parse(readFileSync(join(sealDir, file), "utf-8")); const sourceObj = raw?.source?.hose || raw?.source || raw?.hose; const appKey = sourceObj?.appKey; const appSecurity = sourceObj?.appSecurity; if (!appKey || !appSecurity) continue; const corpId: string = sourceObj.corpId || raw.id; const sealName: string = raw.name || corpId; const domain = normalizeBaseUrl(sourceObj.domain || DEFAULT_EKB_BASE_URL); const rawStaffId: string = sourceObj.staffId || `${corpId}:admin`; const staffId = rawStaffId.includes(":") ? rawStaffId : `${corpId}:${rawStaffId}`; if (kw) { const matched = corpId.toLowerCase().includes(kw) || sealName.toLowerCase().includes(kw) || String(raw.id || "").toLowerCase().includes(kw); if (!matched) continue; } const targetPath = join(targetDir, `${corpId}.json`); if (existsSync(targetPath)) { const existing = CorpConfigSchema.parse(JSON.parse(readFileSync(targetPath, "utf-8"))); if (hasOpenApiPersistentCredentials(existing) && options.overwrite === false) { items.push({ corpId, name: existing.name, appKey: existing.credentials.appKey || appKey, domain: existing.baseUrl || domain, staffId: existing.credentials.staffId, action: "skipped", }); continue; } existing.credentials.appKey = appKey; existing.credentials.appSecurity = appSecurity; if (!existing.baseUrl) existing.baseUrl = domain; if (!existing.credentials.staffId) existing.credentials.staffId = staffId; if (options.verify) { await refreshSingleCorpAccessToken(existing); } else { saveCorpConfig(existing, targetDir); } items.push({ corpId, name: existing.name, appKey, domain: existing.baseUrl || domain, staffId: existing.credentials.staffId, action: "merged", }); } else { let createdConfig: CorpConfig | null = null; if (options.verify) { try { createdConfig = await onboardHosePersistent({ id: corpId, name: sealName, appKey, appSecurity, domain, corpId, staffId, overwrite: true, enterprisesDir: targetDir, }); } catch { // fallback to saving raw OpenAPI credentials below } } if (!createdConfig) { createdConfig = { id: corpId, name: sealName, corpId, staffId, source: "openapi", baseUrl: domain, cluster: resolveCorpCluster({ baseUrl: domain }), credentials: { accessToken: "", corpId, staffId, appKey, appSecurity, }, auth: { refreshTtl: 300, }, }; saveCorpConfig(createdConfig, targetDir); } items.push({ corpId, name: createdConfig.name, appKey, domain: createdConfig.baseUrl || domain, staffId: createdConfig.credentials.staffId, action: "created", }); } } catch { // ignore invalid file } } return { sealDir, targetDir, items, }; } /** * 为已配置企业提取并持久化 OpenAPI 密钥 */ export async function elevateCorpWithOpenApiKey( corp: CorpConfig, options: { appKey?: string; keyId?: string; force?: boolean; silent?: boolean; enterprisesDir?: string; } = {} ): Promise { const corpId = corp.corpId || corp.credentials.corpId; const staffId = corp.staffId || corp.credentials.staffId; const baseUrl = corp.baseUrl || DEFAULT_EKB_BASE_URL; try { const ttlMs = (corp.auth?.refreshTtl || 300) * 1000; const expMs = corp.auth?.expiresAt || corp.session?.expTime; if (canRefreshCorpAccessToken(corp) && (!corp.credentials.accessToken || (expMs && Date.now() >= expMs - ttlMs))) { await refreshSingleCorpAccessToken(corp); } const keys = await fetchOpenApiKeysBySession({ baseUrl, corpId, staffId, accessToken: corp.credentials.accessToken, }).catch(async (err) => { if (canRefreshCorpAccessToken(corp)) { const refreshed = await refreshSingleCorpAccessToken(corp); if (refreshed) { return fetchOpenApiKeysBySession({ baseUrl, corpId, staffId, accessToken: corp.credentials.accessToken, }); } } throw err; }); if (keys.length === 0) { if (options.silent) return undefined; throw new AuthenticationError(`企业 [${corp.name}] 暂未创建 OpenAPI 密钥`); } const selected = selectOpenApiKey(keys, corpId, { appKey: options.appKey, keyId: options.keyId, force: options.force ?? options.silent, }); corp.credentials.appKey = selected.appKey; corp.credentials.appSecurity = selected.appSecurity; saveCorpConfig(corp, options.enterprisesDir); return selected; } catch (err) { if (options.silent) return undefined; throw err; } } /** * 生成指定企业的合思 Web 免密登录直达链接 (thirdparty.html) * 优先走 OpenAPI getProvisionalAuth 签发独立授权链接;若无 OpenAPI 密钥则尝试自动提权,最后回退当前有效会话 Token。 */ export async function getCorpProvisionalAuthLink( corp: CorpConfig, options: { expiresIn?: number | string; ttl?: number | string; pageType?: string; force?: boolean; syncLocalSession?: boolean; enterprisesDir?: string; staffId?: string; staffName?: string; persistStaff?: boolean; } = {} ): Promise<{ corpId: string; corpName: string; staffId: string; staffName?: string; url: string; token: string; expiresIn: number; expiresAt: string; persistent: boolean; method: "provisional-openapi" | "session-token"; }> { const explicitDuration = options.expiresIn ?? options.ttl; const expiresIn = parseExpiresInSeconds(explicitDuration, 7200); const pageType = options.pageType || "home"; const corpId = corp.corpId || corp.credentials.corpId; const targetStaffId = options.staffId || corp.staffId || corp.credentials.staffId; const targetStaffName = options.staffName || (options.staffId ? undefined : corp.staffName || corp.session?.staffName); const baseUrl = normalizeBaseUrl(corp.baseUrl || DEFAULT_EKB_BASE_URL); const syncLocalSession = options.syncLocalSession !== false && (!options.staffId || options.persistStaff === true); if (options.staffId && !hasOpenApiPersistentCredentials(corp)) { throw new AuthenticationError("切换员工签发链接需要已配置的 OpenAPI 持久化密钥,现有会话不能代表其他员工。"); } // 1. 若尚未配置 appKey/appSecurity,先确保会话有效并尝试自动提权提取密钥 if (!hasOpenApiPersistentCredentials(corp)) { const ttlMs = (corp.auth?.refreshTtl || 300) * 1000; const expMs = corp.auth?.expiresAt || corp.session?.expTime; if (canRefreshCorpAccessToken(corp) && (!corp.credentials.accessToken || (expMs && Date.now() >= expMs - ttlMs))) { await refreshSingleCorpAccessToken(corp); } if (corp.credentials.accessToken) { await elevateCorpWithOpenApiKey(corp, { silent: true, force: true, enterprisesDir: options.enterprisesDir }); } } // 2. 若具备 OpenAPI 持久化密钥,直接走 getProvisionalAuth 签发标准免密链接 const openApiCreds = getCorpOpenApiCredentials(corp); if (openApiCreds) { const openapiToken = await fetchHoseOpenApiAccessToken({ appKey: openApiCreds.appKey, appSecurity: openApiCreds.appSecurity, baseUrl, forceRefresh: options.force, }); const provisional = await fetchHoseProvisionalAuth({ baseUrl, openapiToken, corpId, staffId: targetStaffId, expiresIn, pageType, }); const normalizedStaffId = targetStaffId.includes(":") ? targetStaffId : `${corpId}:${targetStaffId}`; if (provisional.uid !== normalizedStaffId) { throw new AuthenticationError("免密链接签发身份与目标员工不一致,未更新本地会话。"); } if (syncLocalSession) { const updated = structuredClone(corp); updated.credentials.accessToken = provisional.token; if (!updated.auth) updated.auth = { refreshTtl: 300 }; updated.auth.expiresAt = provisional.expiresAt; if (updated.session) { updated.session.expTime = provisional.expiresAt; } if (options.persistStaff && options.staffId) { updated.staffId = normalizedStaffId; updated.credentials.staffId = normalizedStaffId; updated.staffName = options.staffName; if (updated.session) updated.session.staffName = options.staffName; } saveCorpConfig(updated, options.enterprisesDir); Object.assign(corp, updated); invalidateCorpSubdomainTokenCaches(corp); } return { corpId, corpName: corp.name, staffId: provisional.uid || targetStaffId, staffName: targetStaffName ?? undefined, url: provisional.url, token: provisional.token, expiresIn: provisional.expiresIn, expiresAt: formatBeijingIso(provisional.expiresAt), persistent: true, method: "provisional-openapi", }; } // 3. 回退路径:无 OpenAPI 密钥时,使用主账号或现有有效 Session Token 拼装免密链接 if (!corp.credentials.accessToken) { throw new AuthenticationError( `企业 [${corp.name}] 缺少可用访问令牌且未配置 OpenAPI 持久化密钥,请重新登录或导入链接。` ); } const expMs = explicitDuration !== undefined ? Date.now() + expiresIn * 1000 : corp.auth?.expiresAt || corp.session?.expTime || Date.now() + expiresIn * 1000; if (expMs <= Date.now() && !canRefreshCorpAccessToken(corp)) { throw new AuthenticationError( `企业 [${corp.name}] 临时凭证已过期且未配置持久化密钥,请使用 hose-use corps add-link 重新导入。` ); } if (explicitDuration !== undefined && syncLocalSession) { if (!corp.auth) corp.auth = { refreshTtl: 300 }; corp.auth.expiresAt = expMs; if (corp.session) { corp.session.expTime = expMs; } saveCorpConfig(corp, options.enterprisesDir); } const url = `${baseUrl}/web/thirdparty.html?accessToken=${encodeURIComponent( corp.credentials.accessToken )}&ekbCorpId=${encodeURIComponent(corpId)}&pageType=${encodeURIComponent( pageType )}&overdueTokenRedirect=&noPathCache=true`; return { corpId, corpName: corp.name, staffId: targetStaffId, staffName: targetStaffName || corp.staffName || corp.session?.staffName || undefined, url, token: corp.credentials.accessToken, expiresIn: Math.max(1, Math.round((expMs - Date.now()) / 1000)), expiresAt: formatBeijingIso(expMs), persistent: canRefreshCorpAccessToken(corp), method: "session-token", }; }