Files
seal-use/src/core/auth/seal-renew.test.ts
T
gitea 8c9f102931 feat: 原生 Seal 授权续期自愈与本地 SQLite 分歧待办闭环
- 授权自愈: 引入长效会话 Cookie 备份池,支持 Seal 原生协助授权到期与 401 报错时平滑自动换发与静默续期;
- 存储升级: 审核报告人工裁决底座迁移至 SQLite (~/.config/seal-use/state/reviews.sqlite),支持历史 JSONL 自动平滑导入与向后兼容双写;
- 分歧待办: 新增 report review unreviewed 与 dismiss 命令,收集人机不一致单据并在日常企业命令完成后于 stderr 注入 Agent 动作指引;
- 精密频控: 实现 30 天单据时效窗口过滤(陈年单据自动归档)、动态 5 小时滑动窗口频控与 24 小时人工拒审静音抑制协议;
- 透明认知: 全面补充 Skill 路由与帮助手册,消除黑盒,透传数据边界与安全红线。
2026-11-02 15:22:47 +08:00

319 lines
11 KiB
TypeScript

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 type { CorpConfig } from "../config/types.js";
import {
clearSealToken,
getSealSessionForCorp,
recoverSealSessionForCorp,
renewNativeSealSession
} from "./seal.js";
import {
getSealDelegateAuthCache,
getSealSession,
setSealDelegateAuthCache
} from "./token-store.js";
const originalFetch = globalThis.fetch;
let tempDir: string;
let storePath: string;
const fixtureCorp: CorpConfig = {
id: "test-delegate-corp",
name: "测试委托租户",
environment: "production",
seal: {
url: "https://mytenant.sealai.cc",
tenantSlug: "mytenant",
endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" }
},
source: {
type: "seal",
token: "initial-static-token",
sealUrl: "https://mytenant.sealai.cc",
expiresIn: 3600,
expiresAt: new Date(Date.now() + 3600 * 1000).toISOString(),
staffId: "u-123",
corpId: "test-delegate-corp",
tenantId: "t-456",
tenantSlug: "mytenant",
tenantName: "My Tenant",
provider: "seal"
},
auth: { refreshTtl: 300 }
};
describe("seal-renew: 原生 Seal 协助授权长效续期与会话池救险", () => {
beforeEach(() => {
tempDir = mkdtempSync(join(tmpdir(), "seal-renew-test-"));
storePath = join(tempDir, "tokens.json");
process.env.SEAL_USE_TOKEN_STORE = storePath;
clearSealToken(fixtureCorp.id);
});
afterEach(() => {
globalThis.fetch = originalFetch;
clearSealToken(fixtureCorp.id);
delete process.env.SEAL_USE_TOKEN_STORE;
rmSync(tempDir, { recursive: true, force: true });
});
test("无可用 Cookie 时安全返回 undefined,平滑回退到静态 token", async () => {
const renewed = await renewNativeSealSession(fixtureCorp);
expect(renewed).toBeUndefined();
const session = await getSealSessionForCorp(fixtureCorp);
expect(session.token).toBe("initial-static-token");
});
test("主 Cookie 有效时成功自动续期换发新 token,并轮转归档历史 Cookie", async () => {
setSealDelegateAuthCache(fixtureCorp.id, {
cookie: "__Secure-x-seal.session_token=old-cookie-token",
backupCookies: []
});
let delegationCreateCalledWithCookie = "";
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const url = new URL(
typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url
);
const headers = input instanceof Request ? input.headers : new Headers(init?.headers);
if (url.pathname === "/api/v1/delegation/create") {
delegationCreateCalledWithCookie = headers.get("cookie") || "";
return new Response(
JSON.stringify({
data: {
link: "https://mytenant.sealai.cc/delegate?token=minted-delegation-token",
token: "minted-delegation-token"
}
}),
{ headers: { "Content-Type": "application/json" } }
);
}
if (url.pathname === "/api/v1/delegation/consume") {
return new Response(
JSON.stringify({
data: {
userId: "u-123",
userName: "Alice",
tenantId: "t-456",
tenantName: "My Tenant",
delegationId: "del-new"
}
}),
{
headers: {
"Content-Type": "application/json",
"Set-Cookie":
"__Secure-x-seal.session_token=fresh-cookie-token.sig; Path=/; HttpOnly; Secure"
}
}
);
}
if (url.pathname === "/api/auth/get-session") {
return new Response(
JSON.stringify({
user: { id: "u-123", name: "Alice" },
session: {
token: "brand-new-bearer-token",
expiresAt: new Date(Date.now() + 168 * 3600 * 1000).toISOString()
}
}),
{ headers: { "Content-Type": "application/json" } }
);
}
if (url.pathname === "/api/v1/auth/me") {
return new Response(
JSON.stringify({
data: {
user: { id: "u-123", name: "Alice" },
tenant: { id: "t-456", name: "My Tenant", tenantSlug: "mytenant" }
}
}),
{ headers: { "Content-Type": "application/json" } }
);
}
return new Response("Not found", { status: 404 });
}) as typeof fetch;
const renewed = await renewNativeSealSession(fixtureCorp);
expect(renewed).toBeDefined();
expect(renewed!.token).toBe("brand-new-bearer-token");
expect(delegationCreateCalledWithCookie).toBe(
"__Secure-x-seal.session_token=old-cookie-token"
);
// 检查 tokens.json 中更新状态
const delegateCache = getSealDelegateAuthCache(fixtureCorp.id);
expect(delegateCache.cookie).toBe("__Secure-x-seal.session_token=fresh-cookie-token.sig");
expect(delegateCache.backupCookies).toEqual(["__Secure-x-seal.session_token=old-cookie-token"]);
// 再次读取 session 命中新缓存
const session = await getSealSessionForCorp(fixtureCorp);
expect(session.token).toBe("brand-new-bearer-token");
});
test("主 Cookie 失效时,依次由 backupCookies 兜底救险成功(断电超期场景)", async () => {
// 模拟主 Cookie 已在服务端注销失效,但历史 backupCookies 中包含一份 30 天未过期的长效会话
setSealDelegateAuthCache(fixtureCorp.id, {
cookie: "expired-cookie",
backupCookies: ["valid-backup-cookie"]
});
const attemptedCookies: string[] = [];
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const url = new URL(
typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url
);
const headers = input instanceof Request ? input.headers : new Headers(init?.headers);
if (url.pathname === "/api/v1/delegation/create") {
const cookie = headers.get("cookie") || "";
attemptedCookies.push(cookie);
if (cookie === "expired-cookie") {
return new Response(JSON.stringify({ error: { message: "Session expired" } }), {
status: 401,
headers: { "Content-Type": "application/json" }
});
}
return new Response(
JSON.stringify({
data: {
link: "https://mytenant.sealai.cc/delegate?token=rescued-delegation-token",
token: "rescued-delegation-token"
}
}),
{ headers: { "Content-Type": "application/json" } }
);
}
if (url.pathname === "/api/v1/delegation/consume") {
return new Response(
JSON.stringify({
data: {
userId: "u-123",
userName: "Alice",
tenantId: "t-456",
tenantName: "My Tenant"
}
}),
{
headers: {
"Content-Type": "application/json",
"Set-Cookie": "__Secure-x-seal.session_token=rescued-cookie.sig; Path=/; HttpOnly"
}
}
);
}
if (url.pathname === "/api/auth/get-session") {
return new Response(
JSON.stringify({
session: {
token: "rescued-bearer-token",
expiresAt: new Date(Date.now() + 168 * 3600 * 1000).toISOString()
}
}),
{ headers: { "Content-Type": "application/json" } }
);
}
if (url.pathname === "/api/v1/auth/me") {
return new Response(
JSON.stringify({
data: {
user: { id: "u-123", name: "Alice" },
tenant: { id: "t-456", name: "My Tenant", tenantSlug: "mytenant" }
}
}),
{ headers: { "Content-Type": "application/json" } }
);
}
return new Response("Not found", { status: 404 });
}) as typeof fetch;
const renewed = await renewNativeSealSession(fixtureCorp);
expect(renewed).toBeDefined();
expect(renewed!.token).toBe("rescued-bearer-token");
expect(attemptedCookies).toEqual(["expired-cookie", "valid-backup-cookie"]);
const delegateCache = getSealDelegateAuthCache(fixtureCorp.id);
expect(delegateCache.cookie).toBe("__Secure-x-seal.session_token=rescued-cookie.sig");
expect(delegateCache.backupCookies).toContain("valid-backup-cookie");
});
test("recoverSealSessionForCorp 在收到 401 时自动触发自愈", async () => {
setSealDelegateAuthCache(fixtureCorp.id, {
cookie: "valid-cookie",
backupCookies: []
});
globalThis.fetch = (async (input: RequestInfo | URL) => {
const url = new URL(
typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url
);
if (url.pathname === "/api/v1/delegation/create") {
return new Response(
JSON.stringify({
data: {
link: "https://mytenant.sealai.cc/delegate?token=recovered-delegation-token",
token: "recovered-delegation-token"
}
}),
{ headers: { "Content-Type": "application/json" } }
);
}
if (url.pathname === "/api/v1/delegation/consume") {
return new Response(
JSON.stringify({
data: { userId: "u-123", userName: "Alice", tenantId: "t-456", tenantName: "My Tenant" }
}),
{
headers: {
"Content-Type": "application/json",
"Set-Cookie": "__Secure-x-seal.session_token=recovered-cookie.sig"
}
}
);
}
if (url.pathname === "/api/auth/get-session") {
return new Response(
JSON.stringify({
session: {
token: "recovered-bearer-token",
expiresAt: new Date(Date.now() + 168 * 3600 * 1000).toISOString()
}
}),
{ headers: { "Content-Type": "application/json" } }
);
}
if (url.pathname === "/api/v1/auth/me") {
return new Response(
JSON.stringify({
data: {
user: { id: "u-123", name: "Alice" },
tenant: { id: "t-456", name: "My Tenant", tenantSlug: "mytenant" }
}
}),
{ headers: { "Content-Type": "application/json" } }
);
}
return new Response("Not found", { status: 404 });
}) as typeof fetch;
// 假设当前正在使用 stale-token 遭遇 401
const recovered = await recoverSealSessionForCorp(fixtureCorp, "initial-static-token");
expect(recovered.token).toBe("recovered-bearer-token");
const sessionInStore = getSealSession(fixtureCorp.id);
expect(sessionInStore?.token).toBe("recovered-bearer-token");
});
});