Refresh Token Rotation
Two feature stages in Tablewise's bookings API: replace a never-expiring API key with short-lived access tokens and refresh tokens, then make refresh tokens single-use with reuse detection and logout everywhere. The assistant's first version usually passes the happy path; the work is deciding what it must also survive.
On this page
The codebase
Tablewise is a table-booking service for restaurants. Its bookings API (Express 5, zod 4, strict TypeScript) signs staff in with an API key stored on the user row, and every route behind requireAuth looks it up.
The database layer is asynchronous on purpose: every statement yields to the event loop before it runs, as a round trip to the production Postgres would, so two requests interleave between any two statements of either. Only a transaction runs its statements with nothing in between.
Everything is injected: the clock, the configuration and the database. Each test builds a fresh app over a fresh in-memory database and moves its clock.
Where things live
src/services/auth.tslogin, authenticate and, by stage 2, refresh and logoutAll: where every decision of this challenge is made.src/services/tokens.tsThe four token functions the rest of the code calls. Their names and signatures are fixed.src/repositories/refreshTokens.tsData access for refresh_tokens. Every statement on the table goes here.src/http/routes/auth.tsPOST /auth/login, POST /auth/refresh, POST /auth/logout-all and GET /auth/me.src/http/middleware/requireAuth.tsReads the Bearer token and asks authenticate who it belongs to.src/util/crypto.tssafeEqual (constant time, different lengths unequal) and sha256Hex: reuse them.src/db/connection.tsThe asynchronous wrapper over node:sqlite, and db.transaction.src/config.tsToken lifetimes, the skew, the cookie name and the signing secret.candidate_tests/candidate.test.tsYour tests. The helpers in tests/helpers.ts (createTestApp, login, refresh, refreshTokenOf, me) work here.Rules that shape every fix
- Keep the HTTP API of the existing routes. New routes answer as the Reference and the stage questions say.
- A refresh token is a credential: made with node:crypto, kept only as its hash, sent only in its cookie.
- No new dependencies: there is no JWT or cookie library, and node:crypto signs and hashes.
- The set of files is fixed and
tests/is read-only.
How to work each stage
- Read the sign-in path and the helpers before asking for a change, and say what you will reuse.
- Ask for tests before the fix, and name the cases the happy path misses: a forged or cut token, the expiry boundary, what the database stores, several refreshes at once.
- Press Test and watch it fail. Then name the failing test and the value it showed.
- Decide the design yourself and say why: where the randomness comes from, what is stored, how the check and the use cannot interleave.
- Press Test again after the last change, then Continue or Submit.
Short-lived access tokens and refresh
What the ticket asks
Tablewise's staff app signs in with a long-lived API key that never expires. Replace it with sessions: a login answers an access token that lives five minutes and sets a refresh token in its cookie, and POST /auth/refresh exchanges a valid refresh token for a new access token.
Every signed-in route takes the access token as a Bearer token, and the old API key no longer signs anyone in. The task's Reference fixes the formats, the lifetimes and every answer.
Where to look
src/services/auth.tslogin hands out the user row's API key and authenticate looks it up. Both are what the stage replaces.src/services/tokens.tsThe four token functions are declared and throw. Their names and signatures are fixed, and a type-level test checks them.src/util/crypto.tssafeEqual already compares in constant time and answers false for different lengths, and sha256Hex already hashes. Reuse both.src/repositories/refreshTokens.tsThe record type exists and the repository is empty. Every statement on refresh_tokens belongs here.src/http/cookies.tsreadCookie reads one cookie. Express does not parse cookies itself.src/config.tsThe lifetimes (300 seconds, 30 seconds of skew, 14 days), the cookie name and the secret. No literal numbers elsewhere.What the contract pins down
refresh_tokens.token_hash.refresh_token, set with HttpOnly, Secure, SameSite=Strict and Path=/auth. Never in a response body.invalid_token and never a 500. A bad refresh token answers 401 invalid_refresh_token.Where the first version goes wrong
- The happy-path tests in
tests/sessions.test.tspass with refresh tokens made byMath.random, with the raw token stored, or with a cookie that only setsHttpOnly. Hidden tests check each of these. - timingSafeEqual on buffers of different lengths throws, so a cut signature becomes a 500 instead of a 401. safeEqual exists to avoid that.
- A verifier that skips the version check, ignores the skew, or keeps the API key as a fallback still passes the visible tests.
The fix
- Sign v1.<payload> with createHmac, and in the verifier split into exactly three parts, refuse any version but v1, compare signatures with safeEqual, then parse the claims with a zod schema.
- Refuse a token when nowSeconds > exp + skewSeconds, with the skew from config.
- Make refresh tokens with randomBytes(32) and store only sha256Hex of them, through the repository.
- Set the cookie with all four attributes and answer only accessToken and expiresIn.
- Drop the API-key lookup from authenticate, and the dead API-key code from login.
src/services/tokens.tsThe verifier refuses in a fixed order and never throws: shape, version, signature (constant time, any length), claims, expiry. The refresh token is a credential: random bytes from node:crypto, and only its hash is kept.-export function verifyAccessToken(token: string, secret: string, nowSeconds: number, skewSeconds: number): AccessTokenCheck {- throw new Error("verifyAccessToken is not implemented");+export function verifyAccessToken(token: string, secret: string, nowSeconds: number, skewSeconds: number): AccessTokenCheck {+ const parts = token.split(".");+ if (parts.length !== 3) return { ok: false, reason: "malformed" };+ const [version, payload, given] = parts as [string, string, string];+ if (version !== VERSION) return { ok: false, reason: "unsupported_version" };+ const expected = signature(`${version}.${payload}`, secret);+ if (!safeEqual(Buffer.from(given, "utf8"), Buffer.from(expected, "utf8"))) return { ok: false, reason: "bad_signature" };+ const claims = decodeClaims(payload);+ if (claims === undefined) return { ok: false, reason: "malformed" };+ if (nowSeconds > claims.exp + skewSeconds) return { ok: false, reason: "expired" };+ return { ok: true, claims }; }-export function newRefreshToken(): string {- throw new Error("newRefreshToken is not implemented");+export function newRefreshToken(): string {+ return randomBytes(REFRESH_TOKEN_BYTES).toString("base64url"); }-export function hashRefreshToken(token: string): string {- throw new Error("hashRefreshToken is not implemented");+export function hashRefreshToken(token: string): string {+ return sha256Hex(token); }src/services/auth.tsauthenticate verifies the access token and loads its user. The API key no longer signs anyone in.- async authenticate(credential: string): Promise<AuthUser> {- const user = await repos.users.findByApiKey(credential);+ async authenticate(accessToken: string): Promise<AuthUser> {+ const check = verifyAccessToken(accessToken, config.tokenSecret, epochSeconds(deps.clock), config.accessTokenSkewSeconds);+ if (!check.ok) throw unauthorized("invalid_token");+ const user = await repos.users.findById(check.claims.sub);src/http/routes/auth.tsThe refresh token travels only in its cookie, with every attribute the Reference names.+ response.cookie(config.refreshCookieName, session.refreshToken, {+ httpOnly: true,+ secure: true,+ sameSite: "strict",+ path: "/auth",+ });+ response.json({ accessToken: session.accessToken, expiresIn: session.expiresIn });Tests that prove it
- An access token whose payload was changed, one whose signature was cut short and one signed with another secret: each 401
invalid_token, never a 500. - The access token is accepted at exp + 30 and refused at exp + 31, by moving the test clock.
refresh_tokensholds only the SHA-256 of the cookie's token, and the cookie has its four attributes.- Two logins with
Math.randomstubbed byvi.spyOnstill get different refresh tokens, and the old API key gets 401.
The conversation
Only your side is shown: the assistant reads, writes and runs between your messages. Each chip is a rubric item the step earns.
DirectionPrompt qualityVerificationCorrectnessCode quality
- Press Test. Red at the first visible test: login still answers the API key. Your own tests run next to it.
- Verification: Checks own, 8 points
- Verification: Security cases, 6 points
- Press Test. Every test passes after the last change, your own included.
- Verification: Run after last change, 6 points
- Continue. The stage closes. Scope, the hidden tests and code quality are judged on the final code.
- Direction: Scope, 6 points
- Correctness: Hidden tests, 20 points
- Code quality: Code quality, 10 points
Where the stage lands
Measured when this conversation was played on the platform. A+ needs 92, S needs 95.
Rotation, reuse detection and logout everywhere
What the ticket asks
Make refresh tokens single-use. Every refresh uses up its token and sets the next one in the cookie, in the login's family. A token presented again after it was used is taken as stolen: the refresh answers 401 and every token of that login is revoked, the newest included.
From then on the login's access tokens are refused too, and POST /auth/logout-all signs the user out on every device. Simultaneous refreshes with one token count as reuse: exactly one succeeds.
Where to look
src/db/connection.tsEvery statement yields to the event loop first, as a Postgres round trip would. A read and a separate update can interleave with another request. db.transaction holds the turn.src/services/auth.tsrefresh finds the token and signs a new access token without using it up. The whole stage lives here.src/repositories/refreshTokens.tsinsert and findByHash exist. Marking a token used, revoking a family and checking one belong next to them.src/services/bookings.tsAlready books inside a transaction, for the same reason.tests/rotation.test.tsThe happy path of rotation and logout-all. Nothing in it fires two refreshes at once.What the contract pins down
invalid_refresh_token and revokes its family, the newest token included. The user's other logins keep working.invalid_token at once, not when their five minutes are up./auth/logout-all with a valid access token answers 204 with no body and revokes every family of the user.Where the first version goes wrong
- A rotation that reads the token, checks
used_atand then updates it in separate statements lets two simultaneous refreshes both pass the check, because the database yields between statements. The visible tests never fire two at once. - Revoking only the presented token on reuse leaves the thief's newest token working.
- Throwing the refusal inside the transaction rolls the revocation back with it.
- Without a family check in authenticate, a revoked login's access tokens keep working for five minutes.
The fix
- Do the find, the reuse check, the use and the insert of the next token in one
db.transaction. - Mark the token used with a conditional UPDATE ... WHERE
used_atIS NULL and let its changed-row count decide the winner. - On reuse, revoke the whole family with one update, and return the refusal out of the transaction so the revocation commits.
- Refuse access tokens whose family has a revoked token, and revoke every family of the user at logout-all.
src/services/auth.tsOne transaction decides the refresh. A refusal is returned out of it and thrown after, so a revocation is never rolled back. An access token of a revoked family is refused at once.- async refresh(refreshToken: string | undefined): Promise<Session> {- const record = await repos.refreshTokens.findByHash(hashRefreshToken(refreshToken));- ...+ const outcome = await deps.db.transaction(async (tx): Promise<RefreshOutcome> => {+ const txRepos = createRepositories(tx);+ const record = await txRepos.refreshTokens.findByHash(tokenHash);+ if (record === undefined || record.revokedAt !== null) return { kind: "refused" };+ if (record.usedAt !== null) {+ await txRepos.refreshTokens.revokeFamily(record.familyId, now);+ return { kind: "refused" };+ }+ if (!(await txRepos.refreshTokens.markUsed(record.id, now))) return { kind: "refused" };+ const next = await issue(txRepos, record.userId, record.familyId);+ return { kind: "rotated", userId: record.userId, familyId: record.familyId, refreshToken: next };+ });+ if (outcome.kind === "refused") throw unauthorized("invalid_refresh_token");- if (!check.ok) {+ if (!check.ok || (await repos.refreshTokens.isFamilyRevoked(check.claims.sid))) { throw unauthorized("invalid_token"); }src/repositories/refreshTokens.tsUsing a token is a conditional update: only the first caller changes the row.+ async markUsed(id: number, at: number): Promise<boolean> {+ const result = await q.run(+ "UPDATE refresh_tokens SET used_at = ? WHERE id = ? AND used_at IS NULL AND revoked_at IS NULL",+ at,+ id,+ );+ return result.changes === 1;+ },Tests that prove it
- Eight refreshes with the login's token at once through
Promise.all: exactly one 200, and the winner's next refresh answers 401. - t1 refreshed to t2 and t2 to t3, then t1 again: 401, and t3 and its access token are refused.
- A second login of the same user still refreshes after the first login's reuse.
- logout-all ends every login of the user and their access tokens, and another user keeps working.
The conversation
Only your side is shown: the assistant reads, writes and runs between your messages. Each chip is a rubric item the step earns.
DirectionPrompt qualityVerificationCorrectnessCode quality
- Press Test. Red at the first rotation test: the refresh sets no new cookie. Your own tests run next to it.
- Verification: Checks own, 7 points
- Verification: Race and reuse tested, 7 points
- Press Test. Every test passes after the last change, your own included.
- Verification: Run after last change, 6 points
- Submit. The stage closes. Scope, the hidden tests and code quality are judged on the final code.
- Direction: Scope, 5 points
- Correctness: Hidden tests, 20 points
- Code quality: Code quality, 10 points
Where the stage lands
Measured when this conversation was played on the platform. A+ needs 92, S needs 95.