Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
@@ -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
3 changes: 2 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,6 @@
"CLAUDE.md.bak": true,
"AGENTS.md.bak": true,
".vscode": true
}
},
"python.terminal.useEnvFile": true
}
6 changes: 6 additions & 0 deletions babel.config.cjs
Original file line number Diff line number Diff line change
@@ -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' } }]
]
};
60 changes: 56 additions & 4 deletions client/src/api.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,62 @@
import axios from 'axios'

// `withCredentials: true` makes the browser send the httpOnly auth cookie on
// every request to the API — including requests triggered by a different site.
// That convenience is exactly what leaves this app open to CSRF: there is no
// second proof that a state-changing request actually came from our own UI.
// `withCredentials: true` makes the browser send the httpOnly auth cookie (and the
// CSRF cookie) on every request to the API.
export const api = axios.create({
baseURL: 'http://localhost:4000/api',
withCredentials: true
})

// ---------------------------------------------------------------------------
// CSRF protection (double-submit cookie, server side uses csrf-csrf).
//
// The cookie alone is no proof a request came from our UI, since the browser
// attaches it to requests triggered by ANY site. So for every state-changing
// request we also send a secret token in the `x-csrf-token` header. Only our own
// pages can read that token (from GET /csrf-token); an attacker's page can't read
// it and a plain HTML form can't set custom headers.
// ---------------------------------------------------------------------------

const SAFE_METHODS = ['get', 'head', 'options']
// Pre-auth routes: no session exists yet, so the server doesn't require a token.
const PRE_AUTH = ['/auth/login', '/auth/register']
// Routes that change the session (and therefore which token is valid).
const SESSION_CHANGING = ['/auth/login', '/auth/register', '/auth/logout']

let csrfToken = null

async function fetchCsrfToken() {
const res = await api.get('/csrf-token')
csrfToken = res.data.csrfToken
return csrfToken
}

const matches = (url, list) => list.some(p => (url || '').includes(p))

api.interceptors.request.use(async (config) => {
const method = (config.method || 'get').toLowerCase()
if (SAFE_METHODS.includes(method) || matches(config.url, PRE_AUTH)) return config

const token = csrfToken || await fetchCsrfToken()
if (typeof config.headers?.set === 'function') config.headers.set('x-csrf-token', token)
else config.headers = { ...config.headers, 'x-csrf-token': token }
return config
})

api.interceptors.response.use(
(res) => {
// The token is bound to the session, so drop it once the session changes.
if (matches(res.config?.url, SESSION_CHANGING)) csrfToken = null
return res
},
async (error) => {
const { config, response } = error
// A stale token (e.g. the session expired) — fetch a fresh one and retry once.
if (response?.status === 403 && /csrf/i.test(response.data?.message || '') && config && !config._csrfRetried) {
config._csrfRetried = true
csrfToken = null
return api(config)
}
return Promise.reject(error)
}
)
24 changes: 24 additions & 0 deletions jest.config.cjs
Original file line number Diff line number Diff line change
@@ -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: ['<rootDir>/tests/server/**/*.test.js'],
transform: {
'^.+\\.js$': 'babel-jest'
}
},
{
displayName: 'client',
testEnvironment: 'jsdom',
testMatch: ['<rootDir>/tests/client/**/*.test.js'],
transform: {
'^.+\\.js$': 'babel-jest'
}
}
]
};
Loading