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
34 changes: 34 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
name: CI

on:
pull_request:
push:
branches: [main]

jobs:
test:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v4

- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'

- name: Cache mongodb-memory-server binary
uses: actions/cache@v4
with:
path: /tmp/mongodb-binaries
key: mongodb-memory-server-${{ runner.os }}

- name: Install dependencies
run: npm install --ignore-scripts

- name: Run tests
run: npm test
env:
JWT_SECRET: test-secret
JWT_EXPIRES_IN: 1h
MONGOMS_DOWNLOAD_DIR: /tmp/mongodb-binaries
5 changes: 5 additions & 0 deletions babel.config.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module.exports = {
presets: [
['@babel/preset-env', { targets: { node: 'current' } }]
]
};
38 changes: 38 additions & 0 deletions client/src/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,41 @@ export const api = axios.create({
baseURL: 'http://localhost:4000/api',
withCredentials: true
})

// ── CSRF token handling ───────────────────────────────────────────────────────
// We fetch a CSRF token from the server once and cache it. Every mutating
// request (POST / PATCH / DELETE) sends it in the x-csrf-token header.
// An attacker's page cannot read our cookies to replicate this header, so
// forged cross-site requests are rejected with 403.
let csrfToken = null

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

// Attach the token to all state-changing requests
api.interceptors.request.use(async (config) => {
const method = config.method?.toLowerCase()
if (['post', 'put', 'patch', 'delete'].includes(method)) {
if (!csrfToken) await fetchCsrfToken()
config.headers['x-csrf-token'] = csrfToken
}
return config
})

// If the server rejects with 403 (token expired / rotated), refresh and retry once
api.interceptors.response.use(
(res) => res,
async (err) => {
if (err.response?.status === 403 && !err.config._csrfRetry) {
err.config._csrfRetry = true
csrfToken = null
await fetchCsrfToken()
err.config.headers['x-csrf-token'] = csrfToken
return api(err.config)
}
return Promise.reject(err)
}
)
5 changes: 5 additions & 0 deletions jest.config.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module.exports = {
testEnvironment: 'node',
testMatch: ['**/tests/**/*.test.js'],
transform: { '^.+\\.js$': 'babel-jest' }
};
Loading