Validate bearer tokens before header construction and return users to sign-in when a saved token contains unsupported characters. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
52 lines
2.1 KiB
TypeScript
52 lines
2.1 KiB
TypeScript
import assert from "node:assert/strict";
|
|
import test from "node:test";
|
|
|
|
import { answerApproval, composerStream, resetClass, rotateAdminToken, setToken } from "../src/archie/api.ts";
|
|
|
|
test("composer stream rejects an unsafe saved token before Fetch", async () => {
|
|
const originalFetch = globalThis.fetch;
|
|
const originalStorage = Object.getOwnPropertyDescriptor(globalThis, "sessionStorage");
|
|
const values = new Map<string, string>();
|
|
Object.defineProperty(globalThis, "sessionStorage", {
|
|
configurable: true,
|
|
value: {
|
|
getItem: (key: string) => values.get(key) ?? null,
|
|
setItem: (key: string, value: string) => values.set(key, value),
|
|
removeItem: (key: string) => values.delete(key),
|
|
},
|
|
});
|
|
const fetchCalls: string[] = [];
|
|
const authorization: string[] = [];
|
|
globalThis.fetch = async (_input, init) => {
|
|
fetchCalls.push(String(_input));
|
|
authorization.push(new Headers(init?.headers).get("Authorization") ?? "");
|
|
return new Response(null);
|
|
};
|
|
|
|
try {
|
|
assert.equal(setToken("valid-prefix-\u23CE"), false);
|
|
assert.equal(values.has("archie.adminToken"), false);
|
|
const invalidCalls = [
|
|
() => composerStream(new AbortController().signal).next(),
|
|
() => rotateAdminToken(),
|
|
() => answerApproval("approval", true),
|
|
() => resetClass("class"),
|
|
];
|
|
for (const invoke of invalidCalls) {
|
|
values.set("archie.adminToken", "valid-prefix-\u23CE");
|
|
await assert.rejects(invoke(), /Admin token contains unsupported characters/);
|
|
assert.equal(fetchCalls.length, 0);
|
|
assert.equal(values.has("archie.adminToken"), false);
|
|
}
|
|
|
|
values.set("archie.adminToken", "plain-ascii-admin-token");
|
|
assert.deepEqual(await composerStream(new AbortController().signal).next(), { done: true, value: undefined });
|
|
assert.deepEqual(fetchCalls, ["/api/composer/stream"]);
|
|
assert.deepEqual(authorization, ["Bearer plain-ascii-admin-token"]);
|
|
} finally {
|
|
globalThis.fetch = originalFetch;
|
|
if (originalStorage) Object.defineProperty(globalThis, "sessionStorage", originalStorage);
|
|
else Reflect.deleteProperty(globalThis, "sessionStorage");
|
|
}
|
|
});
|