Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | 32x 32x 32x 18x 18x 3x 13x 13x 1x 12x 2x 10x 2x 8x 8x 8x 8x 8x | import { UserRepository } from './user-repository';
import { TokenPair, TokenService } from './token-service';
import { TokenRevocationService } from './token-revocation-service';
import { InvalidTokenError } from './errors/invalid-token.error';
export class RefreshUserSessionUseCase {
constructor(
private readonly userRepository: UserRepository,
private readonly tokenService: TokenService,
private readonly tokenRevocationService: TokenRevocationService,
) {}
async execute(refreshToken: string): Promise<TokenPair> {
const payload = this.tokenService.verifyRefreshToken(refreshToken);
if (await this.tokenRevocationService.isRevoked(payload.jti)) {
throw new InvalidTokenError();
}
const user = await this.userRepository.findById(payload.sub);
if (!user) {
throw new InvalidTokenError();
}
// Bulk invalidation: a password reset increments the account's session version, so every
// refresh token minted before it stops matching here — no list of jtis to keep, and no clock to
// agree on. A token from before this claim existed carries no version and reads as 0, the value
// every account starts at.
if ((payload.sessionVersion ?? 0) !== user.sessionVersion) {
throw new InvalidTokenError();
}
// A demo account ends at its expiry, not whenever the hourly sweep reaches it — the sweep only
// runs while the instance is awake. Refusing the refresh here bounds the overrun by the access
// token's 15 minutes, with no extra read: the user was already loaded above.
if (user.isExpiredDemoAt(new Date())) {
throw new InvalidTokenError();
}
const tokenPair = this.tokenService.generateTokenPair(user.id, user.sessionVersion);
// Refresh tokens are single-use/rotating: revoke the one that was just spent so a leaked or
// replayed copy of it is rejected immediately, functioning as reuse detection.
const remainingTtlSeconds = payload.exp - Math.floor(Date.now() / 1000);
Eif (remainingTtlSeconds > 0) {
await this.tokenRevocationService.revoke(payload.jti, remainingTtlSeconds);
}
return tokenPair;
}
}
|