All files / src/infrastructure/security jwt-token.service.ts

100% Statements 19/19
100% Branches 14/14
100% Functions 4/4
100% Lines 19/19

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 54 55 56 57 58 59 60 61 62 63 64 65 66              22x 22x 22x 22x       236x             236x           236x       469x 469x   469x 2x     464x   5x         16x 16x   16x               3x     11x   5x        
import { randomUUID } from 'node:crypto';
import jwt, { SignOptions } from 'jsonwebtoken';
import { AccessTokenPayload, RefreshTokenPayload, TokenPair, TokenService } from '../../application/user/token-service';
import { InvalidTokenError } from '../../application/user/errors/invalid-token.error';
 
export class JwtTokenService implements TokenService {
  constructor(
    private readonly accessSecret: string,
    private readonly refreshSecret: string,
    private readonly accessExpiresIn: string,
    private readonly refreshExpiresIn: string,
  ) {}
 
  generateTokenPair(userId: string, sessionVersion: number): TokenPair {
    const accessToken = jwt.sign({ sub: userId, type: 'access' }, this.accessSecret, {
      expiresIn: this.accessExpiresIn,
    } as SignOptions);
 
    // jti identifies this refresh token individually so a single one can be revoked (logout,
    // rotation) without invalidating every session the user has; sessionVersion is the opposite
    // handle — it invalidates all of them at once, without the server keeping a list.
    const refreshToken = jwt.sign(
      { sub: userId, type: 'refresh', jti: randomUUID(), sessionVersion },
      this.refreshSecret,
      { expiresIn: this.refreshExpiresIn } as SignOptions,
    );
 
    return { accessToken, refreshToken };
  }
 
  verifyAccessToken(token: string): AccessTokenPayload {
    try {
      const payload = jwt.verify(token, this.accessSecret);
 
      if (typeof payload === 'string' || payload.type !== 'access' || typeof payload.sub !== 'string') {
        throw new InvalidTokenError();
      }
 
      return { sub: payload.sub };
    } catch {
      throw new InvalidTokenError();
    }
  }
 
  verifyRefreshToken(token: string): RefreshTokenPayload {
    try {
      const payload = jwt.verify(token, this.refreshSecret);
 
      if (
        typeof payload === 'string' ||
        payload.type !== 'refresh' ||
        typeof payload.sub !== 'string' ||
        typeof payload.jti !== 'string' ||
        typeof payload.exp !== 'number' ||
        (payload.sessionVersion !== undefined && typeof payload.sessionVersion !== 'number')
      ) {
        throw new InvalidTokenError();
      }
 
      return { sub: payload.sub, jti: payload.jti, exp: payload.exp, sessionVersion: payload.sessionVersion };
    } catch {
      throw new InvalidTokenError();
    }
  }
}