Anh Tran dev notes

Production bugs from mobile and backend work, written up with the fix and how it was checked.

Note 13 / NestJS / Security / Auth

Refresh token rotation with reuse detection in NestJS, and the gaps that survived my first fix

A 30-day refresh token on a URL, no rotation, access tokens that outlived a ban. The rotation design I ended up with, and the lock, cache and test mistakes that came after it.

By
Trần Thế Anh, Software Engineer
Published
Work done
October 2026, AI Note Taker (NestJS, Prisma, Postgres, Redis)
Stack
NestJS 11, Prisma, Postgres advisory locks, Redis (ioredis), jsonwebtoken-style JWTs, Jest
Reading
9 min, 1,869 words

My audit list for the AI Note Taker backend had a handful of lines about sessions. The app sent its refresh token in a query string. The server never rotated that token, so a copy stolen on day one worked in parallel with the real one until day 30 and nothing would notice. A ban, a logout or an account deletion request changed the database but not the access token already in someone’s hand, which kept working until it expired 15 minutes later. The refresh cookie for the web admin lived 7 days while the token inside it lived 30.

Each of those is a small fix. What took the time was that the first version of three of the fixes had a race in it, and one of those races was not covered by any test. This note walks through the design as it stands in the code now and then through the three mistakes, because the mistakes are the transferable part.

Token on the URL, and why the old route is still there

The app called GET /auth/refresh-token?refreshToken=<jwt>. A query string lands in proxy access logs, in crash-report strings and in anything that records URLs. The new route is POST /auth/refresh with the token in the body, or in an httpOnly cookie for the web client. The Flutter client now stores the rotated token before it replays the request that got a 401, because a rotated-out token sent a second time looks exactly like theft to the server.

The old GET route is still in the controller. App versions 1.0.0 to 1.0.3 are on the stores and use it, so removing it logs those users out. It rotates like the new one, answers through Set-Cookie where the shipped app reads it, and writes a warning line each time it is called so I can tell when nobody uses it any more. A scan of the app source for queryParameters with a token, refresh-token or ?refreshToken= finds no call site; the only match is a comment in api_config.dart.

What a rotated token row remembers

The table keeps a SHA-256 of the token, not the token. The tokens are signed JWTs with high entropy, so a slow hash like bcrypt protects nothing here and would add latency to every refresh. Three more columns carry the design: family_id (every token descended from one login shares it), parent_id with a unique index, and rotated_at.

Rotation is one transaction, and its first statement takes a per-user advisory lock:

await prisma.$transaction(async (tx) => {
  await tx.$executeRaw`SELECT pg_advisory_xact_lock(${NS}::int4, ${userId}::int4)`;

  const parent = await tx.refreshToken.findFirst({ where: { id: parentId, deletedAt: null } });
  if (!parent) return { kind: 'revoked' };

  if (parent.rotatedAt) {
    const inGrace = now - parent.rotatedAt.getTime() <= GRACE_MS;   // 60 s
    const pair = inGrace ? await replayStore.get(parent.id) : null;
    if (pair) return { kind: 'replayed', pair };

    await tx.refreshToken.updateMany({
      where: { familyId: parent.familyId, deletedAt: null },
      data: { deletedAt: now },
    });
    return { kind: 'reused' };            // return, do not throw
  }
  // first use: mark parent rotated, insert the child with the same family_id
});

The return on reuse matters. Throwing inside a Prisma interactive transaction rolls it back, and the rollback would undo the revocation that the branch exists to perform. The caller turns reused into a 401 with its own error code and clears the access-token cache for every session in the family.

This is the behaviour RFC 9700 describes for public clients: when a rotated token is presented again, the server cannot tell the thief from the legitimate client, so it revokes the active token and the user signs in again.

The grace window, and the first version that was wrong

Two requests with the same token do happen: two browser tabs, or a retry after a response was lost on a bad network. Rejecting the second one would sign out honest users. My first fix allowed a 60 second grace window in which the old token was accepted again and got a sibling child token. A comment in the current code records why that went: a thief who re-presents the token within the window receives a second live branch of the session, and nothing detects it.

The code now returns the exact pair of tokens issued by the first rotation. That pair is kept in Redis for the length of the grace window, encrypted with AES-GCM under a key derived (HKDF-SHA256) from the parent refresh token itself. Someone who can read Redis cannot open it without the parent token, and it fails to open if copied to another row. If the pair is missing, because the window passed or Redis was down, the presented token counts as reused and the family is revoked. That fails closed: the worst outcome is one extra login.

The unique index on parent_id is the last line of defence. A parent cannot have two children even if the lock is bypassed.

The cookie expiry was Date.now() + COOKIE_EXPIRES_IN, a constant of 604,800,000 ms, set in two places. The token in it carried its own exp thirty days out. The CMS user was thrown to the login page on day 8 with 23 days of token life left. The fix is to stop having two sources: setRefreshCookie reads exp from the JWT it is about to store and uses that for expires, and the constant is gone. A rotated child inherits the family’s exp, so rotation does not stretch a session, and a test asserts the child’s exp equals the parent’s. A scan for .cookie( now returns one call.

RFC 6265 defines Expires as the absolute time the browser may drop the cookie, so a cookie that expires before the token it holds is a plain bug, not a security feature.

Revocation that works before the access token expires

The guard used to verify the signature and set request.user. Logout, an admin ban, a deletion request, password change, guest upgrade and guest merge all wrote to the database and none of them could reach a token already issued. Seven places touched sessions.

The access token now carries the id of its refresh-token row, and the guard asks a SessionStateService whether that session and its owner are still allowed. It does one Redis MGET for both keys with a 30 second TTL and a 50 ms command timeout. A miss or a Redis error reads Postgres instead. The guard never lets a request through because it could not find out. Every revocation door, after its database write commits, overwrites the cache key with 0. The overwrite is the point: deleting the key would let a request that read the database a moment earlier refill it with a stale 1.

That last sentence is the second mistake.

Mistake one: reading before taking the lock (BL-088)

revokeFamilyOf, the logout path, first looked up { userId, familyId } for the session and then opened a transaction and took the lock. Rows issued before rotation existed have family_id NULL, and rotation assigns the family on first refresh. When a refresh slipped in between the read and the lock, logout still held familyId = null, revoked only the parent row, and the child token created in the gap survived. The user logged out and their new access token still passed the guard.

// wrong: decision data read outside the lock
const row = await db.refreshToken.findFirst({ where: { id }, select: { userId: true, familyId: true } });
await db.$transaction(async (tx) => {
  await lock(tx, row.userId);
  await revoke(tx, row.familyId ? { familyId: row.familyId } : { id });
});

// right: only immutable data before the lock, everything else after
const owner = await db.refreshToken.findFirst({ where: { id }, select: { userId: true } });
await db.$transaction(async (tx) => {
  await lock(tx, owner.userId);
  const fresh = await tx.refreshToken.findFirst({ where: { id }, select: { familyId: true } });
  await revoke(tx, fresh?.familyId ? { familyId: fresh.familyId } : { id });
});

The rule I wrote down: before the lock you may read only what cannot change, here the owner of the row, to know whose lock to take. PostgreSQL’s pg_advisory_xact_lock waits when the lock is held and releases at the end of the transaction, so everything read after it is a consistent view for that user. I grepped the four write paths in the service (create, rotate, revoke family, revoke all for user) and each takes the lock first; revokeAllForUser filters by userId and reads nothing beforehand.

Mistake two: refilling the cache over a revocation (BL-089)

Filling the cache after a database read uses SET key '1' EX 30 NX. NX means set only if the key does not exist. A request can read the database as “alive”, then logout runs and writes 0, and then the first request writes its stale 1. Without NX that revived the session for up to 30 seconds. Redis documents NX as only setting a key that does not already exist, which is exactly the property the stale write must lose to.

Mistake three: the race had no test

A reviewer deleted the 'NX' argument as a mutation test. The suite still reported 22 passing tests. The mechanism existed only in the code. The new test uses a fake database with an afterRead hook that runs logout between the guard’s read and its cache fill, then asserts the next request is rejected. Remove NX and it goes red.

The same pattern covers the logout race: a unit test with a hook that fires when the lock is acquired and injects the refresh, and an integration test on a real Postgres that holds the advisory lock in a separate transaction and waits until pg_locks shows the other session waiting. Making the read-before-lock mistake again turns both red. My working rule is that each anti-race mechanism needs a test that builds the exact interleaving, and the mutation that removes the mechanism must fail it. A green run after the mutation means the test does not guard anything.

What was checked and what was not

From my lesson notes: the integration spec for the session lifecycle passed 7 of 7 on a local Postgres and Redis, and the mutations described above turned the matching tests red and green again when restored. Cache-hit overhead measured at about 0.08 ms p95 and a miss about 0.48 ms on that setup. I did not re-run the suites while writing this note, because the checkout I read has no node_modules; what I did re-run is the source scans quoted above. I have no production evidence of a reuse event, and the code paths in this note had not been committed to a release branch when I wrote the lessons.

Two limits remain in the design. A revocation write to Redis can fail, in which case the code logs an error and a stale cache entry lives up to 30 seconds. Long-lived SSE streams re-check the session every 25 seconds rather than instantly.

Sources: RFC 9700, section 4.14.2 (refresh token rotation, https://www.rfc-editor.org/rfc/rfc9700); RFC 6265, section 5.2.1 (the Expires attribute); PostgreSQL documentation, advisory lock functions (https://www.postgresql.org/docs/current/functions-admin.html); Redis documentation for SET (https://redis.io/docs/latest/commands/set/).