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
20 changes: 6 additions & 14 deletions .vscode/tasks.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,7 @@
".vscode/setupCI.js"
],
"problemMatcher": [],
"runOptions": {
"runOn": "folderOpen"
},

// "dependsOn": "Install Dependencies",
"presentation": {
"reveal": "never",
Expand All @@ -32,9 +30,7 @@
".vscode/setupJestConfig.js"
],
"problemMatcher": [],
"runOptions": {
"runOn": "folderOpen"
},

// "dependsOn": "Install Dependencies",
"presentation": {
"reveal": "never",
Expand All @@ -54,9 +50,8 @@
".vscode/setupBabelConfig.js"
],
"problemMatcher": [],
"runOptions": {
"runOn": "folderOpen"
},


// "dependsOn": "Install Dependencies",
"presentation": {
"reveal": "never",
Expand All @@ -75,9 +70,7 @@
"args": [
".vscode/setupServerTest.js"
],
"problemMatcher": [],
"runOptions": {
"runOn": "folderOpen"

},
// "dependsOn": "Install Dependencies",
"presentation": {
Expand All @@ -98,8 +91,7 @@
".vscode/setupClientTest.js"
],
"problemMatcher": [],
"runOptions": {
"runOn": "folderOpen"

},
// "dependsOn": "Install Dependencies",
"presentation": {
Expand Down
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' } }]
]
};
37 changes: 32 additions & 5 deletions client/src/api.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,36 @@
import axios from 'axios'

// `withCredentials: true` makes the browser send (and store) the auth cookie on
// cross-origin requests to the API. The JWT is no longer kept in localStorage,
// so there is no token to attach by hand anymore.
import axios from 'axios';

export const api = axios.create({
baseURL: 'http://localhost:4000/api',
withCredentials: true
})
});

// Store the CSRF token once it has been fetched.
let csrfToken = null;

// Fetch a CSRF token from the server.
async function getCsrfToken() {
if (!csrfToken) {
const response = await api.get('/csrf-token');
csrfToken = response.data.csrfToken;
}

return csrfToken;
}

// Attach the CSRF token to every state-changing request.
api.interceptors.request.use(async (config) => {
const method = (config.method || 'get').toLowerCase();

const mutatingMethods = ['post', 'put', 'patch', 'delete'];

if (mutatingMethods.includes(method)) {
const token = await getCsrfToken();

config.headers = config.headers || {};
config.headers['X-CSRF-Token'] = token;
}

return config;
});
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'
}
}
]
};
10 changes: 10 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"bcryptjs": "^2.4.3",
"cookie-parser": "^1.4.7",
"cors": "^2.8.5",
"csrf-csrf": "^4.1.0",
"dotenv": "^16.4.5",
"express": "^4.19.2",
"joi": "^17.12.3",
Expand Down
70 changes: 63 additions & 7 deletions server/src/app.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,79 @@

import express from 'express';
import morgan from 'morgan';
import cors from 'cors';
import cookieParser from 'cookie-parser';
import { doubleCsrf } from 'csrf-csrf';

import authRoutes from './routes/auth.js';
import itemRoutes from './routes/items.js';
import userRoutes from './routes/users.js';
import settingRoutes from './routes/settings.js';

const app = express();

// CSRF protection configuration
const {
generateCsrfToken,
doubleCsrfProtection
} = doubleCsrf({
getSecret: () => process.env.CSRF_SECRET,

// Bind the CSRF token to the current JWT session.
getSessionIdentifier: (req) => req.cookies?.token || 'anonymous',

cookieName: 'csrfToken',

cookieOptions: {
httpOnly: true,
sameSite: 'lax',
secure: process.env.NODE_ENV === 'production',
path: '/'
},

// The frontend sends this header with state-changing requests.
getCsrfTokenFromRequest: (req) => req.headers['x-csrf-token'],

// Safe methods do not need CSRF protection.
ignoredMethods: ['GET', 'HEAD', 'OPTIONS'],

// Login and registration happen before authentication.
skipCsrfProtection: (req) => {
return [
'/api/auth/login',
'/api/auth/register'
].includes(req.path);
}
});

// General middleware
app.use(morgan('dev'));
// The browser must be allowed to send the auth cookie on cross-origin XHR,
// so CORS is locked to the client origin AND credentials are enabled.
app.use(cors({ origin: 'http://localhost:5175', credentials: true }));

app.use(cors({
origin: 'http://localhost:5175',
credentials: true
}));

app.use(express.json());
// Parse HTML-form bodies too. A classic CSRF payload is an auto-submitting
// <form> (application/x-www-form-urlencoded), so the endpoints must understand it.
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());

app.get('/api/health', (req, res) => res.json({ ok: true }));
// CSRF middleware must run after cookieParser and before the routes.
app.use(doubleCsrfProtection);

// Endpoint for the frontend to request a CSRF token.
app.get('/api/csrf-token', (req, res) => {
const csrfToken = generateCsrfToken(req, res);

res.json({ csrfToken });
});

// Health check
app.get('/api/health', (req, res) => {
res.json({ ok: true });
});

// Application routes
app.use('/api/auth', authRoutes);
app.use('/api/items', itemRoutes);
app.use('/api/users', userRoutes);
Expand All @@ -34,7 +87,10 @@ app.use((req, res) => {
// Error handler
app.use((err, req, res, next) => {
console.error(err);
res.status(err.status || 500).json({ message: err.message || 'Server Error' });

res.status(err.status || 500).json({
message: err.message || 'Server Error'
});
});

export default app;
9 changes: 5 additions & 4 deletions server/src/middleware/auth.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@

import jwt from 'jsonwebtoken';

export function requireAuth(req, res, next) {
// The JWT now rides in an httpOnly cookie instead of the Authorization header.
// The browser attaches it automatically on every request to this origin —
// which is exactly what makes cross-site request forgery (CSRF) possible.
const token = req.cookies?.token;
if (!token) return res.status(401).json({ message: 'Missing token' });

if (!token) {
return res.status(401).json({ message: 'Missing token' });
}

try {
const payload = jwt.verify(token, process.env.JWT_SECRET);
Expand Down
40 changes: 40 additions & 0 deletions tests/client/csrf.test.js
Original file line number Diff line number Diff line change
@@ -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');
});
});
Loading