Labs · Lab
Lab C — only a fare officer may change a fare
Hash a password properly, sign someone in with a session cookie, and put the write endpoint behind it — while reading stays open to everyone.
In this lab
- Hashing a password with a salt, and comparing it safely
- Keeping a session, and what the cookie actually holds
- Guarding one endpoint while the rest stays public
Right now anyone who can reach your server can change what a trip costs. Lab B made that possible; this lab makes it accountable.
Three separate problems hide inside “add a login”, and they are worth naming before you write anything:
- A password must never be stored. Not encrypted — not stored.
- The browser has to prove who it is on every request, without carrying the password around.
- Only some requests need that proof. Reading a fare stays public: a parent at a car park should never meet a login screen.
Catch up
git checkout checkpoint/lab-b-done
npm run reset
Steps
1. Hash passwords. Create api/auth/password.js with two functions,
using Node’s built-in crypto — no library needed:
import { scrypt, randomBytes, timingSafeEqual } from 'node:crypto';
import { promisify } from 'node:util';
const scryptAsync = promisify(scrypt);
const KEY_LENGTH = 64;
export async function hashPassword(plain) {
const salt = randomBytes(16).toString('hex');
const derived = await scryptAsync(plain, salt, KEY_LENGTH);
return `${salt}:${derived.toString('hex')}`;
}
scrypt is deliberately slow and memory-hungry, which is what makes guessing
expensive. The random salt means two people who pick the same password still
get different rows, so cracking one tells you nothing about the other.
Write verifyPassword(plain, stored) yourself: split off the salt, hash the
attempt with it, and compare. Compare with timingSafeEqual, not ===.
A normal comparison returns faster when the first byte is wrong, and that
difference is enough to guess a hash one byte at a time.
2. Make a fare officer. Write prisma/create-user.js that hashes a
password and upserts a user, then run it:
node prisma/create-user.js
Fare officer ready: bursar (role: fare_officer)
The database stores only the hash:
9a3e015040aedcd597d0ca8af8e7ed7a:0f5c5326de608cb…
Go and look at the row yourself. This is the point of the whole step:
psql -d passo_fares -c "select username, password_hash from users;"
Nothing in that column can be turned back into passo2026. If your database
leaks tomorrow, the passwords do not leak with it.
3. Keep the sessions. Create api/auth/session.js holding a Map of
session id → user, and four helpers: createSession(user), which stores the
user against a randomUUID() and returns that id; setSessionCookie(res, id);
readSession(req); and destroySession(req).
Setting the cookie is its own function because logging in is the only place that does it, and the cookie carries a random id and nothing else:
export function setSessionCookie(res, id) {
res.cookie(COOKIE, id, {
httpOnly: true,
sameSite: 'lax',
path: '/',
maxAge: 1000 * 60 * 60 * 8,
});
}
httpOnly keeps JavaScript on the page from reading it, so a script injected
into your site cannot steal the session. Everything the server knows about the
user stays on the server — a cookie someone edits by hand simply matches
nothing.
4. Write the three endpoints in api/routes/auth.js: POST /api/login,
POST /api/logout, GET /api/me. Mount them in api/app.js.
One thing to get right in login — the highlighted lines:
router.post('/login', async (req, res) => {
const { username, password } = req.body ?? {};
const user = await db.user.findUnique({
where: { username: String(username) },
});
const ok = user && (await verifyPassword(String(password), user.passwordHash));
if (!ok) {
return res.status(401).json({ error: 'Wrong username or password' });
}
// TODO: make a session, set the cookie, answer with the username and role
});
The same message whether the username exists or not. Two different messages would hand an attacker a free list of real usernames.
Note what ok does when there is no such user: user is null, the &&
stops there, and verifyPassword is never called. That is a small timing leak
— a wrong username answers faster than a wrong password — and worth naming
when you teach it.
5. Guard the write. Add a requireLogin middleware to session.js that
answers 401 when there is no session, then put it in front of the POST —
and only the POST. One word changes; the handler body from Lab B stays exactly
as it was:
router.post('/', requireLogin, async (req, res) => {
// ... the validation and the create you wrote in Lab B, unchanged
});
Checkpoint
Run these in order. The cookie jar is what a browser does for you.
curl -X POST localhost:3000/api/fares -H 'Content-Type: application/json' \
-d '{"from":1,"to":8,"amountDalasi":55,"source":"test"}'
{"error":"Sign in to do that"}
Wrong password, 401:
{"error":"Wrong username or password"}
Right password, 200, and the cookie is saved:
curl -c jar.txt -X POST localhost:3000/api/login -H 'Content-Type: application/json' \
-d '{"username":"bursar","password":"passo2026"}'
{"username":"bursar","role":"fare_officer"}
Now the same POST that failed a minute ago, with -b jar.txt, returns
201:
{"id":41,"from":"Westfield","to":"Brikama","amountDalasi":55,"effectiveFrom":"2026-11-20T00:00:00.000Z","source":"test","status":"verified"}
Your effectiveFrom will be whatever today is: the body never sent one, and
Lab B’s validator defaults it to now.
Log out — 204 — and try once more. Back to 401.
And the thing that must not have broken:
curl "localhost:3000/api/fares?from=1&to=8"
200, no cookie needed. Reading is still public. If that returns 401 you have guarded the router rather than the POST.
If it breaks
Login works but the next request is 401 — the cookie is not coming back.
With curl you need -c jar.txt to save it and -b jar.txt to send it.
401 on everything, even with a good cookie — the server restarted. The sessions live in memory, so a restart signs everyone out. Log in again.
verifyPassword always returns false — you hashed with a new random salt
instead of the one stored alongside the hash.
“data and hash must be the same length” — timingSafeEqual throws rather
than returning false when lengths differ. Check the lengths first.
Reading now asks for a login — requireLogin went on the router instead
of the POST handler.
The finished files
Three new files, as they stand on checkpoint/lab-c-done. The one-line
change to api/routes/fares.js is in step 5 above, and api/app.js gains
exactly two: an import and app.use('/api', auth).
Note what is not there: no cookie-parsing library. res.cookie() is
Express’s own, and reading one back is the dozen lines of cookieValue in
session.js — worth seeing once before you reach for a dependency.
import { scrypt, randomBytes, timingSafeEqual } from 'node:crypto';
import { promisify } from 'node:util';
const scryptAsync = promisify(scrypt);
const KEY_LENGTH = 64;
// A password is never stored. What is stored is the result of a slow,
// one-way function, plus the random salt that made it unique.
export async function hashPassword(plain) {
const salt = randomBytes(16).toString('hex');
const derived = await scryptAsync(plain, salt, KEY_LENGTH);
return `${salt}:${derived.toString('hex')}`;
}
export async function verifyPassword(plain, stored) {
const [salt, hash] = String(stored).split(':');
if (!salt || !hash) return false;
const expected = Buffer.from(hash, 'hex');
const derived = await scryptAsync(plain, salt, KEY_LENGTH);
if (expected.length !== derived.length) return false;
// Compare in constant time. A normal === returns faster on an early
// mismatch, and that difference is enough to guess a hash byte by byte.
return timingSafeEqual(expected, derived);
}
import { randomUUID } from 'node:crypto';
// Sessions live in this process's memory. Restart the server and everyone is
// signed out. That is fine for a workshop and wrong for production, where
// this belongs in Redis or a sessions table.
const sessions = new Map();
export const COOKIE = 'passo_session';
export function createSession(user) {
const id = randomUUID();
sessions.set(id, { userId: user.id, username: user.username, role: user.role });
return id;
}
function cookieValue(req) {
const header = req.headers.cookie ?? '';
const match = header
.split(';')
.map((part) => part.trim())
.find((part) => part.startsWith(`${COOKIE}=`));
return match ? match.slice(COOKIE.length + 1) : null;
}
export function readSession(req) {
const id = cookieValue(req);
return id ? (sessions.get(id) ?? null) : null;
}
export function destroySession(req) {
const id = cookieValue(req);
if (id) sessions.delete(id);
}
// The cookie holds a random id and nothing else. Everything the server knows
// about you stays on the server, so a tampered cookie just fails to match.
export function setSessionCookie(res, id) {
res.cookie(COOKIE, id, {
httpOnly: true,
sameSite: 'lax',
path: '/',
maxAge: 1000 * 60 * 60 * 8,
});
}
export function requireLogin(req, res, next) {
const session = readSession(req);
if (!session) {
return res.status(401).json({ error: 'Sign in to do that' });
}
req.user = session;
next();
}
import { Router } from 'express';
import { db } from '../db.js';
import { verifyPassword } from '../auth/password.js';
import {
createSession,
destroySession,
readSession,
setSessionCookie,
COOKIE,
} from '../auth/session.js';
const router = Router();
router.post('/login', async (req, res) => {
const { username, password } = req.body ?? {};
if (!username || !password) {
return res.status(400).json({ error: 'username and password are required' });
}
const user = await db.user.findUnique({ where: { username: String(username) } });
// One message for "no such user" and for "wrong password". Telling them
// apart hands an attacker a list of real usernames for free.
const ok = user && (await verifyPassword(String(password), user.passwordHash));
if (!ok) {
return res.status(401).json({ error: 'Wrong username or password' });
}
setSessionCookie(res, createSession(user));
res.json({ username: user.username, role: user.role });
});
router.post('/logout', (req, res) => {
destroySession(req);
res.clearCookie(COOKIE, { path: '/' });
res.status(204).end();
});
router.get('/me', (req, res) => {
const session = readSession(req);
if (!session) {
return res.status(401).json({ error: 'Not signed in' });
}
res.json({ username: session.username, role: session.role });
});
export default router;
Stretch
- Check the role, not just the login.
requireLoginproves who you are. AddrequireRole('fare_officer')for what you may do, and think about which endpoints each one belongs on. - Add the login form to
web/. Sign in from the page, then show the add-a-fare form only whenGET /api/mesucceeds.
This is not production
Say this part out loud when you teach it. The session store is a Map in one
process: it dies on restart, and it cannot be shared by two servers. In
production it belongs in Redis or a sessions table, the cookie needs
secure: true behind HTTPS, and logins need rate limiting — otherwise the
slow hash you just wrote is the only thing standing between an attacker and
unlimited guesses.
Everything else here — the hashing, the salt, the constant-time compare, the opaque cookie, the single error message — is production-shaped already.
For trainers
- Where would your students get stuck first?
- What would you cut if you had twenty-five minutes instead of forty?
- What would you add that is missing here?