[frontend] Add CSRF token to all mutating fetch requests (fixes 403 regression) #933

Closed
sleepy wants to merge 0 commits from fix/csrf-frontend-token-403 into dev
Owner

Problem

CSRF middleware (commit 397edbb) enforces X-CSRF-Token on all mutating requests, but the frontend has 718 fetch() calls with zero CSRF token handling. Every POST/PUT/DELETE/PATCH from the browser returns 403.

Fix

Part 1: static/js/csrf.js — A small JS module that:

  • Reads the csrf_token cookie (set by the server on GET requests)
  • Monkey-patches window.fetch to auto-inject X-CSRF-Token header on all mutating requests (POST/PUT/DELETE/PATCH)
  • Handles both plain object and Headers instance cases

Part 2: static/index.html — Added <script type="module" src="/static/js/csrf.js"> as the first module script (before storage.js and all other modules) so window.fetch is patched before any module makes requests.

Testing

  • Full test suite: 1178 passed, 9 failed (all 9 failures are pre-existing on dev baseline), 7 skipped — zero regressions introduced.
## Problem CSRF middleware (commit 397edbb) enforces `X-CSRF-Token` on all mutating requests, but the frontend has 718 `fetch()` calls with zero CSRF token handling. Every POST/PUT/DELETE/PATCH from the browser returns 403. ## Fix **Part 1: `static/js/csrf.js`** — A small JS module that: - Reads the `csrf_token` cookie (set by the server on GET requests) - Monkey-patches `window.fetch` to auto-inject `X-CSRF-Token` header on all mutating requests (POST/PUT/DELETE/PATCH) - Handles both plain object and `Headers` instance cases **Part 2: `static/index.html`** — Added `<script type="module" src="/static/js/csrf.js">` as the **first** module script (before `storage.js` and all other modules) so `window.fetch` is patched before any module makes requests. ## Testing - Full test suite: 1178 passed, 9 failed (all 9 failures are pre-existing on dev baseline), 7 skipped — zero regressions introduced.
- Create static/js/csrf.js: monkey-patches window.fetch to auto-inject
  X-CSRF-Token header from csrf_token cookie on POST/PUT/DELETE/PATCH
- Load csrf.js as first ES module in index.html (before all other modules)
  so fetch is patched before any module makes mutating requests
sleepy closed this pull request 2026-06-04 14:44:37 +02:00

Pull request closed

Sign in to join this conversation.
No description provided.