diff --git a/frontend/src/lib/ocr/useOcrJob.svelte.test.ts b/frontend/src/lib/ocr/useOcrJob.svelte.test.ts index 8c83f6e1..ecbeb5fe 100644 --- a/frontend/src/lib/ocr/useOcrJob.svelte.test.ts +++ b/frontend/src/lib/ocr/useOcrJob.svelte.test.ts @@ -139,6 +139,35 @@ describe('createOcrJob.triggerOcr', () => { }); }); +describe('createOcrJob — CSRF on mutating requests', () => { + afterEach(() => { + document.cookie = 'XSRF-TOKEN=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/'; + }); + + it('injects X-XSRF-TOKEN on the trigger POST', async () => { + document.cookie = 'XSRF-TOKEN=tok-123; path=/'; + const fetchImpl = makeFetch({ + '/ocr': () => + new Response(JSON.stringify({ jobId: 'job-1' }), { + status: 200, + headers: { 'Content-Type': 'application/json' } + }) + }); + + const job = createOcrJob({ documentId: () => 'doc-1', fetchImpl }); + await job.triggerOcr('KURRENT', false); + job.destroy(); + + const postCall = fetchImpl.mock.calls.find( + ([url, init]) => + url.toString().includes('/ocr') && (init as RequestInit | undefined)?.method === 'POST' + ); + expect(postCall).toBeDefined(); + const headers = new Headers((postCall![1] as RequestInit).headers); + expect(headers.get('X-XSRF-TOKEN')).toBe('tok-123'); + }); +}); + describe('createOcrJob.checkStatus', () => { it('starts polling when status is RUNNING with a jobId', async () => { const fetchImpl = makeFetch({ diff --git a/frontend/src/lib/ocr/useOcrJob.svelte.ts b/frontend/src/lib/ocr/useOcrJob.svelte.ts index e5a74af1..af6e5adf 100644 --- a/frontend/src/lib/ocr/useOcrJob.svelte.ts +++ b/frontend/src/lib/ocr/useOcrJob.svelte.ts @@ -1,6 +1,7 @@ import { m } from '$lib/paraglide/messages.js'; import { getErrorMessage } from '$lib/shared/errors'; import { translateOcrProgress } from '$lib/ocr/translateOcrProgress'; +import { makeCsrfFetch } from '$lib/shared/cookies'; export interface OcrJobOptions { documentId: () => string; @@ -27,7 +28,7 @@ const DEFAULT_RESET_DELAY_MS = 1000; export function createOcrJob(options: OcrJobOptions): OcrJobController { const { documentId, onJobFinished } = options; - const fetchImpl = options.fetchImpl ?? fetch; + const fetchImpl = makeCsrfFetch(options.fetchImpl ?? fetch); const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS; const resetDelayMs = options.resetDelayMs ?? DEFAULT_RESET_DELAY_MS;