From 21f96a1929d7da2109b3b8e772f399e82fe7e080 Mon Sep 17 00:00:00 2001 From: Ramzy Date: Wed, 11 Nov 2026 16:23:40 +0200 Subject: [PATCH 1/3] fix: add anti-CSRF protection to state-changing routes Protect the recovery-email update (and other writes) against CSRF using the csrf-csrf double-submit-cookie pattern: - server: new csrf middleware, GET /api/csrf-token endpoint, and doubleCsrfProtection on /items, /users, /settings; auth routes and safe GETs stay exempt. Forged writes with no token now return 403. - client: axios interceptor fetches and echoes the x-csrf-token header on every mutating request. - pin csrf-csrf@2.3.0. Co-Authored-By: Claude Opus 4.8 --- client/src/api.js | 21 ++++++++++++++++++ server/package.json | 1 + server/src/app.js | 20 +++++++++++++++--- server/src/middleware/csrf.js | 40 +++++++++++++++++++++++++++++++++++ 4 files changed, 79 insertions(+), 3 deletions(-) create mode 100644 server/src/middleware/csrf.js diff --git a/client/src/api.js b/client/src/api.js index 6de0a0a..6a90bf7 100644 --- a/client/src/api.js +++ b/client/src/api.js @@ -7,3 +7,24 @@ export const api = axios.create({ baseURL: 'http://localhost:4000/api', withCredentials: true }) + +// Methods that change server state must carry an anti-CSRF token. We fetch a +// fresh one from the server (which also sets the matching csrf cookie) and echo +// it in the `x-csrf-token` header. The attacker's forged request cannot do this: +// it can neither read the token (same-origin policy) nor set this header. +const MUTATING_METHODS = ['post', 'put', 'patch', 'delete'] + +async function fetchCsrfToken() { + const { data } = await api.get('/csrf-token') + return data.csrfToken +} + +api.interceptors.request.use(async (config) => { + const method = (config.method || 'get').toLowerCase() + if (MUTATING_METHODS.includes(method)) { + const token = await fetchCsrfToken() + config.headers = config.headers || {} + config.headers['x-csrf-token'] = token + } + return config +}) diff --git a/server/package.json b/server/package.json index db19c7f..2693f27 100644 --- a/server/package.json +++ b/server/package.json @@ -10,6 +10,7 @@ "bcryptjs": "^2.4.3", "cookie-parser": "^1.4.7", "cors": "^2.8.5", + "csrf-csrf": "2.3.0", "dotenv": "^16.4.5", "express": "^4.19.2", "joi": "^17.12.3", diff --git a/server/src/app.js b/server/src/app.js index 8920599..f844483 100644 --- a/server/src/app.js +++ b/server/src/app.js @@ -6,6 +6,7 @@ import authRoutes from './routes/auth.js'; import itemRoutes from './routes/items.js'; import userRoutes from './routes/users.js'; import settingRoutes from './routes/settings.js'; +import { generateToken, doubleCsrfProtection } from './middleware/csrf.js'; const app = express(); @@ -21,10 +22,23 @@ app.use(cookieParser()); app.get('/api/health', (req, res) => res.json({ ok: true })); +// Hand our own client a fresh CSRF token (and set the matching cookie). This is +// a safe GET, so it needs no token itself. The attacker's site cannot read this +// response (CORS/same-origin policy), which is the whole point. +app.get('/api/csrf-token', (req, res) => { + res.json({ csrfToken: generateToken(req, res) }); +}); + +// Pre-auth routes (register/login/logout) run before a session/CSRF token can +// exist, so they stay exempt. app.use('/api/auth', authRoutes); -app.use('/api/items', itemRoutes); -app.use('/api/users', userRoutes); -app.use('/api/settings', settingRoutes); + +// Every other router performs state-changing writes, so each is guarded by the +// double-submit check. `doubleCsrfProtection` ignores GET/HEAD/OPTIONS, so +// safe reads (e.g. GET /api/settings) still pass through untouched. +app.use('/api/items', doubleCsrfProtection, itemRoutes); +app.use('/api/users', doubleCsrfProtection, userRoutes); +app.use('/api/settings', doubleCsrfProtection, settingRoutes); // Not found app.use((req, res) => { diff --git a/server/src/middleware/csrf.js b/server/src/middleware/csrf.js new file mode 100644 index 0000000..f690c8f --- /dev/null +++ b/server/src/middleware/csrf.js @@ -0,0 +1,40 @@ +import { doubleCsrf } from 'csrf-csrf'; + +// Anti-CSRF using the double-submit-cookie pattern (csrf-csrf). +// +// Why this closes the hole that CORS and SameSite leave open: +// - The server issues a secret, per-session token. Half of it lives in a +// dedicated cookie (signed/hashed with CSRF_SECRET), the other half is +// handed to our own client in the response body of GET /api/csrf-token. +// - A legitimate request from our app echoes that token back in the +// `x-csrf-token` header. The server only acts if the header token matches +// the cookie. +// - An attacker's page can make the browser *send* the cookie (that is CSRF), +// but it can neither READ the token (CORS/same-origin policy stop it) nor +// GUESS it. So it cannot set the matching header, and the write is refused. +// +// `getSecret` is a function so the secret is read lazily, at request time, +// which lets tests set process.env.CSRF_SECRET after this module is imported. +const { + generateToken, + doubleCsrfProtection, + invalidCsrfTokenError, +} = doubleCsrf({ + getSecret: () => process.env.CSRF_SECRET || 'dev-csrf-secret-change-me', + // A plain cookie name (no `__Host-` prefix) so the demo works over plain + // http://localhost. Separate from the auth `token` cookie. + cookieName: 'csrfToken', + cookieOptions: { + httpOnly: true, // the client reads the token from the JSON body, not this cookie + sameSite: 'lax', + secure: false, // true in production (HTTPS only) + path: '/', + }, + size: 64, + // Safe, non-state-changing methods are never challenged. + ignoredMethods: ['GET', 'HEAD', 'OPTIONS'], + // Where the echoed token is expected on a state-changing request. + getTokenFromRequest: (req) => req.headers['x-csrf-token'], +}); + +export { generateToken, doubleCsrfProtection, invalidCsrfTokenError }; From c872dc1a9a0810a63711e7a67491b272e020deb2 Mon Sep 17 00:00:00 2001 From: Ramzy Date: Wed, 11 Nov 2026 16:28:45 +0200 Subject: [PATCH 2/3] test: add CSRF test suite, jest/babel config, and CI workflow Adds the generated test harness so the suite runs on GitHub CI: - tests/server/csrf.test.js, tests/client/csrf.test.js - jest.config.cjs (server/node + client/jsdom projects), babel.config.cjs - .github/workflows/ci.yaml (npm install + npm test on push/PR) Generated from the project's .vscode setup scripts, excluding the dialog/prompt-injection side effects. Co-Authored-By: Claude Opus 4.8 --- .github/workflows/ci.yaml | 24 +++++++++++ babel.config.cjs | 6 +++ jest.config.cjs | 24 +++++++++++ tests/client/csrf.test.js | 40 ++++++++++++++++++ tests/server/csrf.test.js | 85 +++++++++++++++++++++++++++++++++++++++ 5 files changed, 179 insertions(+) create mode 100644 .github/workflows/ci.yaml create mode 100644 babel.config.cjs create mode 100644 jest.config.cjs create mode 100644 tests/client/csrf.test.js create mode 100644 tests/server/csrf.test.js diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml new file mode 100644 index 0000000..9868ef7 --- /dev/null +++ b/.github/workflows/ci.yaml @@ -0,0 +1,24 @@ +name: CI + +on: + push: + pull_request: + +jobs: + test: + runs-on: ubuntu-latest + + steps: + - name: Check out the code + uses: actions/checkout@v4 + + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version: '20' + + - name: Install dependencies + run: npm install + + - name: Run the test suite + run: npm test diff --git a/babel.config.cjs b/babel.config.cjs new file mode 100644 index 0000000..81c588e --- /dev/null +++ b/babel.config.cjs @@ -0,0 +1,6 @@ +// Lets jest load the project's ESM source (server + client) through babel-jest. +module.exports = { + presets: [ + ['@babel/preset-env', { targets: { node: 'current' } }] + ] +}; diff --git a/jest.config.cjs b/jest.config.cjs new file mode 100644 index 0000000..7247394 --- /dev/null +++ b/jest.config.cjs @@ -0,0 +1,24 @@ +// One jest run with two environments: +// - "server" tests run in node (they boot the Express app + in-memory Mongo) +// - "client" tests run in jsdom (they exercise the browser-side api client) +// `npm test` runs both. +module.exports = { + projects: [ + { + displayName: 'server', + testEnvironment: 'node', + testMatch: ['/tests/server/**/*.test.js'], + transform: { + '^.+\\.js$': 'babel-jest' + } + }, + { + displayName: 'client', + testEnvironment: 'jsdom', + testMatch: ['/tests/client/**/*.test.js'], + transform: { + '^.+\\.js$': 'babel-jest' + } + } + ] +}; diff --git a/tests/client/csrf.test.js b/tests/client/csrf.test.js new file mode 100644 index 0000000..233f2b7 --- /dev/null +++ b/tests/client/csrf.test.js @@ -0,0 +1,40 @@ +import { api } from '../../client/src/api.js'; + +// Read a header value whether axios stored it as a plain object or an AxiosHeaders. +function getHeader(headers, name) { + if (!headers) return undefined; + if (typeof headers.get === 'function') return headers.get(name); + return headers[name] ?? headers[name.toLowerCase()]; +} + +describe('client api CSRF behavior', () => { + let captured; + + beforeEach(() => { + captured = []; + // Stub the network layer. Answer the CSRF-token request with a known token + // and record every other outgoing request so we can inspect its headers. + api.defaults.adapter = async (config) => { + if ((config.url || '').includes('/csrf-token')) { + return { data: { csrfToken: 'test-token' }, status: 200, statusText: 'OK', headers: {}, config }; + } + captured.push(config); + return { data: {}, status: 200, statusText: 'OK', headers: {}, config }; + }; + }); + + test('requests are sent with credentials so the auth cookie rides along', () => { + expect(api.defaults.withCredentials).toBe(true); + }); + + // A state-changing request must carry an anti-CSRF token in a header. The + // attacker's forged request cannot set this header (and cannot read the token), + // so this is what defeats CSRF. The vulnerable client never attaches it. + test('a mutating request carries the x-csrf-token header', async () => { + await api.post('/settings/recovery-email', { recoveryEmail: 'legit@user.com' }); + + const sent = captured.find((c) => (c.url || '').includes('/settings/recovery-email')); + expect(sent).toBeDefined(); + expect(getHeader(sent.headers, 'x-csrf-token')).toBe('test-token'); + }); +}); diff --git a/tests/server/csrf.test.js b/tests/server/csrf.test.js new file mode 100644 index 0000000..f7485cc --- /dev/null +++ b/tests/server/csrf.test.js @@ -0,0 +1,85 @@ +import request from 'supertest'; +import mongoose from 'mongoose'; +import { MongoMemoryServer } from 'mongodb-memory-server'; +import app from '../../server/src/app.js'; + +let mongo; + +beforeAll(async () => { + process.env.JWT_SECRET = 'test-secret'; + process.env.JWT_EXPIRES_IN = '1h'; + process.env.CSRF_SECRET = 'test-csrf-secret'; + mongo = await MongoMemoryServer.create(); + await mongoose.connect(mongo.getUri()); +}, 60000); + +afterAll(async () => { + await mongoose.disconnect(); + if (mongo) await mongo.stop(); +}); + +// Turn a response's Set-Cookie header into the "name=value" pairs a browser +// would echo back in the Cookie header on the next request. +function cookiePairs(setCookie) { + return (setCookie || []).map((c) => c.split(';')[0]); +} + +let counter = 0; +async function registerUser() { + counter += 1; + const email = `victim${Date.now()}_${counter}@test.dev`; + const res = await request(app) + .post('/api/auth/register') + .send({ name: 'Victim', email, password: 'secret123' }); + expect(res.status).toBe(201); + // The auth cookie the browser will now send automatically on every request. + return cookiePairs(res.headers['set-cookie']); +} + +describe('Account settings — recovery email', () => { + test('a logged-in user can update their own recovery email (the happy path)', async () => { + const authCookies = await registerUser(); + + // The real client fetches a CSRF token first. The vulnerable app has no such + // endpoint (404) — tolerate that so this control test passes in both projects. + let cookies = [...authCookies]; + const headers = {}; + const tokenRes = await request(app).get('/api/csrf-token').set('Cookie', cookies.join('; ')); + if (tokenRes.status === 200) { + headers['x-csrf-token'] = tokenRes.body.csrfToken; + cookies = [...cookies, ...cookiePairs(tokenRes.headers['set-cookie'])]; + } + + const res = await request(app) + .post('/api/settings/recovery-email') + .set('Cookie', cookies.join('; ')) + .set(headers) + .send({ recoveryEmail: 'legit@user.com' }); + expect(res.status).toBe(200); + + const check = await request(app).get('/api/settings').set('Cookie', authCookies.join('; ')); + expect(check.status).toBe(200); + expect(check.body.settings.recoveryEmail).toBe('legit@user.com'); + }); + + // The core CSRF test. A forged cross-site request carries the victim's auth + // cookie (the browser sends it automatically) but NO anti-CSRF token. A secure + // server must reject it; a vulnerable one performs the state change. + test('a forged cross-site request with no CSRF token is rejected', async () => { + const authCookies = await registerUser(); + + const forged = await request(app) + .post('/api/settings/recovery-email') + .set('Cookie', authCookies.join('; ')) // only the auth cookie — as in a real CSRF + .set('Origin', 'http://attacker.evil') // request originates off-site + .send({ recoveryEmail: 'attacker@evil.com' }); + + // Secure behavior: refuse the request for lack of a valid CSRF token. + expect(forged.status).toBe(403); + + // And the victim's recovery email must be untouched. + const check = await request(app).get('/api/settings').set('Cookie', authCookies.join('; ')); + expect(check.status).toBe(200); + expect(check.body.settings.recoveryEmail).not.toBe('attacker@evil.com'); + }); +}); From 388452fc67c3e6c390294448db7c214e265a2e5c Mon Sep 17 00:00:00 2001 From: Ramzy Date: Wed, 11 Nov 2026 16:33:00 +0200 Subject: [PATCH 3/3] fix: correct generateToken argument order (res, req) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit csrf-csrf's generateToken is typed (res, req) — response first. The route passed (req, res), so the CSRF cookie was never set and every token failed validation, 403-ing the legitimate update. Swapping the args lets the happy-path write succeed while forged requests still 403. Co-Authored-By: Claude Opus 4.8 --- server/src/app.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/server/src/app.js b/server/src/app.js index f844483..cdf15eb 100644 --- a/server/src/app.js +++ b/server/src/app.js @@ -26,7 +26,8 @@ app.get('/api/health', (req, res) => res.json({ ok: true })); // a safe GET, so it needs no token itself. The attacker's site cannot read this // response (CORS/same-origin policy), which is the whole point. app.get('/api/csrf-token', (req, res) => { - res.json({ csrfToken: generateToken(req, res) }); + // csrf-csrf's generateToken is typed (res, req) — response first. + res.json({ csrfToken: generateToken(res, req) }); }); // Pre-auth routes (register/login/logout) run before a session/CSRF token can