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:
1 parent
887df2d32f
commit
71a2e9a2e3
19 files changed
+964
-84
No files matched your search
@@ -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);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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.
|
||||
}
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
@@ -5,8 +5,11 @@ 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({
|
||||
@@ -98,3 +101,52 @@ describe("cloud session isolation", () => {
|
||||
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();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
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
|
||||
@@ -13,6 +14,15 @@ export type CorpCredentials = {
|
||||
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 {
|
||||
@@ -36,7 +46,20 @@ export function cloudAuthRequiredError(corp: CorpConfig): CliError {
|
||||
*/
|
||||
export async function resolveCorpCredentials(corp: CorpConfig): Promise<CorpCredentials> {
|
||||
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;
|
||||
|
||||
+122
-32
@@ -3,7 +3,7 @@ import { CorpConfig, HoseSealSource } from "../config/types.js";
|
||||
import { createSealClientForUrl } from "../http/factory.js";
|
||||
import { resolveSealCustomHeaders } from "../http/request-headers.js";
|
||||
import { getHoseAuthCache, setHoseAuthCache } from "./token-store.js";
|
||||
import { isCloudCorp, resolveCorpCredentials, type CorpCredentials } from "./credentials.js";
|
||||
import { cloudAuthRequiredError, isCloudCorp, resolveCorpCredentials, type CorpCredentials } from "./credentials.js";
|
||||
import { SealEnterpriseConfig, SealSession, TokenEntry } from "./types.js";
|
||||
|
||||
type HoseLoginResponse = {
|
||||
@@ -115,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>>();
|
||||
@@ -315,6 +359,23 @@ export async function getHoseOpenapiToken(
|
||||
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 };
|
||||
|
||||
@@ -339,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>();
|
||||
|
||||
@@ -403,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));
|
||||
@@ -448,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");
|
||||
}
|
||||
@@ -608,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)
|
||||
});
|
||||
@@ -658,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)
|
||||
});
|
||||
@@ -715,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)
|
||||
});
|
||||
|
||||
|
||||
+26
-4
@@ -15,7 +15,8 @@ import {
|
||||
rotateBackupCookies
|
||||
} from "./session-fallback.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 { formatBeijingIso } from "../config/timestamps.js";
|
||||
|
||||
@@ -107,9 +108,27 @@ export async function renewNativeSealSession(corp: CorpConfig): Promise<SealSess
|
||||
}
|
||||
|
||||
async function refreshSealSession(corp: CorpConfig): Promise<SealSession> {
|
||||
if (isCloudCorp(corp)) {
|
||||
// Phase 3 replaces this with the bridge credential fetch.
|
||||
throw cloudAuthRequiredError(corp);
|
||||
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) {
|
||||
@@ -165,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,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 });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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 = [
|
||||
|
||||
Reference in new issue
Block a user