- Cybersecurity
- security
- jwt
- nestjs
Refresh Tokens That Catch Thieves: Rotation, Reuse Detection and Family Revocation
A stolen refresh token is a quiet, long-lived key. How Lunexa rotates it on every use and turns a replayed token into an alarm.
Nayan Sukhadiya
Full Stack Engineer
Published
Updated at
When I started Lunexa's authentication I wrote the version most tutorials teach: a JWT access token, a JWT refresh token, and an endpoint that trades one for the other. It works. It also means that if a refresh token ever leaks, the attacker can mint fresh access tokens for weeks and nothing on the server will ever notice. For an app that holds someone's entire financial picture, "nothing will notice" was the part I couldn't accept.
The short answer
- Two tokens, two homes. The short-lived access token lives only in the client's memory. The long-lived refresh token lives in an HttpOnly cookie that JavaScript can't read, scoped to the /auth path.
- Every refresh token is a database row. The server stores a SHA-256 hash of it, so a token can be revoked, expired and traced.
- Every refresh rotates. Using a refresh token retires it and issues a new one, linked to the old.
- A retired token used again is theft. The server revokes every session the user has and invalidates all their access tokens.
The one idea behind it all A legitimate client only ever holds the newest refresh token. So if an old one shows up, somebody else has a copy, and you can't tell which party is the real user. The safe answer is to sign everyone out.
1. Where the tokens live
Access token: memory only. It is sent as a Bearer header and expires quickly. It is never written to localStorage, so a cross-site scripting bug can't read a stored copy, and a page refresh simply asks for a new one.
Refresh token: an HttpOnly cookie. The browser attaches it automatically, but page scripts can't see it. Two flags narrow it further:
res.cookie("refresh_token", refreshToken, {
httpOnly: true, // invisible to JavaScript
sameSite: "lax", // not sent on cross-site sub-requests
path: "/auth", // only travels to the auth endpoints
// secure: true in production
});Scoping the cookie to /auth means the most valuable token in the system isn't attached to every API call, only to the few routes that need it.
2. A token you can take back
A plain JWT is valid until it expires; the server can't recall it. So each refresh token in Lunexa is also a row in a refresh_sessions table: user, expiry, device hints, and a hash of the token. Storing the hash, not the token, means a database leak doesn't hand out working tokens.
export function hashRefreshToken(token: string): string {
return createHash("sha256").update(token).digest("hex");
}3. Rotation: one use per token
Every call to the refresh endpoint walks the same steps:
- Verify the JWT's signature and that it is a refresh token (typ: "refresh"), not an access token used in the wrong place.
- Look up the session row by the token's hash.
- If the row is expired, revoke it and refuse.
- Check the user's token version (more on that below).
- Issue a new access token and a new refresh token, store the new session row, and mark the old row as rotated, pointing at its replacement.
After step 5 the old refresh token is dead. The client got a new one in the response cookie and never needs the old one again.
4. Reuse detection: the alarm
The interesting case is a token whose row is already revoked and has a replacement. A real client would never send it, because it already received the newer one. So either the client is buggy, or the token was copied.
if (row.revokedAt) {
if (row.replacedById) {
// Reuse detected: possible theft. Kill the family.
await this.sessions.revokeFamily(row.userId);
await this.userService.incrementTokenVersion(row.userId);
}
throw unauthorized("Session reused or revoked");
}Revoking the family ends every refresh session for that user. Incrementing the token version handles the other half: access tokens already in circulation.
5. Token versions: logging out everywhere, instantly
Each user row has a token_version number, and every token is signed with the version that was current when it was issued. When the version goes up, every older token stops being accepted, without keeping a blocklist of individual tokens.
The same switch powers "log out of all devices": bump the version, revoke the sessions, done. It is also what reuse detection pulls when it fires.
What it costs
Nothing here is free, and I'd rather say so:
- Honest users get signed out sometimes. Two tabs refreshing at the exact same moment can look like reuse. The cost is one extra sign-in; the alternative is letting a thief keep a session.
- Every refresh writes to the database. A stateless JWT setup doesn't. For an app where each refresh happens every few minutes per user, the extra row is cheap.
- The client must handle rotation correctly. It always has to keep the newest cookie, which the browser does automatically for cookies, and which is exactly why the refresh token is a cookie.
The design decisions, side by side
| Decision | Why | Trade-off |
|---|---|---|
| Access token in memory | Nothing for injected scripts to steal from storage | A page refresh needs a silent refresh call |
| Refresh token in an HttpOnly cookie on /auth | Unreadable by JavaScript, absent from normal API calls | Needs CORS and cookie settings done carefully |
| Hashed session rows | Tokens are revocable and a leaked table is useless | A database write on every refresh |
| Rotate on every use | A copied token works at most once | Concurrent refreshes need care |
| Reuse revokes the family | Theft ends every session immediately | Rare false alarms sign a real user out |
| Token version on the user | "Log out everywhere" without a blocklist | One extra check per refresh |
What I take from it
Authentication is easy to make work and hard to make honest. The question that changed my design wasn't "is this token valid?" but "if this token were stolen, would I ever find out?" With rotation and reuse detection, the answer is yes, at the first moment the thief and the real user both try to use it.
Sources
Frequently asked questions
Why not keep the access token in localStorage?
Anything in localStorage can be read by any script running on the page, so one cross-site scripting bug exposes it. In memory, it disappears with the tab and can't be read from storage.
What is a refresh token "family"?
All the sessions that descend from one sign-in through rotation. Lunexa revokes every session for the user on reuse, which is the strictest version of the same idea.
Can two browser tabs cause a false alarm?
They can if both refresh at the same instant with the same cookie. It is rare, and the result is a sign-in prompt, which is the right side to fail on for a finance app.
- security
- jwt
- nestjs
- authentication
- lunexa