Refresh-token rotation with reuse detection in NestJS
A refresh token is the most valuable string your API hands out. It lives for weeks, it mints new access tokens, and if someone copies it from a leaked log, a compromised laptop or a careless proxy, they can quietly stay logged in as your user. Most of the time, nobody notices.
Rotation with reuse detection turns that silent theft into something you can see, and stop.
The idea in three rules
- Every refresh returns a new refresh token and marks the old one as used.
- All tokens issued from one login share a family ID.
- If a token that was already used (or revoked) comes back, someone has a copy. Revoke the whole family and record it.
The real user and the attacker now hold tokens from the same family. Whoever refreshes second triggers the alarm, and both are logged out. The real user signs in again; the attacker has nothing.
What it looks like
async refresh(rawToken: string, context: RequestContext) { const token = await this.refreshTokens.findRefreshTokenByHash(this.hashToken(rawToken)); if (!token || token.expiresAt <= new Date()) { throw new UnauthorizedException({ code: 'INVALID_REFRESH_TOKEN', message: 'Invalid refresh token' }); } if (token.usedAt || token.revokedAt) { await this.refreshTokens.revokeRefreshFamily(token.familyId); await this.audit.record({ event: 'REFRESH_TOKEN_REUSE', ...context, userId: token.userId }); throw new UnauthorizedException({ code: 'REFRESH_TOKEN_REUSED', message: 'Refresh token reuse detected' }); } const user = await this.users.findById(token.userId); if (!user) { throw new UnauthorizedException({ code: 'INVALID_REFRESH_TOKEN', message: 'Invalid refresh token' }); } await this.refreshTokens.markRefreshTokenUsed(token.id); return this.issueSession(user, context, token.familyId, token.id); } Three details worth copying:
- The token is looked up by its hash. The database never stores the raw value, so a database leak is not a session leak.
- Reuse is an audit event, not just an error. During an incident,
REFRESH_TOKEN_REUSErows tell you which accounts were targeted and from which IP. - The new token keeps the family ID. That's what makes "revoke everything from this login" a single query.
Testing it
The test that matters is the attack itself: log in, refresh once, then replay the first token. Expect 401 with REFRESH_TOKEN_REUSED, and expect the second token to be dead too. If your test suite doesn't do this against a real database, you don't know that it works.
When not to do this
- If your clients can't store a new token on every refresh (some embedded devices), rotation will log them out constantly.
- Two browser tabs refreshing at the same moment can look like reuse. Either refresh from one place in the client, or allow a short grace window — and accept that the window is also a window for an attacker.
- It costs one extra write per refresh. For most APIs that's nothing; for very high traffic, measure.
The full, tested implementation, including sessions, "log out everywhere" and e2e tests, is part of Salnor Kit.
النسخة العربية: تدوير الـ Refresh Token مع كشف إعادة الاستخدام في NestJS
原文:https://www.a8q9.cn/en/article/refresh-token-rotation-with-reuse-detection-in-nestjs-a3b5c0.html