Merge pull request #290 from yunyingk/mac15/cloud-enterprise-config

Add cloud enterprise config with bridge device login
This commit is contained in:
yunyingk authored and GitHub committed 2026-11-19 17:51:09 +08:00
commit 57e01e5079
26 files changed
+1433 -90

No files matched your search

@@ -0,0 +1,160 @@
# 云端企业配置方案(seal-use 侧)
状态:阶段一、二、三已实施(2026-11-19);桥接设备码已接入,`doctor` 已增加云端登录检查。
## 仓库边界
- `seal-use` 与 `hose-fde-workbench` 保持**两个独立仓库**,不合并为 monorepo(2026-11-19 决定)。
- 对 seal-use 而言,cloud 企业配置是**增量功能**:默认 `storage: local`,现有用户、配置与命令行为不变。
- 桥接作为独立凭据服务,通过 HTTP 契约交互;登录、scope、审计都在桥接侧。
## 进度
| 侧 | 状态 |
|---|---|
| seal-use | 阶段一、二已实施并提交(`mac15/cloud-enterprise-config`,`887df2d`);阶段三待设备码 |
| 桥接 | 凭据服务已交付(PR #102);设备码端点需求已发送,待实现 |
| 下一步 | 设备码契约定稿 → seal-use `bridge-client` + `auth login` → 预签发 token 注入、提权禁用、doctor 检查 |
## 已定决策
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/enterprise-credentials/resolve?type=hose&corpId=<corpId>
Cookie: hose_sealai_session=<token>
```
响应(桥接实际返回):
```json
// hose:服务端已用 appKey/appSecurity 换好短期 accessToken
{ "ok": true, "credential": {
"type": "hose", "corpId": "...", "name": "...", "baseUrl": "...",
"token": "<accessToken>", "tokenType": "query", "tokenName": "accessToken",
"expiresAt": "2026-11-19T10:05:00.000Z", "metadata": { "note": "生产" } } }
// seal:Bearer Token,可能附带协助授权会话 Cookie,expiresAt 可能为 null
{ "ok": true, "credential": {
"type": "seal", "corpId": "...", "name": "...", "baseUrl": "...",
"token": "<bearer>", "tokenType": "bearer", "tokenName": "Authorization",
"expiresAt": "2026-12-01T00:00:00.000Z", "sessionCookie": "sid=...", "metadata": null } }
```
与本文早期假设的关键差异:
1. **hose 返回的是已换好的 accessToken**,不是 appKey/appSecurity。`getHoseOpenapiToken` 需要新增"预签发 token"路径,跳过本地换发。
2. **`tokenType` / `tokenName` 决定注入位置**(`query` / `header` / `bearer` / `body`)。现有 `fetchHoseCloseApiToken` 与 SSO 请求写死 `accessToken` 查询参数,需要按响应注入。
3. **seal 的 `expiresAt` 可能为 null**:此时按本地保守策略缓存,并在 401/403 时重新拉取。
4. **读取需要菜单 scope**:hose 要 `expense`,seal 要 `sealai`;403 响应带 `requiredScope`。
错误语义(桥接实际):
| HTTP / code | seal-use 行为 | 退出码 |
|---|---|---|
| 401 `AUTH_REQUIRED` | 提示重新登录后重试一次 | 11 |
| 403 `FORBIDDEN` | 提示管理员授予 `expense` / `sealai` scope | 11 |
| 404 `CREDENTIAL_NOT_FOUND` | 该企业未在云端登记 | 13 |
| 409 `CREDENTIAL_DISABLED` / `CREDENTIAL_MISMATCH` | 提示管理员启用或核对密钥归属 | 13 |
| 500 `DECRYPT_FAILED` / `INTERNAL_ERROR` | 平台侧问题,退避后告警 | 1 |
| 502 `UPSTREAM_AUTH_FAILED` | 合思授权失败,指数退避重试 | 1 |
### CLI 登录
**决定:采用设备码登录,等待桥接新增 `/api/auth/device/start` 与 `/api/auth/device/token`。** 在设备码端点可用前,不实现基于账号密码或 Cookie 的登录方式。
桥接当前只提供账号密码登录换会话 Cookie,**没有设备码或 PAT**:
```http
POST /api/auth/login
Origin: https://<bridge-host>
{ "username": "seal-use-service", "password": "..." }
```
- 会话 Cookie `hose_sealai_session` 有效期 180 天、滑动续期;响应带新 `Set-Cookie` 时覆盖保存。
- seal-use 保存 Cookie 到 `~/.config/seal-use/bridge.json`(`0600`),支持 `SEAL_USE_BRIDGE_TOKEN` 环境变量覆盖。
- **遗留缺口**:Cookie 过期后必须重新用密码登录。若不想在本地保存服务账号密码,需要桥接补设备码或 PAT;当前契约下只能二选一(存密码自动重登,或过期后交互式输入)。
## 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`:账号登录换 Cookie、Cookie 持久化与滑动续期、凭据请求与内存缓存。
9. `resolveCorpCredentials` 的 cloud 分支返回预签发凭据;`getHoseOpenapiToken` 增加预签发 token 路径,并按 `tokenType` / `tokenName` 注入请求。
10. `seal-use auth login/logout/status` 命令;`doctor` 增加登录、scope 与连通性检查。
11. cloud 企业禁用提权类命令(`add-link --as-hose`、`hose-extract-keys`、`corps keys`),提示到云端管理。
实施状态:8–11 已完成。CLI 命令为 `auth login` / `auth logout` / `auth bridge`。
## 兼容与行为变化
- 旧配置无 `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. 桥接设备码端点的具体形态与令牌有效期(已决定用设备码,待桥接提供)。
2. cloud 企业是否允许本地缓存派生会话(当前定为不允许,纯内存)。
3. 切换 `local ↔ cloud` 的命令形态。
4. 桥接管理端前端页面(当前仅 API,凭据由管理员通过接口维护)。
+3
View File
@@ -175,6 +175,9 @@ seal-use config mode <stateful|stateless> [--corp <corpId>]
seal-use config test-dir [<path>|--clear]
seal-use config lint [status|enable|disable] [--linter <name|path>] [--min-score <score>]
seal-use auth check [--corp <corpId>]
seal-use auth login [--bridge <https://bridge-host>]
seal-use auth logout
seal-use auth bridge
seal-use auth link [--note <note>] [--expire <duration>] [--corp <corpId>]
seal-use auth link --from-link <url> [--note <note>] [--expire <duration>]
seal-use auth link list [--corp <corpId>]
+82 -7
View File
@@ -6,6 +6,18 @@ import {
normalizeBaseUrl
} from "../../core/auth/hose.js";
import { clearCorpTokenCache } from "../../core/auth/token-store.js";
import { resolveCorpCredentials } from "../../core/auth/credentials.js";
import {
clearBridgeCredentialCache,
pollBridgeDeviceToken,
revokeBridgeToken,
startBridgeDeviceLogin
} from "../../core/auth/bridge-client.js";
import {
clearBridgeSession,
readBridgeSession,
saveBridgeSession
} from "../../core/auth/bridge-token.js";
import { formatBeijingIso } from "../../core/config/timestamps.js";
import type { CorpConfig } from "../../core/config/types.js";
import { CliError, validationError, usageError } from "../../core/errors.js";
@@ -46,10 +58,71 @@ export async function handleAuthExtractKeysCommand(maybeName: string | undefined
});
}
async function handleBridgeLogin(args: ParsedArgs): Promise<void> {
const url = stringOption(args.options.bridge) ?? stringOption(args.options.url) ?? process.env.SEAL_USE_BRIDGE_URL?.trim();
if (!url) {
throw usageError("Usage: seal-use auth login --bridge <https://bridge-host>");
}
const start = await startBridgeDeviceLogin(url);
console.error(`👉 请在浏览器打开: ${start.verificationUrl}`);
console.error(` 核对代码: ${start.userCode}(${Math.round(start.expiresIn / 60)} 分钟内有效)`);
const token = await pollBridgeDeviceToken(url, start.deviceCode, start.interval, start.expiresIn, {
onPending: (attempt) => {
if (attempt === 1) console.error("⏳ 等待浏览器确认...");
}
});
saveBridgeSession({ url, token: token.token, expiresAt: token.expiresAt, username: token.username });
printJson({
ok: true,
url,
username: token.username ?? null,
expiresAt: token.expiresAt ?? null
});
}
async function handleBridgeLogout(): Promise<void> {
const session = readBridgeSession();
if (session) await revokeBridgeToken(session);
clearBridgeSession();
clearBridgeCredentialCache();
printJson({ ok: true, loggedOut: true });
}
async function handleBridgeStatus(): Promise<void> {
const session = readBridgeSession();
if (!session) {
printJson({ ok: true, loggedIn: false });
return;
}
printJson({
ok: true,
loggedIn: true,
url: session.url,
username: session.username ?? null,
expiresAt: session.expiresAt ?? null
});
}
export async function handleAuthCommand(action: string | undefined, corp: CorpConfig | null, args: ParsedArgs) {
const subAction = args.command[2]?.toLowerCase();
const fromLink = stringOption(args.options["from-link"]) ?? (subAction === "from-link" ? args.command[3] : undefined);
if (action === "login") {
await handleBridgeLogin(args);
return;
}
if (action === "logout") {
await handleBridgeLogout();
return;
}
if (action === "bridge" || action === "bridge-status") {
await handleBridgeStatus();
return;
}
if ((action === "seal-link" || action === "link" || (action === "hose-link" && corp?.source?.type === "seal")) && fromLink) {
const note = stringOption(args.options.note);
const expireOption = args.options.expire ?? args.options["expires-in"] ?? args.options.expiresIn;
@@ -175,8 +248,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 +311,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<Record<string, unknown>> = [];
if ((!appKey || !appSecurity) && !source.closeToken) {
if ((!appKey || !appSecurity) && !credentials.closeToken) {
return {
corp: {
id: corp.id,
@@ -282,7 +357,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 +367,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 () => {
+10 -2
View File
@@ -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";
@@ -405,12 +406,19 @@ export async function extractKeysFromLinkAction(link: string, options: { reveal?
export async function showCorpKeysAction(targetCorpId: string | undefined, options: { reveal?: boolean }) {
const corp = selectCorp(targetCorpId);
const reveal = options.reveal === true;
if ((corp.storage ?? "local") === "cloud") {
throw new CliError(
`企业「${corp.name}」(id: ${corp.id}) 使用云端凭据,本地不提供密钥查看或提权。\n请在桥接平台的凭据管理中维护该企业。`,
2
);
}
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;
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({
+3
View File
@@ -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,
+21
View File
@@ -1108,6 +1108,27 @@ export const HELP_REGISTRY: AreaHelp[] = [
summary: "Check auth session and platform connectivity",
usage: ["seal-use auth check [--corp <corpId>]"]
},
{
name: "login",
summary: "【云端企业】通过设备码登录桥接凭据服务",
usage: ["seal-use auth login [--bridge <https://bridge-host>]"],
options: [
{ flag: "--bridge <url>", description: "桥接服务地址;也可用 SEAL_USE_BRIDGE_URL 环境变量" }
],
description:
"仅 cloud 企业需要。CLI 申请设备码后,用户在浏览器确认授权;令牌保存在 ~/.config/seal-use/bridge.json(0600),30 天有效,到期后重新登录。"
},
{
name: "logout",
summary: "【云端企业】撤销并删除本地桥接令牌",
usage: ["seal-use auth logout"]
},
{
name: "bridge",
aliases: ["bridge-status"],
summary: "【云端企业】查看桥接登录状态",
usage: ["seal-use auth bridge"]
},
{
name: "link",
summary: "【Seal 审核后台】生成免密登录/委托访问直达链接",
+1 -1
View File
@@ -45,7 +45,7 @@ export const VALUE_FLAGS = new Set([
"min-file-size", "min-file-size-bytes", "minFileSize", "minFileSizeBytes",
"max-file-size", "max-file-size-bytes", "maxFileSize", "maxFileSizeBytes", "templates",
"access-token", "accessToken", "action", "add-approver-ids", "addApproverIds", "ai", "ai-accuracy", "aiAccuracy", "app-key", "app-security", "appKey", "appSecurity",
"base-url", "batch", "batch-id", "batchId", "both", "both-accurate", "bothAccurate", "business-codes", "businessCodes",
"base-url", "batch", "batch-id", "batchId", "both", "both-accurate", "bothAccurate", "bridge", "business-codes", "businessCodes",
"channel", "chrome", "code", "comment", "concurrency", "confirm-code", "confirmCode", "content", "content-file", "content-hints", "content-type", "contentFile",
"content-format", "contentFormat", "contentType", "context-chars", "context-lines", "contextLines", "corp", "corp-id", "corpId", "corporation-id", "corporationId", "date", "days",
"dedupe-by", "dedupeBy", "default", "departmentId", "dept", "desc",
+1 -1
View File
@@ -67,7 +67,7 @@ const READ_ONLY_COMMANDS: Record<string, string[]> = {
// read forms cannot be separated from the value-taking write forms. `config get` returns
// the same summary (mode + lint included), so read access loses nothing.
config: ["paths", "get"],
auth: ["check", "diagnose", "status", "test", "doctor", "link list", "seal-link list"],
auth: ["check", "diagnose", "status", "test", "doctor", "bridge", "bridge-status", "link list", "seal-link list"],
users: ["search", "get"],
contacts: ["departments", "children", "users", "sync-time"],
data: ["expenses", "invoices"],
+151
View File
@@ -0,0 +1,151 @@
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 {
clearBridgeCredentialCache,
pollBridgeDeviceToken,
resolveCloudCredential
} from "./bridge-client.js";
import { BRIDGE_SESSION_FILE_ENV, BRIDGE_TOKEN_ENV, BRIDGE_URL_ENV } from "./bridge-token.js";
const originalFetch = globalThis.fetch;
let tempDir: string;
function cloudSealCorp(): CorpConfig {
return CorpConfigSchema.parse({
id: "cloud-seal",
name: "Cloud Seal",
storage: "cloud",
source: { type: "seal", sealUrl: "https://seal.example.com" }
});
}
function jsonResponse(body: unknown, status = 200, headers: Record<string, string> = {}): Response {
return new Response(JSON.stringify(body), {
status,
headers: { "content-type": "application/json", ...headers }
});
}
beforeEach(() => {
tempDir = mkdtempSync(join(tmpdir(), "seal-bridge-client-test-"));
process.env[BRIDGE_SESSION_FILE_ENV] = join(tempDir, "bridge.json");
process.env[BRIDGE_URL_ENV] = "https://bridge.test";
process.env[BRIDGE_TOKEN_ENV] = "device-token";
clearBridgeCredentialCache();
});
afterEach(() => {
globalThis.fetch = originalFetch;
delete process.env[BRIDGE_SESSION_FILE_ENV];
delete process.env[BRIDGE_URL_ENV];
delete process.env[BRIDGE_TOKEN_ENV];
clearBridgeCredentialCache();
rmSync(tempDir, { recursive: true, force: true });
});
describe("resolveCloudCredential", () => {
test("requests the bridge with the device token and caches in memory", async () => {
let calls = 0;
let authorization = "";
globalThis.fetch = (async (_input: RequestInfo | URL, init?: RequestInit) => {
calls += 1;
authorization = new Headers(init?.headers).get("authorization") ?? "";
return jsonResponse({
ok: true,
credential: {
type: "seal",
corpId: "cloud-seal",
token: "bearer-token",
expiresAt: new Date(Date.now() + 3600_000).toISOString()
}
});
}) as unknown as typeof fetch;
const corp = cloudSealCorp();
const first = await resolveCloudCredential(corp);
const second = await resolveCloudCredential(corp);
expect(first.token).toBe("bearer-token");
expect(second.token).toBe("bearer-token");
expect(calls).toBe(1);
expect(authorization).toBe("Bearer device-token");
});
test("maps 401 to an auth error with exit code 11", async () => {
globalThis.fetch = (async () =>
jsonResponse({ ok: false, code: "AUTH_REQUIRED", error: "unauthenticated" }, 401)) as unknown as typeof fetch;
try {
await resolveCloudCredential(cloudSealCorp());
throw new Error("expected rejection");
} catch (error) {
expect(error).toBeInstanceOf(CliError);
expect((error as CliError).exitCode).toBe(11);
}
});
test("maps 404 to a configuration error with exit code 13", async () => {
globalThis.fetch = (async () =>
jsonResponse({ ok: false, code: "CREDENTIAL_NOT_FOUND", error: "missing" }, 404)) as unknown as typeof fetch;
try {
await resolveCloudCredential(cloudSealCorp());
throw new Error("expected rejection");
} catch (error) {
expect(error).toBeInstanceOf(CliError);
expect((error as CliError).exitCode).toBe(13);
}
});
test("fails closed when no bridge session exists", async () => {
delete process.env[BRIDGE_TOKEN_ENV];
delete process.env[BRIDGE_URL_ENV];
try {
await resolveCloudCredential(cloudSealCorp());
throw new Error("expected rejection");
} catch (error) {
expect(error).toBeInstanceOf(CliError);
expect((error as CliError).exitCode).toBe(11);
}
});
});
describe("pollBridgeDeviceToken", () => {
test("keeps polling while authorization is pending", async () => {
let calls = 0;
globalThis.fetch = (async () => {
calls += 1;
if (calls === 1) return jsonResponse({ ok: false, error: "authorization_pending" }, 202);
return jsonResponse({ ok: true, token: "issued-token", expiresAt: "2026-12-19T08:00:00.000Z" });
}) as unknown as typeof fetch;
const result = await pollBridgeDeviceToken("https://bridge.test", "device-code", 1, 600, {
sleep: async () => undefined,
now: () => 0
});
expect(result.token).toBe("issued-token");
expect(calls).toBe(2);
});
test("stops when the user denies the request", async () => {
globalThis.fetch = (async () =>
jsonResponse({ ok: false, error: "access_denied" }, 403)) as unknown as typeof fetch;
try {
await pollBridgeDeviceToken("https://bridge.test", "device-code", 1, 600, {
sleep: async () => undefined,
now: () => 0
});
throw new Error("expected rejection");
} catch (error) {
expect(error).toBeInstanceOf(CliError);
expect((error as CliError).exitCode).toBe(11);
}
});
});
+265
View File
@@ -0,0 +1,265 @@
import type { CorpConfig } from "../config/types.js";
import { CliError } from "../errors.js";
import { readBridgeSession, type BridgeSession } from "./bridge-token.js";
export type BridgeCredential = {
type: "hose" | "seal";
corpId: string;
token: string;
tokenType?: "query" | "header" | "bearer" | "body";
tokenName?: string;
expiresAt?: string | null;
sessionCookie?: string;
};
export type DeviceLoginStart = {
deviceCode: string;
userCode: string;
verificationUrl: string;
interval: number;
expiresIn: number;
};
export type DeviceLoginToken = {
token: string;
tokenType?: string;
expiresAt?: string;
username?: string;
};
const CACHE_SKEW_MS = 60_000;
const NULL_EXPIRY_TTL_MS = 5 * 60_000;
const REQUEST_TIMEOUT_MS = 20_000;
const credentialCache = new Map<string, { credential: BridgeCredential; expiresAt: number }>();
export function clearBridgeCredentialCache(corpId?: string): void {
if (corpId === undefined) {
credentialCache.clear();
return;
}
for (const key of credentialCache.keys()) {
if (key.endsWith(`:${corpId}`)) credentialCache.delete(key);
}
}
function normalizeBaseUrl(url: string): string {
return url.replace(/\/+$/, "");
}
function authRequired(message: string, nextAction?: string): CliError {
return new CliError(message, 11, nextAction ?? "运行 seal-use auth login 登录桥接服务后重试。");
}
function bridgeSessionOrThrow(): BridgeSession {
const session = readBridgeSession();
if (!session) {
throw authRequired("尚未登录桥接服务,无法读取云端企业凭据。");
}
return session;
}
function cacheTtl(credential: BridgeCredential): number {
if (!credential.expiresAt) return NULL_EXPIRY_TTL_MS;
const expiresAt = Date.parse(credential.expiresAt);
if (!Number.isFinite(expiresAt)) return NULL_EXPIRY_TTL_MS;
return Math.max(0, expiresAt - Date.now() - CACHE_SKEW_MS);
}
type BridgeErrorBody = {
ok?: boolean;
code?: string;
error?: string;
requiredScope?: string;
};
async function readJson<T>(response: Response): Promise<T | undefined> {
try {
return (await response.json()) as T;
} catch {
return undefined;
}
}
function mapResolveError(status: number, body: BridgeErrorBody | undefined): CliError {
const code = body?.code ?? body?.error ?? `HTTP ${status}`;
if (status === 401) {
return authRequired(`桥接会话已失效(${code}),请重新登录。`);
}
if (status === 403) {
const scope = body?.requiredScope ? `(需要菜单权限:${body.requiredScope})` : "";
return authRequired(`当前账号没有读取该企业凭据的权限${scope}。`, "请联系管理员授予 expense / sealai 菜单权限后重试。");
}
if (status === 404) {
return new CliError(`云端没有登记该企业凭据(${code})。`, 13, "请管理员在桥接平台补录该企业凭据。");
}
if (status === 409) {
return new CliError(`云端凭据当前不可用(${code}):${body?.error ?? ""}`.trim(), 13, "请管理员在桥接平台启用或核对凭据归属。");
}
return new CliError(`桥接凭据服务调用失败(${code})。`, 1, "稍后重试;持续失败请联系平台运维。");
}
/**
* Fetch a cloud enterprise credential from the bridge. The result is cached in
* memory only; nothing is written to disk.
*/
export async function resolveCloudCredential(corp: CorpConfig): Promise<BridgeCredential> {
const type = corp.source.type;
const key = `${type}:${corp.id}`;
const cached = credentialCache.get(key);
if (cached && Date.now() < cached.expiresAt) {
return cached.credential;
}
const session = bridgeSessionOrThrow();
const url = new URL(`${normalizeBaseUrl(session.url)}/api/enterprise-credentials/resolve`);
url.searchParams.set("type", type);
url.searchParams.set("corpId", corp.id);
let response: Response;
try {
response = await fetch(url, {
headers: {
Authorization: `Bearer ${session.token}`,
Accept: "application/json"
},
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
});
} catch (error) {
throw new CliError(
`无法连接桥接凭据服务:${error instanceof Error ? error.message : String(error)}`,
1,
"检查网络或 SEAL_USE_BRIDGE_URL 后重试。"
);
}
const body = await readJson<{ ok?: boolean; credential?: BridgeCredential } & BridgeErrorBody>(response);
if (!response.ok || !body?.ok || !body.credential) {
throw mapResolveError(response.status, body);
}
const credential = body.credential;
if (credential.type !== type || !credential.token) {
throw new CliError("桥接返回的凭据与请求类型不一致。", 1, "请联系平台运维检查凭据配置。");
}
credentialCache.set(key, { credential, expiresAt: Date.now() + cacheTtl(credential) });
return credential;
}
export async function startBridgeDeviceLogin(
bridgeUrl: string,
clientName = "seal-use-cli"
): Promise<DeviceLoginStart> {
let response: Response;
try {
response = await fetch(`${normalizeBaseUrl(bridgeUrl)}/api/auth/device/start`, {
method: "POST",
headers: { "Content-Type": "application/json", Accept: "application/json" },
body: JSON.stringify({ clientName }),
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
});
} catch (error) {
throw new CliError(
`无法连接桥接服务:${error instanceof Error ? error.message : String(error)}`,
1,
"检查 --bridge 地址或 SEAL_USE_BRIDGE_URL 后重试。"
);
}
const body = await readJson<DeviceLoginStart & BridgeErrorBody>(response);
if (!response.ok || !body?.deviceCode || !body.userCode || !body.verificationUrl) {
throw new CliError(
`设备码申请失败(${body?.code ?? body?.error ?? `HTTP ${response.status}`})。`,
response.status === 429 ? 1 : 2,
response.status === 429 ? "请求过于频繁,请稍后再试。" : "检查桥接地址是否正确。"
);
}
return body;
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
/**
* Poll until the user confirms in the browser. Exposed `sleep`/`now` are for
* tests; production callers should not pass them.
*/
export async function pollBridgeDeviceToken(
bridgeUrl: string,
deviceCode: string,
intervalSeconds: number,
expiresInSeconds: number,
options: {
onPending?: (attempt: number) => void;
sleep?: (ms: number) => Promise<void>;
now?: () => number;
} = {}
): Promise<DeviceLoginToken> {
const sleepFn = options.sleep ?? sleep;
const now = options.now ?? Date.now;
const deadline = now() + expiresInSeconds * 1000;
let interval = Math.max(1, intervalSeconds);
let attempt = 0;
while (now() < deadline) {
await sleepFn(interval * 1000);
attempt += 1;
options.onPending?.(attempt);
let response: Response;
try {
response = await fetch(`${normalizeBaseUrl(bridgeUrl)}/api/auth/device/token`, {
method: "POST",
headers: { "Content-Type": "application/json", Accept: "application/json" },
body: JSON.stringify({ deviceCode }),
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
});
} catch (error) {
throw new CliError(
`轮询设备码状态失败:${error instanceof Error ? error.message : String(error)}`,
1,
"检查网络后重试。"
);
}
const body = await readJson<DeviceLoginToken & BridgeErrorBody & { interval?: number }>(response);
if (response.status === 202 || body?.error === "authorization_pending") continue;
if (response.status === 429 || body?.error === "slow_down") {
const retryAfter = Number(response.headers.get("retry-after") ?? body?.interval ?? 0);
interval = retryAfter > 0 ? retryAfter : interval + 5;
continue;
}
if (body?.error === "access_denied") {
throw authRequired("用户拒绝了本次设备授权。", "如需重试,请重新运行 seal-use auth login。");
}
if (body?.error === "expired_token") {
throw authRequired("设备码已过期或已被使用。", "请重新运行 seal-use auth login。");
}
if (!response.ok || !body?.token) {
throw new CliError(
`设备码换令牌失败(${body?.code ?? body?.error ?? `HTTP ${response.status}`})。`,
1,
"稍后重试;持续失败请联系平台运维。"
);
}
return body;
}
throw authRequired("设备码已过期,未收到授权确认。", "请重新运行 seal-use auth login。");
}
export async function revokeBridgeToken(session: BridgeSession): Promise<void> {
try {
await fetch(`${normalizeBaseUrl(session.url)}/api/auth/device/revoke`, {
method: "POST",
headers: { Authorization: `Bearer ${session.token}`, Accept: "application/json" },
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
});
} catch {
// Best effort: local logout still removes the token.
}
}
+51
View File
@@ -0,0 +1,51 @@
import { existsSync, readFileSync, rmSync } from "node:fs";
import { join } from "node:path";
import { z } from "zod";
import { SEAL_CONFIG_DIR } from "../paths.js";
import { writeSecureFile } from "../util/secure-file.js";
export const BRIDGE_SESSION_FILE_ENV = "SEAL_USE_BRIDGE_FILE";
export const BRIDGE_URL_ENV = "SEAL_USE_BRIDGE_URL";
export const BRIDGE_TOKEN_ENV = "SEAL_USE_BRIDGE_TOKEN";
const BridgeSessionSchema = z.object({
url: z.string().url(),
token: z.string(),
expiresAt: z.string().optional(),
username: z.string().optional()
});
export type BridgeSession = z.infer<typeof BridgeSessionSchema>;
export function bridgeSessionFile(): string {
const configured = process.env[BRIDGE_SESSION_FILE_ENV]?.trim();
return configured || join(SEAL_CONFIG_DIR, "bridge.json");
}
/**
* Environment variables win over the file so CI can inject a short-lived token
* without touching the developer's local login.
*/
export function readBridgeSession(): BridgeSession | undefined {
const envToken = process.env[BRIDGE_TOKEN_ENV]?.trim();
const envUrl = process.env[BRIDGE_URL_ENV]?.trim();
if (envToken && envUrl) {
return { url: envUrl, token: envToken };
}
const file = bridgeSessionFile();
if (!existsSync(file)) return undefined;
try {
return BridgeSessionSchema.parse(JSON.parse(readFileSync(file, "utf8")));
} catch {
return undefined;
}
}
export function saveBridgeSession(session: BridgeSession): void {
writeSecureFile(bridgeSessionFile(), `${JSON.stringify(session, null, 2)}\n`);
}
export function clearBridgeSession(): void {
rmSync(bridgeSessionFile(), { force: true });
}
+152
View File
@@ -0,0 +1,152 @@
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 { getHoseOpenapiToken } from "./hose.js";
import { getSealSession } from "./token-store.js";
import { isCloudCorp, resolveCorpCredentials } from "./credentials.js";
import { clearBridgeCredentialCache } from "./bridge-client.js";
import { BRIDGE_TOKEN_ENV, BRIDGE_URL_ENV } from "./bridge-token.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();
});
});
describe("cloud hose credentials", () => {
test("uses the bridge-minted openapi token instead of local key exchange", async () => {
const originalFetch = globalThis.fetch;
process.env[BRIDGE_URL_ENV] = "https://bridge.test";
process.env[BRIDGE_TOKEN_ENV] = "device-token";
clearBridgeCredentialCache();
globalThis.fetch = (async () =>
new Response(
JSON.stringify({
ok: true,
credential: {
type: "hose",
corpId: "cloud-hose",
token: "openapi-token",
tokenType: "query",
tokenName: "accessToken",
expiresAt: new Date(Date.now() + 3600_000).toISOString()
}
}),
{ status: 200, headers: { "content-type": "application/json" } }
)) as unknown as typeof fetch;
try {
const corp = CorpConfigSchema.parse({
id: "cloud-hose",
name: "Cloud Hose",
storage: "cloud",
source: {
type: "hose",
domain: "https://app.ekuaibao.com",
corpId: "ID01",
staffId: "ID01:STAFF01"
}
});
const entry = await getHoseOpenapiToken(corp);
expect(entry.token).toBe("openapi-token");
expect(entry.tokenType).toBe("query");
expect(entry.tokenName).toBe("accessToken");
} finally {
globalThis.fetch = originalFetch;
delete process.env[BRIDGE_URL_ENV];
delete process.env[BRIDGE_TOKEN_ENV];
clearBridgeCredentialCache();
}
});
});
+78
View File
@@ -0,0 +1,78 @@
import type { CorpConfig } from "../config/types.js";
import { CliError } from "../errors.js";
import { resolveCloudCredential } from "./bridge-client.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<string, string>;
/** Cloud-only: a short-lived Hose OpenAPI token minted by the bridge. */
openapiToken?: string;
/** Cloud-only: how the Hose token must be injected into upstream requests. */
tokenType?: "query" | "header" | "bearer" | "body";
tokenName?: string;
/** Cloud-only: optional Seal delegation cookie returned by the bridge. */
sessionCookie?: string;
/** Cloud-only: ISO timestamp; absent means the bridge did not provide one. */
expiresAt?: string;
};
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<CorpCredentials> {
if (isCloudCorp(corp)) {
const credential = await resolveCloudCredential(corp);
if (corp.source.type === "hose") {
return {
openapiToken: credential.token,
tokenType: credential.tokenType,
tokenName: credential.tokenName,
expiresAt: credential.expiresAt ?? undefined
};
}
return {
token: credential.token,
sessionCookie: credential.sessionCookie,
expiresAt: credential.expiresAt ?? undefined
};
}
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
};
}
+133 -39
View File
@@ -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 { cloudAuthRequiredError, isCloudCorp, resolveCorpCredentials, type CorpCredentials } from "./credentials.js";
import { SealEnterpriseConfig, SealSession, TokenEntry } from "./types.js";
type HoseLoginResponse = {
@@ -114,7 +115,51 @@ export type HoseProbeResult = {
};
/** A Hose OpenAPI access token plus whether it was served from the local SWR cache. */
export type HoseOpenapiTokenResult = TokenEntry & { cached: boolean };
export type HoseOpenapiTokenResult = TokenEntry & {
cached: boolean;
/** Cloud credentials may require a different injection than the default query. */
tokenType?: "query" | "header" | "bearer" | "body";
tokenName?: string;
};
export type HoseOpenapiAuth = {
token: string;
tokenType?: "query" | "header" | "bearer" | "body";
tokenName?: string;
};
function normalizeHoseAuth(auth: string | HoseOpenapiAuth): HoseOpenapiAuth {
return typeof auth === "string" ? { token: auth } : auth;
}
/**
* Build the token injection pieces for one request. `body` on GET/HEAD
* degrades to a query parameter, matching the bridge contract.
*/
function hoseAuthInjection(auth: HoseOpenapiAuth, method: "GET" | "POST"): {
query: Record<string, string>;
headers: Record<string, string>;
bodyField?: string;
} {
const type = auth.tokenType ?? "query";
const name = auth.tokenName ?? (type === "bearer" ? "Authorization" : "accessToken");
const query: Record<string, string> = {};
const headers: Record<string, string> = {};
if (type === "query") {
query[name] = auth.token;
} else if (type === "header") {
headers[name] = auth.token;
} else if (type === "bearer") {
headers.Authorization = `Bearer ${auth.token}`;
} else if (method === "POST") {
return { query, headers, bodyField: name };
} else {
query[name] = auth.token;
}
return { query, headers };
}
const openapiTokenRequests = new Map<string, Promise<TokenEntry>>();
const closeApiTokenRequests = new Map<string, Promise<TokenEntry>>();
@@ -272,10 +317,10 @@ function hoseClient(source: HoseSealSource): KyInstance {
});
}
async function fetchHoseOpenapiToken(source: HoseSealSource): Promise<TokenEntry> {
async function fetchHoseOpenapiToken(source: HoseSealSource, credentials: CorpCredentials): Promise<TokenEntry> {
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,15 +353,34 @@ 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 };
}
if (cloud) {
const credentials = await resolveCorpCredentials(corp);
if (!credentials.openapiToken) {
throw cloudAuthRequiredError(corp);
}
const expiresAt = credentials.expiresAt
? Date.parse(credentials.expiresAt)
: Date.now() + 55 * 60_000;
return {
token: credentials.openapiToken,
expiresAt,
cached: false,
tokenType: credentials.tokenType,
tokenName: credentials.tokenName
};
}
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),
@@ -336,24 +400,36 @@ export async function ensureHoseOpenapiToken(
return (await getHoseOpenapiToken(corp, options)).token;
}
/** Token plus the injection shape cloud credentials require. */
export async function ensureHoseOpenapiTokenAuth(
corp: CorpConfig,
options?: { force?: boolean }
): Promise<HoseOpenapiAuth> {
const entry = await getHoseOpenapiToken(corp, options);
return { token: entry.token, tokenType: entry.tokenType, tokenName: entry.tokenName };
}
export async function fetchHoseCloseApiToken(
source: HoseSealSource,
openapiToken: string,
auth: string | HoseOpenapiAuth,
expiresIn = 7200
): Promise<TokenEntry> {
const normalized = normalizeHoseAuth(auth);
const injection = hoseAuthInjection(normalized, "POST");
const client = hoseClient(source);
const uid = hoseUid(source);
const json: Record<string, unknown> = {
uid,
pageType: "home",
expireDate: expiresIn
};
if (injection.bodyField) json[injection.bodyField] = normalized.token;
const response = await client
.post("api/openapi/v1.1/provisional/getProvisionalAuth", {
searchParams: {
accessToken: openapiToken
},
json: {
uid,
pageType: "home",
expireDate: expiresIn
}
searchParams: injection.query,
headers: injection.headers,
json
})
.json<HoseProvisionalResponse>();
@@ -379,19 +455,20 @@ export async function ensureHoseCloseApiToken(corp: CorpConfig): Promise<TokenEn
throw new Error(`Unsupported Seal source: ${corp.source.type}`);
}
const source = corp.source;
const credentials = await resolveCorpCredentials(corp);
if (source.closeToken) {
if (credentials.closeToken) {
const expiresAt = source.expiresAt ? Date.parse(source.expiresAt) : Number.MAX_SAFE_INTEGER;
if (expiresAt !== Number.MAX_SAFE_INTEGER && Date.now() >= 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;
}
@@ -399,13 +476,15 @@ export async function ensureHoseCloseApiToken(corp: CorpConfig): Promise<TokenEn
const pending = closeApiTokenRequests.get(corp.id);
if (pending) return pending;
const request = ensureHoseOpenapiToken(corp)
.then((openapiToken) => fetchHoseCloseApiToken(source, openapiToken))
const request = ensureHoseOpenapiTokenAuth(corp)
.then((auth) => fetchHoseCloseApiToken(source, auth))
.then((closeapi) => {
setHoseAuthCache(corp.id, {
...getHoseAuthCache(corp.id),
closeapi
});
if (!isCloudCorp(corp)) {
setHoseAuthCache(corp.id, {
...getHoseAuthCache(corp.id),
closeapi
});
}
return closeapi;
})
.finally(() => closeApiTokenRequests.delete(corp.id));
@@ -444,8 +523,8 @@ export async function getHoseProvisionalAuthLink(
throw new Error(`Invalid expire seconds: ${expiresIn}. Must be a positive integer.`);
}
const openapiToken = await ensureHoseOpenapiToken(corp, { force: options?.force });
const provisional = await fetchHoseCloseApiToken(corp.source, openapiToken, expiresIn);
const auth = await ensureHoseOpenapiTokenAuth(corp, { force: options?.force });
const provisional = await fetchHoseCloseApiToken(corp.source, auth, expiresIn);
if (!provisional.url) {
throw new Error("Hose provisional auth URL was not available");
}
@@ -604,13 +683,16 @@ async function testSingleHoseDomain(
export async function fetchHoseRoleDefGroups(
domain: string,
openapiToken: string
auth: string | HoseOpenapiAuth
): Promise<HoseRoleDefGroup[]> {
const url = `${normalizeBaseUrl(domain)}/api/openapi/v1/roleDefGroups?accessToken=${encodeURIComponent(openapiToken)}`;
const injection = hoseAuthInjection(normalizeHoseAuth(auth), "GET");
const url = new URL(`${normalizeBaseUrl(domain)}/api/openapi/v1/roleDefGroups`);
for (const [key, value] of Object.entries(injection.query)) url.searchParams.set(key, value);
const response = await fetch(url, {
headers: {
"content-type": "application/json",
Accept: "application/json"
Accept: "application/json",
...injection.headers
},
signal: AbortSignal.timeout(10000)
});
@@ -654,17 +736,22 @@ export async function fetchHoseRoleDefGroups(
export async function fetchHoseRoleStaffs(
domain: string,
openapiToken: string,
auth: string | HoseOpenapiAuth,
roledefId: string,
staffBy = "id"
): Promise<{ id: string; name: string; count: number; staffs: string[] }> {
const cleanId = roledefId.startsWith("$") ? roledefId.slice(1) : roledefId;
const url = `${normalizeBaseUrl(domain)}/api/openapi/v1/roledefs/$${cleanId}?accessToken=${encodeURIComponent(openapiToken)}&staffBy=${encodeURIComponent(staffBy)}&pathType=name`;
const injection = hoseAuthInjection(normalizeHoseAuth(auth), "GET");
const url = new URL(`${normalizeBaseUrl(domain)}/api/openapi/v1/roledefs/$${cleanId}`);
for (const [key, value] of Object.entries(injection.query)) url.searchParams.set(key, value);
url.searchParams.set("staffBy", staffBy);
url.searchParams.set("pathType", "name");
const response = await fetch(url, {
headers: {
"content-type": "application/json",
Accept: "application/json"
Accept: "application/json",
...injection.headers
},
signal: AbortSignal.timeout(10000)
});
@@ -711,22 +798,29 @@ export async function fetchHoseRoleStaffs(
export async function fetchHoseStaffDetails(
domain: string,
openapiToken: string,
auth: string | HoseOpenapiAuth,
staffIds: string[]
): Promise<HoseStaffDetail[]> {
if (staffIds.length === 0) return [];
const url = `${normalizeBaseUrl(domain)}/api/openapi/v1/staffs/getStaffIds?accessToken=${encodeURIComponent(openapiToken)}`;
const normalized = normalizeHoseAuth(auth);
const injection = hoseAuthInjection(normalized, "POST");
const url = new URL(`${normalizeBaseUrl(domain)}/api/openapi/v1/staffs/getStaffIds`);
for (const [key, value] of Object.entries(injection.query)) url.searchParams.set(key, value);
const body: Record<string, unknown> = {
type: "STAFFID",
conditionIds: staffIds.slice(0, 100)
};
if (injection.bodyField) body[injection.bodyField] = normalized.token;
const response = await fetch(url, {
method: "POST",
headers: {
"content-type": "application/json",
Accept: "application/json"
Accept: "application/json",
...injection.headers
},
body: JSON.stringify({
type: "STAFFID",
conditionIds: staffIds.slice(0, 100)
}),
body: JSON.stringify(body),
signal: AbortSignal.timeout(10000)
});
+6
View File
@@ -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<SealSession> {
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
+33 -2
View File
@@ -15,6 +15,8 @@ import {
rotateBackupCookies
} from "./session-fallback.js";
import { createSealDelegationLink, exchangeSealDelegateLink } from "./delegate.js";
import { cloudAuthRequiredError, isCloudCorp, resolveCorpCredentials } from "./credentials.js";
import { clearBridgeCredentialCache } from "./bridge-client.js";
import { saveCorpConfig } from "../config/repository.js";
import { formatBeijingIso } from "../config/timestamps.js";
@@ -32,6 +34,8 @@ function isExpired(session: SealSession, refreshTtl: number): boolean {
export async function renewNativeSealSession(corp: CorpConfig): Promise<SealSession | undefined> {
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 +108,29 @@ export async function renewNativeSealSession(corp: CorpConfig): Promise<SealSess
}
async function refreshSealSession(corp: CorpConfig): Promise<SealSession> {
if (isCloudCorp(corp) && corp.source.type === "seal") {
const credentials = await resolveCorpCredentials(corp);
if (!credentials.token) throw cloudAuthRequiredError(corp);
const source = corp.source;
const expiresAt = credentials.expiresAt
? Date.parse(credentials.expiresAt)
: Date.now() + 5 * 60_000;
return {
token: credentials.token,
expiresAt,
enterprise: {
corpId: source.corpId ?? corp.id,
staffId: source.staffId,
sealUrl: corp.seal.url ?? source.sealUrl,
tenantId: source.tenantId,
tenantSlug: corp.seal.tenantSlug ?? source.tenantSlug,
tenantName: source.tenantName,
raw: { sourceType: "seal", storage: "cloud" }
}
};
}
switch (corp.source.type) {
case "hose":
return getHoseSealSession(corp);
@@ -130,7 +157,8 @@ export async function getSealSessionForCorp(corp: CorpConfig): Promise<SealSessi
return cached;
}
const stored = getSealSession(corp.id);
const cloud = isCloudCorp(corp);
const stored = cloud ? undefined : getSealSession(corp.id);
if (stored && !isExpired(stored, refreshTtl)) {
memoryCache.set(corp.id, stored);
return stored;
@@ -140,7 +168,7 @@ export async function getSealSessionForCorp(corp: CorpConfig): Promise<SealSessi
if (pending) return pending;
const request = refreshSealSession(corp).then((next) => {
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);
@@ -156,6 +184,9 @@ export async function resolveSealEnterpriseConfig(
export function clearSealToken(corpId: string): void {
memoryCache.delete(corpId);
clearSealSession(corpId);
// A cloud 401 means the bridge token may be stale too; drop the cached
// credential so the next read goes back to the bridge.
clearBridgeCredentialCache(corpId);
}
/** Reuse a concurrent refresh rather than invalidating a newer session on a late 401. */
+1 -1
View File
@@ -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;
+102
View File
@@ -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",
+68 -17
View File
@@ -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<typeof CorpEnvironmentSchema>;
export type CorpStorage = z.infer<typeof CorpStorageSchema>;
export type HoseSealSource = z.infer<typeof HoseSealSourceSchema>;
export type NativeSealSource = z.infer<typeof NativeSealSourceSchema>;
export type SealSource = z.infer<typeof SealSourceSchema>;
+44
View File
@@ -1,4 +1,7 @@
import { describe, expect, test } from "bun:test";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { VERSION } from "../../version.js";
import { diagnoseSystem, formatDoctorDashboard } from "./diagnose.js";
import {
@@ -76,3 +79,44 @@ describe("Doctor Diagnosis Engine", () => {
expect(dashboard).toContain("seal-use doctor guide");
});
});
describe("Doctor cloud enterprise login check", () => {
test("warns when cloud enterprises exist without a bridge session", () => {
const dir = mkdtempSync(join(tmpdir(), "seal-doctor-cloud-"));
const previousEnterprises = process.env.SEAL_USE_ENTERPRISES_DIR;
const previousBridgeFile = process.env.SEAL_USE_BRIDGE_FILE;
const previousBridgeUrl = process.env.SEAL_USE_BRIDGE_URL;
const previousBridgeToken = process.env.SEAL_USE_BRIDGE_TOKEN;
try {
process.env.SEAL_USE_ENTERPRISES_DIR = dir;
process.env.SEAL_USE_BRIDGE_FILE = join(dir, "bridge.json");
delete process.env.SEAL_USE_BRIDGE_URL;
delete process.env.SEAL_USE_BRIDGE_TOKEN;
writeFileSync(
join(dir, "cloud.json"),
JSON.stringify({
id: "cloud-seal",
name: "Cloud Seal",
storage: "cloud",
source: { type: "seal", sealUrl: "https://seal.example.com" }
})
);
const diagnosis = diagnoseSystem();
const check = diagnosis.checks.find((item) => item.id === "bridge_login");
expect(check?.status).toBe("warn");
expect(check?.message).toContain("auth login");
} finally {
if (previousEnterprises === undefined) delete process.env.SEAL_USE_ENTERPRISES_DIR;
else process.env.SEAL_USE_ENTERPRISES_DIR = previousEnterprises;
if (previousBridgeFile === undefined) delete process.env.SEAL_USE_BRIDGE_FILE;
else process.env.SEAL_USE_BRIDGE_FILE = previousBridgeFile;
if (previousBridgeUrl === undefined) delete process.env.SEAL_USE_BRIDGE_URL;
else process.env.SEAL_USE_BRIDGE_URL = previousBridgeUrl;
if (previousBridgeToken === undefined) delete process.env.SEAL_USE_BRIDGE_TOKEN;
else process.env.SEAL_USE_BRIDGE_TOKEN = previousBridgeToken;
rmSync(dir, { recursive: true, force: true });
}
});
});
+30
View File
@@ -7,6 +7,7 @@ import { getLastCorpConfigLoadIssues, getLastGlobalConfigIssue, loadCorpConfigs,
import { formatBeijingIso } from "../config/timestamps.js";
import { getDefaultGlobalSkillDir, getSkillVersionStatus } from "../skill/skill-version.js";
import { resolveUsageFilePath } from "../stats/usage-tracker.js";
import { readBridgeSession } from "../auth/bridge-token.js";
import {
EMBEDDED_DIRECTORY_SPECS,
EMBEDDED_DOMAIN_CAPABILITIES,
@@ -337,6 +338,35 @@ export function diagnoseSystem(): DoctorDiagnosis {
: `${looseCredentialFiles.length} 个凭据文件权限宽于 0600(同机其他用户可读,取决于父目录权限),建议 chmod 600:${looseCredentialFiles.join("、")}`
});
// Check 5b: Cloud enterprise login. Local-only read (no network) so `doctor`
// keeps its fast path; connectivity failures surface when the command runs.
const cloudCorps = corps.filter((corp) => (corp.storage ?? "local") === "cloud");
if (cloudCorps.length > 0) {
const session = readBridgeSession();
if (!session) {
checks.push({
id: "bridge_login",
title: "云端企业登录",
status: "warn",
message: `检测到 ${cloudCorps.length} 家 cloud 企业,但尚未登录桥接服务;运行 seal-use auth login --bridge <url>`
});
} else if (session.expiresAt && Date.parse(session.expiresAt) <= Date.now()) {
checks.push({
id: "bridge_login",
title: "云端企业登录",
status: "warn",
message: `桥接令牌已于 ${session.expiresAt} 过期;请重新运行 seal-use auth login`
});
} else {
checks.push({
id: "bridge_login",
title: "云端企业登录",
status: "ok",
message: `${session.url}${session.username ? ` (${session.username})` : ""}${session.expiresAt ? `,令牌有效至 ${session.expiresAt}` : ""}`
});
}
}
// Check 6: Config file parseability. A single malformed JSON file otherwise
// silently removes that enterprise from every command; surface it by name.
const configIssues = [
+4 -2
View File
@@ -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 执行审批回调。`
+23 -9
View File
@@ -1,10 +1,12 @@
import ky, { HTTPError, type KyInstance } from "ky";
import { ensureHoseOpenapiToken, normalizeBaseUrl } from "../../../core/auth/hose.js";
import { ensureHoseOpenapiTokenAuth, normalizeBaseUrl } from "../../../core/auth/hose.js";
import type { CorpConfig } from "../../../core/config/types.js";
export interface HoseOpenClientCredentials {
domain?: string;
accessToken: string;
tokenType?: "query" | "header" | "bearer" | "body";
tokenName?: string;
}
export function createHoseOpenClientWithCredentials(
@@ -12,15 +14,25 @@ export function createHoseOpenClientWithCredentials(
customHeaders?: Record<string, string>
): KyInstance {
const baseUrl = normalizeBaseUrl(credentials.domain || "https://app.ekuaibao.com");
const tokenType = credentials.tokenType ?? "query";
const tokenName = credentials.tokenName ?? (tokenType === "bearer" ? "Authorization" : "accessToken");
const searchParams: Record<string, string> = {};
const headers: Record<string, string> = { ...customHeaders };
if (tokenType === "query" || tokenType === "body") {
// GET-only client: body mode degrades to query per the bridge contract.
searchParams[tokenName] = credentials.accessToken;
} else if (tokenType === "header") {
headers[tokenName] = credentials.accessToken;
} else {
headers.Authorization = `Bearer ${credentials.accessToken}`;
}
return ky.create({
prefix: baseUrl,
timeout: 30000,
searchParams: {
accessToken: credentials.accessToken
},
headers: {
...customHeaders
},
searchParams,
headers,
hooks: {
beforeError: [
async ({ error }) => {
@@ -45,11 +57,13 @@ export async function createHoseOpenClient(
throw new Error(`Unsupported Hose source type: ${corp.source.type}. Expected 'hose'.`);
}
const token = await ensureHoseOpenapiToken(corp, { force: options?.force });
const auth = await ensureHoseOpenapiTokenAuth(corp, { force: options?.force });
return createHoseOpenClientWithCredentials(
{
domain: corp.source.domain,
accessToken: token
accessToken: auth.token,
tokenType: auth.tokenType,
tokenName: auth.tokenName
},
customHeaders
);
+3 -3
View File
@@ -7,7 +7,7 @@ import {
type MaterialPackFilePolicyPatch
} from "./material-pack/policy.js";
import { CorpConfig } from "../../core/config/types.js";
import { ensureHoseOpenapiToken, fetchHoseCloseApiToken, defaultSealUrl, normalizeBaseUrl } from "../../core/auth/hose.js";
import { ensureHoseOpenapiTokenAuth, fetchHoseCloseApiToken, defaultSealUrl, normalizeBaseUrl } from "../../core/auth/hose.js";
import { createSealClientForUrl } from "../../core/http/factory.js";
import { redactSensitiveText } from "../../core/util/redact.js";
import { safetyBlocked, validationError } from "../../core/errors.js";
@@ -1300,8 +1300,8 @@ export async function createDelegationForUser(
(cleanPhone ? `${corp.source.corpId}:${cleanPhone}` : undefined);
if (staffId) {
const openapiToken = await ensureHoseOpenapiToken(corp);
const provisional = await fetchHoseCloseApiToken({ ...corp.source, staffId }, openapiToken);
const auth = await ensureHoseOpenapiTokenAuth(corp);
const provisional = await fetchHoseCloseApiToken({ ...corp.source, staffId }, auth);
const closeapiToken = provisional.token;
const sealUrl = defaultSealUrl(corp, corp.source);
@@ -1,5 +1,5 @@
import type { KyInstance } from "ky"
import { ensureHoseOpenapiToken, fetchHoseRoleDefGroups, fetchHoseStaffDetails } from "../../../core/auth/hose.js"
import { ensureHoseOpenapiTokenAuth, fetchHoseRoleDefGroups, fetchHoseStaffDetails } from "../../../core/auth/hose.js"
import type { CorpConfig } from "../../../core/config/types.js"
import { getMe } from "../api.js"
import type { MeData } from "../types.js"
@@ -36,8 +36,8 @@ export async function resolveHoseLinkIdentity(corp: CorpConfig): Promise<LinkIde
const canonicalId = (id: string) => id.includes(":") ? id : `${source.corpId}:${id}`
const targetId = canonicalId(source.staffId)
try {
const token = await ensureHoseOpenapiToken(corp)
const staffs = await fetchHoseStaffDetails(source.domain, token, [targetId])
const auth = await ensureHoseOpenapiTokenAuth(corp)
const staffs = await fetchHoseStaffDetails(source.domain, auth, [targetId])
const matches = staffs.filter(staff => typeof staff.id === "string" && canonicalId(staff.id) === targetId)
const staff = matches.length === 1 ? matches[0] : undefined
if (!staff || typeof staff.name !== "string" || !staff.name.trim()) return unresolved
@@ -47,7 +47,7 @@ export async function resolveHoseLinkIdentity(corp: CorpConfig): Promise<LinkIde
if (staff.roles.length === 0) roleNames = []
else {
try {
const roles = (await fetchHoseRoleDefGroups(source.domain, token)).flatMap(group => group.roleDefs)
const roles = (await fetchHoseRoleDefGroups(source.domain, auth)).flatMap(group => group.roleDefs)
const names = staff.roles.map(role => roles.find(item => item.id === role.roleDefId)?.name)
if (names.every((name): name is string => typeof name === "string" && name.trim().length > 0)) {
roleNames = [...new Set(names)]
+4 -2
View File
@@ -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<HosecloudSyncResult> {
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),