Chapter 14

The server

server/server.ts is a single-file Node server with no runtime dependencies. In dev it embeds Vite (one port, hot reload); in production it serves dist/.

14.1 Endpoints#

Method and path Purpose
GET /api/session Creates or refreshes the session cookie. Returns { csrfToken, encryption: { alg, kid, spki, challenge } }.
POST /api/register Registration (sample). Responds 201, 400, 403, 409, 413, 415, 422 or 429; every reply includes the next challenge.
POST /api/otp/send Generates a 6-digit code (CSPRNG) for the session and stores only an HMAC of it, valid 5 minutes. Dev mode prints the code in the server console in place of an SMS. 3/min per IP.
POST /api/otp/verify { code }. Constant-time check; 5 wrong attempts burn the code; single use; 10/min per IP. Wrong codes return fieldErrors.code with the attempts left.
GET /api/health Liveness check

14.2 What every request goes through#

  1. Security headers (strict CSP, nosniff, DENY framing, no-referrer, COOP/CORP, Permissions-Policy).
  2. Host allow-list (DNS-rebinding defence): localhost, 127.0.0.1, [::1], plus EXTRA_ALLOWED_HOSTS.
  3. Global per-IP rate limit: 120 requests/minute.

State-changing endpoints additionally check:

  1. Origin equals the host, and Sec-Fetch-Site (when sent) is same-origin.
  2. Content-Type: application/json; body ≤ 16 KB (checked both by declared length and while streaming).
  3. Session cookie (HttpOnly; SameSite=Strict, 30-minute idle expiry) and a matching X-CSRF-Token (HMAC of the session id, compared in constant time).
  4. Route rate limit: 5/minute per IP, then exponential lockout (1 min, doubling, max 30 min).
  5. Single-use challenge consumed; PFE1 decryption of secret fields.
  6. validatePayload(): unknown fields, wrong types and __proto__ keys are rejected.

Timeouts: 10 s for headers, 15 s per request. Error responses never echo submitted values.

14.3 Password storage#

hashPassword(bytes) computes HMAC-SHA256(pepper, password), then scrypt N=2¹⁷, r=8, p=1 with a 16-byte salt, stored as scrypt$v1$N$r$p$salt$hash. verifyPassword(bytes, stored) compares in constant time and reads the parameters from the stored string, so you can raise the cost later without breaking old hashes. Expect about 0.5–1 s per hash. That's intentional, and the route rate limits stop it being abused.

14.4 Adding an endpoint: sign-in#

Add this inside handleApi in server/server.ts. It reuses the same building blocks as /api/register:

if (path === '/api/login' && req.method === 'POST') {
  if (!sameOrigin(req)) return json(res, 403, { ok: false, message: 'Cross-origin request blocked.' });
  const current = getSession(req);
  const token = req.headers['x-csrf-token'];
  if (!current || typeof token !== 'string' || !safeEqual(token, csrfFor(current.sid))) {
    return json(res, 403, { ok: false, message: 'Your session expired. Please reload the page.' });
  }
  const challenge = current.session.challenge;
  current.session.challenge = newChallenge();                        // single use
  const reply = (s: number, b: Record<string, unknown>) => json(res, s, { ...b, challenge: current.session.challenge });

  const limit = rateLimit(`login:${clientIp(req)}`, 10, 60_000);
  if (!limit.ok) return reply(429, { ok: false, message: `Too many attempts. Try again in ${limit.retryAfter}s.` });

  let body: { email?: unknown; password?: unknown };
  try { body = JSON.parse(await readBody(req)); } catch { return reply(400, { ok: false, message: 'Malformed JSON.' }); }

  let pw: Buffer;
  try { pw = openEnvelope(body.password, pfe.byKid, `${challenge}|password`); }
  catch { return reply(400, { ok: false, message: 'Please type your password again.' }); }

  try {
    const user = typeof body.email === 'string' ? users.get(body.email.toLowerCase()) : undefined;
    // Always run the hash so response timing doesn't reveal whether the email exists.
    const ok = user ? await verifyPassword(pw, user.passwordHash) : (await hashPassword(pw), false);
    if (!ok) return reply(401, { ok: false, message: 'Email or password is incorrect.' });
    // Rotate the session id on login (prevents session fixation), then set auth state.
    return reply(200, { ok: true, message: `Welcome back, ${user!.username}!` });
  } finally {
    pw.fill(0);
  }
}

14.5 Sending real codes#

Replace the console.log in /api/otp/send with your SMS or email provider. For Android WebOTP, end the SMS with @your.domain #123456 on its own line. Set OTP_DEV_LOG=1 only for local testing of a production build. State-changing endpoints share guardStateChange(req, res) (POST, same origin, JSON, session + CSRF); use it for your own endpoints too.

14.6 Replacing the in-memory store#

users is a Map for demonstration. Swap it for your database and keep these properties: