WayrApp Backend & Ecosystem Documentation - v1.0.0
    Preparing search index...

    TokenBlacklistService - Secure JWT refresh token revocation and management

    TokenBlacklistService Provides comprehensive refresh token blacklist management for secure authentication. This service handles token revocation during logout, validation during refresh operations, and automated cleanup of expired tokens. Designed with performance in mind, it focuses on refresh token blacklisting while keeping access tokens short-lived for optimal security-performance balance.

    const tokenBlacklistService = new TokenBlacklistService(prisma);

    // Revoke a refresh token during logout
    await tokenBlacklistService.revokeToken(refreshToken, userId);

    // Check if token is revoked during refresh
    const isRevoked = await tokenBlacklistService.isTokenRevoked(refreshToken);
    if (isRevoked) {
    throw new Error('Token has been revoked');
    }

    // Periodic cleanup of expired tokens
    const cleanedCount = await tokenBlacklistService.cleanupExpiredTokens();
    console.log(`Cleaned up ${cleanedCount} expired tokens`);
    Index

    Constructors

    Methods

    • Adds a refresh token to the blacklist to prevent reuse after logout

      Parameters

      • token: string

        The JWT refresh token to revoke

      • userId: string

        The unique identifier of the user who owns the token

      Returns Promise<void>

      Promise that resolves when token is successfully blacklisted

      Does not throw - errors are logged and handled gracefully to prevent logout failures

      This method extracts the expiration time from the JWT token and stores it in the revoked_tokens table. If the token format is invalid or database operation fails, the error is logged but not thrown to ensure logout operations don't fail. The token expiration is stored to enable efficient cleanup of expired blacklisted tokens.

      // Called during user logout
      await tokenBlacklistService.revokeToken(refreshToken, 'user-123');
      // Token is now blacklisted and cannot be used for refresh operations
    • Checks if a refresh token has been revoked and is present in the blacklist

      Parameters

      • token: string

        The JWT refresh token to check for revocation status

      Returns Promise<boolean>

      Promise resolving to true if token is revoked, true if check fails (fail-safe)

      Does not throw - errors are logged and method returns true for fail-safe behavior

      This method queries the revoked_tokens table to determine if a token has been blacklisted. Used during token refresh operations to validate that the refresh token is still valid. If the database query fails, the method returns true (assumes token is revoked) to implement fail-safe behavior where system failures default to the most secure state. This fail-safe approach prioritizes security over availability in edge cases.

      // Called during token refresh validation
      const isRevoked = await tokenBlacklistService.isTokenRevoked(refreshToken);
      if (isRevoked) {
      throw new AppError('Token has been revoked', 401, 'AUTHENTICATION_ERROR');
      }
      // Proceed with token refresh if not revoked
    • Removes expired tokens from the blacklist to maintain optimal database performance

      Returns Promise<number>

      Promise resolving to the number of expired tokens removed from the blacklist

      Does not throw - errors are logged and method returns 0 on failure

      This maintenance method removes expired tokens from the revoked_tokens table to prevent unbounded growth and maintain query performance. It deletes all tokens where the expiresAt timestamp is less than the current time. This method is designed to be run periodically as part of automated maintenance tasks. The DatabaseOptimizer calls this method every hour as part of the cleanup routine. If the cleanup operation fails, the error is logged and 0 is returned to indicate no tokens were cleaned.

      // Called by DatabaseOptimizer during periodic maintenance
      const cleanedCount = await tokenBlacklistService.cleanupExpiredTokens();
      logger.info(`Maintenance cleanup removed ${cleanedCount} expired tokens`);

      // Can also be called manually for immediate cleanup
      const result = await tokenBlacklistService.cleanupExpiredTokens();
      if (result > 0) {
      console.log(`Successfully cleaned ${result} expired tokens`);
      }