From 9e8f160f255b21760cdea509455533cd1eef7a96 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Thu, 19 Nov 2026 10:08:59 +1100 Subject: [PATCH] fix(ui): reject unsafe composer admin tokens (#2047) 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> --- ui/src/archie/App.vue | 18 ++++++++++--- ui/src/archie/api.ts | 32 +++++++++++++++++++---- ui/test/archie-auth.test.ts | 51 +++++++++++++++++++++++++++++++++++++ 3 files changed, 92 insertions(+), 9 deletions(-) create mode 100644 ui/test/archie-auth.test.ts diff --git a/ui/src/archie/App.vue b/ui/src/archie/App.vue index e4de6e847..87fcc823a 100644 --- a/ui/src/archie/App.vue +++ b/ui/src/archie/App.vue @@ -5,18 +5,27 @@ import { RouterLink, RouterView } from "vue-router"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Section } from "@/components/ui/section"; -import { clearToken, setToken, token } from "./api"; +import { clearToken, invalidTokenMessage, isValidToken, setToken, token } from "./api"; /** * The shell: the admin token gate, then the composer and runs. The token is * the bootstrap credential until identities exist. */ -const signedIn = ref(token() !== ""); +const savedToken = token(); +const invalidSavedToken = savedToken !== "" && !isValidToken(savedToken); +if (invalidSavedToken) clearToken(); +const signedIn = ref(savedToken !== "" && !invalidSavedToken); const draft = ref(""); +const signInError = ref(invalidSavedToken ? invalidTokenMessage : ""); function signIn() { - if (!draft.value.trim()) return; - setToken(draft.value.trim()); + const value = draft.value.trim(); + if (!value) return; + if (!setToken(value)) { + signInError.value = invalidTokenMessage; + return; + } + signInError.value = ""; draft.value = ""; signedIn.value = true; } @@ -53,6 +62,7 @@ function signOut() { + diff --git a/ui/src/archie/api.ts b/ui/src/archie/api.ts index 0caf06399..19272ba42 100644 --- a/ui/src/archie/api.ts +++ b/ui/src/archie/api.ts @@ -1,8 +1,17 @@ // The dashboard keeps the bootstrap admin token in browser session storage. const TOKEN_KEY = "archie.adminToken"; +export const invalidTokenMessage = "Admin token contains unsupported characters. Paste the token again."; export class Unauthorized extends Error {} +export class InvalidAdminToken extends Error { + constructor() { + super(invalidTokenMessage); + } +} + +export const isValidToken = (value: string) => value.length > 0 && /^[\x20-\x7E]+$/.test(value); + /** A failed HTTP request with its response status. */ export class ApiError extends Error { readonly status: number; @@ -14,11 +23,24 @@ export class ApiError extends Error { } export const token = (): string => sessionStorage.getItem(TOKEN_KEY) ?? ""; -export const setToken = (value: string) => sessionStorage.setItem(TOKEN_KEY, value); +export const setToken = (value: string) => { + if (!isValidToken(value)) return false; + sessionStorage.setItem(TOKEN_KEY, value); + return true; +}; export const clearToken = () => sessionStorage.removeItem(TOKEN_KEY); +function authorization(): string { + const value = token(); + if (!isValidToken(value)) { + clearToken(); + throw new InvalidAdminToken(); + } + return `Bearer ${value}`; +} + async function request(path: string, signal?: AbortSignal): Promise { - const res = await fetch(path, { headers: { Authorization: `Bearer ${token()}` }, signal }); + const res = await fetch(path, { headers: { Authorization: authorization() }, signal }); if (res.status === 401) throw new Unauthorized("Sign in with a valid admin token."); if (!res.ok) { const body = (await res.json().catch(() => ({}))) as { error?: string; detail?: string }; @@ -270,7 +292,7 @@ async function putJSON(path: string, payload: unknown): Promise { async function send(method: string, path: string, payload?: unknown): Promise { const res = await fetch(path, { method, - headers: { Authorization: `Bearer ${token()}`, "Content-Type": "application/json" }, + headers: { Authorization: authorization(), "Content-Type": "application/json" }, body: payload === undefined ? undefined : JSON.stringify(payload), }); if (res.status === 401) throw new Unauthorized("Sign in with a valid admin token."); @@ -303,7 +325,7 @@ export const messagesAfter = (seq: number, signal?: AbortSignal) => export async function answerApproval(id: string, approved: boolean): Promise { const res = await fetch(`/api/approvals/${encodeURIComponent(id)}/answer`, { method: "POST", - headers: { Authorization: `Bearer ${token()}`, "Content-Type": "application/json" }, + headers: { Authorization: authorization(), "Content-Type": "application/json" }, body: JSON.stringify({ approved }), }); if (res.status === 401) throw new Unauthorized("Sign in with a valid admin token."); @@ -368,7 +390,7 @@ export const classDetail = (id: string, signal?: AbortSignal) => export async function resetClass(id: string): Promise { const res = await fetch(`/api/classes/${encodeURIComponent(id)}/reset`, { method: "POST", - headers: { Authorization: `Bearer ${token()}` }, + headers: { Authorization: authorization() }, }); if (res.status === 401) throw new Unauthorized("Sign in with a valid admin token."); if (!res.ok) { diff --git a/ui/test/archie-auth.test.ts b/ui/test/archie-auth.test.ts new file mode 100644 index 000000000..865d08d89 --- /dev/null +++ b/ui/test/archie-auth.test.ts @@ -0,0 +1,51 @@ +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(); + 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"); + } +});