irfan@backend:~/portfolio
Email me
← cd ../blog

Security / Node.js / Backend / Beginner

Backend Security from Zero: one shop API, from first login to its first attack

A beginner guide to backend security in Node.js: passwords, sessions, resets, IDOR, injection, CSRF, SSRF and race conditions, on one shop API.

On this page
  1. Setup: helpers every route uses
  2. The trust boundary mindset
  3. Passwords: slow on purpose
  4. Sessions and JWTs
  5. Sessions done right
  6. JWTs done right
  7. Brute force: a limit that can't be raced
  8. Password reset
  9. IDOR and mass assignment
  10. Put the owner in the WHERE clause
  11. Mass assignment: the user picks the columns
  12. SQL and command injection
  13. Parameters for every value
  14. Commands without a shell
  15. CORS and CSRF
  16. CORS: an exact list
  17. CSRF: SameSite plus a cross-site check
  18. SSRF: your server fetches a URL
  19. Why a simple IP check fails
  20. Check the address you connect to
  21. Race conditions and idempotency
  22. One statement checks and writes
  23. Idempotency keys for retries
  24. Recap

You run a small shop API. Alice and Bob are customers. Mallory wants their accounts, their orders and your server. Each chapter is one of her attacks, and the code that stops it.

After this post you can:

  • store passwords, sessions and reset links safely
  • check the owner in every query, and keep input out of SQL and shell commands
  • stop attacks that come from other websites, from your own server, and from two requests landing at once

The code uses Node.js 24, TypeScript, Express 5 and Postgres. Each chapter names its category in the OWASP Top 10:2025, a nonprofit's list of the most common web app risks.

Setup: helpers every route uses#

Errors use RFC 9457 problem details, an internet standard for the JSON shape of API errors.

Routes in this post throw an error on bad input. In Express 4, an error thrown in an async handler became an unhandled rejection (a failed promise nobody catches): the request hung or Node crashed. Express 5 passes it to your error handler, which decides what the client sees:

error-handler
  1. A route gets bad input and throws a ZodError.
  2. The handler answers 400 with the list of bad fields.
  3. Another route throws a database error.
  4. The handler logs the full error under a new requestId.
  5. The client gets only a 500 and the requestId. No stack trace.
step 1 / 5
The client learns what to fix, never how your code works inside.
// errors.ts (key lines)
if (err instanceof ZodError) {
  return problem(res, 400, 'The request is not valid.', {
    errors: err.issues.map((i) => ({ path: i.path.join('.'), message: i.message })),
  });
}
if (e.expose && e.status && e.status < 500) return problem(res, e.status); // bad JSON (400), too big (413)
// ...
problem(res, 500, 'Something went wrong.', { requestId }); // no stack trace
  • ZodError comes from zod, a library that checks data against a schema (the exact shape you accept). parse() returns clean data or throws a ZodError.
  • The body parser is the Express code that reads the JSON body. It sets expose on its errors that are safe to show, like bad JSON.
  • Any other error is logged with a requestId. Support finds the full error in the logs by that id.
Show full code: db.ts, problem.ts, errors.ts, auth.ts
// db.ts: one shared Postgres connection pool (the pg driver)
import pg from 'pg';
export const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });

// problem.ts: every error is RFC 9457 problem details (application/problem+json)
import { STATUS_CODES } from 'node:http';
import type { Response } from 'express';

export function problem(res: Response, status: number, detail?: string, extra?: object) {
  res.status(status).type('application/problem+json').json({
    type: 'about:blank', title: STATUS_CODES[status], status, detail, ...extra,
  });
}
// errors.ts. Register it after all routes: app.use(errorHandler)
import crypto from 'node:crypto';
import type { Request, Response, NextFunction } from 'express';
import { ZodError } from 'zod';
import { problem } from './problem.ts';

export function errorHandler(err: unknown, req: Request, res: Response, _next: NextFunction) {
  if (err instanceof ZodError) {
    return problem(res, 400, 'The request is not valid.', {
      errors: err.issues.map((i) => ({ path: i.path.join('.'), message: i.message })),
    });
  }
  const e = err as { status?: number; expose?: boolean; name?: string; code?: string; message?: string; stack?: string };
  if (e.expose && e.status && e.status < 500) return problem(res, e.status); // bad JSON (400), too big (413)

  const requestId = crypto.randomUUID();
  // Chosen fields only: no "detail", where Postgres puts row values. "message" can still echo
  // input (invalid input syntax for type uuid: "abc"), so keep logs private.
  console.error(JSON.stringify({ requestId, path: req.path, name: e.name, code: e.code, message: e.message, stack: e.stack }));
  problem(res, 500, 'Something went wrong.', { requestId }); // no stack trace
}
// db.ts (add): run several writes as one transaction, so they all happen or none do
export async function inTransaction<T>(fn: (db: pg.PoolClient) => Promise<T>): Promise<T> {
  const client = await pool.connect();
  try {
    await client.query('BEGIN');
    const result = await fn(client);
    await client.query('COMMIT');
    return result;
  } catch (err) {
    await client.query('ROLLBACK');
    throw err;
  } finally {
    client.release();
  }
}

// auth.ts
export function requireLogin(req: Request, res: Response, next: NextFunction) {
  if (!req.session.userId) return problem(res, 401);
  next();
}

The trust boundary mindset#

A trust boundary is the line where data enters from something you don't control. Everything crossing it is untrusted: body, query, headers, cookies, file names, other services. Your own frontend too, since anyone can edit a request.

Each box is its own layer, and each has a chapter. If one fails, the next can still stop the attack (defense in depth).

quick-check

A route in Express 5 throws a ZodError inside an async handler. What does the client get?

Passwords: slow on purpose#

OWASP Top 10:2025: A04 Cryptographic Failures.

Words you need:

  • A hash is a one-way function. Same input, same output, and you can't turn it back.
  • A salt is random bytes added to each password before hashing, so equal passwords get different hashes.

Alice and Bob both pick password123. The shop stores its SHA-256 hash (SHA-256 is a common, very fast hash function). Then the table leaks:

email              password_hash
alice@example.com  ef92b778bafe771e89245b89ecbc08a44a4e166c06659911881f383d4473e94f
bob@example.com    ef92b778bafe771e89245b89ecbc08a44a4e166c06659911881f383d4473e94f
password-leak
  1. The same SHA-256 hash shows up twice.
  2. Mallory takes the hash and hashes guesses, very fast.
  3. One guess matches: password123.
  4. One cracked hash opens both accounts.
step 1 / 4
A salt would give two different hashes. Only a slow hash makes every guess expensive.

In 2012, about 6.5 million LinkedIn password hashes leaked, stored as SHA-1 with no salt. In 2016 about 117 million emails and passwords from the same breach showed up.

A salt fixes the "same hash" problem, not the speed: SHA-256 lets an attacker test a huge number of guesses every second. OWASP's password storage guide says fast hashes like SHA-256 are not for passwords. This matters in any app that stores its own passwords instead of using a login provider like Google sign-in.

A password hash must be slow on purpose and use a lot of memory, so each guess costs real time and hardware. OWASP's first choice is argon2id, with at least 19 MiB of memory (a MiB is 1,048,576 bytes) and 2 passes (2 full rounds over that memory).

// passwords.ts
import argon2 from 'argon2';

// argon2id with the library defaults: 64 MiB of memory, 3 passes. Above the OWASP minimum.
// The salt and settings are stored inside the result: $argon2id$v=19$m=65536,p=4,t=3$<salt>$<hash>
export const hashPassword = (password: string) => argon2.hash(password);
export const checkPassword = (hash: string, password: string) => argon2.verify(hash, password);

On an old system with bcrypt, OWASP says use a cost of 10 or more. bcrypt only reads the first 72 bytes of a password, so reject longer ones.

quick-check

Your users table stores SHA-256 with a unique salt per user. Is that safe enough?

Sessions and JWTs#

OWASP Top 10:2025: A07 Authentication Failures.

Words you need:

  • A session is login state kept on the server. The browser only holds a random ID in a cookie.
  • A JWT (JSON Web Token) is a signed token that carries the login data itself. Anyone can read it. Only the server can sign it.

Mallory gets a session ID first. Then Alice logs in using that same ID. Whose session is it now?

session-fixation
  1. Mallory gets session ID abc123 from the shop.
  2. She plants abc123 in Alice's browser, for example from a hostile subdomain.
  3. Alice logs in, and the server marks abc123 as logged in.
  4. Mallory sends abc123 and is now Alice.
step 1 / 4
The fix: a brand new session ID the moment the user logs in.

This is session fixation. OWASP lists "reuses the same session identifier after successful login" as an authentication failure. You need this in any app that logs users in with a cookie.

Sessions done right#

express-session handles the cookie. connect-pg-simple keeps sessions in Postgres, so they survive restarts and work across many app servers. The fix is one call at login:

// session.ts (key lines)
name: '__Host-sid',
// ...
cookie: {
  httpOnly: true, // JavaScript in the page can't read it
  secure: true, // HTTPS only
  sameSite: 'lax', // not sent on cross-site POSTs (the CSRF chapter goes deeper)
},
// ...
req.session.regenerate((err) => {
  if (err) return next(err);
  req.session.userId = userId; // the new ID gets the login, the old one is gone
Show full code: session.ts
// session.ts
import express, { type Request, type Response, type NextFunction } from 'express';
import session from 'express-session';
import connectPgSimple from 'connect-pg-simple';
import { pool } from './db.ts';

declare module 'express-session' {
  interface SessionData { userId: string }
}

const SESSION_SECRET = process.env.SESSION_SECRET ?? ''; // openssl rand -base64 64
if (SESSION_SECRET.length < 64) throw new Error('SESSION_SECRET is too short');

const PgStore = connectPgSimple(session);
export const app = express();
app.set('trust proxy', 1); // one load balancer (the server that spreads traffic) in front
app.use(express.json());

app.use(session({
  store: new PgStore({ pool, createTableIfMissing: true }),
  secret: SESSION_SECRET,
  name: '__Host-sid',
  resave: false,
  saveUninitialized: false,
  cookie: {
    httpOnly: true, // JavaScript in the page can't read it
    secure: true, // HTTPS only
    sameSite: 'lax', // not sent on cross-site POSTs (the CSRF chapter goes deeper)
  },
}));

export function startSession(req: Request, res: Response, next: NextFunction, userId: string) {
  req.session.regenerate((err) => {
    if (err) return next(err);
    req.session.userId = userId; // the new ID gets the login, the old one is gone
    req.session.save((err) => (err ? next(err) : res.sendStatus(204)));
  });
}
  • sameSite: 'lax' keeps the cookie off POSTs that other sites send. That attack is CSRF (cross-site request forgery), and it has its own chapter.
  • The __Host- prefix is a browser rule. The browser only accepts that cookie with Secure, Path=/ and no Domain, so a subdomain can't plant or overwrite it.
  • On logout, call req.session.destroy() and clear the cookie. Also regenerate when a user's role changes.
  • express-session won't set a secure cookie over plain HTTP, so run local dev over HTTPS (mkcert makes a local certificate). Never ship a secure: false switch.

JWTs done right#

Words you need:

  • The payload is the JSON data inside the token, like sub (the "subject" field, the user ID).
  • HS256 signs and checks with one shared secret.
  • RS256 signs with a private RSA key and checks with the matching public key, which anyone may see.

A JWT header names its algorithm, and classic attacks change it:

  • alg: none: Mallory removes the signature and says "no algorithm".
  • Key confusion: your server uses RS256, and Mallory signs her own token with HS256, using your public key as the secret.
key-confusion
  1. Mallory downloads your public RSA key. It is public on purpose.
  2. She writes a token with alg HS256 and sub set to the admin ID.
  3. She signs it with HS256, using your public key as the secret.
  4. The library trusts the alg in the token. It checks HS256 with the key it has: your public key.
  5. The signature matches. Mallory is the admin.
step 1 / 5
The fix: your code says which algorithm is allowed, never the token.

jsonwebtoken v9 blocks both by default. Older versions and other libraries did not, so always pass an algorithms list:

// jwt.ts
import jwt from 'jsonwebtoken';

const SECRET = process.env.JWT_SECRET ?? ''; // openssl rand -base64 64
if (SECRET.length < 64) throw new Error('JWT_SECRET is too short');

const opts = { issuer: 'my-api', audience: 'my-app' };

export const signToken = (userId: string) =>
  jwt.sign({}, SECRET, { ...opts, algorithm: 'HS256', subject: userId, expiresIn: '15m' }); // short life

export const verifyToken = (token: string) =>
  jwt.verify(token, SECRET, { ...opts, algorithms: ['HS256'] }); // only this one
  • issuer and audience name who made the token and who it is for. verify rejects a token with other values.
  • Keep secrets and personal data out of the payload. It is only base64url (a text encoding, not encryption), so anyone can decode it.

For a browser app with its own backend, I start with sessions: logging someone out is one deleted row. A JWT stays valid until it expires.

quick-check

Your code calls jwt.verify(token, SECRET) with no options. What should you add?

quick-check

Mallory planted session ID abc123 in Alice's browser. Alice logs in. What stops Mallory from using abc123?

Brute force: a limit that can't be raced#

OWASP Top 10:2025: A07 Authentication Failures.

Words you need:

  • Brute force is trying many passwords on one account.
  • Redis is an in-memory database, used here for counters that every app server shares.
  • Atomic means done as one step, so no other request can run in the middle of it.

A common pattern: read the fail count for the email, refuse at 5, and add 1 after each wrong password. It has two bugs:

  1. It can be raced. Send 100 guesses at once, and all 100 read 0 before any write.
  2. Anyone can lock anyone. Five wrong passwords on a victim's email lock the real user out.

Use two layers instead. A per-IP limit (20 tries per 15 minutes) stops one machine from hammering you.

The second layer is a wait with exponential backoff: it doubles after each failure, up to a cap. Each wait is kept per account plus IP, so Mallory only slows herself down. Alice, on her own IP, still logs in.

The key lines: one Redis command checks and claims the next try at the same time.

// login.ts (key lines)
// One try per (account + IP) per wait time. Returns seconds to wait, 0 = go.
async function waitBeforeTry(who: string): Promise<number> {
  const fails = Number(await redis.get(`login:fails:${who}`)) || 0;
  const waitMs = Math.min(1000 * 2 ** Math.max(0, fails - 3), 15 * 60 * 1000);
  const slot = `login:slot:${who}`;
  const got = await redis.set(slot, '1', { condition: 'NX', expiration: { type: 'PX', value: waitMs } });
  if (got) return 0;
  return Math.max(1, Math.ceil((await redis.pTTL(slot)) / 1000)); // never 0 without the slot
}

app.post('/login', limit('login', 15, 20), async (req, res, next) => {
  // ...
  const who = `${email}|${ipKeyGenerator(req.ip ?? '')}`; // IPv6 grouped by network
  // ...
  const ok = await argon2.verify(user?.password_hash ?? DUMMY_HASH, password);
  • limit('login', 15, 20) is the per-IP layer: 20 tries per 15 minutes.
  • SET with NX ("only if it does not exist yet") is atomic in Redis.
  • PX gives the key a lifetime in milliseconds. pTTL asks how many milliseconds are left.
  • A refused try gets 429 (Too Many Requests), and the Retry-After header says how many seconds to wait.

Here is one IP sending three guesses at once:

login-slot
  1. Requests A, B and C all run SET login:slot:... NX.
  2. Redis runs them one at a time. A creates the key.
  3. B and C find the key there, so SET returns null. They get 429 with Retry-After.
  4. Only A goes on to the password check.
step 1 / 4
The check and the claim are one Redis command, so there is no gap to race.
Show full code: limits.ts, login.ts
// limits.ts: shared Redis client + one rate-limit helper
import type { Request } from 'express';
import { createClient } from 'redis';
import { rateLimit } from 'express-rate-limit';
import { RedisStore } from 'rate-limit-redis';
import { problem } from './problem.ts';

export const redis = await createClient({ url: process.env.REDIS_URL }).connect();

export function limit(name: string, minutes: number, max: number, key?: (req: Request) => string) {
  return rateLimit({
    windowMs: minutes * 60 * 1000, limit: max, standardHeaders: 'draft-8', legacyHeaders: false,
    ...(key ? { keyGenerator: key } : {}), // default key: the client IP
    store: new RedisStore({ prefix: `rl:${name}:`, sendCommand: (...args: string[]) => redis.sendCommand(args) }),
    handler: (req, res) => problem(res, 429, 'Too many requests. Try again later.'),
  });
}
// login.ts
import crypto from 'node:crypto';
import argon2 from 'argon2';
import { ipKeyGenerator } from 'express-rate-limit';
import { z } from 'zod';
import { app, startSession } from './session.ts';
import { pool } from './db.ts';
import { problem } from './problem.ts';
import { redis, limit } from './limits.ts';

// Made once at startup, so unknown emails still cost one real argon2 check.
const DUMMY_HASH = await argon2.hash(crypto.randomBytes(16).toString('hex'));
const LoginBody = z.object({ email: z.email().toLowerCase(), password: z.string().min(1).max(256) });

// One try per (account + IP) per wait time. Returns seconds to wait, 0 = go.
async function waitBeforeTry(who: string): Promise<number> {
  const fails = Number(await redis.get(`login:fails:${who}`)) || 0;
  const waitMs = Math.min(1000 * 2 ** Math.max(0, fails - 3), 15 * 60 * 1000);
  const slot = `login:slot:${who}`;
  const got = await redis.set(slot, '1', { condition: 'NX', expiration: { type: 'PX', value: waitMs } });
  if (got) return 0;
  return Math.max(1, Math.ceil((await redis.pTTL(slot)) / 1000)); // never 0 without the slot
}

app.post('/login', limit('login', 15, 20), async (req, res, next) => {
  const { email, password } = LoginBody.parse(req.body);
  const who = `${email}|${ipKeyGenerator(req.ip ?? '')}`; // IPv6 grouped by network

  const wait = await waitBeforeTry(who);
  if (wait > 0) {
    res.set('Retry-After', String(wait));
    return problem(res, 429, 'Too many tries. Wait and try again.');
  }

  const { rows } = await pool.query('SELECT id, password_hash FROM users WHERE email = $1', [email]);
  const user = rows[0];
  const ok = await argon2.verify(user?.password_hash ?? DUMMY_HASH, password);

  if (!user || !ok) {
    const replies = await redis.multi()
      .incr(`login:fails:${who}`).expire(`login:fails:${who}`, 3600)
      .incr(`login:fails:any:${email}`).expire(`login:fails:any:${email}`, 3600) // all IPs together
      .exec();
    const accountFails = Number(replies[2]);
    if (accountFails === 20) console.warn(JSON.stringify({ event: 'login_attack_suspected', userId: user?.id ?? null }));
    // Never blocks. Tells your frontend to show a CAPTCHA, which your CAPTCHA provider checks.
    return problem(res, 401, 'Wrong email or password.', { captchaRequired: accountFails >= 5 });
  }
  await redis.del(`login:fails:${who}`);
  startSession(req, res, next, user.id);
});

The wait for one account plus one IP:

Failures so far0 to 34567 to 1213 or more
Wait before the next try1 s2 s4 s8 sdoubles each time15 min (the cap)
  • The fail counter is forgotten after an hour without failures.
  • Unknown emails get the same 401, and the dummy hash makes a missing email take about as long as a wrong password. Otherwise attackers learn which emails have accounts (user enumeration).

What this does not stop:

  • A botnet (thousands of hacked machines, each with its own IP) still gets a few slow tries per IP. The account-wide counter catches this.
  • After 5 failures from any IPs, each failed login's 401 says captchaRequired. A CAPTCHA is a small test that bots fail and people pass. The flag never blocks: a correct password still logs in.
  • At 20 failures you get an alert. OWASP names multi-factor authentication (MFA) as the best defense.
  • People behind one shared IP (an office, a campus, a mobile network) share one wait. One person failing a lot can slow the others down on that account, up to 15 minutes.
quick-check

Mallory fails 13 times on Alice's account from one IP. Alice then logs in from her home IP. What happens?

Password reset#

OWASP Top 10:2025: A07 Authentication Failures (it lists weak password recovery).

The login now knows who the user is. Password reset is the side door. A common reset link: https://app.example.com/reset?token= + md5(email + Date.now()). MD5 is an old, fast hash, and here it only scrambles two values Mallory can guess: Alice's email and roughly when she asked.

And if the database stores the token as plain text, anyone who steals the table can use every open reset link. Every app with "forgot password" needs this chapter.

Words you need:

  • A token is a secret random string that proves the user got the email.
  • The Referer header is where the browser sends the URL of the page you came from.
  • A transaction is a group of writes that all happen or none happen. Commit saves them all. Roll back undoes them all.

The safe flow:

password-reset
  1. Alice asks for a reset. The API answers 202 at once, for every email.
  2. The API makes a random 32-byte token and stores only its SHA-256 hash.
  3. The email link carries the token after the # sign.
  4. Alice sends the token and a new password.
  5. One UPDATE marks the token used, only if unused and not expired.
  6. Same transaction: new password, the other links die, all sessions end.
step 1 / 6
A second request with the same token finds nothing to update.

The key lines: the token is checked and used in one statement.

// reset.ts (key lines)
const token = crypto.randomBytes(32).toString('base64url'); // 256 random bits
// ...
const { rows } = await db.query(
  `UPDATE password_resets SET used_at = now()
   WHERE token_hash = $1 AND used_at IS NULL AND expires_at > now() RETURNING user_id`,
  [tokenHash]);
if (rows.length === 0) return false;
Show full code: the password_resets table and reset.ts
CREATE TABLE password_resets (
  id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  token_hash text NOT NULL UNIQUE,
  expires_at timestamptz NOT NULL,
  used_at timestamptz
);
CREATE INDEX ON password_resets (user_id) WHERE used_at IS NULL; -- partial index: covers only rows still unused
CREATE INDEX ON "session" ((sess->>'userId')); -- connect-pg-simple's table
// reset.ts
import crypto from 'node:crypto';
import { z } from 'zod';
import { app } from './session.ts';
import { pool, inTransaction } from './db.ts';
import { problem } from './problem.ts';
import { limit } from './limits.ts';
import { hashPassword } from './passwords.ts';

const sha256 = (s: string) => crypto.createHash('sha256').update(s).digest('hex');

async function sendResetEmail(email: string) {
  const { rows } = await pool.query('SELECT id FROM users WHERE email = $1', [email]);
  if (rows.length === 0) return;
  const token = crypto.randomBytes(32).toString('base64url'); // 256 random bits
  await pool.query(
    `INSERT INTO password_resets (user_id, token_hash, expires_at)
     VALUES ($1, $2, now() + interval '15 minutes')`,
    [rows[0].id, sha256(token)], // the database only ever sees the hash
  );
  await sendEmail(email, `https://app.example.com/reset#token=${token}`); // your email sender
}

// Max 3 reset emails per address per hour, so nobody can flood an inbox.
const resetEmailLimit = limit('reset', 60, 3, (req) => String(req.body?.email).toLowerCase());

app.post('/password-reset', resetEmailLimit, (req, res) => {
  const { email } = z.object({ email: z.email().toLowerCase() }).parse(req.body);
  res.sendStatus(202); // same answer, same speed, for every email
  sendResetEmail(email).catch((err) => console.error('reset email failed', err.message));
});

async function resetPassword(token: string, newPassword: string): Promise<boolean> {
  const tokenHash = sha256(token);
  // Cheap lookup first, so a random token never costs a 64 MiB argon2 hash.
  const found = await pool.query(
    'SELECT 1 FROM password_resets WHERE token_hash = $1 AND used_at IS NULL AND expires_at > now()',
    [tokenHash]);
  if (found.rowCount === 0) return false;
  const newHash = await hashPassword(newPassword);

  return inTransaction(async (db) => {
    // The real check: test and use the token in ONE statement.
    const { rows } = await db.query(
      `UPDATE password_resets SET used_at = now()
       WHERE token_hash = $1 AND used_at IS NULL AND expires_at > now() RETURNING user_id`,
      [tokenHash]);
    if (rows.length === 0) return false;
    const userId = rows[0].user_id;
    await db.query('UPDATE users SET password_hash = $1 WHERE id = $2', [newHash, userId]);
    await db.query('UPDATE password_resets SET used_at = now() WHERE user_id = $1 AND used_at IS NULL', [userId]);
    await db.query(`DELETE FROM "session" WHERE sess->>'userId' = $1`, [userId]); // log out everywhere
    return true;
  });
}

const ResetBody = z.object({ token: z.string().length(43), password: z.string().min(12).max(256) });

app.post('/password-reset/confirm', limit('reset-confirm', 15, 10), async (req, res) => {
  const { token, password } = ResetBody.parse(req.body);
  if (!(await resetPassword(token, password))) return problem(res, 400, 'This link is invalid or expired.');
  res.sendStatus(204);
});

Why it holds up:

  • Only the hash is stored. A leaked table has no usable links.
  • The token sits after #. Browsers never send that part of a URL to a server or put it in the Referer header. Your reset page reads it and POSTs it.
  • The UPDATE ... WHERE used_at IS NULL is the check. If two requests send the same token, Postgres runs one UPDATE first and makes the second wait. The second then finds used_at set and changes nothing.
  • Every other open link dies when one is used, and all sessions end.
  • The 202 goes out first, so real and fake emails take the same time.
quick-check

The reset token is hashed with SHA-256, a fast hash. The passwords chapter said fast hashes are bad for passwords. Why is it fine here?

IDOR and mass assignment#

OWASP Top 10:2025: A01 Broken Access Control (IDOR) and A08 Software or Data Integrity Failures (mass assignment).

Words you need:

  • IDOR (Insecure Direct Object Reference): the API uses an ID from the request and never checks that the user may touch that object. The OWASP API list calls it BOLA and ranks it number 1.
  • UUID: a random 128-bit ID like 9f1c2b7e-4d0a-4c1e-9b8a-2f6d1e3c5a70.

Alice calls GET /api/orders/9f1c2b7e-..., and that order belongs to Bob. What does this send back?

app.get('/api/orders/:id', requireLogin, async (req, res) => {
  const { rows } = await pool.query('SELECT * FROM orders WHERE id = $1', [req.params.id]);
  res.json(rows[0]); // logged in? yes. Owner? never checked.
});

Bob's order. Any order ID that shows up in a link, a log or a screenshot now opens someone else's data. Every route that takes an ID from the request needs the fix.

Put the owner in the WHERE clause#

Make the owner part of the query, so a wrong owner finds nothing:

const OrderParams = z.object({ id: z.uuid() });

app.get('/api/orders/:id', requireLogin, async (req, res) => {
  const { id } = OrderParams.parse(req.params); // "abc" or "123" gets a 400
  const { rows } = await pool.query(
    'SELECT id, item_id, quantity FROM orders WHERE id = $1 AND user_id = $2',
    [id, req.session.userId], // the user ID comes from the session, never the request
  );
  if (rows.length === 0) return problem(res, 404); // not yours = does not exist
  res.json(rows[0]);
});
owner-in-the-query
  1. Alice asks for order 9f1c..., which is Bob's.
  2. The session says Alice. The user ID never comes from the request.
  3. WHERE id = 9f1c... AND user_id = Alice.
  4. No row matches: it is Bob's order.
  5. Alice gets 404 Not Found, as if the order does not exist.
step 1 / 5
A wrong owner finds nothing, so there is nothing to leak.

The same goes for writes: DELETE FROM comments WHERE id = $1 AND user_id = $2, then a 404 when rowCount is 0. Answer 404, never 403, because 403 tells the attacker the order exists. Random UUIDs are harder to guess, but they leak, so keep the owner check either way.

Mass assignment: the user picks the columns#

A profile update builds SQL from whatever keys the client sent:

const keys = Object.keys(req.body); // the client chose these
const sets = keys.map((k, i) => `${k} = $${i + 1}`).join(', ');
await pool.query(`UPDATE users SET ${sets} WHERE id = $${keys.length + 1}`,
  [...Object.values(req.body), req.session.userId]);

Mallory sends { "name": "x", "role": "admin" } and becomes an admin. This is mass assignment: request fields copied straight into a row.

  • The keys also land in the SQL text. A key like "role = 'admin', name" changes the SQL itself. That is SQL injection, the next chapter.
  • An ORM (a library like Prisma that writes SQL for you) has the same bug with update({ data: req.body }).

The fix is an allow-list plus fixed SQL:

const ProfileUpdate = z.strictObject({ // strictObject: unknown keys are an error
  name: z.string().trim().min(1).max(100).optional(),
  bio: z.string().max(500).optional(),
});

app.patch('/api/users/me', requireLogin, async (req, res) => {
  const { name, bio } = ProfileUpdate.parse(req.body); // { role: 'admin' } fails here
  const { rows } = await pool.query(
    `UPDATE users SET name = COALESCE($1, name), bio = COALESCE($2, bio)
     WHERE id = $3 RETURNING id, name, bio`, // safe columns only, never RETURNING *
    [name ?? null, bio ?? null, req.session.userId],
  );
  res.json(rows[0]);
});

COALESCE($1, name) means "use the new value, or keep the old one if none was sent".

quick-check

Alice asks for an order that belongs to Bob. What should the API answer?

SQL and command injection#

OWASP Top 10:2025: A05 Injection.

Words you need:

  • Injection is when user input gets read as code instead of data.
  • A parameter is a placeholder like $1. The value travels apart from the SQL text, so the database never reads it as SQL.

A login form builds SQL by gluing strings. Mallory types admin' -- as the username:

SELECT * FROM users WHERE username = 'admin' --' AND password = 'anything'

The ' closes the string early, and -- turns the rest into a comment. The password check is gone. Watch for this anywhere user input reaches SQL, a shell command, or other code your app builds as text.

Parameters for every value#

// Wrong: the input becomes part of the SQL text
await pool.query(`SELECT id, name FROM users WHERE name = '${req.query.name}'`);

// Right: $1 is a parameter, the value is sent separately
await pool.query('SELECT id, name FROM users WHERE name = $1', [String(req.query.name ?? '')]);
parameters
  1. Wrong: the API glues Mallory's input into the SQL text and sends one string.
  2. Postgres reads her input as SQL. OR '1'='1' is true for every row.
  3. Right: the API sends the SQL text with $1 in it.
  4. Then it sends her input on its own, as a value.
  5. Postgres compares the name with her whole input. No user has that name.
step 1 / 5
The SQL is fixed before the value arrives, so a value can never change it.

Now ' OR '1'='1 is a strange name that matches nobody.

Parameters only carry values. Column names and ASC/DESC can't be $1, so map user choices to fixed SQL:

// orders list (key lines)
sort: z.enum(['newest', 'oldest']).default('newest'),
// ...
const ORDER_BY = { newest: 'created_at DESC', oldest: 'created_at ASC' } as const;
// ...
`SELECT id, item_id, quantity FROM orders WHERE user_id = $1 ORDER BY ${ORDER_BY[sort]} LIMIT $2`,
Show full code: the orders list route
const ListQuery = z.object({
  limit: z.coerce.number().int().min(1).max(100).default(20), // lists are always capped
  sort: z.enum(['newest', 'oldest']).default('newest'),
});
const ORDER_BY = { newest: 'created_at DESC', oldest: 'created_at ASC' } as const;

app.get('/api/orders', requireLogin, async (req, res) => {
  const { limit, sort } = ListQuery.parse(req.query);
  const { rows } = await pool.query(
    `SELECT id, item_id, quantity FROM orders WHERE user_id = $1 ORDER BY ${ORDER_BY[sort]} LIMIT $2`,
    [req.session.userId, limit]);
  res.json(rows);
});
  • The schema also catches surprises. Express 5's default query parser (the code that turns ?a=1 into req.query) makes ?limit=1&limit=2 the array ['1', '2']. The schema wants one number, so parse() rejects it.
  • An ORM also has functions that run raw SQL. Prisma's $queryRawUnsafe with a glued string is as unsafe as the "wrong" line.

Commands without a shell#

// host = "example.com; cat /etc/passwd" runs a second command
exec(`ping -c 1 ${req.body.host}`, (err, stdout) => res.send(stdout));

exec starts a shell, and the shell treats ;, | and $(...) as commands. execFile runs the program directly with an args list, so ; is only a character.

A ping endpoint also lets users reach machines inside your network, so check the address too. promisify turns execFile into a function you can await:

// ping.ts (key lines)
const run = promisify(execFile);
const Host = z.string().max(253).regex(/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/i); // no leading "-"
// ...
const host = Host.parse(req.body.host);
const { address } = await dns.lookup(host, { family: 4 });
if (!isPublicIp(address)) return problem(res, 422, 'That host is not allowed.');
// Ping the IP we checked. "--" means everything after it is never an option.
const { stdout } = await run('ping', ['-c', '1', '--', address], { timeout: 5000 });
Show full code: ping.ts
// ping.ts
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
import dns from 'node:dns/promises'; // the promise version: await dns.lookup(...)
import ipaddr from 'ipaddr.js';
import { ipKeyGenerator } from 'express-rate-limit';
import type { Request } from 'express';
import { z } from 'zod';
import { app } from './session.ts';
import { problem } from './problem.ts';
import { limit } from './limits.ts';
import { requireLogin } from './auth.ts';

const run = promisify(execFile);
const Host = z.string().max(253).regex(/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/i); // no leading "-"

// Loopback, private, link-local (169.254.x.x, used by cloud metadata) are not "unicast".
export function isPublicIp(address: string): boolean {
  return ipaddr.process(address).range() === 'unicast'; // ipaddr.js; process() unwraps ::ffff:127.0.0.1
}

// Rate limit key: the user when logged in, else the IP (IPv6 grouped by network).
export const perUser = (req: Request) => req.session.userId ?? ipKeyGenerator(req.ip ?? '');

app.post('/api/ping', requireLogin, limit('ping', 1, 5, perUser), async (req, res) => { // 5 per minute
  const host = Host.parse(req.body.host);
  const { address } = await dns.lookup(host, { family: 4 });
  if (!isPublicIp(address)) return problem(res, 422, 'That host is not allowed.');
  // Ping the IP we checked. "--" means everything after it is never an option.
  const { stdout } = await run('ping', ['-c', '1', '--', address], { timeout: 5000 });
  res.type('text/plain').send(stdout);
});

The "no leading dash" rule and -- block option injection, where a host like -f becomes a flag. Now localhost, 10.0.0.1 and 169.254.169.254 get 422.

The safest command is no command. Use a library when one exists, like sharp for images. The SSRF chapter reuses isPublicIp and perUser.

quick-check

In SELECT * FROM orders WHERE user_id = 7 ORDER BY created_at DESC, which part can NOT be a $1 parameter?

CORS and CSRF#

OWASP Top 10:2025: A01 Broken Access Control (it lists both CORS mistakes and CSRF).

The next attacks come from another website open in the same browser.

Words you need:

  • An origin is scheme + host + port, like https://app.example.com.
  • CORS (Cross-Origin Resource Sharing) is a set of headers that tell the browser which other origins may read your responses.
  • CSRF (Cross-Site Request Forgery) is when another site makes the browser send a request to you, with the user's cookies.

The classic example: Alice is logged in to bank.example. In another tab she opens evil.example, which has this page:

<form action="https://bank.example/transfer" method="POST">
  <input name="to" value="attacker">
  <input name="amountCents" value="1000000">
</form>
<script>document.forms[0].submit()</script>
csrf
  1. Without defenses: Alice opens evil.example. Its page submits a hidden transfer form.
  2. Without defenses: her browser sends the POST with her bank cookie, and the money moves.
  3. Same attack, with defenses. Defense 1: SameSite=Lax keeps the cookie off cross-site POSTs.
  4. With defenses. Defense 2: the browser labels the request Sec-Fetch-Site: cross-site.
  5. With defenses: the server refuses it with 403. No money moves.
step 1 / 5
CORS is not in this story: it only decides who may read answers.

Any API that a browser calls with cookies needs both defenses.

CORS: an exact list#

The common mistake reflects whatever origin asks:

app.use(cors({ origin: true, credentials: true })); // any site can read your users' data

Now evil.example can call fetch('https://api.example.com/me', { credentials: 'include' }) and read the answer. Use an exact list. Avoid "ends with" checks, because evilexample.com ends with example.com.

const TRUSTED_ORIGINS = ['https://app.example.com'];
app.use(cors({ origin: TRUSTED_ORIGINS, credentials: true })); // the cors package

CORS can't stop CSRF. Some requests get a preflight: the browser asks your server first, with an OPTIONS request. Others are "simple requests", sent at once:

Request from evil.examplePreflight first?Does your CORS list stop it?
a plain form POST, like the one aboveno, it is sent at onceno, CORS only hides the answer, so the transfer happens
a JSON fetch with cookiesyesyes, the real request is never sent

CSRF: SameSite plus a cross-site check#

sameSite: 'lax' from the sessions chapter already keeps the cookie off that form POST. (httpOnly is the different setting that hides the cookie from JavaScript.) OWASP calls SameSite defense in depth, because it has gaps:

  • Lax still sends cookies on a top-level GET (clicking a link that loads a new page). A link on evil.example to https://bank.example/transfer?to=attacker arrives with Alice's cookie. So a GET must never change data.
  • Sibling subdomains also count as "same site". A page on blog.example.com is same site for app.example.com.

So add a second check. Modern browsers send a Sec-Fetch-Site header that says where a request came from. OWASP's CSRF guide calls it the primary signal, with an Origin check as the fallback:

const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);

export function blockCrossSite(req: Request, res: Response, next: NextFunction) {
  if (SAFE_METHODS.has(req.method)) return next(); // so GET must never change data
  if (!req.get('Cookie') && req.get('Authorization')) return next(); // token client: no cookie to ride on
  if (req.get('Sec-Fetch-Site') === 'same-origin') return next();
  const origin = req.get('Origin');
  if (origin && TRUSTED_ORIGINS.includes(origin)) return next();
  problem(res, 403, 'Cross-site request blocked.');
}
  • A mobile app that sends a bearer token (a token in the Authorization header) and no cookie passes, because CSRF needs a cookie to ride on.
  • Even a cookieless POST /login is checked. Otherwise a hostile page could log the victim into the attacker's account.
  • A request with neither header is blocked. This is fail closed: when in doubt, refuse.

Order matters. Put the two new lines in session.ts, which already adds express.json() and the session. Every route file imports session.ts, so these run before any route:

// session.ts, right after app.use(session(...))
app.use(cors({ origin: TRUSTED_ORIGINS, credentials: true }));
app.use(blockCrossSite);

// your entry file, after all routes are imported
app.use(errorHandler); // always last

Server-rendered HTML forms? Use a token library, since csurf is no longer maintained. Two maintained ones are csrf-csrf and csrf-sync. The first uses a double-submit cookie: the token sits in a cookie and in the form, and they must match. The second keeps the token in the session.

quick-check

Your API has a perfect CORS allow-list and cookie sessions. Is it safe from CSRF?

SSRF: your server fetches a URL#

OWASP Top 10:2025: A01 Broken Access Control (SSRF was rolled into A01 in this edition).

Words you need:

  • SSRF (Server-Side Request Forgery): the attacker makes your server send a request to a place they can't reach.
  • Loopback: addresses that point back at the same machine, like 127.0.0.1 and ::1.
  • Private address: an IP that only works inside a network, like 10.0.0.5 or AWS's IPv6 metadata address fd00:ec2::254.
  • The cloud metadata service at 169.254.169.254 tells a cloud server about itself. Only that server can reach it.

The shop makes link previews. The user sends a URL, and your server fetches it:

app.post('/api/preview', requireLogin, async (req, res) => {
  const page = await fetch(req.body.url); // any URL at all
  res.send(await page.text()); // any size, any HTML, served from your origin
});
ssrf
  1. Mallory asks for a preview of http://169.254.169.254/latest/meta-data/iam/security-credentials/.
  2. Your server fetches it. Only your server can reach that address.
  3. On AWS, the metadata service can hand out the server's credentials.
  4. The preview sends them straight back to Mallory.
step 1 / 4
The attacker can't reach the metadata service. Your server can, and it does what she asks.

In 2019 an attacker took about 100 million credit card applications from Capital One's AWS setup. Krebs on Security reported that a misconfigured firewall was tricked into calling that service. You need this chapter for link previews, webhooks to user URLs, "import from URL", and PDF and image generators.

Why a simple IP check fails#

A blocklist of strings like "127." and "10." misses all of these:

Mallory sendsThe string check seesIt really reaches
http://2130706433/a number, no 127.127.0.0.1 (the URL parser turns the number into it)
http://[::ffff:127.0.0.1]/IPv6, no 127. at the startloopback, written as IPv6
http://100.64.0.1/no 10. at the startcarrier-grade NAT: a range internet providers use inside their own networks
a normal domaina name, not an IPwhatever its DNS says, like 127.0.0.1
a public URLa public hosta redirect to http://169.254.169.254/
a domain that changes its answera public IP at check time127.0.0.1 at connect time: DNS rebinding, below
dns-rebinding
  1. Your code looks up evil.example.
  2. It gets a public IP, so the check passes.
  3. fetch(url) looks up evil.example again.
  4. The attacker DNS now answers 127.0.0.1.
  5. fetch connects to your own machine.
step 1 / 5
The check and the connection used two different lookups. The fix: check inside the one lookup the connection uses.

Check the address you connect to#

Best case, allow-list the hosts you expect. When users can give any URL, check every resolved address at connect time.

Node's fetch runs on undici, an HTTP client. undici lets you pass a dispatcher: an object that opens the connections. You give it your own DNS lookup, safeLookup:

// ssrf.ts (key lines)
const safeLookup: net.LookupFunction = (hostname, options, callback) => {
  dns.lookup(hostname, { ...options, all: true }, (err, addresses) => {
    // ...
    const blocked = addresses.find((a) => !isPublicIp(a.address)); // check ALL answers
    if (blocked) return callback(new Error(`Blocked address ${blocked.address}`), []);
    // ...
// Every connection runs safeLookup, so the IP we check is the IP we connect to.
const agent = new Agent({ connect: { lookup: safeLookup, timeout: 5000 } });
// ...
export async function safeFetch(rawUrl: string) {
  let url = new URL(rawUrl);
  for (let hop = 0; hop <= 3; hop++) {
    // ...
    // A raw IP skips DNS, so safeLookup would never see it. Refuse it.
    if (net.isIP(url.hostname.replace(/^\[|\]$/g, ''))) throw new Error('Raw IPs are not allowed');

safeFetch also:

  • refuses raw IPs, and ports other than 80 and 443
  • runs the same checks on every redirect, 3 at most

The preview route:

  • caps the size at 1 MB
  • accepts only HTML
  • sends back data you picked (the page title), never the fetched page
Show full code: ssrf.ts and the preview route
// ssrf.ts
import dns from 'node:dns'; // the callback version: Node's connection lookup expects callbacks
import net from 'node:net';
import { Agent, fetch } from 'undici'; // fetch and Agent from the same package
import { z } from 'zod';
import { app } from './session.ts';
import { problem } from './problem.ts';
import { limit } from './limits.ts';
import { requireLogin } from './auth.ts';
import { isPublicIp, perUser } from './ping.ts'; // only "unicast" (normal public) addresses pass

const safeLookup: net.LookupFunction = (hostname, options, callback) => {
  dns.lookup(hostname, { ...options, all: true }, (err, addresses) => {
    if (err) return callback(err, []);
    const blocked = addresses.find((a) => !isPublicIp(a.address)); // check ALL answers
    if (blocked) return callback(new Error(`Blocked address ${blocked.address}`), []);
    if (options.all) return callback(null, addresses);
    callback(null, addresses[0].address, addresses[0].family);
  });
};

// Every connection runs safeLookup, so the IP we check is the IP we connect to.
const agent = new Agent({ connect: { lookup: safeLookup, timeout: 5000 } });

export async function safeFetch(rawUrl: string) {
  let url = new URL(rawUrl);
  for (let hop = 0; hop <= 3; hop++) {
    if (url.protocol !== 'https:' && url.protocol !== 'http:') throw new Error('Bad protocol');
    // A raw IP skips DNS, so safeLookup would never see it. Refuse it.
    if (net.isIP(url.hostname.replace(/^\[|\]$/g, ''))) throw new Error('Raw IPs are not allowed');
    if (url.port && url.port !== '80' && url.port !== '443') throw new Error('Port not allowed');
    const res = await fetch(url, { dispatcher: agent, redirect: 'manual', signal: AbortSignal.timeout(5000) });
    const location = res.headers.get('location');
    if (res.status < 300 || res.status > 399 || !location) return res;
    await res.body?.cancel();
    url = new URL(location, url); // the next hop gets the same checks
  }
  throw new Error('Too many redirects');
}
async function readText(res: Awaited<ReturnType<typeof fetch>>, maxBytes: number) {
  const chunks: Uint8Array[] = [];
  let size = 0;
  for await (const chunk of res.body ?? []) {
    size += chunk.length;
    if (size > maxBytes) throw new Error('Too big'); // stops reading
    chunks.push(chunk);
  }
  return Buffer.concat(chunks).toString('utf8');
}

app.post('/api/preview', requireLogin, limit('preview', 1, 10, perUser), async (req, res) => { // 10 per minute
  const { url } = z.object({ url: z.url() }).parse(req.body);
  try {
    const page = await safeFetch(url);
    if (!page.ok || !page.headers.get('content-type')?.startsWith('text/html')) {
      await page.body?.cancel();
      throw new Error('Not an HTML page');
    }
    const html = await readText(page, 1_000_000); // 1 MB cap
    const title = /<title[^>]*>([^<]{0,200})/i.exec(html)?.[1]?.trim() ?? null;
    res.json({ url, title });
  } catch (err) {
    const e = err as Error & { cause?: Error };
    // Log the refusal with safe fields only: who, which host, why. It shows SSRF attempts.
    console.warn(JSON.stringify({ event: 'preview_refused', userId: req.session.userId, host: new URL(url).hostname, reason: e.cause?.message ?? e.message }));
    problem(res, 422, 'That URL cannot be previewed.');
  }
});

Each item from the list now fails:

  • The redirect to 169.254.169.254 hits the raw IP rule.
  • A domain that resolves to 127.0.0.1 fails in safeLookup.
  • Rebinding fails, because the lookup and the connection are one step.

Add network layers too. On AWS, require IMDSv2: the metadata service then wants a token from a PUT request first. A simple SSRF, like this preview, only sends a GET, so it never gets that token.

quick-check

You call dns.lookup(host), see a public IP, then call fetch(url). What is still open?

Race conditions and idempotency#

OWASP Top 10:2025: A06 Insecure Design. Its mapped list includes CWE-362, the race condition. A CWE is a numbered weakness type in a list kept by MITRE, a US nonprofit.

The last attack needs no hacking at all: two requests landing at once. Alice has $10.00 of shop credit and opens two tabs. In both, she clicks "Withdraw $10.00" at the same moment. The code reads the balance, checks it, then writes the new balance:

two-tab-withdraw
  1. Tab A reads the balance: 1000 cents.
  2. Tab B reads the balance: 1000 cents.
  3. Both check 1000 >= 1000 and pass.
  4. Tab A writes 0 and pays out $10.00.
  5. Tab B writes 0 and pays out $10.00 again.
step 1 / 5
Both checks read the same old balance. $20.00 left a $10.00 account.

This is TOCTOU (time of check to time of use): the data changes between the check and the write. Watch for it in balances, stock counts, coupons, seat bookings, anything with "only if there is enough".

One statement checks and writes#

Put the check inside the UPDATE:

const Withdraw = z.object({ amountCents: z.int().positive() }); // integer cents, never floats

app.post('/api/withdraw', requireLogin, async (req, res) => {
  const { amountCents } = Withdraw.parse(req.body);
  const { rows } = await pool.query(
    `UPDATE accounts SET balance_cents = balance_cents - $1
     WHERE user_id = $2 AND balance_cents >= $1 RETURNING balance_cents`,
    [amountCents, req.session.userId]);
  if (rows.length === 0) return problem(res, 409, 'Not enough balance.');
  res.json({ balanceCents: rows[0].balance_cents });
});

Run both tabs again. Postgres locks the row for the first UPDATE: no other write can change it until that transaction ends. The second waits, re-checks its WHERE against the new balance of 0, and matches nothing. One tab gets 200, the other 409.

This fixes the race. It does not fix retries: a phone that resends the same withdraw would pay twice. A real withdraw also needs the idempotency key below. It is left out here to keep one idea per example.

Idempotency keys for retries#

An idempotent request is one you can repeat safely: the second time changes nothing and returns the same answer. The client sends a random Idempotency-Key header with each new action (Stripe's API uses the same header):

idempotency-key
  1. The phone sends a new order with Idempotency-Key k1.
  2. The API inserts the key first, then the order, in one transaction.
  3. The answer gets lost. The phone retries with the same key.
  4. The insert conflicts, so the API reads the saved response.
  5. The phone gets the same order back. Nothing is created twice.
step 1 / 5
The key turns a retry into a replay of the first answer.
// orders.ts (key lines)
// Insert first. A second request with the same key waits here until the first commits.
const claimed = await db.query(
  'INSERT INTO idempotency_keys (user_id, key) VALUES ($1, $2) ON CONFLICT DO NOTHING RETURNING key',
  [userId, key]);
Show full code: the idempotency_keys table and the orders route
CREATE TABLE idempotency_keys (
  user_id uuid NOT NULL REFERENCES users(id),
  key text NOT NULL,
  response jsonb,
  created_at timestamptz NOT NULL DEFAULT now(), -- delete rows older than 24 hours
  PRIMARY KEY (user_id, key) -- per user, so nobody can replay another user's key
);
const NewOrder = z.object({ itemId: z.string().max(50), quantity: z.int().min(1).max(100) });

app.post('/api/orders', requireLogin, async (req, res) => {
  const key = z.string().min(16).max(255).parse(req.get('Idempotency-Key'));
  const { itemId, quantity } = NewOrder.parse(req.body);
  const userId = req.session.userId!;

  const order = await inTransaction(async (db) => {
    // Insert first. A second request with the same key waits here until the first commits.
    const claimed = await db.query(
      'INSERT INTO idempotency_keys (user_id, key) VALUES ($1, $2) ON CONFLICT DO NOTHING RETURNING key',
      [userId, key]);
    if (claimed.rowCount === 0) {
      const { rows } = await db.query(
        'SELECT response FROM idempotency_keys WHERE user_id = $1 AND key = $2', [userId, key]);
      return rows[0].response; // a repeat: send the first answer again
    }
    const { rows } = await db.query(
      'INSERT INTO orders (user_id, item_id, quantity) VALUES ($1, $2, $3) RETURNING id, item_id, quantity',
      [userId, itemId, quantity]);
    await db.query('UPDATE idempotency_keys SET response = $3 WHERE user_id = $1 AND key = $2',
      [userId, key, rows[0]]);
    return rows[0];
  });
  res.status(201).json(order);
});

Why insert the key first? Looking for the key, then creating the order, has the same two-tab race as the withdraw: both requests find no key. Here the primary key does the locking. Postgres makes a second insert with the same key wait until the first transaction ends:

  • If it committed, the second request finds the saved response.
  • If it rolled back, the key is gone and a retry runs fresh.
quick-check

Two requests with the same Idempotency-Key arrive together. How many orders get created?

Recap#

Mallory triesWhat stops herOWASP 2025
cracking a leaked password tableargon2id, slow and memory-heavyA04
planting a session IDreq.session.regenerate() + a __Host- cookieA07
forging a JWTa fixed algorithms list, short expiryA07
guessing passwords fastper-IP limit + a wait per account and IP, set with SET NXA07
rebuilding a reset linka random token, stored as a hash, used once in one UPDATE, rate limitedA07
reading Bob's orderthe owner in the WHERE clause, 404 for othersA01
making herself adminz.strictObject + fixed SQLA08
SQL or shell injection$1 parameters, execFile with --A05
a form on her own siteexact CORS list, SameSite + Sec-Fetch-Site checkA01
making your server fetch for herevery address checked at connect timeA01
two requests at onceone atomic UPDATE, an idempotency key for retriesA06

What this post skipped: MFA, admin-only routes, NoSQL and template injection, path traversal, file uploads, prototype pollution, open redirects, webhooks, security headers, secrets, dependencies, ReDoS and logging.

Try it on your own app:

  • Send 20 parallel logins and count how many reach the password check.
  • Log in as a second user and try to read the first user's data on every route with an ID.
  • Open two terminals and fire the same request at your money or email endpoint from both at once.

For the skipped topics, the OWASP Top 10:2025 and the OWASP Cheat Sheet Series are where I would go next.