Support Seal native delegate link in corps add-link and refine hose keys
This commit is contained in:
1 parent
3f95932377
commit
d42755f9bc
13 files changed
+1065
-388
No files matched your search
@@ -0,0 +1,167 @@
|
||||
import { describe, test, expect } from "bun:test";
|
||||
import {
|
||||
exchangeSealDelegateLink,
|
||||
isSealDelegateLink,
|
||||
parseSealDelegateLink,
|
||||
previewSealDelegateLink,
|
||||
scoreAssistLink
|
||||
} from "./delegate.js";
|
||||
|
||||
describe("parseSealDelegateLink", () => {
|
||||
test("accepts a well-formed Seal delegate link", () => {
|
||||
const parsed = parseSealDelegateLink(
|
||||
"https://q02gj5lyidv.sealai.cc/delegate?token=abc123"
|
||||
);
|
||||
expect(parsed.sealUrl).toBe("https://q02gj5lyidv.sealai.cc");
|
||||
expect(parsed.delegateToken).toBe("abc123");
|
||||
});
|
||||
|
||||
test("rejects non-sealai.cc hosts", () => {
|
||||
expect(() =>
|
||||
parseSealDelegateLink("https://example.com/delegate?token=abc")
|
||||
).toThrow(/host ending in \.sealai\.cc/);
|
||||
});
|
||||
|
||||
test("rejects wrong path", () => {
|
||||
expect(() =>
|
||||
parseSealDelegateLink("https://x.sealai.cc/web/thirdparty.html?token=abc")
|
||||
).toThrow(/expected path \/delegate/);
|
||||
});
|
||||
|
||||
test("rejects missing token query param", () => {
|
||||
expect(() =>
|
||||
parseSealDelegateLink("https://x.sealai.cc/delegate")
|
||||
).toThrow(/token query parameter is required/);
|
||||
});
|
||||
|
||||
test("rejects plain HTTP", () => {
|
||||
expect(() =>
|
||||
parseSealDelegateLink("http://x.sealai.cc/delegate?token=abc")
|
||||
).toThrow(/expected HTTPS/);
|
||||
});
|
||||
|
||||
test("isSealDelegateLink returns boolean", () => {
|
||||
expect(isSealDelegateLink("https://x.sealai.cc/delegate?token=abc")).toBe(true);
|
||||
expect(isSealDelegateLink("https://x.ekuaibao.com/web/thirdparty.html?accessToken=x&ekbCorpId=y")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("scoreAssistLink", () => {
|
||||
test("scores a Seal delegate link highest for seal-delegate", () => {
|
||||
const scores = scoreAssistLink(
|
||||
"https://q02gj5lyidv.sealai.cc/delegate?token=abc123"
|
||||
);
|
||||
expect(scores[0]!.kind).toBe("seal-delegate");
|
||||
expect(scores[0]!.score).toBe(100);
|
||||
});
|
||||
|
||||
test("scores a Hose assistance link highest for hose", () => {
|
||||
const scores = scoreAssistLink(
|
||||
"https://demo.ekuaibao.com/web/thirdparty.html?accessToken=tok&ekbCorpId=demo"
|
||||
);
|
||||
expect(scores[0]!.kind).toBe("hose");
|
||||
expect(scores[0]!.score).toBe(100);
|
||||
});
|
||||
|
||||
test("returns empty array for garbage", () => {
|
||||
expect(scoreAssistLink("not a url")).toEqual([]);
|
||||
});
|
||||
|
||||
test("seal-delegate does not beat hose on a hose link (no cross-misclassification)", () => {
|
||||
const scores = scoreAssistLink(
|
||||
"https://demo.ekuaibao.com/web/thirdparty.html?accessToken=tok&ekbCorpId=demo"
|
||||
);
|
||||
// hose should be 100; seal-delegate should not appear (host not .sealai.cc)
|
||||
const seal = scores.find((s) => s.kind === "seal-delegate");
|
||||
expect(seal).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("exchangeSealDelegateLink and previewSealDelegateLink", () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
|
||||
test("previewSealDelegateLink queries /api/v1/delegation/preview", async () => {
|
||||
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/preview") {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
data: {
|
||||
userId: "u-123",
|
||||
userName: "Alice",
|
||||
tenantId: "t-456",
|
||||
tenantName: "Acme Corp",
|
||||
delegationId: "del-789"
|
||||
}
|
||||
}),
|
||||
{ headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
return new Response("Not found", { status: 404 });
|
||||
}) as typeof fetch;
|
||||
|
||||
try {
|
||||
const preview = await previewSealDelegateLink("https://mytenant.sealai.cc/delegate?token=mytoken");
|
||||
expect(preview.userName).toBe("Alice");
|
||||
expect(preview.tenantName).toBe("Acme Corp");
|
||||
expect(preview.delegationId).toBe("del-789");
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
|
||||
test("exchangeSealDelegateLink calls consume -> get-session -> auth/me", async () => {
|
||||
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/consume") {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
data: {
|
||||
userId: "u-123",
|
||||
userName: "Alice",
|
||||
tenantId: "t-456",
|
||||
tenantName: "Acme Corp",
|
||||
delegationId: "del-789"
|
||||
}
|
||||
}),
|
||||
{
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Set-Cookie": "__Secure-x-seal.session_token=mock-token.signature; Path=/; HttpOnly; Secure"
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
if (url.pathname === "/api/auth/get-session") {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
user: { id: "u-123", name: "Alice" },
|
||||
session: { token: "extracted-bearer-token", expiresAt: "2026-12-31T23:59:59.000Z" }
|
||||
}),
|
||||
{ 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: "Acme Corp", tenantSlug: "acme-slug" }
|
||||
}
|
||||
}),
|
||||
{ headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
return new Response("Not found", { status: 404 });
|
||||
}) as typeof fetch;
|
||||
|
||||
try {
|
||||
const session = await exchangeSealDelegateLink("https://mytenant.sealai.cc/delegate?token=mytoken");
|
||||
expect(session.sealUrl).toBe("https://mytenant.sealai.cc");
|
||||
expect(session.token).toBe("extracted-bearer-token");
|
||||
expect((session.tenant as any).tenantSlug).toBe("acme-slug");
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,292 @@
|
||||
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;
|
||||
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,
|
||||
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);
|
||||
}
|
||||
Reference in new issue
Block a user