- Preserve TraceLogger console formatting and add DebugLogger with DEBUG namespace output. - Select the logger through LOG_MODE and route application call sites through the factory. - Cover factory selection, console formatting, debug output and auth-log redaction.
77 lines
2.4 KiB
TypeScript
77 lines
2.4 KiB
TypeScript
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 { createAppLogger } from "../common/app-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 = createAppLogger(RevokedTokenCleanupService.name);
|
|
private readonly enabled: boolean;
|
|
private readonly cleanupCron: string;
|
|
|
|
constructor(
|
|
@InjectRepository(RevokedTokenEntity)
|
|
private readonly revokedTokens: Repository<RevokedTokenEntity>,
|
|
config: ConfigService<AppConfig, true>,
|
|
private readonly schedulerRegistry: SchedulerRegistry,
|
|
) {
|
|
this.enabled = config.get("AUTH_ENABLED");
|
|
this.cleanupCron = config.get("AUTH_REVOKED_TOKEN_CLEANUP_CRON");
|
|
}
|
|
|
|
async onModuleInit(): Promise<void> {
|
|
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<void> {
|
|
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);
|
|
}
|
|
}
|