Context
The API serves three roles (admin, instructor, student) and, later, a mobile client. It needs stateless request authentication, sessions that last weeks, and a way to end a session that has leaked. ADR-0002 (point 8) fixed the principle. This record fixes the mechanics as built in apps/api/src/modules/auth.
Decision
- Access token: a JWT signed with
JWT_ACCESS_SECRET(at least 32 characters, checked at boot), valid forJWT_ACCESS_TTL_SECONDS(default 900). Claims aresub,email,role, plusissset toJWT_ISSUER(smartlearn-ai). The strategy verifies the issuer, parses the claims with the sharedjwtPayloadSchema, and re-reads the user, so a deactivated account stops working at once. - Refresh token: 48 random bytes, opaque, valid for
JWT_REFRESH_TTL_DAYS(default 30). Only its SHA-256 hash is stored, inRefreshToken. - Rotation is atomic.
/auth/refreshrevokes with oneupdateManythat matchestokenHash,revokedAt: nullandexpiresAt > now, and continues only if exactly one row changed. Two concurrent refreshes with the same token cannot both succeed. - Reuse detection. If the presented token exists but is already revoked, every live refresh token of that user is revoked and the event is logged at error.
- Login is throttled to 5 attempts per minute per client IP (
LOGIN_THROTTLE); the global limit is 120 per minute. A missing user and a wrong password take the same time: bcrypt runs against a dummy hash when the user does not exist. - Private by default: the global
JwtAuthGuardprotects every route;@Public()opts out.
Alternatives considered
- Server sessions in Redis. Revocation is one delete, but every request needs a Redis read, and a mobile client prefers bearer tokens.
- Long-lived access tokens only. No way to end a leaked session before it expires.
- Passport local strategy. Adds a layer for what is one
comparecall.
Consequences
- Tokens travel in the response body today. Where the web client keeps them (httpOnly cookie through the single origin, or memory) is decided with the web auth work.
- Every authenticated request costs one user lookup. That is accepted for immediate deactivation.
- Throttle counters are in memory, which is correct only for a single api instance.