import ts from "typescript"; import assert from "node:assert/strict"; import { readdirSync, readFileSync } from "node:fs"; import { sep } from "node:path"; import { test } from "node:test"; import vm from "node:vm"; const output = ts.transpileModule(readFileSync(new URL("../src/lib/auth.ts", import.meta.url), "utf8"), { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 }, }).outputText; test("HTTPS marks the session cookie Secure while local HTTP remains usable", () => { for (const protocol of ["https:", "http:"]) { const storage = new Map(); const document = { cookie: "" }; const exports = {}; vm.runInNewContext(output, { exports, document, window: { location: { protocol } }, localStorage: { setItem: (k, v) => storage.set(k, v) }, }); exports.auth.setToken("synthetic-session"); assert.equal(storage.get("artex_token"), "synthetic-session"); assert.equal(document.cookie.includes("; Secure"), protocol === "https:"); assert.ok(document.cookie.includes("SameSite=Lax")); } }); test("the route-guard cookie is a marker and never carries the session token", () => { const storage = new Map(); const document = { cookie: "" }; const exports = {}; vm.runInNewContext(output, { exports, document, window: { location: { protocol: "https:" } }, localStorage: { setItem: (k, v) => storage.set(k, v) }, }); exports.auth.setToken("synthetic.session.token"); assert.equal(storage.get("artex_token"), "synthetic.session.token"); assert.ok(document.cookie.startsWith("artex_token=1;"), document.cookie); assert.ok(!document.cookie.includes("synthetic"), document.cookie); }); // --- one 401 / 403 handler for every API call (src/lib/api-fetch.ts) --- const transpile = (file) => ts.transpileModule(readFileSync(new URL(file, import.meta.url), "utf8"), { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 }, }).outputText; const sources = { "@/lib/auth": output, "@/lib/api-fetch": transpile("../src/lib/api-fetch.ts"), "@/lib/api": transpile("../src/lib/api.ts"), }; // browser loads the API client against a fake browser with a stored session. // respond(url, init) returns { status, body } for each request. function browser(respond, protocol = "https:") { const storage = new Map([["artex_token", "synthetic-session"]]); const window = { location: { protocol, href: "/tasks" } }; const document = { cookie: "artex_token=1" }; const requests = []; const loaded = {}; const load = (name) => { if (!loaded[name]) { loaded[name] = {}; vm.runInNewContext(sources[name], { exports: loaded[name], require, window, document, FormData, URLSearchParams, localStorage: { getItem: (k) => storage.get(k) ?? null, setItem: (k, v) => storage.set(k, v), removeItem: (k) => storage.delete(k), }, fetch: async (url, init) => { requests.push({ url, init }); const { status, body = "" } = respond(url, init); return { status, ok: status >= 200 && status < 300, json: async () => JSON.parse(body), text: async () => body, blob: async () => body, headers: { get: () => null }, }; }, }); } return loaded[name]; }; function require(name) { if (name in sources) return load(name); if (name === "@/i18n") return { t: (key, vars) => key.replace(/\{(\w+)\}/g, (_, k) => String(vars?.[k])) }; if (name === "@/lib/mock/enabled") return { MOCK: false }; if (name === "@/lib/mock/handler") return { mockHandle: () => assert.fail("unexpected mock request") }; if (name === "@/lib/sse") return { SSEStream: class {} }; throw new Error(`Unexpected import: ${name}`); } return { ...load("@/lib/auth"), ...load("@/lib/api-fetch"), ...load("@/lib/api"), storage, window, document, requests, }; } test("clearSession drops the token and the cookie and goes to /login", () => { for (const protocol of ["https:", "http:"]) { const b = browser(() => assert.fail("no request expected"), protocol); b.clearSession(); assert.equal(b.storage.has("artex_token"), false); assert.ok(b.document.cookie.startsWith("artex_token=;"), b.document.cookie); assert.ok(b.document.cookie.includes("max-age=0")); assert.ok(b.document.cookie.includes("SameSite=Lax")); assert.equal(b.document.cookie.includes("; Secure"), protocol === "https:"); assert.equal(b.window.location.href, "/login"); } }); test("apiFetch sends the bearer token and keeps the caller's headers", async () => { const b = browser(() => ({ status: 200, body: "{}" })); const r = await b.apiFetch("/intercept/tool-config", { method: "PUT", headers: { "Content-Type": "application/json" }, }); assert.equal(r.status, 200); assert.equal(b.requests[0].url, "/api/intercept/tool-config"); assert.equal(b.requests[0].init.method, "PUT"); assert.equal(b.requests[0].init.headers.Authorization, "Bearer synthetic-session"); assert.equal(b.requests[0].init.headers["Content-Type"], "application/json"); assert.equal(b.window.location.href, "/tasks"); }); // http() and every API call that used to call fetch itself. const callers = { "http()": (b) => b.http("/tasks"), workspaceUpload: (b) => b.api.workspaceUpload("dir", []), workspaceDownload: (b) => b.api.workspaceDownload("a.txt"), exportFindings: (b) => b.api.exportFindings({ format: "csv", scope: "all" }), downloadFindingTrafficBody: (b) => b.api.downloadFindingTrafficBody("1", "2", "request"), trafficBlob: (b) => b.api.trafficBlob("abc"), trafficExportHAR: (b) => b.api.trafficExportHAR(), report: (b) => b.api.report(), chatUpload: (b) => b.api.chatUpload("task", "1", []), uploadSkill: (b) => b.api.uploadSkill({ name: "s.zip" }), interceptGetToolConfig: (b) => b.api.interceptGetToolConfig(), interceptSetToolConfig: (b) => b.api.interceptSetToolConfig([]), }; for (const [name, call] of Object.entries(callers)) { test(`${name}: a 401 clears the session and redirects to /login`, async () => { const b = browser(() => ({ status: 401, body: '{"error":"token is invalid or expired"}' })); await assert.rejects(call(b), /^Error: Unauthorized$/); assert.equal(b.requests.length, 1); assert.ok(b.requests[0].url.startsWith("/api/"), b.requests[0].url); assert.equal(b.requests[0].init.headers.Authorization, "Bearer synthetic-session"); assert.equal(b.storage.has("artex_token"), false); assert.ok(b.document.cookie.includes("max-age=0"), b.document.cookie); assert.equal(b.window.location.href, "/login"); }); test(`${name}: a 403 throws ForbiddenError and keeps the session`, async () => { const b = browser(() => ({ status: 403, body: '{"error":"Forbidden"}' })); const err = await call(b).then( () => assert.fail("expected a rejection"), (e) => e, ); assert.ok(err instanceof b.ForbiddenError, String(err)); assert.ok(err instanceof b.ApiError); assert.equal(err.status, 403); assert.equal(err.message, "Forbidden"); assert.equal(b.storage.get("artex_token"), "synthetic-session"); assert.equal(b.window.location.href, "/tasks"); }); } test("a 403 without a JSON body keeps the status-based message http() used", async () => { const b = browser(() => ({ status: 403, body: "" })); await assert.rejects(b.http("/tasks", { method: "POST", body: "{}" }), (e) => { assert.ok(e instanceof b.ForbiddenError); assert.equal(e.message, "POST /tasks: 403"); return true; }); }); test("other errors from http() are unchanged", async () => { const b = browser(() => ({ status: 409, body: '{"error":"already running"}' })); await assert.rejects(b.http("/tasks"), (e) => { assert.ok(e instanceof b.ApiError); assert.ok(!(e instanceof b.ForbiddenError)); assert.equal(e.status, 409); assert.equal(e.message, "already running"); return true; }); assert.equal(b.window.location.href, "/tasks"); }); // Only the shared helper and the SSE client call fetch directly. Everything // else goes through apiFetch, so 401 and 403 are handled in one place. test("no other source file calls fetch directly", () => { const src = new URL("../src/", import.meta.url); const allowed = new Set(["lib/api-fetch.ts", "lib/sse.ts"]); const offenders = []; for (const entry of readdirSync(src, { recursive: true })) { const file = String(entry).split(sep).join("/"); if (!/\.(ts|tsx)$/.test(file) || allowed.has(file)) continue; if (/(^|[^\w.])fetch\(/m.test(readFileSync(new URL(file, src), "utf8"))) offenders.push(file); } assert.deepEqual(offenders, []); });