Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Refresh CSRF token before XHR upload and retry once on rejection (#302)
François Catuhe5b9a2c354db3
diff --git a/static/js/modules/composables/upload.js b/static/js/modules/composables/upload.jsindex 58d4b43f..88e480f8 100644--- a/static/js/modules/composables/upload.js+++ b/static/js/modules/composables/upload.js@@ -6,6 +6,7 @@import * as FailedUploads from '../db/failed-uploads.js';import * as IncognitoStorage from '../db/incognito-storage.js';import * as RecordingDB from '../db/recording-persistence.js';+import { getUploadCsrfToken, isCsrfRejection } from '../csrf.js';// Parse error message and return friendly error infofunction getFriendlyError(errorMessage, t) {@@ -546,8 +547,16 @@ export function useUpload(state, utils) {formData.append('keep_audio_only', 'true');}- // Use XMLHttpRequest for per-file upload progress- const data = await new Promise((resolve, reject) => {+ // Use XMLHttpRequest for per-file upload progress. XHR bypasses+ // the fetch interceptor in csrf-refresh.js, so this path must+ // handle CSRF token expiry itself: Flask-WTF's default+ // WTF_CSRF_TIME_LIMIT is one hour, and the meta-tag token goes+ // stale after a long recording or laptop sleep (the 45-minute+ // interval refresh in csrf-refresh.js doesn't fire in throttled /+ // suspended tabs). Without this, the upload 400s and the+ // recording never reaches the server (the IndexedDB retry path+ // would then re-fail with the same stale token).+ const sendUpload = (csrfToken) => new Promise((resolve, reject) => {const xhr = new XMLHttpRequest();xhr.upload.onprogress = (e) => {@@ -560,6 +569,12 @@ export function useUpload(state, utils) {xhr.onload = () => {const contentType = xhr.getResponseHeader('content-type') || '';if (!contentType.includes('application/json')) {+ if (isCsrfRejection(xhr.status, xhr.responseText)) {+ const err = new Error(`CSRF token rejected (${xhr.status})`);+ err.isCsrfRejection = true;+ reject(err);+ return;+ }const titleMatch = xhr.responseText.match(/<title>([^<]+)<\/title>/i);const h1Match = xhr.responseText.match(/<h1>([^<]+)<\/h1>/i);reject(new Error(titleMatch?.[1] || h1Match?.[1] ||@@ -580,7 +595,11 @@ export function useUpload(state, utils) {} else if (!String(xhr.status).startsWith('2')) {let errorMsg = parsed.error || `Upload failed with status ${xhr.status}`;if (xhr.status === 413) errorMsg = parsed.error || `File too large. Max: ${parsed.max_size_mb?.toFixed(0) || maxFileSizeMB.value} MB.`;- reject(new Error(errorMsg));+ const err = new Error(errorMsg);+ if (isCsrfRejection(xhr.status, parsed.error || '')) {+ err.isCsrfRejection = true;+ }+ reject(err);} else {reject(new Error('Unexpected success response from server after upload.'));}@@ -594,13 +613,26 @@ export function useUpload(state, utils) {xhr.open('POST', '/upload');// Include CSRF token (required for POST requests)- const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');if (csrfToken) {xhr.setRequestHeader('X-CSRFToken', csrfToken);}xhr.send(formData);});+ // Refresh the token right before sending, and retry exactly once+ // with another fresh token if the server still rejects it —+ // mirroring what the fetch interceptor in csrf-refresh.js does+ // for non-XHR requests.+ let data;+ try {+ data = await sendUpload(await getUploadCsrfToken());+ } catch (uploadError) {+ if (!uploadError.isCsrfRejection) throw uploadError;+ console.warn(`[Upload] CSRF rejection for ${fileItem.file.name}; refreshing token and retrying once.`);+ fileItem.progress = 5;+ data = await sendUpload(await getUploadCsrfToken());+ }+// Upload succeeded - recording is now on the serverconsole.log(`File ${fileItem.file.name} uploaded. Recording ID: ${data.id}. Server will process via job queue.`);fileItem.status = 'pending';diff --git a/static/js/modules/csrf.js b/static/js/modules/csrf.jsnew file mode 100644index 00000000..0c6dc16b--- /dev/null+++ b/static/js/modules/csrf.js@@ -0,0 +1,84 @@+/**+ * CSRF token helpers for code paths that bypass the fetch interceptor+ * in csrf-refresh.js.+ *+ * Flask-WTF's default WTF_CSRF_TIME_LIMIT is one hour, so the token in+ * the page's meta tag goes stale during long recordings or laptop+ * sleep (the 45-minute setInterval refresh in csrf-refresh.js does not+ * fire in throttled / suspended background tabs). The fetch interceptor+ * recovers from this transparently, but XMLHttpRequest callers (e.g.+ * the upload path in composables/upload.js, which needs XHR for upload+ * progress events) read the meta tag directly and would send the+ * expired token, getting a 400 back. These helpers give such callers+ * the same refresh-before-send / retry-on-rejection behaviour.+ */++/** Read the current CSRF token from the page's meta tag (or null). */+export function getCsrfTokenFromMeta() {+ if (typeof document === 'undefined') return null;+ return document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || null;+}++/**+ * Fetch a fresh CSRF token from the server.+ *+ * Prefers the shared CSRFManager from csrf-refresh.js (so its cached+ * token stays in sync and concurrent refreshes are deduplicated), with+ * a direct call to /api/csrf-token as fallback for contexts where+ * csrf-refresh.js is not loaded. Throws on failure.+ */+export async function fetchFreshCsrfToken() {+ const manager = (typeof window !== 'undefined') ? window.csrfManager : null;+ if (manager && typeof manager.refreshToken === 'function') {+ return await manager.refreshToken();+ }++ // Use the original (un-intercepted) fetch if csrf-refresh.js saved+ // one, to match its own refresh behaviour.+ const doFetch = ((typeof window !== 'undefined') && window.originalFetch) || fetch;+ const response = await doFetch('/api/csrf-token', {+ method: 'GET',+ credentials: 'same-origin',+ headers: { 'Accept': 'application/json' }+ });+ if (!response.ok) {+ throw new Error(`Failed to refresh CSRF token: ${response.status}`);+ }+ const data = await response.json();+ if (!data.csrf_token) {+ throw new Error('No CSRF token in response');+ }+ // Keep the meta tag current for any other code that reads it.+ const metaTag = (typeof document !== 'undefined')+ ? document.querySelector('meta[name="csrf-token"]')+ : null;+ if (metaTag) {+ metaTag.setAttribute('content', data.csrf_token);+ }+ return data.csrf_token;+}++/**+ * Best-effort fresh token for an outgoing upload. A refresh failure+ * (offline, server hiccup) must not block the upload attempt itself,+ * so this falls back to whatever the meta tag currently holds.+ */+export async function getUploadCsrfToken() {+ try {+ return await fetchFreshCsrfToken();+ } catch (error) {+ console.warn('[CSRF] Token refresh failed, falling back to meta tag token:', error);+ return getCsrfTokenFromMeta();+ }+}++/**+ * Heuristic for "the server rejected our CSRF token", mirroring the+ * detection in csrf-refresh.js's fetch interceptor: a 400/403 whose+ * body (JSON error message or HTML error page) mentions csrf/token.+ */+export function isCsrfRejection(status, responseText) {+ if (status !== 400 && status !== 403) return false;+ const text = (responseText || '').toLowerCase();+ return text.includes('csrf') || text.includes('token');+}diff --git a/static/js/modules/csrf.test.js b/static/js/modules/csrf.test.jsnew file mode 100644index 00000000..19d9e02a--- /dev/null+++ b/static/js/modules/csrf.test.js@@ -0,0 +1,129 @@+/**+ * Tests for the CSRF helpers used by XHR code paths that bypass the+ * fetch interceptor in csrf-refresh.js (the upload path in+ * composables/upload.js). Covers token refresh via the shared+ * CSRFManager, the direct /api/csrf-token fallback, the best-effort+ * fallback to the meta-tag token, and the CSRF-rejection heuristic.+ */++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import {+ getCsrfTokenFromMeta,+ fetchFreshCsrfToken,+ getUploadCsrfToken,+ isCsrfRejection+} from './csrf.js';++describe('csrf helpers', () => {+ let originalDocument;+ let originalWindow;+ let metaTag;++ const mockMeta = (token) => {+ metaTag = {+ _content: token,+ getAttribute: vi.fn(() => metaTag._content),+ setAttribute: vi.fn((name, val) => { metaTag._content = val; }),+ };+ global.document = {+ querySelector: vi.fn((sel) =>+ sel === 'meta[name="csrf-token"]' ? metaTag : null),+ };+ };++ beforeEach(() => {+ originalDocument = global.document;+ originalWindow = global.window;+ global.window = {};+ mockMeta('stale-token');+ });++ afterEach(() => {+ global.document = originalDocument;+ global.window = originalWindow;+ vi.restoreAllMocks();+ });++ describe('getCsrfTokenFromMeta', () => {+ it('reads the token from the meta tag', () => {+ expect(getCsrfTokenFromMeta()).toBe('stale-token');+ });++ it('returns null when the meta tag is missing', () => {+ global.document = { querySelector: vi.fn(() => null) };+ expect(getCsrfTokenFromMeta()).toBe(null);+ });+ });++ describe('fetchFreshCsrfToken', () => {+ it('prefers window.csrfManager.refreshToken when available', async () => {+ const refreshToken = vi.fn(async () => 'manager-token');+ global.window.csrfManager = { refreshToken };++ expect(await fetchFreshCsrfToken()).toBe('manager-token');+ expect(refreshToken).toHaveBeenCalledTimes(1);+ });++ it('falls back to /api/csrf-token and updates the meta tag', async () => {+ global.window.originalFetch = vi.fn(async () => ({+ ok: true,+ json: async () => ({ csrf_token: 'fresh-token' }),+ }));++ expect(await fetchFreshCsrfToken()).toBe('fresh-token');+ expect(global.window.originalFetch).toHaveBeenCalledWith(+ '/api/csrf-token',+ expect.objectContaining({ method: 'GET', credentials: 'same-origin' })+ );+ expect(metaTag.setAttribute).toHaveBeenCalledWith('content', 'fresh-token');+ });++ it('throws when the endpoint responds non-OK', async () => {+ global.window.originalFetch = vi.fn(async () => ({ ok: false, status: 500 }));+ await expect(fetchFreshCsrfToken()).rejects.toThrow('500');+ });++ it('throws when the response has no csrf_token', async () => {+ global.window.originalFetch = vi.fn(async () => ({+ ok: true,+ json: async () => ({}),+ }));+ await expect(fetchFreshCsrfToken()).rejects.toThrow('No CSRF token');+ });+ });++ describe('getUploadCsrfToken', () => {+ it('returns the freshly fetched token on success', async () => {+ global.window.csrfManager = { refreshToken: vi.fn(async () => 'fresh-token') };+ expect(await getUploadCsrfToken()).toBe('fresh-token');+ });++ it('falls back to the meta tag token when refresh fails', async () => {+ vi.spyOn(console, 'warn').mockImplementation(() => {});+ global.window.csrfManager = {+ refreshToken: vi.fn(async () => { throw new Error('offline'); }),+ };+ expect(await getUploadCsrfToken()).toBe('stale-token');+ });+ });++ describe('isCsrfRejection', () => {+ it('matches 400/403 with a CSRF-flavoured body', () => {+ expect(isCsrfRejection(400, '{"error": "The CSRF token has expired."}')).toBe(true);+ expect(isCsrfRejection(403, '<html><body>CSRF validation failed</body></html>')).toBe(true);+ expect(isCsrfRejection(400, 'The CSRF session token is missing.')).toBe(true);+ });++ it('rejects other statuses regardless of body', () => {+ expect(isCsrfRejection(500, 'csrf')).toBe(false);+ expect(isCsrfRejection(200, 'csrf token')).toBe(false);+ expect(isCsrfRejection(413, 'token')).toBe(false);+ });++ it('rejects 400s that are not CSRF-related', () => {+ expect(isCsrfRejection(400, '{"error": "No file selected"}')).toBe(false);+ expect(isCsrfRejection(400, '')).toBe(false);+ expect(isCsrfRejection(400, null)).toBe(false);+ });+ });+});