fix(ui): cookie-authed users' writes silently stranded behind bearer gates

THE CLASS: the /api JWT middleware's TokenLookup is
"cookie:token,header:Authorization:Bearer" — the token cookie always
rides same-origin fetches, so a signed-in user never needs the
localStorage bearer. But a dozen call sites gated their fetch on
`localStorage.getItem("token")` and early-returned when absent. The
global 401 interceptor CLEARS that localStorage entry on any session
rotation/blip — after which every gated write silently did nothing:
theme changes reverted on reload (the reported "can no longer change
themes", on top of the interpolation bug d5dbaa48 fixed), chain-order
selects, collection deletion, Add-to-collection submits, filter
save/load/delete, conflict actions, linking actions, stats charts,
tag suggestions, device management, admin scanner actions — all dead
for perfectly authenticated cookie users.

Fix: storage.ts exports authHeaders() (bearer when present, cookie
carries otherwise) and every gate/header site now uses it — theme.ts,
collections.ts (htmx auth, doRemoveBook/doBulkRemove, setChainOrder),
bookPicker submit, filter_builder suggestions + match count,
collection-rules apply hook, bookshelf save/load/delete filter,
conflicts x4, linking x3, admin scanner actions + polls (requireToken
removed — its "Session expired" toast fired for cookie users too),
dashboard preferences/sections, custom-section-builder, header
scanner poll, stats x3, tag suggestions, profile delete-account
(which also wrongly redirected cookie users to /login), and
device-management x4. Reads keep their graceful-empty behavior; the
bearers still ride along when present.

Pinned: the knob-matrix theme spec now REMOVES localStorage.token and
asserts the theme PUT still fires (cookie-only) and the class flips —
the exact strand that started this.

Found by noticing the panel browser's Nord click switched the class
but produced no PUT: the persistence half was gated on a token the
401 interceptor had cleared.
This commit is contained in:
John O'Keefe committed 2026-10-31 17:02:44 -04:00
1 parent 744d33e13f
commit aaf57a66a2
18 files changed
+139 -189

No files matched your search

+15 -22
View File
@@ -1,4 +1,5 @@
import { Alpine } from "./alpine";
import { authHeaders } from "./storage";
import { showToast } from "./toast";
import { createWebSocket } from "./websocket";
import { initLibrarySwitcher, switchWithTransition } from "./library-switcher";
@@ -50,7 +51,9 @@ function initializeCollectionWebSocket(): void {
function setupHTMXAuth(): void {
document.body.addEventListener("htmx:configRequest", function (evt: Event) {
const token = localStorage.getItem("token");
(evt as any).detail.headers["Authorization"] = `Bearer ${token}`;
// Only attach a bearer when localStorage has one — htmx sends
// cookies regardless, and "Bearer null" is never needed.
if (token) (evt as any).detail.headers["Authorization"] = `Bearer ${token}`;
});
}
@@ -299,12 +302,10 @@ function toggleSelection(this: any, id: string): void {
}
async function doRemoveBook(id: string): Promise<void> {
const token = localStorage.getItem("token");
if (!token) return;
try {
const response = await fetch(`/api/collections/${getCollectionId()}/books/${id}`, {
method: "DELETE",
headers: { Authorization: `Bearer ${token}` },
headers: authHeaders(),
});
if (response.ok) {
showToast("Removed from collection", "success");
@@ -318,15 +319,10 @@ async function doRemoveBook(id: string): Promise<void> {
}
async function doBulkRemove(ids: string[]): Promise<void> {
const token = localStorage.getItem("token");
if (!token) return;
try {
const response = await fetch(`/api/collections/${getCollectionId()}/books/bulk-remove`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
headers: { ...authHeaders(), "Content-Type": "application/json" },
body: JSON.stringify({ book_ids: ids }),
});
if (response.ok) {
@@ -426,16 +422,18 @@ Alpine.data("collections", () => ({
// setChainOrder — the detail header's listening-order select (plan
// §10 R2: the collection's chain order is curated HERE, not on the
// player). Merges into view_settings server-side, then reloads so
// the chain producer's stored order takes effect.
// the chain producer's stored order takes effect. The save rides
// the token COOKIE (middleware cookie:token lookup) — never gate on
// localStorage: the 401 interceptor clears it, and a token-gated
// early-return would strand the setting (same class as the
// changeTheme fix, 2026-10-31).
setChainOrder(this: any, collectionID: string, order: string) {
const token = localStorage.getItem("token");
if (!token) return;
const headers: Record<string, string> = { "Content-Type": "application/json" };
if (token) headers.Authorization = "Bearer " + token;
void fetch("/api/collections/" + collectionID + "/view-settings", {
method: "PUT",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
headers,
body: JSON.stringify({ chain_order: order }),
}).then((r) => {
if (r.ok) {
@@ -496,15 +494,10 @@ async function moveCollectionBook(this: any, mediaId: string, direction: number)
.map((c) => c.dataset.mediaId)
.filter((id): id is string => Boolean(id));
const token = localStorage.getItem("token");
if (!token) return;
try {
const response = await fetch(`/api/collections/${getCollectionId()}/items/order`, {
method: "PUT",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
headers: { ...authHeaders(), "Content-Type": "application/json" },
body: JSON.stringify({ item_ids: orderedIds }),
});
if (!response.ok) {