Files
seal-use/src/core/auth/hose.test.ts
T
gitea 5f4906758e Enable strict unused-symbol checks and remove dead code
Turn on noUnusedLocals/noUnusedParameters so the compiler keeps flagging
dead symbols, then clear the 737 findings it reports: unused imports across
src/, unused parameters, unreachable locals, and the copy-pasted 135-line
import prologues in the seal tool modules (each tool file now imports only
what it uses). Also applies the equivalent-safe lint rewrites (Array.from
instead of new Array(n).fill, non-null assertions in tests after toBeDefined,
simplified spreads, unused catch params) that oxlint will gate in a later
commit.
2026-09-29 22:04:01 +08:00

406 lines
14 KiB
TypeScript

import { afterEach, describe, expect, test } from "bun:test";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { CorpConfig, HoseSealSource } from "../config/types.js";
import {
HOSE_STANDARD_DOMAINS,
assertHoseAssistTenantMatches,
defaultSealUrl,
exchangeHoseAssistLink,
fetchHoseStaffDetails,
getHoseEnterpriseUrl,
getHoseProvisionalAuthLink,
getHoseSealSession,
normalizeBaseUrl,
parseHoseAssistLink
} from "./hose.js";
import { getHoseAuthCache } from "./token-store.js";
const ORIGINAL_ENV = process.env.SEAL_HOME_TOKEN_STORE;
const ORIGINAL_FETCH = globalThis.fetch;
const tempDirs: string[] = [];
function setupTokenStore(data: Record<string, unknown>): string {
const dir = mkdtempSync(join(tmpdir(), "hose-auth-test-"));
tempDirs.push(dir);
const storePath = join(dir, "tokens.json");
process.env.SEAL_HOME_TOKEN_STORE = storePath;
writeFileSync(storePath, JSON.stringify(data, null, 2));
return storePath;
}
afterEach(() => {
if (ORIGINAL_ENV === undefined) {
delete process.env.SEAL_HOME_TOKEN_STORE;
} else {
process.env.SEAL_HOME_TOKEN_STORE = ORIGINAL_ENV;
}
globalThis.fetch = ORIGINAL_FETCH;
for (const dir of tempDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
}
});
describe("hose auth helpers", () => {
test("normalizeBaseUrl strips trailing slashes", () => {
expect(normalizeBaseUrl("https://app.ekuaibao.com///")).toBe("https://app.ekuaibao.com");
expect(normalizeBaseUrl("https://app.ekuaibao.com")).toBe("https://app.ekuaibao.com");
});
test("defaultSealUrl resolves corp.seal.url, source.sealUrl, or fallback subdomain", () => {
const source: HoseSealSource = {
type: "hose",
domain: "https://app.ekuaibao.com",
appKey: "key",
appSecurity: "sec",
staffId: "user1",
corpId: "CORP123"
};
const corpWithSealUrl: CorpConfig = {
id: "corp-1",
name: "Corp 1",
environment: "production",
seal: { url: "https://custom.sealai.cc", endpoints: { approvalStylePreferences: "" } },
source,
auth: { refreshTtl: 300 }
};
expect(defaultSealUrl(corpWithSealUrl, source)).toBe("https://custom.sealai.cc");
const corpWithoutSealUrl: CorpConfig = {
id: "corp-1",
name: "Corp 1",
environment: "production",
seal: { endpoints: { approvalStylePreferences: "" } },
source,
auth: { refreshTtl: 300 }
};
expect(defaultSealUrl(corpWithoutSealUrl, source)).toBe("https://corp123.sealai.cc");
});
test("getHoseEnterpriseUrl retrieves cached provisional auth URL", async () => {
setupTokenStore({
"corp-cached": {
hose: {
closeapi: {
token: "close-token",
url: "https://app.ekuaibao.com/web/home.html?accessToken=close-token",
expiresAt: Date.now() + 3600_000
}
}
}
});
const corp: CorpConfig = {
id: "corp-cached",
name: "Corp Cached",
environment: "production",
seal: { endpoints: { approvalStylePreferences: "" } },
source: {
type: "hose",
domain: "https://app.ekuaibao.com",
appKey: "key",
appSecurity: "sec",
staffId: "staff",
corpId: "corp"
},
auth: { refreshTtl: 300 }
};
const url = await getHoseEnterpriseUrl(corp);
expect(url).toBe("https://app.ekuaibao.com/web/home.html?accessToken=close-token");
});
test("uses a configured Hose closeToken without OpenAPI credentials", async () => {
let requestedToken = "";
globalThis.fetch = (async (input: RequestInfo | URL) => {
const requestUrl = typeof input === "string"
? input
: input instanceof URL
? input.toString()
: input.url;
const url = new URL(requestUrl);
requestedToken = url.searchParams.get("token") ?? "";
return new Response(JSON.stringify({ accessToken: "seal-runtime-token", expiresIn: 1800 }), {
status: 200,
headers: { "content-type": "application/json" }
});
}) as typeof fetch;
const corp: CorpConfig = {
id: "corp-web",
name: "Corp Web",
environment: "production",
seal: { endpoints: { approvalStylePreferences: "" } },
source: {
type: "hose",
provider: "hosecloud",
domain: "https://wx2.ekuaibao.com",
closeToken: "hose-close-token",
staffId: "corp-web:staff-1",
corpId: "corp-web"
},
auth: { refreshTtl: 300 }
};
const session = await getHoseSealSession(corp);
expect(requestedToken).toBe("hose-close-token");
expect(session.token).toBe("seal-runtime-token");
expect(session.enterprise.provider).toBe("hose");
});
test("HOSE_STANDARD_DOMAINS contains 6 expected public platform domains", () => {
expect(HOSE_STANDARD_DOMAINS.length).toBe(6);
expect(HOSE_STANDARD_DOMAINS).toContain("https://app.ekuaibao.com");
expect(HOSE_STANDARD_DOMAINS).toContain("https://dd2.hosecloud.com");
expect(HOSE_STANDARD_DOMAINS).toContain("https://wx2.ekuaibao.com");
expect(HOSE_STANDARD_DOMAINS).toContain("https://kdcloud2.ekuaibao.com");
expect(HOSE_STANDARD_DOMAINS).toContain("https://ddenterprise.ekuaibao.com");
expect(HOSE_STANDARD_DOMAINS).toContain("https://feishu.ekuaibao.com");
});
test("fetchHoseStaffDetails returns empty array for empty staffIds", async () => {
const details = await fetchHoseStaffDetails("https://app.ekuaibao.com", "fake-token", []);
expect(details).toEqual([]);
});
test("parses a Hose third-party assistance link without exposing its token", () => {
const result = parseHoseAssistLink(
"https://wx2.ekuaibao.com/web/thirdparty.html?accessToken=temporary-token&ekbCorpId=Acme-01&pageType=home"
);
expect(result).toEqual({
corpId: "acme-01",
accessToken: "temporary-token",
baseUrl: "https://wx2.ekuaibao.com"
});
});
test("rejects unsupported Hose assistance link shapes", () => {
expect(() => parseHoseAssistLink("http://wx2.ekuaibao.com/web/thirdparty.html?accessToken=t&ekbCorpId=acme")).toThrow(
"expected an HTTPS"
);
expect(() => parseHoseAssistLink("https://example.com/web/thirdparty.html?accessToken=t&ekbCorpId=acme")).toThrow(
"expected an HTTPS"
);
expect(() => parseHoseAssistLink("https://wx2.ekuaibao.com/web/home.html?accessToken=t&ekbCorpId=acme")).toThrow(
"expected an HTTPS"
);
expect(() => parseHoseAssistLink("https://wx2.ekuaibao.com/web/thirdparty.html?ekbCorpId=acme")).toThrow(
"required exactly once"
);
});
test("exchanges a Hose assistance link for a Seal session", async () => {
let requestedUrl = "";
globalThis.fetch = (async (input: RequestInfo | URL) => {
requestedUrl = typeof input === "string"
? input
: input instanceof URL
? input.toString()
: input.url;
return new Response(JSON.stringify({
data: {
accessToken: "seal-bearer-token",
expiresIn: 1800
}
}), {
status: 200,
headers: { "content-type": "application/json" }
});
}) as typeof fetch;
const result = await exchangeHoseAssistLink(
"https://wx2.ekuaibao.com/web/thirdparty.html?accessToken=hose-token&ekbCorpId=Acme-01"
);
const url = new URL(requestedUrl);
expect(url.origin).toBe("https://acme-01.sealai.cc");
expect(url.pathname).toBe("/api/auth/oauth2/session/oem-hosecloud");
expect(url.searchParams.get("token")).toBe("hose-token");
expect(url.searchParams.get("returnToken")).toBe("1");
expect(result).toEqual({
corpId: "acme-01",
sealUrl: "https://acme-01.sealai.cc",
token: "seal-bearer-token",
expiresIn: 1800
});
});
test("requires complete and consistent tenant identity metadata", () => {
expect(() => assertHoseAssistTenantMatches("acme-01", {})).toThrow("tenant mismatch");
expect(() => assertHoseAssistTenantMatches("acme-01", {
tenantSlug: "acme-01",
hoseCorpConfig: { corporationId: "other-corp" }
})).toThrow("tenant mismatch");
expect(() => assertHoseAssistTenantMatches("Acme-01", {
hoseCorpConfig: { corporationId: " ACME-01 " }
})).not.toThrow();
});
test("fetchHoseOpenApiKeysFromLink extracts keys with discovered metadata", async () => {
const { fetchHoseOpenApiKeysFromLink, maskHoseSecurity } = await import("./hose.js");
expect(maskHoseSecurity("1234567890abcdef")).toBe("12345678...cdef");
expect(maskHoseSecurity("short")).toBe("******");
expect(maskHoseSecurity("")).toBe("-");
const jwtPayload = Buffer.from(
JSON.stringify({
staffId: "acme-01:admin01",
corporationName: "Acme Corp Ltd",
staffName: "Alice Admin"
})
).toString("base64url");
const fakeJwt = `header.${jwtPayload}.signature`;
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const urlStr = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
const url = new URL(urlStr);
if (url.pathname === "/api/engine/realm/$UNITY/actions/jwt") {
return new Response(JSON.stringify({ value: fakeJwt }), {
status: 200,
headers: { "content-type": "application/json" }
});
}
if (url.pathname === "/api/innerapi/v1/key") {
const reqHeaders = input instanceof Request ? input.headers : new Headers(init?.headers);
expect(reqHeaders.get("accesstoken")).toBe("test-token");
expect(reqHeaders.get("corpid")).toBe("acme-01");
expect(reqHeaders.get("staffid")).toBe("acme-01:admin01");
return new Response(
JSON.stringify({
items: [
{
id: "key-001",
name: "生产系统接入",
appKey: "ak_acme_production_123",
appSecurity: "sec_secret_password_456789",
active: true,
corporationId: "acme-01",
createTime: 1700000000000
}
],
count: 1
}),
{ status: 200, headers: { "content-type": "application/json" } }
);
}
return new Response("not found", { status: 404 });
}) as typeof fetch;
const res = await fetchHoseOpenApiKeysFromLink(
"https://wx2.ekuaibao.com/web/thirdparty.html?accessToken=test-token&ekbCorpId=Acme-01"
);
expect(res.corpId).toBe("acme-01");
expect(res.corpName).toBe("Acme Corp Ltd");
expect(res.staffId).toBe("acme-01:admin01");
expect(res.baseUrl).toBe("https://wx2.ekuaibao.com");
expect(res.keys.length).toBe(1);
expect(res.keys[0]!.appKey).toBe("ak_acme_production_123");
expect(res.keys[0]!.appSecurity).toBe("sec_secret_password_456789");
expect(res.keys[0]!.active).toBe(true);
});
test("getHoseProvisionalAuthLink generates independent provisional link and ignores internal cache", async () => {
const initialExpiresAt = Date.now() + 7134_000;
setupTokenStore({
"corp-test": {
hose: {
openapi: {
token: "existing-openapi-token",
expiresAt: Date.now() + 3600_000
},
closeapi: {
token: "existing-close-token",
url: "https://app.ekuaibao.com/web/thirdparty.html?accessToken=existing-close-token&ekbCorpId=CORP-TEST",
expiresAt: initialExpiresAt
}
}
}
});
const corp: CorpConfig = {
id: "corp-test",
name: "Corp Test",
environment: "production",
seal: { endpoints: { approvalStylePreferences: "" } },
source: {
type: "hose",
domain: "https://app.ekuaibao.com",
appKey: "key",
appSecurity: "sec",
staffId: "staff-1",
corpId: "CORP-TEST"
},
auth: { refreshTtl: 300 }
};
let requestedExpireDate: number | undefined;
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const urlStr = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
const url = new URL(urlStr);
if (url.pathname === "/api/openapi/v1.1/provisional/getProvisionalAuth") {
let body: Record<string, unknown> = {};
if (input instanceof Request) {
body = await input.clone().json().catch(() => ({}));
} else if (typeof init?.body === "string") {
body = JSON.parse(init.body);
}
requestedExpireDate = typeof body.expireDate === "number" ? body.expireDate : undefined;
return new Response(
JSON.stringify({
value: {
message: "https://app.ekuaibao.com/web/thirdparty.html?accessToken=fresh-token-86400&ekbCorpId=CORP-TEST&pageType=home"
}
}),
{ status: 200, headers: { "content-type": "application/json" } }
);
}
return new Response("not found", { status: 404 });
}) as typeof fetch;
const result = await getHoseProvisionalAuthLink(corp, 86400);
expect(requestedExpireDate).toBe(86400);
expect(result.expiresIn).toBe(86400);
expect(result.token).toBe("fresh-token-86400");
expect(result.url).toContain("fresh-token-86400");
// Ensure internal closeapi cache was NOT overwritten
const cacheAfter = getHoseAuthCache("corp-test");
expect(cacheAfter.closeapi?.token).toBe("existing-close-token");
expect(cacheAfter.closeapi?.expiresAt).toBe(initialExpiresAt);
});
test("getHoseProvisionalAuthLink rejects invalid or non-positive expiresIn", async () => {
const corp: CorpConfig = {
id: "corp-test",
name: "Corp Test",
environment: "production",
seal: { endpoints: { approvalStylePreferences: "" } },
source: {
type: "hose",
domain: "https://app.ekuaibao.com",
appKey: "key",
appSecurity: "sec",
staffId: "staff-1",
corpId: "CORP-TEST"
},
auth: { refreshTtl: 300 }
};
expect(getHoseProvisionalAuthLink(corp, -100)).rejects.toThrow("Invalid expire seconds");
expect(getHoseProvisionalAuthLink(corp, 0)).rejects.toThrow("Invalid expire seconds");
});
});