Add bridge device login and cloud credential resolution

Implement the phase-three client: device-code login (auth login/logout/bridge) with a 0600 token file, cloud credential resolution with an in-memory cache, pre-minted Hose token injection via tokenType/tokenName, cloud Seal sessions without local renewal, elevation guards, and a local-only doctor check. Cloud enterprises still avoid tokens.json.
This commit is contained in:
gitea committed 2026-11-19 17:48:58 +08:00
1 parent 887df2d32f
commit 71a2e9a2e3
19 files changed
+964 -84

No files matched your search

+65 -29
View File
@@ -1,6 +1,20 @@
# 云端企业配置方案(seal-use 侧) # 云端企业配置方案(seal-use 侧)
状态:阶段一、二已实施(2026-11-19);阶段三待确认。桥接侧的凭据服务在独立会话中设计,本文件定义 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 检查 |
## 已定决策 ## 已定决策
@@ -45,40 +59,59 @@
### 凭据获取 ### 凭据获取
```http ```http
GET /api/credentials?type=hose&corpId=<corpId> GET /api/enterprise-credentials/resolve?type=hose&corpId=<corpId>
Authorization: Bearer <bridge token> Cookie: hose_sealai_session=<token>
``` ```
响应: 响应(桥接实际返回):
```json ```json
// hose 长期凭据企业 // hose:服务端已用 appKey/appSecurity 换好短期 accessToken
{ "type": "hose", "credentialMode": "persistent", { "ok": true, "credential": {
"openapiToken": "...", "expiresAt": "2026-11-19T18:00:00+08:00" } "type": "hose", "corpId": "...", "name": "...", "baseUrl": "...",
"token": "<accessToken>", "tokenType": "query", "tokenName": "accessToken",
"expiresAt": "2026-11-19T10:05:00.000Z", "metadata": { "note": "生产" } } }
// hose web-session 企业 // seal:Bearer Token,可能附带协助授权会话 Cookie,expiresAt 可能为 null
{ "type": "hose", "credentialMode": "web-session", { "ok": true, "credential": {
"closeToken": "...", "expiresAt": "..." } "type": "seal", "corpId": "...", "name": "...", "baseUrl": "...",
"token": "<bearer>", "tokenType": "bearer", "tokenName": "Authorization",
// seal 企业 "expiresAt": "2026-12-01T00:00:00.000Z", "sessionCookie": "sid=...", "metadata": null } }
{ "type": "seal", "token": "...", "expiresAt": "..." }
``` ```
错误语义: 与本文早期假设的关键差异:
| HTTP | seal-use 行为 | 退出码 | 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 / 403 | 提示重新登录或权限不足 | 11 | | 401 `AUTH_REQUIRED` | 提示重新登录后重试一次 | 11 |
| 404 | 该企业未在云端登记 | 13 | | 403 `FORBIDDEN` | 提示管理员授予 `expense` / `sealai` scope | 11 |
| 5xx / 超时 | 云端不可用,不回退 | 1 | | 404 `CREDENTIAL_NOT_FOUND` | 该企业未在云端登记 | 13 |
| 409 `CREDENTIAL_DISABLED` / `CREDENTIAL_MISMATCH` | 提示管理员启用或核对密钥归属 | 13 |
| 500 `DECRYPT_FAILED` / `INTERNAL_ERROR` | 平台侧问题,退避后告警 | 1 |
| 502 `UPSTREAM_AUTH_FAILED` | 合思授权失败,指数退避重试 | 1 |
### CLI 登录 ### CLI 登录
优先级:设备码,PAT 兜底。 **决定:采用设备码登录,等待桥接新增 `/api/auth/device/start` 与 `/api/auth/device/token`。** 在设备码端点可用前,不实现基于账号密码或 Cookie 的登录方式。
- `POST /api/auth/device/start` → `{ deviceCode, userCode, verificationUrl, interval, expiresIn }` 桥接当前只提供账号密码登录换会话 Cookie,**没有设备码或 PAT**:
- `POST /api/auth/device/token` → `{ token, expiresAt }`(pending 时返回 202)
- 令牌存 `~/.config/seal-use/bridge.json`(`0600`),支持 `SEAL_USE_BRIDGE_TOKEN` 环境变量覆盖。 ```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 改动清单 ## seal-use 改动清单
@@ -97,9 +130,12 @@ Authorization: Bearer <bridge token>
### 阶段三:桥接接入 ### 阶段三:桥接接入
8. 新增 `src/core/auth/bridge-client.ts`:设备码、令牌刷新、凭据请求与内存缓存。 8. 新增 `src/core/auth/bridge-client.ts`:账号登录换 Cookie、Cookie 持久化与滑动续期、凭据请求与内存缓存。
9. `seal-use auth login/logout/status` 命令;`doctor` 增加登录与连通性检查。 9. `resolveCorpCredentials` 的 cloud 分支返回预签发凭据;`getHoseOpenapiToken` 增加预签发 token 路径,并按 `tokenType` / `tokenName` 注入请求。
10. cloud 企业禁用提权类命令(`add-link --as-hose`、`hose-extract-keys`、`corps keys`),提示到云端管理。 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`。
## 兼容与行为变化 ## 兼容与行为变化
@@ -118,7 +154,7 @@ Authorization: Bearer <bridge token>
## 未决问题 ## 未决问题
1. 桥接凭据接口的最终形态(GET 还是 POST、是否返回 `seal.cookies`、是否需要 `environment` 区分)。 1. 桥接设备码端点的具体形态与令牌有效期(已决定用设备码,待桥接提供)。
2. CLI 登录优先设备码还是 PAT;桥接是否本期提供设备码端点。 2. cloud 企业是否允许本地缓存派生会话(当前定为不允许,纯内存)。
3. cloud 企业是否允许本地缓存派生会话(当前定为不允许,纯内存)。 3. 切换 `local ↔ cloud` 的命令形态。
4. 切换 `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 test-dir [<path>|--clear]
seal-use config lint [status|enable|disable] [--linter <name|path>] [--min-score <score>] seal-use config lint [status|enable|disable] [--linter <name|path>] [--min-score <score>]
seal-use auth check [--corp <corpId>] 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 [--note <note>] [--expire <duration>] [--corp <corpId>]
seal-use auth link --from-link <url> [--note <note>] [--expire <duration>] seal-use auth link --from-link <url> [--note <note>] [--expire <duration>]
seal-use auth link list [--corp <corpId>] seal-use auth link list [--corp <corpId>]
+72
View File
@@ -7,6 +7,17 @@ import {
} from "../../core/auth/hose.js"; } from "../../core/auth/hose.js";
import { clearCorpTokenCache } from "../../core/auth/token-store.js"; import { clearCorpTokenCache } from "../../core/auth/token-store.js";
import { resolveCorpCredentials } from "../../core/auth/credentials.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 { formatBeijingIso } from "../../core/config/timestamps.js";
import type { CorpConfig } from "../../core/config/types.js"; import type { CorpConfig } from "../../core/config/types.js";
import { CliError, validationError, usageError } from "../../core/errors.js"; import { CliError, validationError, usageError } from "../../core/errors.js";
@@ -47,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) { export async function handleAuthCommand(action: string | undefined, corp: CorpConfig | null, args: ParsedArgs) {
const subAction = args.command[2]?.toLowerCase(); const subAction = args.command[2]?.toLowerCase();
const fromLink = stringOption(args.options["from-link"]) ?? (subAction === "from-link" ? args.command[3] : undefined); 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) { if ((action === "seal-link" || action === "link" || (action === "hose-link" && corp?.source?.type === "seal")) && fromLink) {
const note = stringOption(args.options.note); const note = stringOption(args.options.note);
const expireOption = args.options.expire ?? args.options["expires-in"] ?? args.options.expiresIn; const expireOption = args.options.expire ?? args.options["expires-in"] ?? args.options.expiresIn;
+6
View File
@@ -406,6 +406,12 @@ export async function extractKeysFromLinkAction(link: string, options: { reveal?
export async function showCorpKeysAction(targetCorpId: string | undefined, options: { reveal?: boolean }) { export async function showCorpKeysAction(targetCorpId: string | undefined, options: { reveal?: boolean }) {
const corp = selectCorp(targetCorpId); const corp = selectCorp(targetCorpId);
const reveal = options.reveal === true; 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") { if (corp.source.type !== "hose") {
throw new CliError(`【合思子域专享能力】当前企业「${corp.name}」(id: ${corp.id}) 为原生 Seal (${corp.source.type}) 租户,非合思 (Hose/合思云/易快报) 渠道企业。\n` + throw new CliError(`【合思子域专享能力】当前企业「${corp.name}」(id: ${corp.id}) 为原生 Seal (${corp.source.type}) 租户,非合思 (Hose/合思云/易快报) 渠道企业。\n` +
"OpenAPI 密钥查询与提权能力专属于合思生态租户(用于从合思协助链接或合思凭据中提取开发者密钥提升权限等级),非合思渠道企业不支持此能力。", 2); "OpenAPI 密钥查询与提权能力专属于合思生态租户(用于从合思协助链接或合思凭据中提取开发者密钥提升权限等级),非合思渠道企业不支持此能力。", 2);
+21
View File
@@ -1108,6 +1108,27 @@ export const HELP_REGISTRY: AreaHelp[] = [
summary: "Check auth session and platform connectivity", summary: "Check auth session and platform connectivity",
usage: ["seal-use auth check [--corp <corpId>]"] 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", name: "link",
summary: "【Seal 审核后台】生成免密登录/委托访问直达链接", 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", "min-file-size", "min-file-size-bytes", "minFileSize", "minFileSizeBytes",
"max-file-size", "max-file-size-bytes", "maxFileSize", "maxFileSizeBytes", "templates", "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", "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", "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", "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", "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 // 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. // the same summary (mode + lint included), so read access loses nothing.
config: ["paths", "get"], 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"], users: ["search", "get"],
contacts: ["departments", "children", "users", "sync-time"], contacts: ["departments", "children", "users", "sync-time"],
data: ["expenses", "invoices"], 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 });
}
+52
View File
@@ -5,8 +5,11 @@ import { join } from "node:path";
import { CorpConfigSchema, type CorpConfig } from "../config/types.js"; import { CorpConfigSchema, type CorpConfig } from "../config/types.js";
import { CliError } from "../errors.js"; import { CliError } from "../errors.js";
import { getSealSessionForCorp } from "./seal.js"; import { getSealSessionForCorp } from "./seal.js";
import { getHoseOpenapiToken } from "./hose.js";
import { getSealSession } from "./token-store.js"; import { getSealSession } from "./token-store.js";
import { isCloudCorp, resolveCorpCredentials } from "./credentials.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 { function localHoseCorp(): CorpConfig {
return CorpConfigSchema.parse({ return CorpConfigSchema.parse({
@@ -98,3 +101,52 @@ describe("cloud session isolation", () => {
expect(getSealSession(corp.id)).toBeUndefined(); 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();
}
});
});
+24 -1
View File
@@ -1,5 +1,6 @@
import type { CorpConfig } from "../config/types.js"; import type { CorpConfig } from "../config/types.js";
import { CliError } from "../errors.js"; import { CliError } from "../errors.js";
import { resolveCloudCredential } from "./bridge-client.js";
/** /**
* Credentials needed to authenticate one enterprise. `local` enterprises read * Credentials needed to authenticate one enterprise. `local` enterprises read
@@ -13,6 +14,15 @@ export type CorpCredentials = {
closeToken?: string; closeToken?: string;
token?: string; token?: string;
cookies?: Record<string, 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 { export function isCloudCorp(corp: CorpConfig): boolean {
@@ -36,7 +46,20 @@ export function cloudAuthRequiredError(corp: CorpConfig): CliError {
*/ */
export async function resolveCorpCredentials(corp: CorpConfig): Promise<CorpCredentials> { export async function resolveCorpCredentials(corp: CorpConfig): Promise<CorpCredentials> {
if (isCloudCorp(corp)) { if (isCloudCorp(corp)) {
throw cloudAuthRequiredError(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; const source = corp.source;
+122 -32
View File
@@ -3,7 +3,7 @@ import { CorpConfig, HoseSealSource } from "../config/types.js";
import { createSealClientForUrl } from "../http/factory.js"; import { createSealClientForUrl } from "../http/factory.js";
import { resolveSealCustomHeaders } from "../http/request-headers.js"; import { resolveSealCustomHeaders } from "../http/request-headers.js";
import { getHoseAuthCache, setHoseAuthCache } from "./token-store.js"; import { getHoseAuthCache, setHoseAuthCache } from "./token-store.js";
import { isCloudCorp, resolveCorpCredentials, type CorpCredentials } from "./credentials.js"; import { cloudAuthRequiredError, isCloudCorp, resolveCorpCredentials, type CorpCredentials } from "./credentials.js";
import { SealEnterpriseConfig, SealSession, TokenEntry } from "./types.js"; import { SealEnterpriseConfig, SealSession, TokenEntry } from "./types.js";
type HoseLoginResponse = { type HoseLoginResponse = {
@@ -115,7 +115,51 @@ export type HoseProbeResult = {
}; };
/** A Hose OpenAPI access token plus whether it was served from the local SWR cache. */ /** 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 openapiTokenRequests = new Map<string, Promise<TokenEntry>>();
const closeApiTokenRequests = new Map<string, Promise<TokenEntry>>(); const closeApiTokenRequests = new Map<string, Promise<TokenEntry>>();
@@ -315,6 +359,23 @@ export async function getHoseOpenapiToken(
return { ...cache.openapi, cached: true }; 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); const pending = openapiTokenRequests.get(corp.id);
if (pending) return { ...(await pending), cached: false }; if (pending) return { ...(await pending), cached: false };
@@ -339,24 +400,36 @@ export async function ensureHoseOpenapiToken(
return (await getHoseOpenapiToken(corp, options)).token; 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( export async function fetchHoseCloseApiToken(
source: HoseSealSource, source: HoseSealSource,
openapiToken: string, auth: string | HoseOpenapiAuth,
expiresIn = 7200 expiresIn = 7200
): Promise<TokenEntry> { ): Promise<TokenEntry> {
const normalized = normalizeHoseAuth(auth);
const injection = hoseAuthInjection(normalized, "POST");
const client = hoseClient(source); const client = hoseClient(source);
const uid = hoseUid(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 const response = await client
.post("api/openapi/v1.1/provisional/getProvisionalAuth", { .post("api/openapi/v1.1/provisional/getProvisionalAuth", {
searchParams: { searchParams: injection.query,
accessToken: openapiToken headers: injection.headers,
}, json
json: {
uid,
pageType: "home",
expireDate: expiresIn
}
}) })
.json<HoseProvisionalResponse>(); .json<HoseProvisionalResponse>();
@@ -403,13 +476,15 @@ export async function ensureHoseCloseApiToken(corp: CorpConfig): Promise<TokenEn
const pending = closeApiTokenRequests.get(corp.id); const pending = closeApiTokenRequests.get(corp.id);
if (pending) return pending; if (pending) return pending;
const request = ensureHoseOpenapiToken(corp) const request = ensureHoseOpenapiTokenAuth(corp)
.then((openapiToken) => fetchHoseCloseApiToken(source, openapiToken)) .then((auth) => fetchHoseCloseApiToken(source, auth))
.then((closeapi) => { .then((closeapi) => {
setHoseAuthCache(corp.id, { if (!isCloudCorp(corp)) {
...getHoseAuthCache(corp.id), setHoseAuthCache(corp.id, {
closeapi ...getHoseAuthCache(corp.id),
}); closeapi
});
}
return closeapi; return closeapi;
}) })
.finally(() => closeApiTokenRequests.delete(corp.id)); .finally(() => closeApiTokenRequests.delete(corp.id));
@@ -448,8 +523,8 @@ export async function getHoseProvisionalAuthLink(
throw new Error(`Invalid expire seconds: ${expiresIn}. Must be a positive integer.`); throw new Error(`Invalid expire seconds: ${expiresIn}. Must be a positive integer.`);
} }
const openapiToken = await ensureHoseOpenapiToken(corp, { force: options?.force }); const auth = await ensureHoseOpenapiTokenAuth(corp, { force: options?.force });
const provisional = await fetchHoseCloseApiToken(corp.source, openapiToken, expiresIn); const provisional = await fetchHoseCloseApiToken(corp.source, auth, expiresIn);
if (!provisional.url) { if (!provisional.url) {
throw new Error("Hose provisional auth URL was not available"); throw new Error("Hose provisional auth URL was not available");
} }
@@ -608,13 +683,16 @@ async function testSingleHoseDomain(
export async function fetchHoseRoleDefGroups( export async function fetchHoseRoleDefGroups(
domain: string, domain: string,
openapiToken: string auth: string | HoseOpenapiAuth
): Promise<HoseRoleDefGroup[]> { ): 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, { const response = await fetch(url, {
headers: { headers: {
"content-type": "application/json", "content-type": "application/json",
Accept: "application/json" Accept: "application/json",
...injection.headers
}, },
signal: AbortSignal.timeout(10000) signal: AbortSignal.timeout(10000)
}); });
@@ -658,17 +736,22 @@ export async function fetchHoseRoleDefGroups(
export async function fetchHoseRoleStaffs( export async function fetchHoseRoleStaffs(
domain: string, domain: string,
openapiToken: string, auth: string | HoseOpenapiAuth,
roledefId: string, roledefId: string,
staffBy = "id" staffBy = "id"
): Promise<{ id: string; name: string; count: number; staffs: string[] }> { ): Promise<{ id: string; name: string; count: number; staffs: string[] }> {
const cleanId = roledefId.startsWith("$") ? roledefId.slice(1) : roledefId; 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, { const response = await fetch(url, {
headers: { headers: {
"content-type": "application/json", "content-type": "application/json",
Accept: "application/json" Accept: "application/json",
...injection.headers
}, },
signal: AbortSignal.timeout(10000) signal: AbortSignal.timeout(10000)
}); });
@@ -715,22 +798,29 @@ export async function fetchHoseRoleStaffs(
export async function fetchHoseStaffDetails( export async function fetchHoseStaffDetails(
domain: string, domain: string,
openapiToken: string, auth: string | HoseOpenapiAuth,
staffIds: string[] staffIds: string[]
): Promise<HoseStaffDetail[]> { ): Promise<HoseStaffDetail[]> {
if (staffIds.length === 0) return []; 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, { const response = await fetch(url, {
method: "POST", method: "POST",
headers: { headers: {
"content-type": "application/json", "content-type": "application/json",
Accept: "application/json" Accept: "application/json",
...injection.headers
}, },
body: JSON.stringify({ body: JSON.stringify(body),
type: "STAFFID",
conditionIds: staffIds.slice(0, 100)
}),
signal: AbortSignal.timeout(10000) signal: AbortSignal.timeout(10000)
}); });
+26 -4
View File
@@ -15,7 +15,8 @@ import {
rotateBackupCookies rotateBackupCookies
} from "./session-fallback.js"; } from "./session-fallback.js";
import { createSealDelegationLink, exchangeSealDelegateLink } from "./delegate.js"; import { createSealDelegationLink, exchangeSealDelegateLink } from "./delegate.js";
import { cloudAuthRequiredError, isCloudCorp } from "./credentials.js"; import { cloudAuthRequiredError, isCloudCorp, resolveCorpCredentials } from "./credentials.js";
import { clearBridgeCredentialCache } from "./bridge-client.js";
import { saveCorpConfig } from "../config/repository.js"; import { saveCorpConfig } from "../config/repository.js";
import { formatBeijingIso } from "../config/timestamps.js"; import { formatBeijingIso } from "../config/timestamps.js";
@@ -107,9 +108,27 @@ export async function renewNativeSealSession(corp: CorpConfig): Promise<SealSess
} }
async function refreshSealSession(corp: CorpConfig): Promise<SealSession> { async function refreshSealSession(corp: CorpConfig): Promise<SealSession> {
if (isCloudCorp(corp)) { if (isCloudCorp(corp) && corp.source.type === "seal") {
// Phase 3 replaces this with the bridge credential fetch. const credentials = await resolveCorpCredentials(corp);
throw cloudAuthRequiredError(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) { switch (corp.source.type) {
@@ -165,6 +184,9 @@ export async function resolveSealEnterpriseConfig(
export function clearSealToken(corpId: string): void { export function clearSealToken(corpId: string): void {
memoryCache.delete(corpId); memoryCache.delete(corpId);
clearSealSession(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. */ /** Reuse a concurrent refresh rather than invalidating a newer session on a late 401. */
+44
View File
@@ -1,4 +1,7 @@
import { describe, expect, test } from "bun:test"; 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 { VERSION } from "../../version.js";
import { diagnoseSystem, formatDoctorDashboard } from "./diagnose.js"; import { diagnoseSystem, formatDoctorDashboard } from "./diagnose.js";
import { import {
@@ -76,3 +79,44 @@ describe("Doctor Diagnosis Engine", () => {
expect(dashboard).toContain("seal-use doctor guide"); 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 { formatBeijingIso } from "../config/timestamps.js";
import { getDefaultGlobalSkillDir, getSkillVersionStatus } from "../skill/skill-version.js"; import { getDefaultGlobalSkillDir, getSkillVersionStatus } from "../skill/skill-version.js";
import { resolveUsageFilePath } from "../stats/usage-tracker.js"; import { resolveUsageFilePath } from "../stats/usage-tracker.js";
import { readBridgeSession } from "../auth/bridge-token.js";
import { import {
EMBEDDED_DIRECTORY_SPECS, EMBEDDED_DIRECTORY_SPECS,
EMBEDDED_DOMAIN_CAPABILITIES, EMBEDDED_DOMAIN_CAPABILITIES,
@@ -337,6 +338,35 @@ export function diagnoseSystem(): DoctorDiagnosis {
: `${looseCredentialFiles.length} 个凭据文件权限宽于 0600(同机其他用户可读,取决于父目录权限),建议 chmod 600:${looseCredentialFiles.join("、")}` : `${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 // Check 6: Config file parseability. A single malformed JSON file otherwise
// silently removes that enterprise from every command; surface it by name. // silently removes that enterprise from every command; surface it by name.
const configIssues = [ const configIssues = [
+23 -9
View File
@@ -1,10 +1,12 @@
import ky, { HTTPError, type KyInstance } from "ky"; 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"; import type { CorpConfig } from "../../../core/config/types.js";
export interface HoseOpenClientCredentials { export interface HoseOpenClientCredentials {
domain?: string; domain?: string;
accessToken: string; accessToken: string;
tokenType?: "query" | "header" | "bearer" | "body";
tokenName?: string;
} }
export function createHoseOpenClientWithCredentials( export function createHoseOpenClientWithCredentials(
@@ -12,15 +14,25 @@ export function createHoseOpenClientWithCredentials(
customHeaders?: Record<string, string> customHeaders?: Record<string, string>
): KyInstance { ): KyInstance {
const baseUrl = normalizeBaseUrl(credentials.domain || "https://app.ekuaibao.com"); 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({ return ky.create({
prefix: baseUrl, prefix: baseUrl,
timeout: 30000, timeout: 30000,
searchParams: { searchParams,
accessToken: credentials.accessToken headers,
},
headers: {
...customHeaders
},
hooks: { hooks: {
beforeError: [ beforeError: [
async ({ error }) => { async ({ error }) => {
@@ -45,11 +57,13 @@ export async function createHoseOpenClient(
throw new Error(`Unsupported Hose source type: ${corp.source.type}. Expected 'hose'.`); 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( return createHoseOpenClientWithCredentials(
{ {
domain: corp.source.domain, domain: corp.source.domain,
accessToken: token accessToken: auth.token,
tokenType: auth.tokenType,
tokenName: auth.tokenName
}, },
customHeaders customHeaders
); );
+3 -3
View File
@@ -7,7 +7,7 @@ import {
type MaterialPackFilePolicyPatch type MaterialPackFilePolicyPatch
} from "./material-pack/policy.js"; } from "./material-pack/policy.js";
import { CorpConfig } from "../../core/config/types.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 { createSealClientForUrl } from "../../core/http/factory.js";
import { redactSensitiveText } from "../../core/util/redact.js"; import { redactSensitiveText } from "../../core/util/redact.js";
import { safetyBlocked, validationError } from "../../core/errors.js"; import { safetyBlocked, validationError } from "../../core/errors.js";
@@ -1300,8 +1300,8 @@ export async function createDelegationForUser(
(cleanPhone ? `${corp.source.corpId}:${cleanPhone}` : undefined); (cleanPhone ? `${corp.source.corpId}:${cleanPhone}` : undefined);
if (staffId) { if (staffId) {
const openapiToken = await ensureHoseOpenapiToken(corp); const auth = await ensureHoseOpenapiTokenAuth(corp);
const provisional = await fetchHoseCloseApiToken({ ...corp.source, staffId }, openapiToken); const provisional = await fetchHoseCloseApiToken({ ...corp.source, staffId }, auth);
const closeapiToken = provisional.token; const closeapiToken = provisional.token;
const sealUrl = defaultSealUrl(corp, corp.source); const sealUrl = defaultSealUrl(corp, corp.source);
@@ -1,5 +1,5 @@
import type { KyInstance } from "ky" 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 type { CorpConfig } from "../../../core/config/types.js"
import { getMe } from "../api.js" import { getMe } from "../api.js"
import type { MeData } from "../types.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 canonicalId = (id: string) => id.includes(":") ? id : `${source.corpId}:${id}`
const targetId = canonicalId(source.staffId) const targetId = canonicalId(source.staffId)
try { try {
const token = await ensureHoseOpenapiToken(corp) const auth = await ensureHoseOpenapiTokenAuth(corp)
const staffs = await fetchHoseStaffDetails(source.domain, token, [targetId]) const staffs = await fetchHoseStaffDetails(source.domain, auth, [targetId])
const matches = staffs.filter(staff => typeof staff.id === "string" && canonicalId(staff.id) === targetId) const matches = staffs.filter(staff => typeof staff.id === "string" && canonicalId(staff.id) === targetId)
const staff = matches.length === 1 ? matches[0] : undefined const staff = matches.length === 1 ? matches[0] : undefined
if (!staff || typeof staff.name !== "string" || !staff.name.trim()) return unresolved 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 = [] if (staff.roles.length === 0) roleNames = []
else { else {
try { 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) 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)) { if (names.every((name): name is string => typeof name === "string" && name.trim().length > 0)) {
roleNames = [...new Set(names)] roleNames = [...new Set(names)]