Module 4 · Authentication and user management
4.4 CSRF tokens, login throttling, and "logged in" is not "allowed"
Write a synchronizer-token CSRF middleware, put the token in every form, limit failed logins per client, and finish authentication by showing what it does not do.
Starting point
Every page needs a login, sessions are regenerated at login, and cookies are HttpOnly and SameSite=Lax.
Outcome
src/middleware/csrf.js (new)src/middleware/rate-limit.js (new)views/**/*.ejs (every POST form carries a hidden _csrf field)test/csrf.test.js test/rate-limit.test.js- Every
POSTmust carry the session's CSRF token, in a hidden form field or anX-CSRF-Tokenheader, or it is refused with403. - More than 10 failed logins from one client in 15 minutes get
429 Too Many Requests. - You can explain the difference between authentication and authorization, using Nora.
The problem
Cross-site request forgery
The browser attaches our session cookie to every request to our site, no matter which page started it. Suppose Alice is logged in, and opens a page that contains:
<form method="post" action="http://localhost:3000/issues/101/delete" id="f"></form><script>document.getElementById('f').submit();</script>The browser sends a POST to our server with Alice's cookie. Our server sees a valid session and deletes the issue. That is cross-site request forgery (CSRF): another page makes the user's browser perform an action the user did not intend.
SameSite=Lax stops the cookie on cross-site POSTs, which covers most attacks in modern browsers. But "site" means scheme plus registrable domain, ignoring ports and subdomains: a page on http://localhost:4000 (or on blog.example.com versus app.example.com) is the same site as http://localhost:3000, and SameSite does not apply. Older browsers ignore it too. So we add a defence that does not depend on the browser: a secret token that the attacker's page cannot know.
Let's see what the server accepts today. We log in as Alice with curl, then send the request the evil page would send. An Origin header from the other page does not stop anything:
npm run dev
> caretaker@1.0.0 dev
> node --env-file=.env --watch src/server.js
Caretaker listening on http://localhost:3000
curl -s -c /tmp/alice.txt -o /dev/null http://localhost:3000/login -d email=alice@example.test -d password=password123
curl -si -b /tmp/alice.txt -H "Origin: http://localhost:4000" -X POST http://localhost:3000/issues/130/delete | head -1
HTTP/1.1 303 See Other
Deleted. (We re-seed later.)
Password guessing
Nothing limits login attempts. A script can try thousands of passwords against alice@example.test:
for i in $(seq 12); do curl -s -o /dev/null -w "%{http_code}\n" http://localhost:3000/login -d email=alice@example.test -d password=guess$i; done | uniq -c
12 401
Twelve guesses, twelve answers. Each costs the server one argon2id verification, so a flood of guesses is also an easy way to overload it.
Build it
1. A CSRF middleware
We use the synchronizer token pattern: a random token stored in the session, embedded in every form the server renders, and compared on every state-changing request. The attacker's page can make the browser send our cookie, but it cannot read our pages, so it cannot learn the token. (The once-popular csurf package is deprecated; the pattern is short enough to write and understand ourselves.)
Create src/middleware/csrf.js:
import crypto from 'node:crypto'; const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']); function tokensMatch(sent, expected) { if (typeof sent !== 'string' || sent.length !== expected.length) { return false; } return crypto.timingSafeEqual(Buffer.from(sent), Buffer.from(expected));} // Synchronizer token: one random token per session, required on every unsafe request.export function csrf(req, res, next) { if (!req.session.csrfToken) { req.session.csrfToken = crypto.randomBytes(32).toString('base64url'); } res.locals.csrfToken = req.session.csrfToken; if (SAFE_METHODS.has(req.method)) { return next(); } const sent = req.body?._csrf ?? req.get('x-csrf-token'); if (!tokensMatch(sent, req.session.csrfToken)) { const err = new Error('This form has expired or did not come from Caretaker. Go back, reload the page and try again.'); err.status = 403; err.expose = true; return next(err); } next();}- The token is 32 random bytes, so it cannot be guessed. It lives in the session, on the server.
GET,HEADandOPTIONSare not checked. That is only safe because ourGETroutes never change anything; we kept that rule from lesson 1.4 onwards (even logout is aPOST).crypto.timingSafeEqualcompares in constant time, so response timing does not reveal how many leading characters were right.- The token is accepted from the form field
_csrfor anX-CSRF-Tokenheader. Browsers send the field; tests and future JavaScript can send the header. - Because
startSessionregenerates the session at login, the token also changes at login.
Register it in src/app.js before the auth routes, so that the login and registration forms are protected too:
import { flash } from './middleware/flash.js';import { csrf } from './middleware/csrf.js';
app.locals.flash = null;app.locals.csrfToken = '';
app.use(flash);app.use(csrf); app.use(authRouter);
Show the whole src/app.js after this change
import express from 'express';import path from 'node:path';import session from 'express-session';import connectPgSimple from 'connect-pg-simple';import { config } from './config.js';import { pool } from './db.js';import { loadUser, requireLogin } from './middleware/auth.js';import { flash } from './middleware/flash.js';import { csrf } from './middleware/csrf.js';import { authRouter } from './routes/auth.js';import { issuesRouter } from './routes/issues.js';import { organisationsRouter } from './routes/organisations.js';import { buildingsRouter } from './routes/buildings.js';import { inspectionsRouter } from './routes/inspections.js';import { getDashboard } from './models/dashboard.js'; export const app = express(); app.set('view engine', 'ejs');app.set('views', path.join(import.meta.dirname, '..', 'views'));app.locals.formatDate = (value) => new Date(value).toLocaleString('en-IE', { dateStyle: 'medium', timeStyle: 'short', timeZone: 'UTC' });app.locals.currentUser = null;app.locals.flash = null;app.locals.csrfToken = ''; const PgSession = connectPgSimple(session); app.use((req, res, next) => { if (process.env.NODE_ENV === 'test') { return next(); } const started = Date.now(); res.on('finish', () => { console.log(`${req.method} ${req.originalUrl} -> ${res.statusCode} (${Date.now() - started} ms)`); }); next();}); app.use(express.static(path.join(import.meta.dirname, '..', 'public')));app.use(express.urlencoded({ extended: false }));app.use(session({ store: new PgSession({ pool, tableName: 'session', pruneSessionInterval: config.env === 'test' ? false : 900 }), name: 'caretaker.sid', secret: config.sessionSecret, resave: false, saveUninitialized: false, cookie: { httpOnly: true, sameSite: 'lax', secure: config.cookieSecure, maxAge: 8 * 60 * 60 * 1000, },}));app.use(loadUser);app.use(flash);app.use(csrf); app.use(authRouter);app.use(requireLogin); app.get('/', async (req, res) => { res.render('dashboard', { title: 'Dashboard', dashboard: await getDashboard() });}); app.use('/issues', issuesRouter);app.use('/organisations', organisationsRouter);app.use('/buildings', buildingsRouter);app.use('/inspections', inspectionsRouter); app.use((req, res) => { res.status(404).render('not-found', { title: 'Not found', path: req.originalUrl });}); app.use((err, req, res, next) => { const status = err.status ?? 500; if (status >= 500) { console.error(err); } const message = err.expose ? err.message : 'Something went wrong'; res.status(status).render('error', { title: 'Error', status, message });});import express from 'express';
import path from 'node:path';
import session from 'express-session';
import connectPgSimple from 'connect-pg-simple';
import { config } from './config.js';
import { pool } from './db.js';
import { loadUser, requireLogin } from './middleware/auth.js';
import { flash } from './middleware/flash.js';
import { csrf } from './middleware/csrf.js';
import { authRouter } from './routes/auth.js';
import { issuesRouter } from './routes/issues.js';
import { organisationsRouter } from './routes/organisations.js';
import { buildingsRouter } from './routes/buildings.js';
import { inspectionsRouter } from './routes/inspections.js';
import { getDashboard } from './models/dashboard.js';
export const app = express();
app.set('view engine', 'ejs');
app.set('views', path.join(import.meta.dirname, '..', 'views'));
app.locals.formatDate = (value) => new Date(value).toLocaleString('en-IE', { dateStyle: 'medium', timeStyle: 'short', timeZone: 'UTC' });
app.locals.currentUser = null;
app.locals.flash = null;
app.locals.csrfToken = '';
const PgSession = connectPgSimple(session);
app.use((req, res, next) => {
if (process.env.NODE_ENV === 'test') {
return next();
}
const started = Date.now();
res.on('finish', () => {
console.log(`${req.method} ${req.originalUrl} -> ${res.statusCode} (${Date.now() - started} ms)`);
});
next();
});
app.use(express.static(path.join(import.meta.dirname, '..', 'public')));
app.use(express.urlencoded({ extended: false }));
app.use(session({
store: new PgSession({ pool, tableName: 'session', pruneSessionInterval: config.env === 'test' ? false : 900 }),
name: 'caretaker.sid',
secret: config.sessionSecret,
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true,
sameSite: 'lax',
secure: config.cookieSecure,
maxAge: 8 * 60 * 60 * 1000,
},
}));
app.use(loadUser);
app.use(flash);
app.use(csrf);
app.use(authRouter);
app.use(requireLogin);
app.get('/', async (req, res) => {
res.render('dashboard', { title: 'Dashboard', dashboard: await getDashboard() });
});
app.use('/issues', issuesRouter);
app.use('/organisations', organisationsRouter);
app.use('/buildings', buildingsRouter);
app.use('/inspections', inspectionsRouter);
app.use((req, res) => {
res.status(404).render('not-found', { title: 'Not found', path: req.originalUrl });
});
app.use((err, req, res, next) => {
const status = err.status ?? 500;
if (status >= 500) {
console.error(err);
}
const message = err.expose ? err.message : 'Something went wrong';
res.status(status).render('error', { title: 'Error', status, message });
});
2. Put the token in every form
Every page publishes the token in a <meta> tag (handy for scripts and tests):
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="csrf-token" content="<%= csrfToken %>">
Show the whole views/partials/head.ejs after this change
<!doctype html><html lang="en"><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="csrf-token" content="<%= csrfToken %>"> <title><%= title %> · Caretaker</title> <link rel="stylesheet" href="/css/style.css"> <script src="/js/app.js" defer></script></head><body><%- include('nav') %><main class="container"><% if (flash) { %> <div class="flash flash-<%= flash.type %>" role="status"><%= flash.message %></div><% } %><!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-token" content="<%= csrfToken %>">
<title><%= title %> · Caretaker</title>
<link rel="stylesheet" href="/css/style.css">
<script src="/js/app.js" defer></script>
</head>
<body>
<%- include('nav') %>
<main class="container">
<% if (flash) { %>
<div class="flash flash-<%= flash.type %>" role="status"><%= flash.message %></div>
<% } %>
Every <form method="post"> needs a hidden _csrf field. We have 13 such forms in 11 templates, and each needs the same line right after the opening tag. This script adds it and prints the files it changed:
node -e "
const fs = require('node:fs');
const path = require('node:path');
const files = fs.readdirSync('views', { recursive: true }).filter((f) => f.endsWith('.ejs')).sort();
for (const file of files) {
const p = path.join('views', file);
const before = fs.readFileSync(p, 'utf8');
const after = before.replace(/(<form method=\"post\"(?:<%[^%]*%>|[^>])*>)/g, '\$1<input type=\"hidden\" name=\"_csrf\" value=\"<%= csrfToken %>\">');
if (after !== before) {
fs.writeFileSync(p, after);
console.log('updated', p);
}
}
"
updated views/auth/login.ejs
updated views/auth/register.ejs
updated views/buildings/form.ejs
updated views/buildings/show.ejs
updated views/inspections/form.ejs
updated views/inspections/show.ejs
updated views/issues/form.ejs
updated views/issues/show.ejs
updated views/organisations/form.ejs
updated views/organisations/show.ejs
updated views/partials/nav.ejs
The pattern (?:<%[^%]*%>|[^>])* matters: some form tags contain EJS, such as action="<%= action %>", and the > inside %> is not the end of the tag. The pattern skips whole EJS tags before it looks for the closing >.
Look at one result, so you know exactly what changed:
git diff views/issues/show.ejs
diff --git a/views/issues/show.ejs b/views/issues/show.ejs
index 13e8cd2..74f3d6c 100644
--- a/views/issues/show.ejs
+++ b/views/issues/show.ejs
@@ -4,7 +4,7 @@
<h1><%= issue.title %></h1>
<div class="actions">
<a class="btn" href="/issues/<%= issue.id %>/edit">Edit</a>
- <form method="post" action="/issues/<%= issue.id %>/delete" data-confirm="Delete this issue? This cannot be undone.">
+ <form method="post" action="/issues/<%= issue.id %>/delete" data-confirm="Delete this issue? This cannot be undone."><input type="hidden" name="_csrf" value="<%= csrfToken %>">
<button type="submit" class="btn btn-danger">Delete</button>
</form>
</div>
From now on, whenever you write a new POST form, add that hidden input yourself. A test below fails if a form is missing it.
3. Limit failed logins
npm install express-rate-limit@8.7.4
added 2 packages, and audited 124 packages in 695ms
38 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
Make the limit configurable, so tests can use a smaller number of attempts without waiting 15 minutes:
cookieSecure: process.env.COOKIE_SECURE === '1', loginRateLimit: Number(process.env.LOGIN_RATE_LIMIT ?? 10),
Show the whole src/config.js after this change
function required(name) { const value = process.env[name]; if (!value) { throw new Error(`Missing required environment variable ${name}. Copy .env.example to .env.`); } return value;} export const config = { port: Number(process.env.PORT ?? 3000), databaseUrl: required('DATABASE_URL'), logSql: process.env.LOG_SQL === '1', env: process.env.NODE_ENV ?? 'development', sessionSecret: required('SESSION_SECRET'), // Set COOKIE_SECURE=1 when the app is served over HTTPS (always, in production). cookieSecure: process.env.COOKIE_SECURE === '1', loginRateLimit: Number(process.env.LOGIN_RATE_LIMIT ?? 10),};function required(name) {
const value = process.env[name];
if (!value) {
throw new Error(`Missing required environment variable ${name}. Copy .env.example to .env.`);
}
return value;
}
export const config = {
port: Number(process.env.PORT ?? 3000),
databaseUrl: required('DATABASE_URL'),
logSql: process.env.LOG_SQL === '1',
env: process.env.NODE_ENV ?? 'development',
sessionSecret: required('SESSION_SECRET'),
// Set COOKIE_SECURE=1 when the app is served over HTTPS (always, in production).
cookieSecure: process.env.COOKIE_SECURE === '1',
loginRateLimit: Number(process.env.LOGIN_RATE_LIMIT ?? 10),
};
SESSION_SECRET=test-only-secret-never-use-this-anywhere-realLOGIN_RATE_LIMIT=5
Show the whole .env.test after this change
# Settings for automated tests. Local learning values only; safe to commit.NODE_ENV=testDATABASE_URL=postgres://caretaker:caretaker_dev_password@localhost:5433/caretaker_testPORT=3001LOG_SQL=0SESSION_SECRET=test-only-secret-never-use-this-anywhere-realLOGIN_RATE_LIMIT=5# Settings for automated tests. Local learning values only; safe to commit.
NODE_ENV=test
DATABASE_URL=postgres://caretaker:caretaker_dev_password@localhost:5433/caretaker_test
PORT=3001
LOG_SQL=0
SESSION_SECRET=test-only-secret-never-use-this-anywhere-real
LOGIN_RATE_LIMIT=5
Create src/middleware/rate-limit.js:
import { rateLimit } from 'express-rate-limit';import { config } from '../config.js'; // At most config.loginRateLimit failed attempts per client IP in 15 minutes.export const loginLimiter = rateLimit({ windowMs: 15 * 60 * 1000, limit: config.loginRateLimit, skipSuccessfulRequests: true, standardHeaders: 'draft-8', legacyHeaders: false, handler: (req, res) => { res.status(429).render('auth/login', { title: 'Log in', email: '', error: 'Too many failed attempts. Wait 15 minutes, then try again.', }); },});skipSuccessfulRequests: truecounts only responses with status 400 or above, so a successful login (303) does not use up the allowance.standardHeaders: 'draft-8'addsRateLimitandRateLimit-Policyheaders that tell well-behaved clients how much allowance is left.- The default key is the client's IP address. The counters live in this process's memory: they reset on restart and are not shared between processes. A production deployment with several processes would use a shared store, and might also count per account, so that an attacker using many IP addresses cannot guess one person's password freely. Per-IP limits can also block a whole office behind one address; choose limits with that in mind.
Apply it to the two routes that check or create passwords:
import { cleanText } from '../lib/validation.js';import { loginLimiter } from '../middleware/rate-limit.js';
authRouter.post('/register', async (req, res) => {authRouter.post('/register', loginLimiter, async (req, res) => {
authRouter.post('/login', async (req, res) => {authRouter.post('/login', loginLimiter, async (req, res) => {
Show the whole src/routes/auth.js after this change
import express from 'express';import { createUser, verifyCredentials, normaliseEmail } from '../models/users.js';import { PG_ERRORS } from '../db.js';import { cleanText } from '../lib/validation.js';import { loginLimiter } from '../middleware/rate-limit.js'; export const authRouter = express.Router(); const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; // Replace the current session with a brand-new one (new ID) that belongs to userId.function startSession(req, userId) { return new Promise((resolve, reject) => { req.session.regenerate((err) => { if (err) return reject(err); req.session.userId = userId; req.session.save((saveErr) => (saveErr ? reject(saveErr) : resolve())); }); });} // Only follow returnTo if it is a path on this site. "//evil.test" would be another host.function safeReturnTo(value) { return typeof value === 'string' && value.startsWith('/') && !value.startsWith('//') ? value : '/';} function validateRegistration(input) { const errors = {}; const name = cleanText(input.name, { min: 1, max: 100 }); const email = normaliseEmail(input.email); const password = typeof input.password === 'string' ? input.password : ''; if (!name.ok) errors.name = 'Enter your name (up to 100 characters).'; if (!EMAIL_PATTERN.test(email) || email.length > 254) errors.email = 'Enter a valid email address.'; if (password.length < 10 || password.length > 200) errors.password = 'Use a password of 10 to 200 characters.'; return { errors, values: { name: name.text, email }, password };} authRouter.get('/register', (req, res) => { res.render('auth/register', { title: 'Create an account', values: {}, errors: {} });}); authRouter.post('/register', loginLimiter, async (req, res) => { const { errors, values, password } = validateRegistration(req.body ?? {}); if (Object.keys(errors).length > 0) { return res.status(400).render('auth/register', { title: 'Create an account', values, errors }); } let user; try { user = await createUser({ ...values, password }); } catch (err) { if (err.code === PG_ERRORS.UNIQUE_VIOLATION) { return res.status(400).render('auth/register', { title: 'Create an account', values, errors: { email: 'An account with this email already exists.' } }); } throw err; } await startSession(req, user.id); req.flash('success', `Welcome to Caretaker, ${user.name}.`); res.redirect(303, '/');}); authRouter.get('/login', (req, res) => { res.render('auth/login', { title: 'Log in', email: '', error: null });}); authRouter.post('/login', loginLimiter, async (req, res) => { const email = normaliseEmail(req.body?.email); const user = await verifyCredentials(email, req.body?.password); if (!user) { return res.status(401).render('auth/login', { title: 'Log in', email, error: 'Email or password is incorrect.' }); } const returnTo = safeReturnTo(req.session.returnTo); await startSession(req, user.id); res.redirect(303, returnTo);}); authRouter.post('/logout', (req, res, next) => { req.session.destroy((err) => { if (err) return next(err); res.clearCookie('caretaker.sid'); res.redirect(303, '/login'); });});import express from 'express';
import { createUser, verifyCredentials, normaliseEmail } from '../models/users.js';
import { PG_ERRORS } from '../db.js';
import { cleanText } from '../lib/validation.js';
import { loginLimiter } from '../middleware/rate-limit.js';
export const authRouter = express.Router();
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
// Replace the current session with a brand-new one (new ID) that belongs to userId.
function startSession(req, userId) {
return new Promise((resolve, reject) => {
req.session.regenerate((err) => {
if (err) return reject(err);
req.session.userId = userId;
req.session.save((saveErr) => (saveErr ? reject(saveErr) : resolve()));
});
});
}
// Only follow returnTo if it is a path on this site. "//evil.test" would be another host.
function safeReturnTo(value) {
return typeof value === 'string' && value.startsWith('/') && !value.startsWith('//') ? value : '/';
}
function validateRegistration(input) {
const errors = {};
const name = cleanText(input.name, { min: 1, max: 100 });
const email = normaliseEmail(input.email);
const password = typeof input.password === 'string' ? input.password : '';
if (!name.ok) errors.name = 'Enter your name (up to 100 characters).';
if (!EMAIL_PATTERN.test(email) || email.length > 254) errors.email = 'Enter a valid email address.';
if (password.length < 10 || password.length > 200) errors.password = 'Use a password of 10 to 200 characters.';
return { errors, values: { name: name.text, email }, password };
}
authRouter.get('/register', (req, res) => {
res.render('auth/register', { title: 'Create an account', values: {}, errors: {} });
});
authRouter.post('/register', loginLimiter, async (req, res) => {
const { errors, values, password } = validateRegistration(req.body ?? {});
if (Object.keys(errors).length > 0) {
return res.status(400).render('auth/register', { title: 'Create an account', values, errors });
}
let user;
try {
user = await createUser({ ...values, password });
} catch (err) {
if (err.code === PG_ERRORS.UNIQUE_VIOLATION) {
return res.status(400).render('auth/register', { title: 'Create an account', values, errors: { email: 'An account with this email already exists.' } });
}
throw err;
}
await startSession(req, user.id);
req.flash('success', `Welcome to Caretaker, ${user.name}.`);
res.redirect(303, '/');
});
authRouter.get('/login', (req, res) => {
res.render('auth/login', { title: 'Log in', email: '', error: null });
});
authRouter.post('/login', loginLimiter, async (req, res) => {
const email = normaliseEmail(req.body?.email);
const user = await verifyCredentials(email, req.body?.password);
if (!user) {
return res.status(401).render('auth/login', { title: 'Log in', email, error: 'Email or password is incorrect.' });
}
const returnTo = safeReturnTo(req.session.returnTo);
await startSession(req, user.id);
res.redirect(303, returnTo);
});
authRouter.post('/logout', (req, res, next) => {
req.session.destroy((err) => {
if (err) return next(err);
res.clearCookie('caretaker.sid');
res.redirect(303, '/login');
});
});
A route can take several handlers: Express runs loginLimiter first, and it either answers 429 or calls next().
4. Tests
Requests in tests now need a token as well. Update the helpers: an "anonymous agent" visits the login page and keeps its token as a default header; loginAs then logs in and picks up the new token from the next page:
export function csrfTokenFrom(html) { const match = html.match(/<meta name="csrf-token" content="([^"]+)">/); if (!match) { throw new Error('No CSRF token on the page'); } return match[1];} // An agent that has visited the login page and sends its CSRF token on every request.export async function anonymousAgent() { const agent = request.agent(app); const page = await agent.get('/login'); agent.set('X-CSRF-Token', csrfTokenFrom(page.text)); return agent;} // Returns a Supertest agent (it keeps cookies) that is logged in as e.g. 'alice'.export async function loginAs(name, password = SEED_PASSWORD) { const agent = request.agent(app); const agent = await anonymousAgent(); const res = await agent.post('/login').type('form').send({ email: `${name}@example.test`, password }); if (res.status !== 303) { throw new Error(`Login as ${name} failed with status ${res.status}`); } // Login regenerated the session, so the token changed. Read the new one. const home = await agent.get('/'); agent.set('X-CSRF-Token', csrfTokenFrom(home.text)); return agent;}
Show the whole test/helpers.js after this change
import request from 'supertest';import { app } from '../src/app.js';import { pool } from '../src/db.js';import { config } from '../src/config.js';import { migrate } from '../src/migrate.js';import { seed, SEED_PASSWORD } from '../src/seed.js'; export function csrfTokenFrom(html) { const match = html.match(/<meta name="csrf-token" content="([^"]+)">/); if (!match) { throw new Error('No CSRF token on the page'); } return match[1];} // An agent that has visited the login page and sends its CSRF token on every request.export async function anonymousAgent() { const agent = request.agent(app); const page = await agent.get('/login'); agent.set('X-CSRF-Token', csrfTokenFrom(page.text)); return agent;} // Returns a Supertest agent (it keeps cookies) that is logged in as e.g. 'alice'.export async function loginAs(name, password = SEED_PASSWORD) { const agent = await anonymousAgent(); const res = await agent.post('/login').type('form').send({ email: `${name}@example.test`, password }); if (res.status !== 303) { throw new Error(`Login as ${name} failed with status ${res.status}`); } // Login regenerated the session, so the token changed. Read the new one. const home = await agent.get('/'); agent.set('X-CSRF-Token', csrfTokenFrom(home.text)); return agent;} export async function resetDatabase() { if (!config.databaseUrl.endsWith('/caretaker_test')) { throw new Error(`Refusing to reset ${config.databaseUrl}: tests only run against caretaker_test.`); } await migrate(config.databaseUrl, { log: () => {} }); const client = await pool.connect(); try { await seed(client); } finally { client.release(); }}import request from 'supertest';
import { app } from '../src/app.js';
import { pool } from '../src/db.js';
import { config } from '../src/config.js';
import { migrate } from '../src/migrate.js';
import { seed, SEED_PASSWORD } from '../src/seed.js';
export function csrfTokenFrom(html) {
const match = html.match(/<meta name="csrf-token" content="([^"]+)">/);
if (!match) {
throw new Error('No CSRF token on the page');
}
return match[1];
}
// An agent that has visited the login page and sends its CSRF token on every request.
export async function anonymousAgent() {
const agent = request.agent(app);
const page = await agent.get('/login');
agent.set('X-CSRF-Token', csrfTokenFrom(page.text));
return agent;
}
// Returns a Supertest agent (it keeps cookies) that is logged in as e.g. 'alice'.
export async function loginAs(name, password = SEED_PASSWORD) {
const agent = await anonymousAgent();
const res = await agent.post('/login').type('form').send({ email: `${name}@example.test`, password });
if (res.status !== 303) {
throw new Error(`Login as ${name} failed with status ${res.status}`);
}
// Login regenerated the session, so the token changed. Read the new one.
const home = await agent.get('/');
agent.set('X-CSRF-Token', csrfTokenFrom(home.text));
return agent;
}
export async function resetDatabase() {
if (!config.databaseUrl.endsWith('/caretaker_test')) {
throw new Error(`Refusing to reset ${config.databaseUrl}: tests only run against caretaker_test.`);
}
await migrate(config.databaseUrl, { log: () => {} });
const client = await pool.connect();
try {
await seed(client);
} finally {
client.release();
}
}
The two authentication test files post to /login directly, without a token. Replace them; the changed lines use anonymousAgent():
import { test, before, after } from 'node:test';import assert from 'node:assert/strict';import { app } from '../src/app.js';import { pool } from '../src/db.js';import { resetDatabase, anonymousAgent } from './helpers.js'; before(resetDatabase);after(() => pool.end()); test('a correct login creates a session and shows the user', async () => { const agent = await anonymousAgent(); const res = await agent.post('/login').type('form').send({ email: 'alice@example.test', password: 'password123' }); assert.equal(res.status, 303); assert.match(res.headers['set-cookie'][0], /^caretaker\.sid=s%3A.+; Path=\/; Expires=.+; HttpOnly; SameSite=Lax$/); const home = await agent.get('/'); assert.match(home.text, /Signed in as <strong>Alice Byrne<\/strong>/);}); test('a wrong password or unknown email gets the same 401', async () => { for (const email of ['alice@example.test', 'mallory@example.test']) { const agent = await anonymousAgent(); const res = await agent.post('/login').type('form').send({ email, password: 'wrong-password' }); assert.equal(res.status, 401); assert.match(res.text, /Email or password is incorrect/); }}); test('registration validates, creates a user, and logs them in', async () => { const agent = await anonymousAgent(); const bad = await agent.post('/register').type('form').send({ name: 'Erin', email: 'not-an-email', password: 'short' }); assert.equal(bad.status, 400); assert.match(bad.text, /Enter a valid email address/); assert.match(bad.text, /Use a password of 10 to 200 characters/); const good = await agent.post('/register').type('form').send({ name: 'Erin Walsh', email: 'Erin@Example.test', password: 'correct horse battery' }); assert.equal(good.status, 303); assert.match((await agent.get('/')).text, /Signed in as <strong>Erin Walsh<\/strong>/); const { rows } = await pool.query("SELECT email FROM users WHERE name = 'Erin Walsh'"); assert.deepEqual(rows, [{ email: 'erin@example.test' }]);}); test('registering an existing email is a field error', async () => { const agent = await anonymousAgent(); const res = await agent.post('/register').type('form').send({ name: 'Alice Again', email: 'alice@example.test', password: 'another long password' }); assert.equal(res.status, 400); assert.match(res.text, /already exists/);}); test('logout destroys the session', async () => { const agent = await anonymousAgent(); await agent.post('/login').type('form').send({ email: 'bob@example.test', password: 'password123' }); const home = await agent.get('/'); agent.set('X-CSRF-Token', home.text.match(/<meta name="csrf-token" content="([^"]+)">/)[1]); await agent.post('/logout'); const after = await agent.get('/'); assert.equal(after.status, 303); assert.equal(after.headers.location, '/login');});import { test, before, after } from 'node:test';import assert from 'node:assert/strict';import request from 'supertest';import { app } from '../src/app.js';import { pool } from '../src/db.js';import { resetDatabase, loginAs, anonymousAgent, csrfTokenFrom } from './helpers.js'; before(resetDatabase);after(() => pool.end()); function sessionId(res) { const cookie = (res.headers['set-cookie'] ?? []).find((c) => c.startsWith('caretaker.sid=')); return cookie ? cookie.split(';')[0] : null;} test('anonymous requests are redirected to the login page', async () => { for (const path of ['/', '/issues', '/issues/101', '/organisations', '/inspections/201', '/buildings/10']) { const res = await request(app).get(path); assert.equal(res.status, 303, path); assert.equal(res.headers.location, '/login', path); }}); test('anonymous writes are refused and change nothing', async () => { const withoutToken = await request(app).post('/issues/101/delete'); assert.equal(withoutToken.status, 403); const agent = await anonymousAgent(); const withToken = await agent.post('/issues/101/delete'); assert.equal(withToken.status, 303); assert.equal(withToken.headers.location, '/login'); const { rowCount } = await pool.query('SELECT 1 FROM issues WHERE id = 101'); assert.equal(rowCount, 1);}); test('login and register pages stay public', async () => { assert.equal((await request(app).get('/login')).status, 200); assert.equal((await request(app).get('/register')).status, 200); assert.equal((await request(app).get('/css/style.css')).status, 200);}); test('login issues a new session id (no session fixation)', async () => { const agent = request.agent(app); await agent.get('/issues'); const page = await agent.get('/login'); const before = sessionId(page) ?? 'cookie set by the first request'; const login = await agent.post('/login').type('form').send({ email: 'alice@example.test', password: 'password123', _csrf: csrfTokenFrom(page.text) }); const afterLogin = sessionId(login); assert.ok(afterLogin); assert.notEqual(afterLogin, before); assert.equal(login.headers.location, '/issues', 'returns to the page the user wanted');}); test('returnTo only follows local paths', async () => { const agent = request.agent(app); await agent.get('//evil.test/phish'); const page = await agent.get('/login'); const login = await agent.post('/login').type('form').send({ email: 'alice@example.test', password: 'password123', _csrf: csrfTokenFrom(page.text) }); assert.equal(login.headers.location, '/');}); test('new issues and transitions record the logged-in user', async () => { const dave = await loginAs('dave'); const res = await dave.post('/issues').type('form').send({ title: 'Loose handrail on stairs', building_id: '20', priority: 'medium', occurred_at: '2026-11-21T08:00', reported_by: '1' }); const id = Number(res.headers.location.split('/').pop()); const { rows } = await pool.query('SELECT reported_by FROM issues WHERE id = $1', [id]); assert.equal(rows[0].reported_by, 4, 'reported_by comes from the session, not the form'); await dave.post('/inspections/203/submit'); const history = await pool.query("SELECT changed_by FROM inspection_status_changes WHERE inspection_id = 203 AND to_status = 'submitted'"); assert.equal(history.rows[0].changed_by, 4);}); test('the session cookie has the attributes we chose', async () => { const agent = await anonymousAgent(); const res = await agent.post('/login').type('form').send({ email: 'alice@example.test', password: 'password123' }); const cookie = res.headers['set-cookie'].find((c) => c.startsWith('caretaker.sid=')); assert.match(cookie, /HttpOnly/); assert.match(cookie, /SameSite=Lax/); assert.match(cookie, /Expires=/); assert.doesNotMatch(cookie, /Secure/, 'not Secure in tests: they use plain HTTP');});New tests for the CSRF rule itself:
import { test, before, after } from 'node:test';import assert from 'node:assert/strict';import { app } from '../src/app.js';import { pool } from '../src/db.js';import { resetDatabase, loginAs } from './helpers.js'; let alice;before(async () => { await resetDatabase(); alice = await loginAs('alice');});after(() => pool.end()); test('a logged-in POST without a token is refused with 403', async () => { const res = await alice.post('/issues/130/delete').set('X-CSRF-Token', ''); assert.equal(res.status, 403); assert.match(res.text, /did not come from Caretaker/); assert.equal((await pool.query('SELECT 1 FROM issues WHERE id = 130')).rowCount, 1);}); test('a token from another session is refused', async () => { const bob = await loginAs('bob'); const bobToken = bob._defaults.find((d) => d.fn === 'set' && d.args[0] === 'X-CSRF-Token').args[1]; const res = await alice.post('/issues/130/delete').set('X-CSRF-Token', bobToken); assert.equal(res.status, 403);}); test('the right token in the form field works', async () => { const page = await alice.get('/issues/130'); const token = page.text.match(/name="_csrf" value="([^"]+)"/)[1]; const res = await alice.post('/issues/130/delete').set('X-CSRF-Token', '').type('form').send({ _csrf: token }); assert.equal(res.status, 303);}); test('every POST form on every page carries the token', async () => { const pages = ['/', '/issues/new', '/issues/101', '/issues/101/edit', '/organisations/1', '/organisations/new', '/buildings/10', '/buildings/10/edit', '/inspections/new', '/inspections/201', '/inspections/203']; for (const path of pages) { const html = (await alice.get(path)).text; const forms = (html.match(/<form method="post"/g) ?? []).length; const tokens = (html.match(/<form method="post"[^>]*><input type="hidden" name="_csrf" value="[^"]+">/g) ?? []).length; assert.ok(forms > 0, `${path} has a POST form`); assert.equal(tokens, forms, `${path}: every POST form has a token`); }});bob._defaults is Supertest's internal list of default headers; we read it only to borrow Bob's token for the test.
import { test, before, after } from 'node:test';import assert from 'node:assert/strict';import { app } from '../src/app.js';import { pool } from '../src/db.js';import { resetDatabase, anonymousAgent } from './helpers.js'; before(resetDatabase);after(() => pool.end()); test('failed logins are limited per client; the limit then blocks even correct passwords', async () => { const agent = await anonymousAgent(); for (let i = 1; i <= 5; i++) { const res = await agent.post('/login').type('form').send({ email: 'alice@example.test', password: `guess-${i}` }); assert.equal(res.status, 401, `attempt ${i}`); } const blocked = await agent.post('/login').type('form').send({ email: 'alice@example.test', password: 'guess-6' }); assert.equal(blocked.status, 429); assert.match(blocked.headers.ratelimit, /r=0/, 'no requests remaining'); const correct = await agent.post('/login').type('form').send({ email: 'alice@example.test', password: 'password123' }); assert.equal(correct.status, 429);});Run and inspect
npm test
> caretaker@1.0.0 test
> node --env-file=.env.test --test --test-concurrency=1 --test-reporter=spec "test/**/*.test.js"
✔ a correct login creates a session and shows the user (264.596958ms)
✔ a wrong password or unknown email gets the same 401 (52.560875ms)
✔ registration validates, creates a user, and logs them in (40.141958ms)
✔ registering an existing email is a field error (30.409291ms)
✔ logout destroys the session (50.249ms)
✔ a building can be created inside an organisation (258.003875ms)
✔ a duplicate building name in the same organisation is a field error (4.685417ms)
✔ the same building name is allowed in another organisation (3.422583ms)
✔ a building with issues cannot be deleted (11.44525ms)
✔ an empty building can be deleted (8.829209ms)
✔ an organisation with buildings cannot be deleted, an empty one can (10.955667ms)
✔ a logged-in POST without a token is refused with 403 (257.201042ms)
✔ a token from another session is refused (36.242875ms)
✔ the right token in the form field works (7.101791ms)
✔ every POST form on every page carries the token (33.739958ms)
✔ the dashboard counts match the database (266.741875ms)
✔ every building appears with its organisation (5.412916ms)
✔ create a draft, edit it, submit it, approve it (273.05075ms)
✔ invalid transitions are refused with 409 and change nothing (9.779833ms)
✔ only drafts can be edited (5.558625ms)
✔ returning a submitted inspection makes it editable again (6.080875ms)
✔ concurrent approvals: exactly one wins (19.25025ms)
✔ unknown actions are 404 (4.70375ms)
✔ the list pages 10 at a time and reports the total (260.020834ms)
✔ pages do not overlap (13.652958ms)
✔ filters combine with AND (4.88225ms)
✔ sorting by priority puts critical first when descending (4.170834ms)
✔ unknown sort keys and SQL in the query string are ignored (22.610209ms)
✔ GET /issues lists issues from the database (238.9435ms)
✔ GET /issues/101 shows one issue with its building (3.627917ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (10.214583ms)
✔ POST /issues re-renders the form with errors (4.572584ms)
✔ POST /issues stores the issue and redirects to it (6.035792ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (4.822167ms)
✔ the stored row has the cleaned values and ignores a client-sent status (3.711417ms)
✔ an issue time in the future is rejected (3.074083ms)
Show 24 more lines
✔ GET /issues/101/edit shows the current values (3.155333ms)
✔ POST /issues/:id/edit changes the status and updated_at (3.348458ms)
✔ POST /issues/:id/delete removes the issue (7.100959ms)
✔ GET /organisations lists organisations with building counts (255.732417ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (4.097666ms)
✔ POST /organisations validates and creates (8.79275ms)
✔ POST /organisations/:id/edit renames the organisation (7.001791ms)
✔ unknown organisations are 404 (5.884209ms)
✔ failed logins are limited per client; the limit then blocks even correct passwords (341.136292ms)
✔ anonymous requests are redirected to the login page (212.077083ms)
✔ anonymous writes are refused and change nothing (10.332916ms)
✔ login and register pages stay public (5.184916ms)
✔ login issues a new session id (no session fixation) (32.055625ms)
✔ returnTo only follows local paths (31.952959ms)
✔ new issues and transitions record the logged-in user (65.6025ms)
✔ the session cookie has the attributes we chose (28.0015ms)
ℹ tests 52
ℹ suites 0
ℹ pass 52
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 4633.777042
Re-seed the development data and restart:
npm run db:seed
> caretaker@1.0.0 db:seed
> node --env-file=.env scripts/seed.js
seeded the Caretaker scenario
npm run dev
> caretaker@1.0.0 dev
> node --env-file=.env --watch src/server.js
Caretaker listening on http://localhost:3000
The forged request from the start of the lesson, now:
rm -f /tmp/alice.txt
TOKEN=$(curl -s -c /tmp/alice.txt http://localhost:3000/login | sed -n 's/.*name="csrf-token" content="\([^"]*\)".*/\1/p')
curl -s -b /tmp/alice.txt -c /tmp/alice.txt -o /dev/null http://localhost:3000/login -d _csrf=$TOKEN -d email=alice@example.test -d password=password123
curl -si -b /tmp/alice.txt -H "Origin: http://localhost:4000" -X POST http://localhost:3000/issues/130/delete | head -1
HTTP/1.1 403 Forbidden
Read the four lines. The first starts with an empty cookie jar. The second fetches the login page and copies the token out of its <meta> tag, the way a form on that page would carry it. The third logs in with the token. The fourth is the evil page's request: Alice's cookie is attached, but the page could not know her token, so the server refuses with 403.
And the guessing loop, with the development limit of 10. Each attempt carries a valid token, so it reaches the limiter:
TOKEN=$(curl -s -c /tmp/guess.txt http://localhost:3000/login | sed -n 's/.*name="csrf-token" content="\([^"]*\)".*/\1/p')
for i in $(seq 12); do curl -s -o /dev/null -w "%{http_code}\n" -b /tmp/guess.txt http://localhost:3000/login -d _csrf=$TOKEN -d email=alice@example.test -d password=guess$i; done | uniq -c
10 401
2 429
Ten 401s, then 429. Restart the server to reset the in-memory counter (the dev server restarts by itself when you save a file):
Experiment
Authentication is now solid. So log in as Nora: she registered, but no organisation has ever given her access to anything.
npm run dev
> caretaker@1.0.0 dev
> node --env-file=.env --watch src/server.js
Caretaker listening on http://localhost:3000

TOKEN=$(curl -s -c /tmp/nora.txt http://localhost:3000/login | sed -n 's/.*name="csrf-token" content="\([^"]*\)".*/\1/p')
curl -s -b /tmp/nora.txt -c /tmp/nora.txt -o /dev/null http://localhost:3000/login -d _csrf=$TOKEN -d email=nora@example.test -d password=password123
curl -s -b /tmp/nora.txt http://localhost:3000/issues/105 | grep -E "<h1>|Signed in"
<span>Signed in as <strong>Nora Quinn</strong></span>
<h1>Boiler lost pressure in plant room</h1>
Reveal Authentication versus authorization
Everything. Our server knows with confidence who Nora is: that is authentication (AuthN), and Module 4 built it carefully. It has no idea what Nora may do: that is authorization (AuthZ). So far the answer is "anything a logged-in user can reach". Being logged in is necessary, but it is not a permission.
Also notice what we can trust now. req.user.id came from a server-side session created after a correct password; it is trustworthy. Everything else in the request (the issue ID in the URL, the building_id in a form, any header) is still chosen by the client. Module 5 decides permissions from req.user plus data loaded from our own database, never from the request.
Checkpoint
npm test
> caretaker@1.0.0 test
> node --env-file=.env.test --test --test-concurrency=1 --test-reporter=spec "test/**/*.test.js"
✔ a correct login creates a session and shows the user (258.573375ms)
✔ a wrong password or unknown email gets the same 401 (55.218667ms)
✔ registration validates, creates a user, and logs them in (38.181334ms)
✔ registering an existing email is a field error (26.506375ms)
✔ logout destroys the session (38.970208ms)
✔ a building can be created inside an organisation (265.0455ms)
✔ a duplicate building name in the same organisation is a field error (4.850333ms)
✔ the same building name is allowed in another organisation (3.604125ms)
✔ a building with issues cannot be deleted (12.394083ms)
✔ an empty building can be deleted (9.044416ms)
✔ an organisation with buildings cannot be deleted, an empty one can (11.689084ms)
✔ a logged-in POST without a token is refused with 403 (275.542292ms)
✔ a token from another session is refused (39.708083ms)
✔ the right token in the form field works (7.79375ms)
✔ every POST form on every page carries the token (33.071958ms)
✔ the dashboard counts match the database (255.699292ms)
✔ every building appears with its organisation (4.697792ms)
✔ create a draft, edit it, submit it, approve it (263.508ms)
✔ invalid transitions are refused with 409 and change nothing (9.53575ms)
✔ only drafts can be edited (4.738208ms)
✔ returning a submitted inspection makes it editable again (6.587667ms)
✔ concurrent approvals: exactly one wins (18.707541ms)
✔ unknown actions are 404 (3.055542ms)
✔ the list pages 10 at a time and reports the total (261.032959ms)
✔ pages do not overlap (13.615292ms)
✔ filters combine with AND (5.021416ms)
✔ sorting by priority puts critical first when descending (4.396167ms)
✔ unknown sort keys and SQL in the query string are ignored (23.074542ms)
✔ GET /issues lists issues from the database (253.635709ms)
✔ GET /issues/101 shows one issue with its building (4.129ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (10.690292ms)
✔ POST /issues re-renders the form with errors (5.18375ms)
✔ POST /issues stores the issue and redirects to it (6.426ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (5.178375ms)
✔ the stored row has the cleaned values and ignores a client-sent status (3.813333ms)
✔ an issue time in the future is rejected (2.960375ms)
Show 24 more lines
✔ GET /issues/101/edit shows the current values (3.199583ms)
✔ POST /issues/:id/edit changes the status and updated_at (3.437083ms)
✔ POST /issues/:id/delete removes the issue (6.726792ms)
✔ GET /organisations lists organisations with building counts (242.181292ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (3.970584ms)
✔ POST /organisations validates and creates (8.087458ms)
✔ POST /organisations/:id/edit renames the organisation (7.261833ms)
✔ unknown organisations are 404 (5.626292ms)
✔ failed logins are limited per client; the limit then blocks even correct passwords (369.819209ms)
✔ anonymous requests are redirected to the login page (205.296125ms)
✔ anonymous writes are refused and change nothing (10.854125ms)
✔ login and register pages stay public (5.616667ms)
✔ login issues a new session id (no session fixation) (32.608ms)
✔ returnTo only follows local paths (31.183541ms)
✔ new issues and transitions record the logged-in user (68.694625ms)
✔ the session cookie has the attributes we chose (28.753125ms)
ℹ tests 52
ℹ suites 0
ℹ pass 52
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 4653.995208
git add -A
git commit -m "CSRF tokens and login throttling"
[main b867229] CSRF tokens and login throttling
25 files changed, 213 insertions(+), 37 deletions(-)
create mode 100644 src/middleware/csrf.js
create mode 100644 src/middleware/rate-limit.js
create mode 100644 test/csrf.test.js
create mode 100644 test/rate-limit.test.js
Symptom Every form submit now shows "This form has expired"
The form is missing the hidden _csrf input, or the page was rendered before you logged in (the token changes at login). Reload the page and submit again. test/csrf.test.js lists the pages it checks.
Symptom Tests fail with No CSRF token on the page
views/partials/head.ejs lacks the <meta name="csrf-token"> tag.
Symptom 429 in the browser while developing
You hit the limit while testing. Restart the dev server to clear the in-memory counters.
Recap and next step
Every state-changing request now proves it came from one of our own pages, with a per-session token compared in constant time. Failed logins are limited per client. Module 4 is complete: hashed passwords, server-side sessions, regeneration at login, deliberate cookie attributes, CSRF tokens, throttling, and identity taken only from the session.
And Nora showed us the gap. Module 5 answers "may this user do this?", first with ordinary JavaScript, so that we can feel exactly where it starts to hurt.
Open the checkpoint files for lesson 4.4 (separate page; only files from this lesson and earlier)