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>
This commit is contained in:
samandCopilot committed 2026-11-19 10:08:59 +11:00
1 parent 64dfad6d53
commit 9e8f160f25
3 files changed
+92 -9

No files matched your search

+14 -4
View File
@@ -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() {
<Input v-model="draft" type="password" autocomplete="off" aria-label="Admin token" />
<Button type="submit">Sign in</Button>
</div>
<p v-if="signInError" role="alert" class="mt-2 text-label text-destructive">{{ signInError }}</p>
</Section>
</form>
<RouterView v-else v-slot="{ Component }">
+27 -5
View File
@@ -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<Response> {
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<T>(path: string, payload: unknown): Promise<T> {
async function send<T>(method: string, path: string, payload?: unknown): Promise<T> {
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<void> {
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<void> {
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) {
+51
View File
@@ -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<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");
}
});