import { Injectable, OnModuleInit } from "@nestjs/common"; import { ConfigService } from "@nestjs/config"; import { SchedulerRegistry } from "@nestjs/schedule"; import { InjectRepository } from "@nestjs/typeorm"; import { CronJob } from "cron"; import { LessThanOrEqual, Repository } from "typeorm"; import { TraceLogger } from "../common/trace-logger"; import { AppConfig } from "../config/app.config"; import { RevokedTokenEntity } from "./revoked-token.entity"; export const AUTH_REVOKED_TOKEN_CLEANUP_JOB = "auth-revoked-token-cleanup"; @Injectable() export class RevokedTokenCleanupService implements OnModuleInit { private readonly logger = new TraceLogger(RevokedTokenCleanupService.name); private readonly enabled: boolean; private readonly cleanupCron: string; constructor( @InjectRepository(RevokedTokenEntity) private readonly revokedTokens: Repository, config: ConfigService, private readonly schedulerRegistry: SchedulerRegistry, ) { this.enabled = config.get("AUTH_ENABLED"); this.cleanupCron = config.get("AUTH_REVOKED_TOKEN_CLEANUP_CRON"); } async onModuleInit(): Promise { if (!this.enabled) return; const job = CronJob.from({ cronTime: this.cleanupCron, start: false, waitForCompletion: true, onTick: async () => { try { await this.cleanupExpiredTokens(); } catch (error) { this.logger.error( `Failed to clean up expired revoked tokens: ${this.errorMessage(error)}`, ); } }, }); this.schedulerRegistry.addCronJob(AUTH_REVOKED_TOKEN_CLEANUP_JOB, job); job.start(); this.logger.debug( `Revoked-token cleanup cron registered: ${this.cleanupCron}`, ); try { await this.cleanupExpiredTokens(); } catch (error) { this.logger.error( `Failed to clean up expired revoked tokens at startup: ${this.errorMessage(error)}`, ); } } async cleanupExpiredTokens(): Promise { if (!this.enabled) return; const now = new Date(); const result = await this.revokedTokens.delete({ expiresAt: LessThanOrEqual(now), }); if (result.affected) { this.logger.debug(`Cleaned up ${result.affected} expired revoked tokens`); } } private errorMessage(error: unknown): string { return error instanceof Error ? error.message : String(error); } }