APIs with Express · Chapter 25 of 29

Project: the auth server

By the end of this chapter you can build sign-up, login and sessions that stay safe when a database or a token leaks. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: Projects
  • 6 tasks
  • Express
  • In the all labs plan

The first 2 chapters of APIs with Express are free. This one comes with the all labs plan.

Why you need this

The Tapri app is getting customer accounts. Anjali wants customers to sign up once and stay logged in for a week. Ravi wants a rider's session ended the moment a phone goes missing. Meera has one rule: if the database ever leaks, no password goes with it.

Chapter 15's tokens prove who is calling, but a token that lasts a week is a week-long key for whoever copies it. And a password stored as it is, or as a plain SHA-256, leaks with the database.

What you build: 6 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    hashPassword and verifyPassword: scrypt with a salt

    Export async hashPassword(password). It makes a fresh random 16-byte salt every time, runs scrypt on the password with those salt bytes (not their hex text) and a 64-byte key length, and resolves with 'saltHex:keyHex': 32 hex characters, a colon, 128 hex characters. The same password twice gives two different strings.

    Export async verifyPassword(password, stored), which resolves with true when password matches the stored 'saltHex:keyHex' and false otherwise, comparing with timingSafeEqual. It never throws: a different password ('chai-at-4PM'), a wrong key, a stored value with no colon ('not-a-hash') or a key that is too short ('<salt>:abcd') all resolve with false.

  2. Task 2

    signToken and verifyToken: HS256 tokens that expire

    Export signToken(payload, secret), which returns an HS256 JWT: the base64url of the JSON header { alg: 'HS256', typ: 'JWT' }, a dot, the base64url of the JSON payload, a dot, and the base64url HMAC-SHA256 of the first two parts (dot included) with secret.

    Export verifyToken(token, secret, nowSeconds), which returns the payload when the signature is right and payload.exp is a number greater than nowSeconds, and null otherwise. A token with exp 1000 is valid at 999 and null at 1000. It is null for another secret, a changed payload, a payload with no exp, and anything malformed: '', 'abc', 'a.b.c', two parts, four parts or undefined. It never throws.

  3. Task 3

    POST /signup and POST /login: accounts and a pair of tokens

    In createApp({ secret, now }) (now() is in milliseconds), keep users inside createApp. POST /signup takes { email, password }. Without an email string containing @ and a password string of 8 or more characters ({} included), it answers 400 { error: 'Email and a password of at least 8 characters are required' }. Emails are trimmed and lowercased; one that is already registered (RAVI@tapri.in after ravi@tapri.in) answers 409 { error: 'Email already registered' }. Otherwise it stores hashPassword(password), never the password, and answers 201 { id, email } with ids 'u1', 'u2' and so on ({ id: 'u2', email: 'anjali@tapri.in' } for ' Anjali@Tapri.in ').

    POST /login takes { email, password }, with the email trimmed and lowercased too. A wrong password and an unknown email both answer 401 { error: 'Invalid email or password' }. Otherwise 200 { accessToken, refreshToken, expiresIn: 900 }, both tokens signed with signToken and secret. With iat = Math.floor(now() / 1000), the access payload is exactly { sub: the user id, type: 'access', iat, exp: iat + ACCESS_TTL }, and the refresh payload is { sub, type: 'refresh', jti, family, iat, exp: iat + REFRESH_TTL }, where jti is a new unique id for every token and family a new id shared by every token of this login.

  4. Task 4

    GET /me: only with a valid access token

    GET /me reads the Authorization header. With no header, or one that does not start with 'Bearer ' (the token alone), it answers 401 { error: 'Missing token' }.

    It answers 401 { error: 'Invalid or expired token' } for a token that fails verifyToken with the app's secret and the current time in seconds (junk, another secret, or 900 seconds or more after login), and for a token whose type is not 'access', such as a refresh token.

    Otherwise it answers 200 { id, email } of the user named by sub ({ id: 'u1', email: 'ravi@tapri.in' }).

  5. Task 5 · interview question

    Interview: POST /refresh, rotation and reuse detection

    POST /refresh takes { refreshToken }. A token that fails verifyToken (garbage, or a week after it was made), is not of type 'refresh' (an access token), was never given out by this app, or whose family has ended answers 401 { error: 'Invalid refresh token' }.

    A valid token that has not been used answers 200 with a new { accessToken, refreshToken, expiresIn: 900 } in the same family, and the token that was sent is now used: the new refresh token is a different string, and its access token opens GET /me.

    A token that was already used once answers 401 { error: 'Refresh token reuse detected' } and ends its whole family, so even the newest token of that family then gets 'Invalid refresh token'. Other logins, with their own families, keep working.

  6. Task 6

    POST /logout: end one session

    POST /logout takes { refreshToken } and always answers 204 with no body, also for 'garbage' or no token at all.

    When the token is a valid refresh token of this app, its whole family ends: refreshing with it afterwards answers 401 { error: 'Invalid refresh token' }. Another login of the same user (the laptop) keeps working.

What you will learn

  • Password hashing: scrypt, a salt for every user, and a comparison that always takes the same time.
  • Access and refresh tokens: a short token for every request, and a long one used only to get new tokens.
  • Rotation and reuse detection: a refresh token works once, and a stolen copy gives itself away.
  • Logout: ending one session and leaving the others alone.

More in Projects

Build "Project: the auth server" yourself

Partner cafés want Tapri’s menu online by Friday: you build its API. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

The first 2 chapters of APIs with Express are free. This one comes with the all labs plan.