import { afterEach, expect, test } from "bun:test"; import { mkdtempSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { getEasoClient, getUnityClient, clearUnityClientCache } from "./unity-easo-client.js"; import { getScriptEngineClient, clearScriptEngineClientCache } from "./piper-workflow-client.js"; import { resetTokenStoreMemory, setCorpTokens } from "../auth/token-store.js"; const oldFetch = globalThis.fetch, oldFile = process.env.HOSE_TOKENS_FILE; afterEach(() => { clearScriptEngineClientCache(); clearUnityClientCache(); resetTokenStoreMemory(); globalThis.fetch = oldFetch; if (oldFile === undefined) delete process.env.HOSE_TOKENS_FILE; else process.env.HOSE_TOKENS_FILE = oldFile; }); for (const kind of ["piper", "easo", "unity"] as const) { for (const denied of [false, true]) { test(`${kind} replaces cached credentials and replays a POST at most once (denied=${denied})`, async () => { process.env.HOSE_TOKENS_FILE = join(mkdtempSync(join(tmpdir(), "hose-renew-")), "tokens.json"); resetTokenStoreMemory(); const corp = { id: `renew-${kind}-${denied}`, source: "manual", credentials: { accessToken: "source", corpId: "corp", staffId: "staff" } } as any; const shared = { sourceAccessToken: "source", expiresAt: Date.now() + 3600000 }; setCorpTokens(corp.id, { piper: { ...shared, easJwt: "stale", hoseToken: "old-hose" }, unity: { ...shared, unityJwt: "stale" }, eas: { ...shared, easToken: "stale", unityJwt: "stale", hoseToken: "old-hose" } }); const sent: Array<{ auth: string | null; body: string }> = []; globalThis.fetch = (async (input: any, init: any) => { const req = input instanceof Request ? input : new Request(input, init); if (req.url.includes("/grant/")) return Response.json({ data: "new-hose" }); if (req.url.includes("/actions/jwt")) return Response.json({ id: "fresh" }); if (req.url.includes("/realms/")) return Response.json({ value: { accessToken: "fresh" } }); sent.push({ auth: req.headers.get("authorization"), body: await req.text() }); return denied || req.headers.get("authorization") === "Bearer stale" ? new Response("expired", { status: 401 }) : Response.json({ ok: true }); }) as any; const client = kind === "piper" ? await getScriptEngineClient(corp, "app") : kind === "easo" ? (await getEasoClient(corp)).client : (await getUnityClient(corp)).client; const request = client.post("api/review", { json: { amount: 42 } }).json(); if (denied) await expect(request).rejects.toThrow(); else expect(await request).toEqual({ ok: true }); expect(sent).toEqual([{ auth: "Bearer stale", body: '{"amount":42}' }, { auth: "Bearer fresh", body: '{"amount":42}' }]); }); } }