From 887df2d32f068f27f520877507cee2902d6aef16 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Thu, 19 Nov 2026 17:00:45 +0800 Subject: [PATCH] Add cloud enterprise storage mode and credential resolver Enterprise configs gain a root-level storage field (default local). Cloud configs must not persist any secret and fail closed on load. Route credential reads through resolveCorpCredentials, which returns local fields unchanged and fails with exit code 11 for cloud enterprises until the bridge client lands. Cloud enterprises skip the local token store and delegation renewal. --- .../proposals/cloud-enterprise-config/plan.md | 124 ++++++++++++++++++ src/cli/commands/auth.ts | 17 ++- src/cli/commands/corps/onboarding.ts | 6 +- src/cli/commands/corps/overview.ts | 3 + src/core/auth/credentials.test.ts | 100 ++++++++++++++ src/core/auth/credentials.ts | 55 ++++++++ src/core/auth/hose.ts | 20 +-- src/core/auth/native.ts | 6 + src/core/auth/seal.ts | 13 +- src/core/config/loader.ts | 2 +- src/core/config/types.test.ts | 102 ++++++++++++++ src/core/config/types.ts | 85 +++++++++--- src/domains/hose/open/approval.ts | 6 +- src/domains/seal/testing/sync.ts | 6 +- 14 files changed, 504 insertions(+), 41 deletions(-) create mode 100644 docs/proposals/cloud-enterprise-config/plan.md create mode 100644 src/core/auth/credentials.test.ts create mode 100644 src/core/auth/credentials.ts diff --git a/docs/proposals/cloud-enterprise-config/plan.md b/docs/proposals/cloud-enterprise-config/plan.md new file mode 100644 index 0000000..6e5c90e --- /dev/null +++ b/docs/proposals/cloud-enterprise-config/plan.md @@ -0,0 +1,124 @@ +# 云端企业配置方案(seal-use 侧) + +状态:阶段一、二已实施(2026-11-19);阶段三待确认。桥接侧的凭据服务在独立会话中设计,本文件定义 seal-use 侧的形态与契约假设。 + +## 已定决策 + +1. 企业配置新增根级 `storage: "local" | "cloud"`,默认 `local`,两种 `source.type` 通用。 +2. `cloud` 企业的本地 JSON **不保存任何密钥**(`appKey`/`appSecurity`/`closeToken`/`token`/`seal.cookies`),只保留路由与身份元数据。 +3. 登录不是下载的前置条件;**只有 cloud 企业需要登录**。安装包分发维持 GitHub(私有)+ Gitea(公开镜像)现状。 +4. cloud 企业:本地不写 `tokens.json`,凭据只在内存缓存到 `expiresAt - 60s`;不自动续费;不提供提权命令。 +5. 云端不可达或未登录时硬失败,不回退、不静默降级。 + +## 配置形态 + +```json +{ + "id": "ID01D3GcYxuyfl", + "name": "南京测绘", + "storage": "cloud", + "environment": "production", + "active": true, + "seal": { + "url": "https://id01d3gcyxuyfl.sealai.cc", + "tenantSlug": "ID01D3GcYxuyfl", + "endpoints": { "approvalStylePreferences": "api/v1/agent/ai-approval/config" } + }, + "source": { + "type": "hose", + "domain": "https://app.ekuaibao.com", + "corpId": "ID01D3GcYxuyfl", + "staffId": "ID01D3GcYxuyfl:ID01JbL19boRwH" + }, + "auth": { "refreshTtl": 300 } +} +``` + +校验规则(fail-closed): + +- `storage: "cloud"` 时出现任何密钥字段 → 加载报错,不静默剥离。 +- `storage: "local"` 行为与现在完全一致。 +- `source.type`、`staffId`、`corpId`、`seal.url` 等路由字段仍为必填。 + +## 与桥接的接口契约(待对齐) + +### 凭据获取 + +```http +GET /api/credentials?type=hose&corpId= +Authorization: Bearer +``` + +响应: + +```json +// hose 长期凭据企业 +{ "type": "hose", "credentialMode": "persistent", + "openapiToken": "...", "expiresAt": "2026-11-19T18:00:00+08:00" } + +// hose web-session 企业 +{ "type": "hose", "credentialMode": "web-session", + "closeToken": "...", "expiresAt": "..." } + +// seal 企业 +{ "type": "seal", "token": "...", "expiresAt": "..." } +``` + +错误语义: + +| HTTP | seal-use 行为 | 退出码 | +|---|---|---| +| 401 / 403 | 提示重新登录或权限不足 | 11 | +| 404 | 该企业未在云端登记 | 13 | +| 5xx / 超时 | 云端不可用,不回退 | 1 | + +### CLI 登录 + +优先级:设备码,PAT 兜底。 + +- `POST /api/auth/device/start` → `{ deviceCode, userCode, verificationUrl, interval, expiresIn }` +- `POST /api/auth/device/token` → `{ token, expiresAt }`(pending 时返回 202) +- 令牌存 `~/.config/seal-use/bridge.json`(`0600`),支持 `SEAL_USE_BRIDGE_TOKEN` 环境变量覆盖。 + +## seal-use 改动清单 + +### 阶段一:不依赖桥接 API + +1. [config/types.ts](../../../src/core/config/types.ts):根级 `storage` 枚举,默认 `local`;cloud 分支的 fail-closed 校验。 +2. [config/repository.ts](../../../src/core/config/repository.ts):`saveCorpConfig` 在 cloud 模式下拒绝含密钥的配置。 +3. `corps list` / `corps get` 输出增加 `storage`。 +4. 测试:cloud 配置合法/非法两种形态、旧配置默认 local。 + +### 阶段二:凭据解析器 + +5. 新增 `src/core/auth/credentials.ts`:`resolveCorpCredentials(corp)`,local 分支直接返回现有字段;cloud 分支在未登录时报 `authRequired`。 +6. 收口现有 7 处直接读取([auth/hose.ts:277](../../../src/core/auth/hose.ts:277)、[hose/open/approval.ts:45](../../../domains/hose/open/approval.ts:45)、[cli/auth.ts:178](../../../cli/commands/auth.ts:178)、[cli/auth.ts:240](../../../cli/commands/auth.ts:240)、[corps/shared.ts:23](../../../cli/commands/corps/shared.ts:23)、[corps/onboarding.ts:412](../../../cli/commands/corps/onboarding.ts:412)、[testing/sync.ts:321](../../../domains/seal/testing/sync.ts:321))。 +7. cloud 企业跳过 `tokens.json` 写入与 `renewNativeSealSession` 的配置回写;401 自愈改为重新向云端取。 + +### 阶段三:桥接接入 + +8. 新增 `src/core/auth/bridge-client.ts`:设备码、令牌刷新、凭据请求与内存缓存。 +9. `seal-use auth login/logout/status` 命令;`doctor` 增加登录与连通性检查。 +10. cloud 企业禁用提权类命令(`add-link --as-hose`、`hose-extract-keys`、`corps keys`),提示到云端管理。 + +## 兼容与行为变化 + +- 旧配置无 `storage` → 解析为 `local`,行为不变。 +- cloud 配置不会因加载被改写;切换 `local → cloud` 需要专门命令(本期不做自动切换)。 +- `corps list/get` 的 JSON 新增 `storage` 字段;依赖旧输出结构的脚本需要容忍新增键。 +- cloud 企业离线不可用,这是预期代价。 + +## 验证 + +1. 配置:cloud 合法形态通过、含密钥被拒、旧配置默认 local。 +2. 解析器:local 行为回归(现有全部测试);cloud 未登录报 11。 +3. 缓存:cloud 企业运行后 `tokens.json` 不新增条目。 +4. 命令:提权命令对 cloud 企业返回明确错误。 +5. `bun run check`、`bun run lint`、全部治理门禁、全量 `bun test`。 + +## 未决问题 + +1. 桥接凭据接口的最终形态(GET 还是 POST、是否返回 `seal.cookies`、是否需要 `environment` 区分)。 +2. CLI 登录优先设备码还是 PAT;桥接是否本期提供设备码端点。 +3. cloud 企业是否允许本地缓存派生会话(当前定为不允许,纯内存)。 +4. 切换 `local ↔ cloud` 的命令形态。 diff --git a/src/cli/commands/auth.ts b/src/cli/commands/auth.ts index e832cc9..01a832f 100644 --- a/src/cli/commands/auth.ts +++ b/src/cli/commands/auth.ts @@ -6,6 +6,7 @@ import { normalizeBaseUrl } from "../../core/auth/hose.js"; import { clearCorpTokenCache } from "../../core/auth/token-store.js"; +import { resolveCorpCredentials } from "../../core/auth/credentials.js"; import { formatBeijingIso } from "../../core/config/timestamps.js"; import type { CorpConfig } from "../../core/config/types.js"; import { CliError, validationError, usageError } from "../../core/errors.js"; @@ -175,8 +176,9 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo 2 ); } - const appKey = corp.source.appKey; - const appSecurity = corp.source.appSecurity; + const credentials = await resolveCorpCredentials(corp); + const appKey = credentials.appKey; + const appSecurity = credentials.appSecurity; if (!appKey || !appSecurity) { throw validationError( `缺少合思凭证:企业「${corp.name}」(id: ${corp.id}) 未配置 appKey/appSecurity,无法向合思 OpenAPI 签发 accessToken。` @@ -237,13 +239,14 @@ async function diagnoseAuth(corp: CorpConfig) { clearCorpTokenCache(corp.id); const source = corp.source; - const appKey = source.appKey; - const appSecurity = source.appSecurity; + const credentials = await resolveCorpCredentials(corp); + const appKey = credentials.appKey; + const appSecurity = credentials.appSecurity; const sealUrl = (corp.seal.url ?? source.sealUrl ?? `https://${source.corpId.toLowerCase()}.sealai.cc`).replace(/\/+$/, ""); const uid = source.staffId.includes(":") ? source.staffId : `${source.corpId}:${source.staffId}`; const stages: Array> = []; - if ((!appKey || !appSecurity) && !source.closeToken) { + if ((!appKey || !appSecurity) && !credentials.closeToken) { return { corp: { id: corp.id, @@ -282,7 +285,7 @@ async function diagnoseAuth(corp: CorpConfig) { if (openapi) stages.push(openapi.public); const openapiToken = openapi?.private?.token; - const provisional = source.closeToken + const provisional = credentials.closeToken ? { public: { name: "hose.closeapi", @@ -292,7 +295,7 @@ async function diagnoseAuth(corp: CorpConfig) { configured: true, expiresAt: source.expiresAt }, - private: { token: source.closeToken } + private: { token: credentials.closeToken } } : openapiToken ? await runDiagnoseStage("hose.provisional", async () => { diff --git a/src/cli/commands/corps/onboarding.ts b/src/cli/commands/corps/onboarding.ts index 11e0efd..13a398f 100644 --- a/src/cli/commands/corps/onboarding.ts +++ b/src/cli/commands/corps/onboarding.ts @@ -1,4 +1,5 @@ import { maskHoseSecurity } from "../../../core/auth/hose.js"; +import { resolveCorpCredentials } from "../../../core/auth/credentials.js"; import { scoreAssistLink } from "../../../core/auth/delegate.js"; import { onboardSealBearer } from "../../../domains/seal/enterprise/onboarding.js"; import { onboardAssistanceLink } from "../../../domains/enterprise/onboarding.js"; @@ -409,8 +410,9 @@ export async function showCorpKeysAction(targetCorpId: string | undefined, optio throw new CliError(`【合思子域专享能力】当前企业「${corp.name}」(id: ${corp.id}) 为原生 Seal (${corp.source.type}) 租户,非合思 (Hose/合思云/易快报) 渠道企业。\n` + "OpenAPI 密钥查询与提权能力专属于合思生态租户(用于从合思协助链接或合思凭据中提取开发者密钥提升权限等级),非合思渠道企业不支持此能力。", 2); } - const appKey = corp.source.appKey; - const appSecurity = corp.source.appSecurity; + const credentials = await resolveCorpCredentials(corp); + const appKey = credentials.appKey; + const appSecurity = credentials.appSecurity; if (!reveal) console.error("💡 [合思子域] 接入密码默认脱敏,附加 --reveal (或 -r) 可查看完整 appSecurity 明文。\n"); else console.error("⚠️ [合思子域] 正在以明文展示合思 appSecurity 接入密码,请妥善保管敏感凭据。\n"); printJson({ diff --git a/src/cli/commands/corps/overview.ts b/src/cli/commands/corps/overview.ts index 5c93efb..ce2448d 100644 --- a/src/cli/commands/corps/overview.ts +++ b/src/cli/commands/corps/overview.ts @@ -93,6 +93,7 @@ export async function handleCorpOverview( name: item.name, active: item.active ?? true, environment: item.environment ?? "production", + storage: item.storage ?? "local", sourceType: item.source.type, staffId: item.source.staffId, testCorpId: item.testCorpId, @@ -118,6 +119,7 @@ export async function handleCorpOverview( name: corp.name, active: corp.active ?? true, environment: corp.environment ?? "production", + storage: corp.storage ?? "local", configFile, seal: { url: sealUrl, @@ -145,6 +147,7 @@ export async function handleCorpOverview( name: corp.name, active: corp.active ?? true, environment: corp.environment ?? "production", + storage: corp.storage ?? "local", sourceType: corp.source.type, staffId: corp.source.staffId, testCorpId: corp.testCorpId, diff --git a/src/core/auth/credentials.test.ts b/src/core/auth/credentials.test.ts new file mode 100644 index 0000000..4e0d1f0 --- /dev/null +++ b/src/core/auth/credentials.test.ts @@ -0,0 +1,100 @@ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { CorpConfigSchema, type CorpConfig } from "../config/types.js"; +import { CliError } from "../errors.js"; +import { getSealSessionForCorp } from "./seal.js"; +import { getSealSession } from "./token-store.js"; +import { isCloudCorp, resolveCorpCredentials } from "./credentials.js"; + +function localHoseCorp(): CorpConfig { + return CorpConfigSchema.parse({ + id: "local-hose", + name: "Local Hose", + source: { + type: "hose", + domain: "https://app.ekuaibao.com", + appKey: "app-key", + appSecurity: "app-security", + corpId: "ID01", + staffId: "ID01:STAFF01" + } + }); +} + +function localSealCorp(): CorpConfig { + return CorpConfigSchema.parse({ + id: "local-seal", + name: "Local Seal", + seal: { cookies: { sdp_app_session: "cookie-value" } }, + source: { + type: "seal", + token: "seal-token", + sealUrl: "https://seal.example.com" + } + }); +} + +function cloudSealCorp(): CorpConfig { + return CorpConfigSchema.parse({ + id: "cloud-seal", + name: "Cloud Seal", + storage: "cloud", + source: { + type: "seal", + sealUrl: "https://seal.example.com" + } + }); +} + +describe("resolveCorpCredentials", () => { + test("returns local hose credentials from the config", async () => { + const credentials = await resolveCorpCredentials(localHoseCorp()); + expect(credentials).toEqual({ + appKey: "app-key", + appSecurity: "app-security", + closeToken: undefined + }); + }); + + test("returns local seal credentials and gateway cookies", async () => { + const credentials = await resolveCorpCredentials(localSealCorp()); + expect(credentials.token).toBe("seal-token"); + expect(credentials.cookies).toEqual({ sdp_app_session: "cookie-value" }); + }); + + test("fails closed with exit code 11 for cloud enterprises", async () => { + const corp = cloudSealCorp(); + expect(isCloudCorp(corp)).toBe(true); + + try { + await resolveCorpCredentials(corp); + throw new Error("expected resolveCorpCredentials to reject"); + } catch (error) { + expect(error).toBeInstanceOf(CliError); + expect((error as CliError).exitCode).toBe(11); + } + }); +}); + +describe("cloud session isolation", () => { + let tempDir: string; + + beforeEach(() => { + tempDir = mkdtempSync(join(tmpdir(), "seal-credentials-test-")); + process.env.SEAL_USE_TOKEN_STORE = join(tempDir, "tokens.json"); + }); + + afterEach(() => { + delete process.env.SEAL_USE_TOKEN_STORE; + rmSync(tempDir, { recursive: true, force: true }); + }); + + test("cloud enterprises never read or write the local token store", async () => { + const corp = cloudSealCorp(); + + await expect(getSealSessionForCorp(corp)).rejects.toBeInstanceOf(CliError); + expect(getSealSession(corp.id)).toBeUndefined(); + }); +}); diff --git a/src/core/auth/credentials.ts b/src/core/auth/credentials.ts new file mode 100644 index 0000000..fc98a98 --- /dev/null +++ b/src/core/auth/credentials.ts @@ -0,0 +1,55 @@ +import type { CorpConfig } from "../config/types.js"; +import { CliError } from "../errors.js"; + +/** + * Credentials needed to authenticate one enterprise. `local` enterprises read + * them from the config file; `cloud` enterprises will receive them from the + * bridge credential service. Callers must never read `corp.source` secrets + * directly so both modes share one path. + */ +export type CorpCredentials = { + appKey?: string; + appSecurity?: string; + closeToken?: string; + token?: string; + cookies?: Record; +}; + +export function isCloudCorp(corp: CorpConfig): boolean { + return (corp.storage ?? "local") === "cloud"; +} + +export function cloudAuthRequiredError(corp: CorpConfig): CliError { + return new CliError( + `企业「${corp.name}」(id: ${corp.id}) 使用云端凭据,需要先登录桥接服务。`, + 11, + "登录能力在阶段三提供;本地 (storage: local) 企业不受影响。" + ); +} + +/** + * Resolve credentials for a corp. + * + * Local enterprises return their config fields unchanged. Cloud enterprises + * fail closed until the bridge client lands: there is no local secret to fall + * back to, so a silent fallback would be worse than an explicit error. + */ +export async function resolveCorpCredentials(corp: CorpConfig): Promise { + if (isCloudCorp(corp)) { + throw cloudAuthRequiredError(corp); + } + + const source = corp.source; + if (source.type === "hose") { + return { + appKey: source.appKey, + appSecurity: source.appSecurity, + closeToken: source.closeToken + }; + } + + return { + token: source.token, + cookies: corp.seal.cookies + }; +} diff --git a/src/core/auth/hose.ts b/src/core/auth/hose.ts index 6cd92ad..d95a7e5 100644 --- a/src/core/auth/hose.ts +++ b/src/core/auth/hose.ts @@ -3,6 +3,7 @@ import { CorpConfig, HoseSealSource } from "../config/types.js"; import { createSealClientForUrl } from "../http/factory.js"; import { resolveSealCustomHeaders } from "../http/request-headers.js"; import { getHoseAuthCache, setHoseAuthCache } from "./token-store.js"; +import { isCloudCorp, resolveCorpCredentials, type CorpCredentials } from "./credentials.js"; import { SealEnterpriseConfig, SealSession, TokenEntry } from "./types.js"; type HoseLoginResponse = { @@ -272,10 +273,10 @@ function hoseClient(source: HoseSealSource): KyInstance { }); } -async function fetchHoseOpenapiToken(source: HoseSealSource): Promise { +async function fetchHoseOpenapiToken(source: HoseSealSource, credentials: CorpCredentials): Promise { const client = hoseClient(source); - const appKey = source.appKey; - const appSecurity = source.appSecurity; + const appKey = credentials.appKey; + const appSecurity = credentials.appSecurity; if (!appKey || !appSecurity) { throw new Error("Hose source has no OpenAPI credentials; the configured closeToken is only valid for Hose web-session APIs"); @@ -308,7 +309,8 @@ export async function getHoseOpenapiToken( if (corp.source.type !== "hose") { throw new Error(`Unsupported Seal source: ${corp.source.type}`); } - const cache = getHoseAuthCache(corp.id); + const cloud = isCloudCorp(corp); + const cache = cloud ? {} : getHoseAuthCache(corp.id); if (!options?.force && isFresh(cache.openapi)) { return { ...cache.openapi, cached: true }; } @@ -316,7 +318,8 @@ export async function getHoseOpenapiToken( const pending = openapiTokenRequests.get(corp.id); if (pending) return { ...(await pending), cached: false }; - const request = fetchHoseOpenapiToken(corp.source) + const credentials = await resolveCorpCredentials(corp); + const request = fetchHoseOpenapiToken(corp.source, credentials) .then((openapi) => { setHoseAuthCache(corp.id, { ...getHoseAuthCache(corp.id), @@ -379,19 +382,20 @@ export async function ensureHoseCloseApiToken(corp: CorpConfig): Promise= expiresAt) { throw new Error("Configured Hose closeToken has expired; import a fresh Hose web session"); } return { - token: source.closeToken, + token: credentials.closeToken, expiresAt }; } - const cache = getHoseAuthCache(corp.id); + const cache = isCloudCorp(corp) ? {} : getHoseAuthCache(corp.id); if (isFresh(cache.closeapi) && cache.closeapi.url) { return cache.closeapi; } diff --git a/src/core/auth/native.ts b/src/core/auth/native.ts index 3a34c14..36c9ed0 100644 --- a/src/core/auth/native.ts +++ b/src/core/auth/native.ts @@ -1,10 +1,16 @@ import { CorpConfig } from "../config/types.js"; +import { validationError } from "../errors.js"; import { SealSession } from "./types.js"; export async function getNativeSealSession(corp: CorpConfig): Promise { if (corp.source.type !== "seal") { throw new Error(`Unsupported Seal source: ${corp.source.type}`); } + if (!corp.source.token) { + throw validationError( + `企业「${corp.name}」(id: ${corp.id}) 没有本地 Seal token;cloud 企业需先通过凭据服务登录后获取。` + ); + } const sealUrl = corp.seal.url ?? corp.source.sealUrl; const expiresAt = corp.source.expiresAt diff --git a/src/core/auth/seal.ts b/src/core/auth/seal.ts index daaf43e..f3d05c3 100644 --- a/src/core/auth/seal.ts +++ b/src/core/auth/seal.ts @@ -15,6 +15,7 @@ import { rotateBackupCookies } from "./session-fallback.js"; import { createSealDelegationLink, exchangeSealDelegateLink } from "./delegate.js"; +import { cloudAuthRequiredError, isCloudCorp } from "./credentials.js"; import { saveCorpConfig } from "../config/repository.js"; import { formatBeijingIso } from "../config/timestamps.js"; @@ -32,6 +33,8 @@ function isExpired(session: SealSession, refreshTtl: number): boolean { export async function renewNativeSealSession(corp: CorpConfig): Promise { const source = corp.source; if (source.type !== "seal") return undefined; + // Cloud enterprises have no local token and never renew through delegation. + if (!source.token) return undefined; const authCache = getSealDelegateAuthCache(corp.id); const candidateCookies = resolveCandidateCookies(authCache); @@ -104,6 +107,11 @@ export async function renewNativeSealSession(corp: CorpConfig): Promise { + if (isCloudCorp(corp)) { + // Phase 3 replaces this with the bridge credential fetch. + throw cloudAuthRequiredError(corp); + } + switch (corp.source.type) { case "hose": return getHoseSealSession(corp); @@ -130,7 +138,8 @@ export async function getSealSessionForCorp(corp: CorpConfig): Promise { memoryCache.set(corp.id, next); - setSealSession(corp.id, next); + if (!cloud) setSealSession(corp.id, next); return next; }).finally(() => pendingSessions.delete(corp.id)); pendingSessions.set(corp.id, request); diff --git a/src/core/config/loader.ts b/src/core/config/loader.ts index 0cd984a..b042349 100644 --- a/src/core/config/loader.ts +++ b/src/core/config/loader.ts @@ -135,7 +135,7 @@ function loadCorpConfigEntries(): Array<{ config: CorpConfig; path: string }> { // Materialize the tenant availability default so every config read from // disk carries an explicit boolean. Legacy files without `active` stay // enabled; `false` (explicit or normalized) gates command execution. - corp = { ...parsed, active: parsed.active ?? true }; + corp = { ...parsed, active: parsed.active ?? true, storage: parsed.storage ?? "local" }; } catch (error) { issues.push({ dir, file, reason: error instanceof Error ? error.message : String(error) }); continue; diff --git a/src/core/config/types.test.ts b/src/core/config/types.test.ts index a8c4d3a..2d64b4e 100644 --- a/src/core/config/types.test.ts +++ b/src/core/config/types.test.ts @@ -158,6 +158,108 @@ describe("CorpConfigSchema", () => { expect(config.source.tenantSlug).toBe("xiezihao"); }); + test("accepts a cloud hose source without local credentials", () => { + const config = CorpConfigSchema.parse({ + id: "cloud-hose", + name: "Cloud Hose", + storage: "cloud", + source: { + type: "hose", + domain: "https://app.ekuaibao.com", + corpId: "ID01", + staffId: "ID01:STAFF01" + } + }); + + expect(config.storage).toBe("cloud"); + expect(config.source.type).toBe("hose"); + }); + + test("accepts a cloud seal source without a local token", () => { + const config = CorpConfigSchema.parse({ + id: "cloud-seal", + name: "Cloud Seal", + storage: "cloud", + source: { + type: "seal", + sealUrl: "https://seal.sealai.cc" + } + }); + + expect(config.storage).toBe("cloud"); + expect(config.source.type).toBe("seal"); + }); + + test("rejects cloud configs that still persist secrets", () => { + const hoseResult = CorpConfigSchema.safeParse({ + id: "cloud-hose", + name: "Cloud Hose", + storage: "cloud", + source: { + type: "hose", + domain: "https://app.ekuaibao.com", + appKey: "app-key", + corpId: "ID01", + staffId: "ID01:STAFF01" + } + }); + expect(hoseResult.success).toBe(false); + + const sealResult = CorpConfigSchema.safeParse({ + id: "cloud-seal", + name: "Cloud Seal", + storage: "cloud", + source: { + type: "seal", + token: "seal-token", + sealUrl: "https://seal.sealai.cc" + } + }); + expect(sealResult.success).toBe(false); + + const cookieResult = CorpConfigSchema.safeParse({ + id: "cloud-seal-cookie", + name: "Cloud Seal Cookie", + storage: "cloud", + seal: { + url: "https://seal.sealai.cc", + cookies: { sdp_app_session: "secret" } + }, + source: { + type: "seal", + sealUrl: "https://seal.sealai.cc" + } + }); + expect(cookieResult.success).toBe(false); + }); + + test("legacy configs without storage remain local", () => { + const config = CorpConfigSchema.parse({ + id: "legacy-local", + name: "Legacy Local", + source: { + type: "seal", + token: "seal-token", + sealUrl: "https://seal.sealai.cc" + } + }); + + expect(config.storage).toBeUndefined(); + }); + + test("requires a token for local seal sources", () => { + const result = CorpConfigSchema.safeParse({ + id: "local-seal", + name: "Local Seal", + source: { + type: "seal", + sealUrl: "https://seal.sealai.cc" + } + }); + + expect(result.success).toBe(false); + }); + test("leaves custom headers and cookies absent by default", () => { const config = CorpConfigSchema.parse({ id: "seal", diff --git a/src/core/config/types.ts b/src/core/config/types.ts index 29857c5..0f2d3d5 100644 --- a/src/core/config/types.ts +++ b/src/core/config/types.ts @@ -17,27 +17,13 @@ export const HoseSealSourceSchema = z.object({ staffId: z.string(), corpId: z.string(), sealUrl: z.string().url().optional() -}).superRefine((source, ctx) => { - if (!source.closeToken && !source.appKey) { - ctx.addIssue({ - code: "custom", - path: ["appKey"], - message: "Hose source requires appKey or closeToken" - }); - } - - if (!source.closeToken && !source.appSecurity) { - ctx.addIssue({ - code: "custom", - path: ["appSecurity"], - message: "Hose source requires appSecurity or closeToken" - }); - } }); export const NativeSealSourceSchema = z.object({ type: z.literal("seal"), - token: z.string(), + // Optional at the source level: local enterprises must supply it, while + // cloud enterprises obtain it at runtime. CorpConfigSchema enforces both. + token: z.string().optional(), sealUrl: z.string().url(), expiresIn: z.number().int().positive().default(3600), expiresAt: IsoSecondTimestampSchema.optional(), @@ -104,9 +90,18 @@ export const CorpAuthConfigSchema = z.object({ export const CorpEnvironmentSchema = z.enum(["production", "test"]).default("production"); +/** + * Where the enterprise credentials live. `local` keeps them in this file; + * `cloud` keeps them in the bridge credential service and the local file must + * not contain any secret. Absent means `local` for legacy configs; the loader + * materializes it on read. + */ +export const CorpStorageSchema = z.enum(["local", "cloud"]); + export const CorpConfigSchema = z.object({ id: z.string(), name: z.string(), + storage: CorpStorageSchema.optional(), // Tenant availability gate. It lives on the enterprise, NOT on a source, so // `hose` and `seal` sources share exactly one switch and cannot diverge. // Fail-closed three-way semantics: @@ -124,6 +119,61 @@ export const CorpConfigSchema = z.object({ environment: CorpEnvironmentSchema, testCorpId: z.string().optional(), prodCorpId: z.string().optional() +}).superRefine((config, ctx) => { + const storage = config.storage ?? "local"; + const source = config.source; + + if (storage === "cloud") { + if (source.type === "hose") { + for (const field of ["appKey", "appSecurity", "closeToken"] as const) { + if (source[field] !== undefined) { + ctx.addIssue({ + code: "custom", + path: ["source", field], + message: `cloud storage must not persist ${field}; manage it in the credential service` + }); + } + } + } else if (source.token !== undefined) { + ctx.addIssue({ + code: "custom", + path: ["source", "token"], + message: "cloud storage must not persist token; manage it in the credential service" + }); + } + + if (config.seal.cookies && Object.keys(config.seal.cookies).length > 0) { + ctx.addIssue({ + code: "custom", + path: ["seal", "cookies"], + message: "cloud storage must not persist seal.cookies; manage them in the credential service" + }); + } + return; + } + + if (source.type === "hose") { + if (!source.closeToken && !source.appKey) { + ctx.addIssue({ + code: "custom", + path: ["source", "appKey"], + message: "Hose source requires appKey or closeToken" + }); + } + if (!source.closeToken && !source.appSecurity) { + ctx.addIssue({ + code: "custom", + path: ["source", "appSecurity"], + message: "Hose source requires appSecurity or closeToken" + }); + } + } else if (!source.token) { + ctx.addIssue({ + code: "custom", + path: ["source", "token"], + message: "Seal source requires token" + }); + } }); export const GlobalLintConfigSchema = z.object({ @@ -144,6 +194,7 @@ export const GlobalConfigSchema = z.object({ }); export type CorpEnvironment = z.infer; +export type CorpStorage = z.infer; export type HoseSealSource = z.infer; export type NativeSealSource = z.infer; export type SealSource = z.infer; diff --git a/src/domains/hose/open/approval.ts b/src/domains/hose/open/approval.ts index 0faf804..d5fe176 100644 --- a/src/domains/hose/open/approval.ts +++ b/src/domains/hose/open/approval.ts @@ -1,6 +1,7 @@ import { HTTPError } from "ky"; import type { CorpConfig } from "../../../core/config/types.js"; import { CliError, validationError } from "../../../core/errors.js"; +import { resolveCorpCredentials } from "../../../core/auth/credentials.js"; import { createHoseOpenClient } from "./client.js"; /** @@ -42,8 +43,9 @@ export async function executeEbotApprovalCallback( ); } - const appKey = corp.source.appKey; - const appSecurity = corp.source.appSecurity; + const credentials = await resolveCorpCredentials(corp); + const appKey = credentials.appKey; + const appSecurity = credentials.appSecurity; if (!appKey || !appSecurity) { throw validationError( `缺少合思凭证:企业「${corp.name}」(id: ${corp.id}) 未配置 appKey/appSecurity,无法换取 accessToken 执行审批回调。` diff --git a/src/domains/seal/testing/sync.ts b/src/domains/seal/testing/sync.ts index d7729ef..6a3d087 100644 --- a/src/domains/seal/testing/sync.ts +++ b/src/domains/seal/testing/sync.ts @@ -1,6 +1,7 @@ import { randomBytes } from "node:crypto"; import type { KyInstance } from "ky"; import { createSealClient } from "../../../core/http/factory.js"; +import { resolveCorpCredentials } from "../../../core/auth/credentials.js"; import { formatBeijingIso } from "../../../core/config/timestamps.js"; import type { CorpConfig } from "../../../core/config/types.js"; import * as api from "../api.js"; @@ -318,8 +319,9 @@ interface HosecloudSyncResult { async function syncHosecloudIntegrationsToTest(prodCorp: CorpConfig, testCorp: CorpConfig, prodClient: KyInstance, testClient: KyInstance): Promise { if (prodCorp.source.type !== "hose") return { skipped: true, reason: "prod source is not hose; no hosecloud credentials available" }; - const appKey = prodCorp.source.appKey?.trim(); - const appSecurity = prodCorp.source.appSecurity?.trim(); + const credentials = await resolveCorpCredentials(prodCorp); + const appKey = credentials.appKey?.trim(); + const appSecurity = credentials.appSecurity?.trim(); 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),