Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(auth): flush pending usage on shutdown and audit the queue-board boundary (#963)
Yudhi Armyndharise4701670ad3c
diff --git a/openapi.json b/openapi.jsonindex 9699399a7..8c01c86ba 100644--- a/openapi.json+++ b/openapi.json@@ -18,6 +18,7 @@"api_key_deleted","api_key_auth_failed","rate_limit_exceeded",+ "queue_board_mutated","session_created","session_started","session_stopped",diff --git a/src/common/security/bull-board-auth.middleware.spec.ts b/src/common/security/bull-board-auth.middleware.spec.tsindex 55145156e..58916a243 100644--- a/src/common/security/bull-board-auth.middleware.spec.ts+++ b/src/common/security/bull-board-auth.middleware.spec.ts@@ -4,6 +4,8 @@ import { Request, Response } from 'express';import { BullBoardAuthMiddleware } from './bull-board-auth.middleware';import { AuthService } from '../../modules/auth/auth.service';import { ApiKeyRole } from '../../modules/auth/entities/api-key.entity';+import { AuditService } from '../../modules/audit/audit.service';+import { AuditAction } from '../../modules/audit/entities/audit-log.entity';import { KeyRateLimiter } from '../../modules/mcp/mcp-rate-limit';const res = {} as Response;@@ -111,6 +113,7 @@ describe('BullBoardAuthMiddleware pre-auth IP throttle (mirrors MCP createIpThroreturn new BullBoardAuthMiddleware(authService as unknown as AuthService,configService as unknown as ConfigService,+ undefined, // no audit service needed for the throttle testsnew KeyRateLimiter(ipLimit, 60_000),);};@@ -187,3 +190,152 @@ describe('BullBoardAuthMiddleware pre-auth IP throttle (mirrors MCP createIpThroexpect(next).toHaveBeenCalledWith(); // allowed});});++// The Bull Board mount is raw Express, so the Nest guard's audit trail never sees it. The middleware+// now mirrors it at the boundary: 401/403 → WARN API_KEY_AUTH_FAILED; an authenticated non-GET/HEAD+// request → INFO QUEUE_BOARD_MUTATED. A throttled 429 is NOT audited — the pre-auth IP limiter is the+// flood bound for both the credential check and the audit table.+describe('BullBoardAuthMiddleware audit trail', () => {+ let mw: BullBoardAuthMiddleware;+ let authService: { validateApiKey: jest.Mock; hasPermission: jest.Mock };+ let auditService: { logWarn: jest.Mock; logInfo: jest.Mock };+ const res = {} as Response;++ const adminKey = { id: 'key-1', name: 'Admin', role: ApiKeyRole.ADMIN };++ const reqFor = (+ method: string,+ headers: Record<string, unknown> = {},+ originalUrl = '/api/admin/queues/api/queues/webhookQueue/1/retry',+ ): Request =>+ ({+ headers,+ query: {},+ ip: '127.0.0.1',+ socket: { remoteAddress: '127.0.0.1' },+ method,+ originalUrl,+ url: originalUrl,+ }) as unknown as Request;++ beforeEach(() => {+ authService = { validateApiKey: jest.fn(), hasPermission: jest.fn() };+ auditService = { logWarn: jest.fn(), logInfo: jest.fn() };+ const configService = { get: jest.fn().mockReturnValue(undefined) };+ mw = new BullBoardAuthMiddleware(+ authService as unknown as AuthService,+ configService as unknown as ConfigService,+ auditService as unknown as AuditService,+ );+ });++ it('audits a 401 (missing key) with IP, method and path', async () => {+ const next = jest.fn();+ await mw.use(reqFor('GET', {}, '/api/admin/queues/'), res, next);++ expect(next).toHaveBeenCalledWith(expect.any(UnauthorizedException));+ expect(auditService.logWarn).toHaveBeenCalledWith(+ AuditAction.API_KEY_AUTH_FAILED,+ expect.objectContaining({+ ipAddress: '127.0.0.1',+ method: 'GET',+ path: '/api/admin/queues/',+ errorMessage: 'API key is required to access the queue dashboard',+ }),+ );+ });++ it('audits a 401 (invalid key) rejection from validateApiKey', async () => {+ authService.validateApiKey.mockRejectedValue(new UnauthorizedException('Invalid API key'));+ const next = jest.fn();+ await mw.use(reqFor('GET', { 'x-api-key': 'bad' }, '/api/admin/queues/'), res, next);++ expect(next).toHaveBeenCalledWith(expect.any(UnauthorizedException));+ expect(auditService.logWarn).toHaveBeenCalledWith(+ AuditAction.API_KEY_AUTH_FAILED,+ expect.objectContaining({ errorMessage: 'Invalid API key' }),+ );+ });++ it('audits a 403 (valid non-admin key)', async () => {+ authService.validateApiKey.mockResolvedValue({ role: ApiKeyRole.OPERATOR });+ authService.hasPermission.mockReturnValue(false);+ const next = jest.fn();+ await mw.use(reqFor('GET', { 'x-api-key': 'op' }, '/api/admin/queues/'), res, next);++ expect(next).toHaveBeenCalledWith(expect.any(ForbiddenException));+ expect(auditService.logWarn).toHaveBeenCalledWith(+ AuditAction.API_KEY_AUTH_FAILED,+ expect.objectContaining({ errorMessage: 'Admin role required to access the queue dashboard' }),+ );+ });++ it('strips the query string from the audited path', async () => {+ const next = jest.fn();+ await mw.use(reqFor('GET', {}, '/api/admin/queues/?foo=bar'), res, next);++ expect(auditService.logWarn).toHaveBeenCalledWith(+ AuditAction.API_KEY_AUTH_FAILED,+ expect.objectContaining({ path: '/api/admin/queues/' }),+ );+ });++ it('audits an authenticated non-GET request as a queue-board mutation with the actor key and method+path', async () => {+ authService.validateApiKey.mockResolvedValue(adminKey);+ authService.hasPermission.mockReturnValue(true);+ const next = jest.fn();+ await mw.use(reqFor('POST', { 'x-api-key': 'admin' }), res, next);++ expect(next).toHaveBeenCalledWith(); // allowed through+ expect(auditService.logInfo).toHaveBeenCalledWith(+ AuditAction.QUEUE_BOARD_MUTATED,+ expect.objectContaining({+ apiKey: adminKey,+ ipAddress: '127.0.0.1',+ method: 'POST',+ path: '/api/admin/queues/api/queues/webhookQueue/1/retry',+ }),+ );+ expect(auditService.logWarn).not.toHaveBeenCalled();+ });++ it('does not audit GET or HEAD requests (read/poll traffic)', async () => {+ authService.validateApiKey.mockResolvedValue(adminKey);+ authService.hasPermission.mockReturnValue(true);++ await mw.use(reqFor('GET', { 'x-api-key': 'admin' }, '/api/admin/queues/'), res, jest.fn());+ await mw.use(reqFor('HEAD', { 'x-api-key': 'admin' }, '/api/admin/queues/'), res, jest.fn());++ expect(auditService.logInfo).not.toHaveBeenCalled();+ expect(auditService.logWarn).not.toHaveBeenCalled();+ });++ it('does not audit a throttled 429 — the pre-auth IP limiter is the flood bound', async () => {+ const tightMw = new BullBoardAuthMiddleware(+ authService as unknown as AuthService,+ { get: jest.fn().mockReturnValue(undefined) } as unknown as ConfigService,+ auditService as unknown as AuditService,+ new KeyRateLimiter(1, 60_000),+ );+ authService.validateApiKey.mockResolvedValue(adminKey);+ authService.hasPermission.mockReturnValue(true);++ await tightMw.use(reqFor('GET', { 'x-api-key': 'admin' }, '/api/admin/queues/'), res, jest.fn()); // consumes the slot+ const next = jest.fn();+ await tightMw.use(reqFor('GET', { 'x-api-key': 'admin' }, '/api/admin/queues/'), res, next); // throttled++ expect(next).toHaveBeenCalledWith(expect.any(HttpException));+ expect(auditService.logWarn).not.toHaveBeenCalled();+ expect(auditService.logInfo).not.toHaveBeenCalled();+ });++ it('degrades gracefully when no audit service is provided (rejections still work)', async () => {+ const noAuditMw = new BullBoardAuthMiddleware(+ authService as unknown as AuthService,+ { get: jest.fn().mockReturnValue(undefined) } as unknown as ConfigService,+ );+ const next = jest.fn();+ await noAuditMw.use(reqFor('GET', {}, '/api/admin/queues/'), res, next);+ expect(next).toHaveBeenCalledWith(expect.any(UnauthorizedException));+ });+});diff --git a/src/common/security/bull-board-auth.middleware.ts b/src/common/security/bull-board-auth.middleware.tsindex ba466636a..8251f3f50 100644--- a/src/common/security/bull-board-auth.middleware.ts+++ b/src/common/security/bull-board-auth.middleware.ts@@ -3,6 +3,8 @@ import { ConfigService } from '@nestjs/config';import { Request, Response, NextFunction } from 'express';import { AuthService } from '../../modules/auth/auth.service';import { ApiKeyRole } from '../../modules/auth/entities/api-key.entity';+import { AuditService } from '../../modules/audit/audit.service';+import { AuditAction } from '../../modules/audit/entities/audit-log.entity';import { KeyRateLimiter, readIpRateLimitConfig } from '../../modules/mcp/mcp-rate-limit';import { resolveClientIp } from '../utils/ip';@@ -20,6 +22,16 @@ import { resolveClientIp } from '../utils/ip';* A pre-auth per-IP throttle (mirroring the MCP mount's createIpThrottle) bounds a credential-probing* flood BEFORE it reaches the validateApiKey DB lookup. It uses the same KeyRateLimiter + IP-rate-limit* settings as MCP, so the two raw-Express mounts share one generous pre-auth IP-flood policy.+ *+ * Audit trail at this boundary (the Nest guard cannot see this mount):+ * - 401/403 rejections are recorded as WARN API_KEY_AUTH_FAILED, mirroring the REST guard and the+ * MCP mount. The pre-auth IP throttle above is the flood bound — a throttled 429 is NOT audited,+ * so a probing flood cannot drown the audit table either.+ * - An authenticated non-GET/HEAD request is recorded as INFO QUEUE_BOARD_MUTATED with method+path.+ * This is a boundary trace of queue-mutation attempts reaching the Bull Board router (the UI's+ * retry/remove/pause actions are POSTs); it deliberately does NOT model Bull Board's internal+ * per-action outcomes, which are invisible from middleware.+ * Both are fire-and-forget: audit logging is best-effort and must never affect the auth decision.*/@Injectable()export class BullBoardAuthMiddleware implements NestMiddleware {@@ -28,6 +40,7 @@ export class BullBoardAuthMiddleware implements NestMiddleware {constructor(private readonly authService: AuthService,private readonly configService: ConfigService,+ private readonly auditService?: AuditService,ipRateLimiter?: KeyRateLimiter,) {// Default to MCP's pre-auth per-IP policy (max 120 / 60s) when not supplied. Tests inject a tight@@ -58,14 +71,43 @@ export class BullBoardAuthMiddleware implements NestMiddleware {throw new ForbiddenException('Admin role required to access the queue dashboard');}+ // Boundary trace of queue-mutation attempts. GET/HEAD are the UI's read/poll traffic; every+ // other method reaching the Bull Board router mutates queue state, so record it with the+ // authenticated key, the resolved client IP, and the method + full path (no query string).+ if (req.method !== 'GET' && req.method !== 'HEAD') {+ void this.auditService?.logInfo(AuditAction.QUEUE_BOARD_MUTATED, {+ apiKey,+ ipAddress: clientIp,+ method: req.method,+ path: this.auditPath(req),+ });+ }+next();} catch (err) {+ // Audit the rejected/denied attempt for a forensic trail, like the REST guard and the MCP+ // mount do. A throttle overrun (HttpException 429) is deliberately NOT audited: the limiter+ // already rejected it, and logging each throttled hit would let a flood write unbounded rows.+ if (err instanceof UnauthorizedException || err instanceof ForbiddenException) {+ void this.auditService?.logWarn(AuditAction.API_KEY_AUTH_FAILED, {+ ipAddress: this.getClientIp(req),+ method: req.method,+ path: this.auditPath(req),+ errorMessage: err instanceof Error ? err.message : String(err),+ });+ }// Forward to Nest's exception layer so the response uses the standard format. A throttle overrun// surfaces here as an HttpException(429) → rendered as a standard 429 by the global exception filter.next(err);}}+ /** Full request path (mount prefix included) with any query string stripped. */+ private auditPath(req: Request): string {+ const url = req.originalUrl ?? req.url ?? '';+ return url.split('?')[0];+ }+private extractKey(req: Request): string | undefined {const header = req.headers['x-api-key'];if (typeof header === 'string' && header) return header;diff --git a/src/main.ts b/src/main.tsindex 697fd333e..391800ea1 100644--- a/src/main.ts+++ b/src/main.ts@@ -29,6 +29,7 @@ import {} from './config/bootstrap-security';import { BullBoardAuthMiddleware } from './common/security/bull-board-auth.middleware';import { AuthService } from './modules/auth/auth.service';+import { AuditService } from './modules/audit/audit.service';import { Request, Response, NextFunction, json, urlencoded } from 'express';import { randomBytes } from 'crypto';import { readFileSync } from 'fs';@@ -308,8 +309,13 @@ async function bootstrap() {// Protect the Bull Board queue UI (/api/admin/queues). It is mounted by// @bull-board/nestjs as raw Express middleware that the global ApiKeyGuard// does not cover; registering this before app.listen() ensures it runs ahead- // of the Bull Board router. Requires a valid ADMIN API key.- const bullBoardAuth = new BullBoardAuthMiddleware(app.get(AuthService), app.get(ConfigService));+ // of the Bull Board router. Requires a valid ADMIN API key. The middleware also+ // writes the audit trail for this mount (auth failures + queue mutations).+ const bullBoardAuth = new BullBoardAuthMiddleware(+ app.get(AuthService),+ app.get(ConfigService),+ app.get(AuditService),+ );app.use('/api/admin/queues', (req: Request, res: Response, next: NextFunction) => {void bullBoardAuth.use(req, res, next);});diff --git a/src/modules/audit/entities/audit-log.entity.ts b/src/modules/audit/entities/audit-log.entity.tsindex 2bd7b72a2..9ca38b109 100644--- a/src/modules/audit/entities/audit-log.entity.ts+++ b/src/modules/audit/entities/audit-log.entity.ts@@ -13,6 +13,9 @@ export enum AuditAction {// EventsGateway — so enforcing a limit never becomes an audit-write flood of its own).RATE_LIMIT_EXCEEDED = 'rate_limit_exceeded',+ // Queue dashboard (Bull Board) events+ QUEUE_BOARD_MUTATED = 'queue_board_mutated',+// Session eventsSESSION_CREATED = 'session_created',SESSION_STARTED = 'session_started',diff --git a/src/modules/auth/auth.service.spec.ts b/src/modules/auth/auth.service.spec.tsindex 253a232e4..4c69bf911 100644--- a/src/modules/auth/auth.service.spec.ts+++ b/src/modules/auth/auth.service.spec.ts@@ -1,8 +1,13 @@+// Spread the real fs so every method passes through, but as configurable props the test can spy on+// (the bare `import * as fs` namespace is non-configurable, so jest.spyOn can't redefine its methods).+jest.mock('fs', () => ({ __esModule: true, ...jest.requireActual<typeof import('fs')>('fs') }));+import { Test, TestingModule } from '@nestjs/testing';import { getRepositoryToken } from '@nestjs/typeorm';import { Repository } from 'typeorm';import { UnauthorizedException, NotFoundException, ConflictException } from '@nestjs/common';import { createHash, createHmac } from 'crypto';+import * as fs from 'fs';import { AuthService, resolveSeedApiKey, bannerKeyLine } from './auth.service';import { ApiKey, ApiKeyRole } from './entities/api-key.entity';@@ -93,6 +98,7 @@ describe('AuthService', () => {create: jest.fn(),save: jest.fn(),remove: jest.fn(),+ increment: jest.fn(),};const module: TestingModule = await Test.createTestingModule({@@ -571,6 +577,181 @@ describe('AuthService', () => {});});+ // ── usage-stat lost-update safety + shutdown flush ────────────────++ describe('usage-stat lost-update safety', () => {+ it('keeps the accumulated delta when the windowed save fails, and the next flush carries it', async () => {+ const rawKey = 'flaky-key';+ // Fresh row per findOne, as TypeORM returns it (no identity map): the DB state never+ // reflects the failed write, so the delta must survive in the pending map.+ const freshRow = () =>+ createMockApiKey({ keyHash: hashKey(rawKey), lastUsedAt: new Date(Date.now() - 5 * 60_000), usageCount: 5 });+ (repository.findOne as jest.Mock).mockImplementation(() => Promise.resolve(freshRow()));+ (repository.save as jest.Mock)+ .mockRejectedValueOnce(new Error('db write failed'))+ .mockImplementation(k => Promise.resolve(k));++ // The windowed write fails: the request still succeeds (the key is valid) and the delta is kept.+ const first = await service.validateApiKey(rawKey);+ expect(first.usageCount).toBe(6);++ // Still due on the next request (DB lastUsedAt was never written) → the retry persists the+ // failed delta plus this request's increment — nothing is lost.+ await service.validateApiKey(rawKey);+ const saves = (repository.save as jest.Mock).mock.calls as Array<[ApiKey]>;+ expect(saves[1][0].usageCount).toBe(7); // DB 5 + failed delta 1 + this request 1++ // The successful retry drained the accumulator — nothing left for the shutdown flush.+ await service.onModuleDestroy();+ expect(repository.increment).not.toHaveBeenCalled();+ });+ });++ describe('usage-stat shutdown flush', () => {+ it('flushes pending deltas on module destroy with an atomic increment, only once', async () => {+ const rawKey = 'recent-key';+ (repository.findOne as jest.Mock).mockResolvedValue(+ createMockApiKey({ keyHash: hashKey(rawKey), lastUsedAt: new Date(), usageCount: 5 }),+ );+ (repository.increment as jest.Mock).mockResolvedValue({ affected: 1 });++ await service.validateApiKey(rawKey); // inside the throttle window → coalesced, no DB write+ expect(repository.save).not.toHaveBeenCalled();++ await service.onModuleDestroy();+ expect(repository.increment).toHaveBeenCalledWith({ id: 'uuid-1' }, 'usageCount', 1);++ await service.onModuleDestroy(); // idempotent — nothing left pending+ expect(repository.increment).toHaveBeenCalledTimes(1);+ });++ it('does nothing on destroy when there is nothing pending', async () => {+ await service.onModuleDestroy();+ expect(repository.increment).not.toHaveBeenCalled();+ });++ it('tolerates a failing flush (destroy still resolves — stats are best-effort)', async () => {+ const rawKey = 'recent-key';+ (repository.findOne as jest.Mock).mockResolvedValue(+ createMockApiKey({ keyHash: hashKey(rawKey), lastUsedAt: new Date(), usageCount: 5 }),+ );+ (repository.increment as jest.Mock).mockRejectedValue(new Error('db gone'));++ await service.validateApiKey(rawKey);+ await expect(service.onModuleDestroy()).resolves.toBeUndefined();+ });+ });++ // ── bootstrap API key file (data/.api-key) staleness ─────────────++ describe('bootstrap API key file (data/.api-key)', () => {+ let existsSpy: jest.SpyInstance;+ let readSpy: jest.Mock;+ let unlinkSpy: jest.Mock;+ let logSpy: jest.SpyInstance;++ const bannerText = (): string => (logSpy.mock.calls as unknown[][]).map(call => String(call[0])).join('\n');++ beforeEach(() => {+ existsSpy = jest.spyOn(fs, 'existsSync').mockReturnValue(false);+ readSpy = jest.spyOn(fs, 'readFileSync') as unknown as jest.Mock;+ readSpy.mockReturnValue('');+ unlinkSpy = jest.spyOn(fs, 'unlinkSync') as unknown as jest.Mock;+ unlinkSpy.mockImplementation(() => undefined);+ logSpy = jest+ .spyOn((service as unknown as { logger: { log: (...args: unknown[]) => void } }).logger, 'log')+ .mockImplementation(() => undefined);+ });++ afterEach(() => {+ jest.restoreAllMocks();+ });++ it('revoke removes the bootstrap key file when it still holds the revoked key', async () => {+ const key = createMockApiKey({ isActive: true }); // keyHash matches hashKey('test-key')+ (repository.findOne as jest.Mock).mockResolvedValue(key);+ (repository.save as jest.Mock).mockImplementation(k => Promise.resolve(k));+ existsSpy.mockReturnValue(true);+ readSpy.mockReturnValue('test-key\n');++ await service.revoke('uuid-1');++ expect(unlinkSpy).toHaveBeenCalledWith(expect.stringContaining('.api-key'));+ });++ it('revoke leaves the file alone when it holds a different (still live) key', async () => {+ const key = createMockApiKey({ isActive: true });+ (repository.findOne as jest.Mock).mockResolvedValue(key);+ (repository.save as jest.Mock).mockImplementation(k => Promise.resolve(k));+ existsSpy.mockReturnValue(true);+ readSpy.mockReturnValue('another-key');++ await service.revoke('uuid-1');++ expect(unlinkSpy).not.toHaveBeenCalled();+ });++ it('delete removes the bootstrap key file when it still holds the deleted key', async () => {+ const key = createMockApiKey();+ (repository.findOne as jest.Mock).mockResolvedValue(key);+ (repository.remove as jest.Mock).mockResolvedValue(key);+ existsSpy.mockReturnValue(true);+ readSpy.mockReturnValue('test-key');++ await service.delete('uuid-1');++ expect(unlinkSpy).toHaveBeenCalledWith(expect.stringContaining('.api-key'));+ });++ it('tolerates a missing file on revoke (nothing to clean up)', async () => {+ const key = createMockApiKey({ isActive: true });+ (repository.findOne as jest.Mock).mockResolvedValue(key);+ (repository.save as jest.Mock).mockImplementation(k => Promise.resolve(k));+ existsSpy.mockReturnValue(false);++ await service.revoke('uuid-1');++ expect(unlinkSpy).not.toHaveBeenCalled();+ });++ it('boot removes a stale bootstrap file and the banner no longer advertises the dead key', async () => {+ (repository.count as jest.Mock).mockResolvedValue(1); // not first boot → the file path is consulted+ existsSpy.mockReturnValue(true);+ readSpy.mockReturnValue('owa_k1_deaddeaddead');+ (repository.findOne as jest.Mock).mockResolvedValue(null); // hash no longer resolves to any key++ await service.onModuleInit();++ expect(unlinkSpy).toHaveBeenCalledWith(expect.stringContaining('.api-key'));+ expect(bannerText()).toContain('(check dashboard for keys)');+ expect(bannerText()).not.toContain('owa_k1_d'); // no fingerprint of the dead key+ });++ it('boot treats a revoked bootstrap key as stale too', async () => {+ (repository.count as jest.Mock).mockResolvedValue(1);+ existsSpy.mockReturnValue(true);+ readSpy.mockReturnValue('test-key');+ (repository.findOne as jest.Mock).mockResolvedValue(createMockApiKey({ isActive: false }));++ await service.onModuleInit();++ expect(unlinkSpy).toHaveBeenCalled();+ expect(bannerText()).toContain('(check dashboard for keys)');+ });++ it('boot keeps a live bootstrap key: file untouched, banner shows the masked fingerprint', async () => {+ (repository.count as jest.Mock).mockResolvedValue(1);+ existsSpy.mockReturnValue(true);+ readSpy.mockReturnValue('test-key');+ (repository.findOne as jest.Mock).mockResolvedValue(createMockApiKey({ isActive: true }));++ await service.onModuleInit();++ expect(unlinkSpy).not.toHaveBeenCalled();+ expect(bannerText()).toContain('(full key in data/.api-key');+ });+ });+// ── hasPermission ─────────────────────────────────────────────────describe('hasPermission', () => {diff --git a/src/modules/auth/auth.service.ts b/src/modules/auth/auth.service.tsindex 905fb3c2e..98c393b36 100644--- a/src/modules/auth/auth.service.ts+++ b/src/modules/auth/auth.service.ts@@ -1,9 +1,16 @@-import { ConflictException, Injectable, NotFoundException, UnauthorizedException, OnModuleInit } from '@nestjs/common';+import {+ ConflictException,+ Injectable,+ NotFoundException,+ UnauthorizedException,+ OnModuleInit,+ OnModuleDestroy,+} from '@nestjs/common';import { ModuleRef } from '@nestjs/core';import { InjectRepository } from '@nestjs/typeorm';import { IsNull, MoreThan, Not, Repository } from 'typeorm';import { randomBytes } from 'crypto';-import { existsSync, readFileSync } from 'fs';+import { existsSync, readFileSync, unlinkSync } from 'fs';import { join } from 'path';import { writeSecretFile } from '../../common/utils/secret-file';import { ipMatches } from '../../common/utils/ip';@@ -47,11 +54,13 @@ export function bannerKeyLine(displayKey: string, isNewKey: boolean): string {}@Injectable()-export class AuthService implements OnModuleInit {+export class AuthService implements OnModuleInit, OnModuleDestroy {private readonly logger = createLogger('AuthService');/** Coalesce per-request usage-stat writes to at most one DB write per key per window. */private static readonly STAT_FLUSH_INTERVAL_MS = 60_000;+ /** Upper bound for the best-effort usage-stat flush on shutdown — teardown must not stall on a wedged DB. */+ private static readonly SHUTDOWN_FLUSH_TIMEOUT_MS = 5_000;/** keyId -> usage increments observed but not yet persisted (flushed on the next windowed write). */private readonly pendingUsage = new Map<string, number>();@@ -93,17 +102,9 @@ export class AuthService implements OnModuleInit {this.logger.warn('Could not save API key file', { error: String(err) });}} else {- // Read saved API key from file if exists- if (existsSync(API_KEY_FILE)) {- try {- displayKey = readFileSync(API_KEY_FILE, 'utf-8').trim();- } catch (error) {- this.logger.warn(`Failed to read API key file: ${API_KEY_FILE}`, { error: String(error) });- displayKey = '(check dashboard for keys)';- }- } else {- displayKey = '(check dashboard for keys)';- }+ // Read the saved bootstrap key from the file — but only while it still resolves to a LIVE+ // key; a revoked/rotated/deleted key must not be advertised in the banner.+ displayKey = (await this.readLiveBootstrapKey()) ?? '(check dashboard for keys)';}// Always show the welcome banner on startup@@ -130,6 +131,97 @@ export class AuthService implements OnModuleInit {this.logger.log('');}+ /**+ * Best-effort flush of the coalesced usage-stat counters on teardown. Nest runs onModuleDestroy+ * before the TypeORM connection closes (the DataSource is destroyed in onApplicationShutdown, the+ * last lifecycle hook), so the DB is still writable here. Bounded so a wedged DB cannot stall+ * shutdown past the grace window; whatever is still unflushed after the bound is dropped — the+ * counters are advisory statistics, authentication never depends on them.+ */+ async onModuleDestroy(): Promise<void> {+ if (this.pendingUsage.size === 0) return;+ this.logger.log(`Flushing usage stats for ${this.pendingUsage.size} API key(s) before shutdown`);+ const timeout = new Promise<'timeout'>(resolve =>+ setTimeout(() => resolve('timeout'), AuthService.SHUTDOWN_FLUSH_TIMEOUT_MS).unref(),+ );+ const result = await Promise.race([this.flushPendingUsage().then(() => 'done' as const), timeout]);+ if (result === 'timeout') {+ this.logger.warn('Usage-stat shutdown flush exceeded its time bound; remaining deltas dropped');+ }+ }++ /** Persist every accumulated usage delta with an atomic increment; entries that fail stay pending. */+ private async flushPendingUsage(): Promise<void> {+ for (const [keyId, delta] of [...this.pendingUsage.entries()]) {+ if (delta <= 0) {+ this.pendingUsage.delete(keyId);+ continue;+ }+ try {+ // Atomic UPDATE ... SET usageCount = usageCount + delta — no read-modify-write race with a+ // concurrent windowed save, unlike reloading the row and saving it back.+ await this.apiKeyRepository.increment({ id: keyId }, 'usageCount', delta);+ this.pendingUsage.delete(keyId);+ } catch (error) {+ this.logger.warn('Usage-stat flush failed for a key; delta kept pending', {+ keyId,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ }+ }++ /**+ * Read the bootstrap key file for the startup banner — only while it still points at a LIVE key.+ * The file is written once at first boot; when that key is later revoked, rotated, or deleted, the+ * file (and the banner quoting it) would otherwise keep advertising a dead credential. A stale file+ * is removed here too, so a backup restore that lost the key self-heals on the next boot.+ * Returns null when the file is absent, unreadable, empty, or stale.+ */+ private async readLiveBootstrapKey(): Promise<string | null> {+ if (!existsSync(API_KEY_FILE)) return null;+ let rawKey: string;+ try {+ rawKey = readFileSync(API_KEY_FILE, 'utf-8').trim();+ } catch (error) {+ this.logger.warn(`Failed to read API key file: ${API_KEY_FILE}`, { error: String(error) });+ return null;+ }+ if (!rawKey) return null;+ const stored = await this.apiKeyRepository.findOne({ where: { keyHash: this.hashKey(rawKey) } });+ const live = Boolean(stored && stored.isActive && (!stored.expiresAt || stored.expiresAt > new Date()));+ if (live) return rawKey;+ this.removeBootstrapKeyFile('it no longer resolves to an active key');+ return null;+ }++ /**+ * Remove the bootstrap key file when it still holds the key being revoked or deleted, so the next+ * boot's banner cannot point the operator at a dead credential. The file is an operator+ * convenience (banner + backup scripts); it is never read for seeding or authentication, so+ * removing it cannot break first-boot seeding — seeding writes it only when no keys exist.+ */+ private removeBootstrapKeyFileIfMatching(apiKey: ApiKey): void {+ try {+ if (!existsSync(API_KEY_FILE)) return;+ const fileKey = readFileSync(API_KEY_FILE, 'utf-8').trim();+ if (!fileKey || this.hashKey(fileKey) !== apiKey.keyHash) return;+ this.removeBootstrapKeyFile('its key was revoked or deleted');+ } catch (error) {+ this.logger.warn(`Failed to inspect API key file: ${API_KEY_FILE}`, { error: String(error) });+ }+ }++ private removeBootstrapKeyFile(reason: string): void {+ try {+ unlinkSync(API_KEY_FILE);+ this.logger.log(`Removed stale bootstrap API key file (${reason}): ${API_KEY_FILE}`);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return; // already gone+ this.logger.warn(`Failed to remove stale API key file: ${API_KEY_FILE}`, { error: String(error) });+ }+ }+private async seedApiKey(rawKey: string, name: string, role: ApiKeyRole): Promise<ApiKey> {const keyHash = this.hashKey(rawKey);const keyPrefix = rawKey.substring(0, 12);@@ -244,6 +336,7 @@ export class AuthService implements OnModuleInit {// Drop any un-flushed usage accumulator so a deleted key leaves nothing behind in the Map.this.pendingUsage.delete(id);await this.apiKeyRepository.remove(apiKey);+ this.removeBootstrapKeyFileIfMatching(apiKey);};// A target that is not a usable admin can skip the lock: it is not counted as one, so removing// it cannot strand the system — some other usable admin (or none at all) exists independently.@@ -267,7 +360,9 @@ export class AuthService implements OnModuleInit {// drop it here.this.pendingUsage.delete(id);apiKey.isActive = false;- return this.apiKeyRepository.save(apiKey);+ const saved = await this.apiKeyRepository.save(apiKey);+ this.removeBootstrapKeyFileIfMatching(apiKey);+ return saved;};const saved = AuthService.isUsableAdmin(apiKey)? await this.adminCapabilityLock.run(AuthService.ADMIN_CAPABILITY_LOCK_KEY, revokeKey)@@ -369,7 +464,19 @@ export class AuthService implements OnModuleInit {apiKey.lastUsedAt.getTime() - previousLastUsedAt.getTime() >= AuthService.STAT_FLUSH_INTERVAL_MS;if (due) {this.pendingUsage.delete(apiKey.id);- await this.apiKeyRepository.save(apiKey);+ try {+ await this.apiKeyRepository.save(apiKey);+ } catch (error) {+ // Lost-update safe: a failed windowed write must not drop the accumulated increments —+ // merge them back (accumulate, never overwrite, in case a concurrent path re-added a+ // delta) so the next windowed write or the shutdown flush persists them. Validation+ // itself succeeded, so a stat-write failure must not fail the request.+ this.pendingUsage.set(apiKey.id, (this.pendingUsage.get(apiKey.id) ?? 0) + pending);+ this.logger.warn('Usage-stat write failed; delta kept pending for the next flush', {+ keyId: apiKey.id,+ error: error instanceof Error ? error.message : String(error),+ });+ }} else {this.pendingUsage.set(apiKey.id, pending);}