- 授权自愈: 引入长效会话 Cookie 备份池,支持 Seal 原生协助授权到期与 401 报错时平滑自动换发与静默续期; - 存储升级: 审核报告人工裁决底座迁移至 SQLite (~/.config/seal-use/state/reviews.sqlite),支持历史 JSONL 自动平滑导入与向后兼容双写; - 分歧待办: 新增 report review unreviewed 与 dismiss 命令,收集人机不一致单据并在日常企业命令完成后于 stderr 注入 Agent 动作指引; - 精密频控: 实现 30 天单据时效窗口过滤(陈年单据自动归档)、动态 5 小时滑动窗口频控与 24 小时人工拒审静音抑制协议; - 透明认知: 全面补充 Skill 路由与帮助手册,消除黑盒,透传数据边界与安全红线。
337 lines
9.9 KiB
TypeScript
337 lines
9.9 KiB
TypeScript
import { createSealClientForUrl } from "../http/factory.js";
|
||
|
||
/**
|
||
* Seal 原生委托链接(delegate link)消费能力。
|
||
*
|
||
* 链接格式:https://<tenant>.sealai.cc/delegate?token=<delegateToken>
|
||
* 交换端点:GET {sealUrl}/api/auth/get-session?delegateToken=<delegateToken>
|
||
* 返回结构:{ user, session: { token, expiresAt, ... } }
|
||
*/
|
||
|
||
export interface SealDelegateLink {
|
||
sealUrl: string;
|
||
delegateToken: string;
|
||
}
|
||
|
||
export interface SealDelegateSealSession {
|
||
sealUrl: string;
|
||
token: string;
|
||
expiresIn: number;
|
||
sessionCookie?: string;
|
||
user: Record<string, unknown>;
|
||
tenant: Record<string, unknown>;
|
||
}
|
||
|
||
const SEALAI_HOST_SUFFIX = ".sealai.cc";
|
||
const DELEGATE_PATH = "/delegate";
|
||
|
||
/**
|
||
* 判断一个 URL 是否为 Seal 原生委托链接。
|
||
* 规则:HTTPS、host 以 .sealai.cc 结尾、pathname 为 /delegate、query 含 token。
|
||
*/
|
||
export function isSealDelegateLink(value: string): boolean {
|
||
try {
|
||
parseSealDelegateLink(value);
|
||
return true;
|
||
} catch {
|
||
return false;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 解析 Seal 委托链接,提取 sealUrl 与 delegateToken。
|
||
*/
|
||
export function parseSealDelegateLink(value: string): SealDelegateLink {
|
||
let url: URL;
|
||
try {
|
||
url = new URL(value.trim());
|
||
} catch {
|
||
throw new Error("Invalid Seal delegate link: expected a valid HTTPS URL");
|
||
}
|
||
|
||
if (url.protocol !== "https:") {
|
||
throw new Error("Invalid Seal delegate link: expected HTTPS");
|
||
}
|
||
|
||
const host = url.hostname.toLowerCase();
|
||
if (!host.endsWith(SEALAI_HOST_SUFFIX)) {
|
||
throw new Error(
|
||
`Invalid Seal delegate link: expected host ending in ${SEALAI_HOST_SUFFIX}, got ${host}`
|
||
);
|
||
}
|
||
|
||
const pathname = url.pathname.replace(/\/+$/, "");
|
||
if (pathname !== DELEGATE_PATH) {
|
||
throw new Error(
|
||
`Invalid Seal delegate link: expected path ${DELEGATE_PATH}, got ${pathname}`
|
||
);
|
||
}
|
||
|
||
const token = url.searchParams.get("token");
|
||
if (!token) {
|
||
throw new Error("Invalid Seal delegate link: token query parameter is required");
|
||
}
|
||
|
||
return {
|
||
sealUrl: url.origin,
|
||
delegateToken: token
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 预览 Seal 委托链接对应的租户与用户信息(调用 /api/v1/delegation/preview,不产生消费)。
|
||
*/
|
||
export async function previewSealDelegateLink(
|
||
value: string | SealDelegateLink
|
||
): Promise<{
|
||
userId: string;
|
||
userName: string;
|
||
tenantId: string;
|
||
tenantName: string;
|
||
delegationId: string;
|
||
}> {
|
||
const link = typeof value === "string" ? parseSealDelegateLink(value) : value;
|
||
const client = createSealClientForUrl(link.sealUrl, undefined);
|
||
const resp = await client
|
||
.post("api/v1/delegation/preview", {
|
||
json: { token: link.delegateToken }
|
||
})
|
||
.json<{
|
||
data: {
|
||
userId: string;
|
||
userName: string;
|
||
tenantId: string;
|
||
tenantName: string;
|
||
delegationId: string;
|
||
};
|
||
}>();
|
||
return resp.data;
|
||
}
|
||
|
||
/**
|
||
* 通过 Seal 委托链接换取临时 Seal Bearer session。
|
||
*
|
||
* 流程:
|
||
* 1. POST {sealUrl}/api/v1/delegation/consume { token: <delegateToken> }
|
||
* → 200 OK,响应体包含 { data: { userId, userName, tenantId, tenantName, delegationId } }
|
||
* → Set-Cookie 包含 __Secure-x-seal.session_token / x-seal.session_token
|
||
* 2. GET {sealUrl}/api/auth/get-session(携带 session_token cookie)
|
||
* → { user, session: { token, expiresAt, ... } }
|
||
* 3. GET {sealUrl}/api/v1/auth/me(携带 Authorization: Bearer <session.token>)
|
||
* → 获取完整租户与用户元数据
|
||
*/
|
||
export async function exchangeSealDelegateLink(
|
||
value: string | SealDelegateLink
|
||
): Promise<SealDelegateSealSession> {
|
||
const link = typeof value === "string" ? parseSealDelegateLink(value) : value;
|
||
const sealUrl = link.sealUrl;
|
||
|
||
const unauthedClient = createSealClientForUrl(sealUrl, undefined);
|
||
|
||
// Step 1: consume delegation token
|
||
const consumeResp = await unauthedClient.post("api/v1/delegation/consume", {
|
||
json: { token: link.delegateToken }
|
||
});
|
||
|
||
const rawSetCookie = consumeResp.headers.get("set-cookie") ?? "";
|
||
const setCookies: string[] = typeof (consumeResp.headers as any).getSetCookie === "function"
|
||
? (consumeResp.headers as any).getSetCookie()
|
||
: [rawSetCookie];
|
||
|
||
let sessionCookie = "";
|
||
for (const sc of setCookies) {
|
||
if (sc && sc.includes("session_token=")) {
|
||
sessionCookie = (sc.split(";")[0] ?? "").trim();
|
||
break;
|
||
}
|
||
}
|
||
|
||
// Step 2: exchange cookie for session details via get-session
|
||
let sessionResp: {
|
||
user?: Record<string, unknown>;
|
||
session?: { token?: string; expiresAt?: string };
|
||
} | undefined;
|
||
|
||
try {
|
||
sessionResp = await unauthedClient
|
||
.get("api/auth/get-session", {
|
||
headers: sessionCookie ? { cookie: sessionCookie } : {}
|
||
})
|
||
.json<{
|
||
user?: Record<string, unknown>;
|
||
session?: { token?: string; expiresAt?: string };
|
||
}>();
|
||
} catch {
|
||
// If get-session fails, fallback to cookie token extraction
|
||
}
|
||
|
||
let bearerToken = sessionResp?.session?.token;
|
||
if (!bearerToken && sessionCookie) {
|
||
const match = sessionCookie.match(/session_token=([^.;]+)/);
|
||
if (match?.[1]) {
|
||
bearerToken = decodeURIComponent(match[1]);
|
||
}
|
||
}
|
||
|
||
if (!bearerToken) {
|
||
throw new Error("Seal delegate exchange did not return a session token");
|
||
}
|
||
|
||
// expiresAt is an ISO 8601 string; compute expiresIn seconds
|
||
let expiresIn = 86400; // default 24h
|
||
if (sessionResp?.session?.expiresAt) {
|
||
const expMs = new Date(sessionResp.session.expiresAt).getTime();
|
||
if (Number.isFinite(expMs)) {
|
||
const diffSec = Math.floor((expMs - Date.now()) / 1000);
|
||
if (diffSec > 0) expiresIn = diffSec;
|
||
}
|
||
}
|
||
|
||
// Step 3: fetch full /api/v1/auth/me (user & tenant metadata)
|
||
const authedClient = createSealClientForUrl(sealUrl, bearerToken);
|
||
const meRaw = (await authedClient.get("api/v1/auth/me").json()) as Record<string, unknown>;
|
||
const me = (meRaw.data && typeof meRaw.data === "object"
|
||
? meRaw.data
|
||
: meRaw) as { user?: Record<string, unknown>; tenant?: Record<string, unknown> };
|
||
const user = (me.user ?? sessionResp?.user ?? {}) as Record<string, unknown>;
|
||
const tenant = (me.tenant ?? {}) as Record<string, unknown>;
|
||
|
||
return {
|
||
sealUrl,
|
||
token: bearerToken,
|
||
expiresIn,
|
||
sessionCookie: sessionCookie || undefined,
|
||
user,
|
||
tenant
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 调用 SealAI 服务端为当前租户创建新的协助授权链接(最长支持 168 小时 / 7 天)
|
||
*/
|
||
export async function createSealDelegationLink(
|
||
sealUrl: string,
|
||
options?: {
|
||
cookie?: string;
|
||
token?: string;
|
||
expiresInHours?: number;
|
||
note?: string;
|
||
customHeaders?: Record<string, string>;
|
||
}
|
||
): Promise<{ link: string; token: string; expiresInHours: number }> {
|
||
const expiresInHours = options?.expiresInHours ?? 168;
|
||
const note = options?.note ?? "权限续期";
|
||
const headers: Record<string, string> = {
|
||
...options?.customHeaders
|
||
};
|
||
if (options?.cookie) {
|
||
headers.Cookie = options.cookie;
|
||
}
|
||
|
||
const client = createSealClientForUrl(sealUrl, options?.token, headers);
|
||
const resp = await client
|
||
.post("api/v1/delegation/create", {
|
||
json: { expiresInHours, note }
|
||
})
|
||
.json<{
|
||
data?: { link?: string; token?: string };
|
||
link?: string;
|
||
token?: string;
|
||
}>();
|
||
|
||
const link = resp.data?.link ?? resp.link;
|
||
const token = resp.data?.token ?? resp.token;
|
||
if (!link || !token) {
|
||
throw new Error("Seal create delegation did not return a valid link/token");
|
||
}
|
||
|
||
return { link, token, expiresInHours };
|
||
}
|
||
|
||
/* ------------------------------------------------------------------ *
|
||
* Link-type scoring (classification by score)
|
||
* ------------------------------------------------------------------ */
|
||
|
||
export type AssistLinkKind = "hose" | "seal-delegate";
|
||
|
||
export interface AssistLinkScore {
|
||
kind: AssistLinkKind;
|
||
/** 0–100. Higher means a better match. 0 = not a match. */
|
||
score: number;
|
||
/** Human-readable reason for the score, used for diagnostics. */
|
||
reason: string;
|
||
}
|
||
|
||
/**
|
||
* Score an incoming assistance/delegate link against known link types.
|
||
*
|
||
* This is the single entry point used by `corps add-link` to decide which
|
||
* exchange path to take. Adding a new link type = adding a new scorer here.
|
||
*/
|
||
export function scoreAssistLink(rawUrl: string): AssistLinkScore[] {
|
||
const scores: AssistLinkScore[] = [];
|
||
|
||
// --- Scorer 1: Hose assistance link (thirdparty.html) ---
|
||
let hoseScore = 0;
|
||
let hoseReason = "";
|
||
try {
|
||
const u = new URL(rawUrl.trim());
|
||
const host = u.hostname.toLowerCase();
|
||
const path = u.pathname.replace(/\/+$/, "");
|
||
const isHoseHost =
|
||
host.endsWith(".ekuaibao.com") ||
|
||
host.endsWith(".hosecloud.com") ||
|
||
host === "ekuaibao.com" ||
|
||
host === "hosecloud.com";
|
||
if (isHoseHost) {
|
||
hoseScore += 40;
|
||
hoseReason = "host is Hose domain";
|
||
}
|
||
if (path === "/web/thirdparty.html") {
|
||
hoseScore += 40;
|
||
hoseReason += "; path is /web/thirdparty.html";
|
||
}
|
||
if (u.searchParams.has("accessToken")) {
|
||
hoseScore += 10;
|
||
hoseReason += "; has accessToken";
|
||
}
|
||
if (u.searchParams.has("ekbCorpId")) {
|
||
hoseScore += 10;
|
||
hoseReason += "; has ekbCorpId";
|
||
}
|
||
} catch {
|
||
hoseScore = 0;
|
||
}
|
||
if (hoseScore > 0) {
|
||
scores.push({ kind: "hose", score: hoseScore, reason: hoseReason });
|
||
}
|
||
|
||
// --- Scorer 2: Seal native delegate link ---
|
||
let sealScore = 0;
|
||
let sealReason = "";
|
||
try {
|
||
const u = new URL(rawUrl.trim());
|
||
const host = u.hostname.toLowerCase();
|
||
const path = u.pathname.replace(/\/+$/, "");
|
||
if (host.endsWith(".sealai.cc")) {
|
||
sealScore += 40;
|
||
sealReason = "host ends with .sealai.cc";
|
||
}
|
||
if (path === "/delegate") {
|
||
sealScore += 40;
|
||
sealReason += "; path is /delegate";
|
||
}
|
||
if (u.searchParams.has("token")) {
|
||
sealScore += 20;
|
||
sealReason += "; has token query param";
|
||
}
|
||
} catch {
|
||
sealScore = 0;
|
||
}
|
||
if (sealScore > 0) {
|
||
scores.push({ kind: "seal-delegate", score: sealScore, reason: sealReason });
|
||
}
|
||
|
||
return scores.sort((a, b) => b.score - a.score);
|
||
}
|