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: 1 addition & 2 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
"**/Thumbs.db": true,
".vscode/public": true,
"CLAUDE.md": true,
"AGENTS.md": true,
".vscode": true
"AGENTS.md": true
}
}
115 changes: 0 additions & 115 deletions .vscode/tasks.json

This file was deleted.

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' } }]
]
};
54 changes: 54 additions & 0 deletions client/src/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,57 @@ export const api = axios.create({
baseURL: 'http://localhost:4000/api',
withCredentials: true
})

// ---- CSRF protection -------------------------------------------------------
// The server requires an anti-CSRF token on every state-changing request.
// We fetch it from GET /api/csrf-token (only our own origin can read that
// response, thanks to CORS) and echo it back in the `x-csrf-token` header.
// An attacker's page can do neither, so its forged requests get a 403.

const SAFE_METHODS = ['get', 'head', 'options']
let csrfToken = null

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

// The token is bound to the session, so drop it whenever the session changes
// (login, register, logout). A fresh one is fetched on the next write.
export function clearCsrfToken() {
csrfToken = null
}

function setHeader(config, name, value) {
if (config.headers && typeof config.headers.set === 'function') {
config.headers.set(name, value)
} else {
config.headers = { ...(config.headers || {}), [name]: value }
}
}

// Attach the token to every mutating request.
api.interceptors.request.use(async (config) => {
const method = (config.method || 'get').toLowerCase()
if (!SAFE_METHODS.includes(method)) {
if (!csrfToken) await fetchCsrfToken()
setHeader(config, 'x-csrf-token', csrfToken)
}
return config
})

// If the token was stale (e.g. the session changed), get a new one and retry once.
api.interceptors.response.use(
(res) => res,
async (error) => {
const config = error.config
if (error.response?.status === 403 && config && !config._csrfRetried) {
config._csrfRetried = true
await fetchCsrfToken()
setHeader(config, 'x-csrf-token', csrfToken)
return api(config)
}
return Promise.reject(error)
}
)
5 changes: 4 additions & 1 deletion client/src/context/AuthContext.jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { createContext, useCallback, useContext, useEffect, useState } from 'react'
import { api } from '../api'
import { api, clearCsrfToken } from '../api'

const AuthContext = createContext(null)

Expand All @@ -19,16 +19,19 @@ export function AuthProvider({ children }) {

const login = useCallback(async (email, password) => {
const res = await api.post('/auth/login', { email, password })
clearCsrfToken() // new session -> the old CSRF token no longer matches
setUser(res.data.user)
}, [])

const register = useCallback(async (name, email, password) => {
const res = await api.post('/auth/register', { name, email, password })
clearCsrfToken() // new session -> the old CSRF token no longer matches
setUser(res.data.user)
}, [])

const logout = useCallback(async () => {
try { await api.post('/auth/logout') } catch { /* ignore */ }
clearCsrfToken()
setUser(null)
window.location.href = '/login'
}, [])
Expand Down
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