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:
1 parent
744d33e13f
commit
aaf57a66a2
18 files changed
+139
-189
No files matched your search
+14
-47
@@ -1,5 +1,6 @@
|
||||
import { confirmDialog } from "./confirm";
|
||||
import { Alpine } from "./alpine";
|
||||
import { authHeaders } from "./storage";
|
||||
import { showToast } from "./toast";
|
||||
|
||||
// Admin API calls authenticate with the Bearer token stashed at login,
|
||||
@@ -7,23 +8,11 @@ import { showToast } from "./toast";
|
||||
// web session can still have an empty/stale localStorage token. User-
|
||||
// triggered actions must never die silently in that state (the
|
||||
// /admin/archived purge + delete buttons were invisible dead-ends: the
|
||||
// missing-token return fired before the confirm dialog): requireToken
|
||||
// fails loudly instead.
|
||||
function requireToken(): string | null {
|
||||
const token = localStorage.getItem("token");
|
||||
if (!token) {
|
||||
showToast("Session expired — sign out and back in, then retry", "error");
|
||||
}
|
||||
return token;
|
||||
}
|
||||
|
||||
async function scanAllLibraries(): Promise<void> {
|
||||
const token = requireToken();
|
||||
if (!token) return;
|
||||
|
||||
try {
|
||||
const libsResp = await fetch("/api/libraries", {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
headers: authHeaders(),
|
||||
});
|
||||
|
||||
if (!libsResp.ok) {
|
||||
@@ -46,7 +35,7 @@ async function scanAllLibraries(): Promise<void> {
|
||||
const scanResp = await fetch(`/api/libraries/${lib.id}/scan`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ force: true }),
|
||||
@@ -125,7 +114,6 @@ function showScanProgress(jobIds: string[], libraryNames: Record<string, string>
|
||||
let scanPollInterval: ReturnType<typeof setInterval> | undefined = undefined;
|
||||
|
||||
function pollScanProgress(jobIds: string[], _libraryNames: Record<string, string>): void {
|
||||
const token = localStorage.getItem("token");
|
||||
const startTime = Date.now();
|
||||
const cancelledJobs = new Set<string>();
|
||||
|
||||
@@ -140,7 +128,7 @@ function pollScanProgress(jobIds: string[], _libraryNames: Record<string, string
|
||||
for (const jobId of jobIds) {
|
||||
try {
|
||||
const resp = await fetch(`/api/scanner/status/${jobId}`, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
headers: authHeaders(),
|
||||
});
|
||||
|
||||
if (resp.ok) {
|
||||
@@ -241,8 +229,6 @@ function updateLibraryProgress(jobId: string, status: any): void {
|
||||
// aborts the walk at its next context check and skips the archive pass,
|
||||
// so cancelling never archives unvisited files.
|
||||
async function cancelScan(jobId: string): Promise<void> {
|
||||
const token = requireToken();
|
||||
if (!token) return;
|
||||
|
||||
const btn = document.querySelector<HTMLButtonElement>(`[data-cancel-job="${jobId}"]`);
|
||||
if (btn) {
|
||||
@@ -253,7 +239,7 @@ async function cancelScan(jobId: string): Promise<void> {
|
||||
try {
|
||||
const resp = await fetch(`/api/scanner/cancel/${jobId}`, {
|
||||
method: "POST",
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
headers: authHeaders(),
|
||||
});
|
||||
if (!resp.ok) {
|
||||
const err = await resp.json().catch(() => ({}));
|
||||
@@ -273,12 +259,10 @@ async function cancelScan(jobId: string): Promise<void> {
|
||||
// list so it also covers jobs this page never started (e.g. started
|
||||
// before a refresh), then cancels each one.
|
||||
async function cancelAllScans(): Promise<void> {
|
||||
const token = requireToken();
|
||||
if (!token) return;
|
||||
|
||||
try {
|
||||
const resp = await fetch("/api/scanner/active", {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
headers: authHeaders(),
|
||||
});
|
||||
if (!resp.ok) {
|
||||
throw new Error("Failed to list active scans");
|
||||
@@ -303,13 +287,10 @@ function setCancelAllVisible(visible: boolean): void {
|
||||
// widget and re-attach polling. Websocket start-events only reach pages
|
||||
// that were already open when the scan began.
|
||||
async function checkActiveScans(): Promise<void> {
|
||||
// Passive page-load probe, not a user action: stay silent when the API
|
||||
// token is absent (requireToken's toast would fire on every page visit).
|
||||
const token = localStorage.getItem("token");
|
||||
if (!token) return;
|
||||
// Passive page-load probe, not a user action — cookie auth carries it.
|
||||
try {
|
||||
const resp = await fetch("/api/scanner/active", {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
headers: authHeaders(),
|
||||
});
|
||||
if (!resp.ok) return;
|
||||
const data = await resp.json();
|
||||
@@ -323,7 +304,7 @@ async function checkActiveScans(): Promise<void> {
|
||||
const libraryNames: Record<string, string> = {};
|
||||
try {
|
||||
const libsResp = await fetch("/api/libraries", {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
headers: authHeaders(),
|
||||
});
|
||||
if (libsResp.ok) {
|
||||
const libsData = await libsResp.json();
|
||||
@@ -389,13 +370,10 @@ function hideScanProgress(): void {
|
||||
async function loadWatchStatus(): Promise<void> {
|
||||
// Passive status fetch inside the admin component's init, not a user
|
||||
// action: stay silent when the API token is absent (requireToken's
|
||||
// toast would fire on every page visit).
|
||||
const token = localStorage.getItem("token");
|
||||
if (!token) return;
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/scanner/watch/status", {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
headers: authHeaders(),
|
||||
});
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
@@ -420,8 +398,6 @@ function stopScanStatusPolling(): void {
|
||||
// window for the library admin page's inline button; reading history is
|
||||
// deleted with the rows, so a confirm dialog guards it.
|
||||
async function purgeArchivedItems(): Promise<void> {
|
||||
const token = requireToken();
|
||||
if (!token) return;
|
||||
|
||||
if (
|
||||
!(await confirmDialog(
|
||||
@@ -434,7 +410,7 @@ async function purgeArchivedItems(): Promise<void> {
|
||||
try {
|
||||
const resp = await fetch("/api/media-items/purge-archived", {
|
||||
method: "POST",
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
headers: authHeaders(),
|
||||
});
|
||||
if (!resp.ok) {
|
||||
const err = await resp.json().catch(() => ({}));
|
||||
@@ -452,12 +428,10 @@ async function purgeArchivedItems(): Promise<void> {
|
||||
// its file to return (POST /api/media-items/:id/unarchive). If the file is
|
||||
// still gone the next scan hides it again.
|
||||
async function unarchiveItem(id: string): Promise<void> {
|
||||
const token = requireToken();
|
||||
if (!token) return;
|
||||
try {
|
||||
const resp = await fetch(`/api/media-items/${id}/unarchive`, {
|
||||
method: "POST",
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
headers: authHeaders(),
|
||||
});
|
||||
if (!resp.ok) {
|
||||
const err = await resp.json().catch(() => ({}));
|
||||
@@ -473,8 +447,6 @@ async function unarchiveItem(id: string): Promise<void> {
|
||||
// Permanently delete one archived item and its reading history
|
||||
// (DELETE /api/media-items/:id).
|
||||
async function deleteArchivedItem(id: string): Promise<void> {
|
||||
const token = requireToken();
|
||||
if (!token) return;
|
||||
if (
|
||||
!(await confirmDialog(
|
||||
"Permanently delete this item? Its reading progress, notes, and highlights will be lost.",
|
||||
@@ -485,7 +457,7 @@ async function deleteArchivedItem(id: string): Promise<void> {
|
||||
try {
|
||||
const resp = await fetch(`/api/media-items/${id}`, {
|
||||
method: "DELETE",
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
headers: authHeaders(),
|
||||
});
|
||||
if (!resp.ok) {
|
||||
const err = await resp.json().catch(() => ({}));
|
||||
@@ -502,8 +474,6 @@ async function deleteArchivedItem(id: string): Promise<void> {
|
||||
// same content hash (POST /api/media-items/:id/merge), then remove the
|
||||
// archived entry. Covers copy-then-delete-later moves between libraries.
|
||||
async function mergeArchivedItem(sourceId: string, targetId: string): Promise<void> {
|
||||
const token = requireToken();
|
||||
if (!token) return;
|
||||
if (
|
||||
!(await confirmDialog(
|
||||
"Merge this archived copy's reading progress, notes, and highlights into the active copy? The archived entry is removed.",
|
||||
@@ -514,10 +484,7 @@ async function mergeArchivedItem(sourceId: string, targetId: string): Promise<vo
|
||||
try {
|
||||
const resp = await fetch(`/api/media-items/${sourceId}/merge`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
headers: { ...authHeaders(), "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ target_id: targetId }),
|
||||
});
|
||||
if (!resp.ok) {
|
||||
|
||||
Reference in new issue
Block a user