import { createSealClientForUrl } from "../http/factory.js"; /** * Seal 原生委托链接(delegate link)消费能力。 * * 链接格式:https://.sealai.cc/delegate?token= * 交换端点:GET {sealUrl}/api/auth/get-session?delegateToken= * 返回结构:{ user, session: { token, expiresAt, ... } } */ export interface SealDelegateLink { sealUrl: string; delegateToken: string; } export interface SealDelegateSealSession { sealUrl: string; token: string; expiresIn: number; user: Record; tenant: Record; } 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: } * → 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 ) * → 获取完整租户与用户元数据 */ export async function exchangeSealDelegateLink( value: string | SealDelegateLink ): Promise { 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; session?: { token?: string; expiresAt?: string }; } | undefined; try { sessionResp = await unauthedClient .get("api/auth/get-session", { headers: sessionCookie ? { cookie: sessionCookie } : {} }) .json<{ user?: Record; 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; const me = (meRaw.data && typeof meRaw.data === "object" ? meRaw.data : meRaw) as { user?: Record; tenant?: Record }; const user = (me.user ?? sessionResp?.user ?? {}) as Record; const tenant = (me.tenant ?? {}) as Record; return { sealUrl, token: bearerToken, expiresIn, user, tenant }; } /* ------------------------------------------------------------------ * * 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); }