Skip to content
Recommended solution · HC-9 · TypeScript

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

  1. Read the sign-in path and the helpers before asking for a change, and say what you will reuse.
  2. 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.
  3. Press Test and watch it fail. Then name the failing test and the value it showed.
  4. Decide the design yourself and say why: where the randomness comes from, what is stored, how the check and the use cannot interleave.
  5. Press Test again after the last change, then Continue or Submit.
Stage 1 · 01-sessions

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

Access tokenv1.<payload>.<signature>: the base64url JSON of sub, sid, iat and exp, then the base64url HMAC-SHA256 of the first two parts. Accepted up to exp + 30, refused at exp + 31.
Refresh token32 random bytes from node:crypto in base64url. The database keeps only its lowercase-hex SHA-256 in refresh_tokens.token_hash.
The cookierefresh_token, set with HttpOnly, Secure, SameSite=Strict and Path=/auth. Never in a response body.
Bad inputAny access token that is not valid, the old API key included, answers 401 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.ts pass with refresh tokens made by Math.random, with the raw token stored, or with a cookie that only sets HttpOnly. 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

  1. 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.
  2. Refuse a token when nowSeconds > exp + skewSeconds, with the skew from config.
  3. Make refresh tokens with randomBytes(32) and store only sha256Hex of them, through the repository.
  4. Set the cookie with all four attributes and answer only accessToken and expiresIn.
  5. 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_tokens holds only the SHA-256 of the cookie's token, and the cookie has its four attributes.
  • Two logins with Math.random stubbed by vi.spyOn still 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

  1. Your message 1

    Before I change anything, walk me through how signing in works today: login and authenticate in src/services/auth.ts, src/http/middleware/requireAuth.ts and src/http/routes/auth.ts; what src/repositories/refreshTokens.ts and the refresh_tokens table in src/db/schema.ts hold; and what src/util/crypto.ts and src/http/cookies.ts already give us. Don't change anything yet.

    Read the sign-in path and the helpers you will reuse before asking for a change.

    • Direction: Oriented first, 6 points
  2. Your message 2

    Thanks. Before any change to src/, write tests in candidate_tests/candidate.test.ts with the helpers from tests/helpers.ts for these cases: an access token whose payload was changed (sub set to 3) gets 401 invalid_token; a token whose signature was cut short, and one signed with another secret, get 401 invalid_token and never a 500; the access token is accepted at exp + 30 seconds and refused at exp + 31 (move the test clock); refresh_tokens holds only the lowercase-hex SHA-256 of the cookie's refresh token and no column contains the token itself; the refresh_token cookie has HttpOnly, Secure, SameSite=Strict and Path=/auth; two logins with Math.random stubbed by vi.spyOn still get different refresh tokens; and the old API key (ANA.apiKey) gets 401 invalid_token. Don't change src/ yet.

    You choose the cases the happy path misses, and you say how bad input must fail.

    • Prompt quality: Stated failures, 4 points
    • Prompt quality: Named the cases, 3 points
  3. 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
  4. Your message 3

    Test fails at tests/sessions.test.ts::login answers an access token that lives five minutes: login still answers { apiKey } instead of { accessToken, expiresIn: 300 }. Now build stage 1 like this. (1) src/services/tokens.ts: signAccessToken builds v1.<base64url of the JSON {sub, sid, iat, exp}> and appends the base64url HMAC-SHA256 of those two parts under the secret with createHmac. verifyAccessToken splits on '.' into exactly three parts (else malformed), refuses any version but v1 (unsupported_version), compares the expected and the given signature with safeEqual from src/util/crypto.ts, which answers false for different lengths, so a cut or foreign signature is bad_signature and never a throw or a 500; only then parses the payload inside a try with a zod schema for the four claims (malformed), and refuses when nowSeconds > exp + skewSeconds (expired). newRefreshToken is randomBytes(32).toString('base64url'), never Math.random, because a refresh token is a credential; hashRefreshToken is sha256Hex, so a leaked database holds no usable token. (2) The refresh-token repository gets insert and findByHash; all SQL stays in it. (3) login checks the password as now, makes a family id with randomBytes, stores only the token's hash with issued_at and expires_at from the injected clock and config.refreshTokenTtlSeconds, and signs the access token with sid = the family id, iat = epochSeconds(clock) and exp = iat + config.accessTokenTtlSeconds. The route sets the cookie with response.cookie(config.refreshCookieName, token, { httpOnly: true, secure: true, sameSite: 'strict', path: '/auth' }) and answers only { accessToken, expiresIn }: the refresh token never goes into a body. (4) POST /auth/refresh reads the cookie with readCookie, finds the hash, refuses an unknown, revoked or expired (now >= expires_at) token or a disabled account with unauthorized('invalid_refresh_token'), and answers a new access token with the record's family id. (5) authenticate verifies the access token with config.accessTokenSkewSeconds and loads the user; drop the API-key lookup so the old key gets invalid_token, and remove the dead API-key code and the 'not implemented' throws. Use the clock, config and the AppError helpers: no Date.now(), no literal 300, no second hashing or comparison helper, no any. Don't change the tests.

    Name the failing test and its value, then decide the credential and the verifier yourself, with the reason for each choice.

    • Direction: Credential design, 9 points
    • Direction: Verify design, 9 points
    • Prompt quality: Named contract, 6 points
    • Prompt quality: Asked for conventions, 4 points
    • Prompt quality: Failure follow-up, 3 points
  5. Press Test. Every test passes after the last change, your own included.
    • Verification: Run after last change, 6 points
  6. 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.

Direction30/30
Prompt quality20/20
Verification20/20
Correctness20/20
Code quality10/10
Stage total 100/100Grade S
Stage 2 · 02-rotation

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

RotationA refresh answers a new access token and sets the next refresh token, in the same family.
ReuseA used token presented again answers 401 invalid_refresh_token and revokes its family, the newest token included. The user's other logins keep working.
Immediate logoutAccess tokens of a revoked family answer 401 invalid_token at once, not when their five minutes are up.
logout-allPOST /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_at and 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

  1. Do the find, the reuse check, the use and the insert of the next token in one db.transaction.
  2. Mark the token used with a conditional UPDATE ... WHERE used_at IS NULL and let its changed-row count decide the winner.
  3. On reuse, revoke the whole family with one update, and return the refusal out of the transaction so the revocation commits.
  4. 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

  1. Your message 1

    Stage 2: refresh tokens become single-use. Before any change: how does refresh use the repository now, and what does src/db/connection.ts say about statements running between two awaits and about db.transaction? Don't change anything yet.

    No points of its own, but the answer about transactions and statements that yield is the reason for the design you ask for later.

  2. Your message 2

    Before any change to src/, add tests to candidate_tests/candidate.test.ts, keeping the stage-1 ones, for: eight refreshes with the login's token at once through Promise.all, where exactly one answers 200 and the winner's next refresh then answers 401; t1 refreshed to t2 and t2 to t3, then t1 sent again answers 401 invalid_refresh_token and t3 and its access token are refused; a second login of the same user still refreshes and calls /auth/me after the first login's reuse; and logout-all ending every login of the user and their access tokens while another user's login keeps working. Don't change src/ yet.

    The cases include the hard one, several refreshes at once, with the result each must give.

    • Prompt quality: Stated constraints, 5 points
    • Prompt quality: Named the cases, 3 points
  3. 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
  4. Your message 3

    Test fails at tests/rotation.test.ts::refresh hands out a new refresh token: the refresh answers 200 but sets no new cookie (newCookie: false). The rules: every refresh uses up its token and sets the next one in the cookie, in the same family. A token presented after it was used is a reuse: answer 401 invalid_refresh_token and revoke every token of that family, the newest included, while the user's other logins keep working. Access tokens of a revoked family are refused at once, so authenticate checks the family. POST /auth/logout-all with a valid access token answers 204 with no body and revokes every family of the user. It must hold when several refreshes with one token arrive at the same moment: exactly one wins and the family ends revoked, because the database wrapper yields between statements, so reading used_at and then running a separate UPDATE lets two requests both pass the check. Please: in the auth service, do the find, the reuse check, the use and the insert of the next token in one db.transaction, marking the token used with a conditional UPDATE ... WHERE id = ? AND used_at IS NULL AND revoked_at IS NULL whose changes count decides the winner; on reuse revoke the family with one UPDATE by family_id; return the refusal out of the transaction and throw unauthorized after it, because a throw inside would roll the revocation back. Add markUsed, revokeFamily, revokeAllForUser and isFamilyRevoked to the repository (all SQL there); authenticate refuses an access token whose family has a revoked token; the logout-all route sits behind requireAuth. Update the docstrings that say a refresh keeps its token. Don't change the tests.

    The assistant never saw this stage's question: give it the rules, the constraint with its reason, and the mechanism.

    • Direction: Reuse rule, 9 points
    • Direction: Atomic rotation, 9 points
    • Direction: Immediate revocation, 7 points
    • Prompt quality: Gave rules, 6 points
    • Prompt quality: Specified mechanism, 3 points
    • Prompt quality: Failure follow-up, 3 points
  5. Press Test. Every test passes after the last change, your own included.
    • Verification: Run after last change, 6 points
  6. 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.

Direction30/30
Prompt quality20/20
Verification20/20
Correctness20/20
Code quality10/10
Stage total 100/100Grade S
Refresh Token Rotation Solution — TypeScript Walkthrough | Hunicode