Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(auth): report an unparseable stored key expiry as expired
Yudhi Armyndharis0fe022aa7236
diff --git a/src/modules/auth/auth.controller.spec.ts b/src/modules/auth/auth.controller.spec.tsindex 7aaee27b0..1c77d3ff7 100644--- a/src/modules/auth/auth.controller.spec.ts+++ b/src/modules/auth/auth.controller.spec.ts@@ -172,3 +172,71 @@ describe('AuthController — API-key lifecycle audit logging', () => {expect(lastContextFor(AuditAction.API_KEY_REVOKED)?.metadata?.targetKeyId).toBe('k1');});});++// A key stored before expiresAt was validated can hold an unparseable expiry, which SQLite reads back as+// an Invalid Date. The gateway refuses such a key as expired, so every response must report it as expired+// too, not serialize the expiry as null (no expiry) and leave the key looking active.+describe('AuthController: unparseable stored expiry', () => {+ const stored = {+ id: 'k1',+ name: 'legacy',+ keyPrefix: 'ow_',+ role: 'user',+ isActive: true,+ usageCount: 0,+ createdAt: new Date('2026-01-01T00:00:00Z'),+ expiresAt: new Date('2026-W40-1'),+ } as unknown as ApiKey;+ const epoch = '1970-01-01T00:00:00.000Z';+ const makeReq = (): Request => ({ method: 'PUT', path: '/auth/api-keys/k1' }) as unknown as Request;++ let authService: Record<'createApiKey' | 'findAll' | 'findOne' | 'update' | 'revoke', jest.Mock>;+ let auditService: { logInfo: jest.Mock };+ let controller: AuthController;++ beforeEach(() => {+ authService = {+ createApiKey: jest.fn().mockResolvedValue({ apiKey: stored, rawKey: 'raw' }),+ findAll: jest.fn().mockResolvedValue([stored]),+ findOne: jest.fn().mockResolvedValue(stored),+ update: jest.fn().mockResolvedValue(stored),+ revoke: jest.fn().mockResolvedValue(stored),+ };+ auditService = { logInfo: jest.fn().mockResolvedValue(null) };+ controller = new AuthController(authService as unknown as AuthService, auditService as unknown as AuditService);+ });++ it('records the expiry as a past instant in the audited scope', async () => {+ await controller.create({ name: 'legacy' }, makeReq());+ await controller.update('k1', {}, makeReq());+ const [created, updated] = (+ JSON.parse(JSON.stringify(auditService.logInfo.mock.calls.map(call => (call as unknown[])[1]))) as {+ metadata: Record<string, { expiresAt: string | null }>;+ }[]+ ).map(ctx => ctx.metadata);+ expect(created.scope.expiresAt).toBe(epoch);+ expect(updated.before.expiresAt).toBe(epoch);+ expect(updated.after.expiresAt).toBe(epoch);+ });++ it('reports the expiry as a past instant in every key response', async () => {+ const responses = [+ await controller.create({ name: 'legacy' }, makeReq()),+ ...(await controller.findAll()),+ await controller.findOne('k1'),+ await controller.update('k1', {}, makeReq()),+ await controller.revoke('k1', makeReq()),+ ];+ for (const res of responses) {+ expect((JSON.parse(JSON.stringify(res)) as { expiresAt?: string }).expiresAt).toBe(epoch);+ }+ });++ it('passes a valid expiry and an unset one through unchanged', async () => {+ const expiresAt = new Date('2027-01-01T00:00:00Z');+ authService.findOne.mockResolvedValueOnce({ ...stored, expiresAt });+ expect((await controller.findOne('k1')).expiresAt).toBe(expiresAt);+ authService.findOne.mockResolvedValueOnce({ ...stored, expiresAt: null });+ expect((await controller.findOne('k1')).expiresAt).toBeUndefined();+ });+});diff --git a/src/modules/auth/auth.controller.ts b/src/modules/auth/auth.controller.tsindex e2766f39f..9ad565d8a 100644--- a/src/modules/auth/auth.controller.ts+++ b/src/modules/auth/auth.controller.ts@@ -8,6 +8,13 @@ import { type ApiKey, ApiKeyRole } from './entities/api-key.entity';import { AuditService } from '../audit/audit.service';import { AuditAction } from './../audit/entities/audit-log.entity';+// A key stored before expiresAt was validated can hold an unparseable expiry, which SQLite reads back as+// an Invalid Date. The gateway refuses such a key as expired, but JSON would serialize the expiry as null+// (no expiry). Report it as the epoch instead, so the key shows as expired and can be given a new expiry.+function readableExpiry(expiresAt: Date | null): Date | null {+ return expiresAt && Number.isNaN(expiresAt.getTime()) ? new Date(0) : expiresAt;+}+@ApiTags('auth')@Controller('auth/api-keys')// Key lifecycle routes have no session dimension, so a session-scoped ADMIN key could otherwise@@ -41,7 +48,24 @@ export class AuthController {allowedIps: key.allowedIps,allowedSessions: key.allowedSessions,allowedChats: key.allowedChats,- expiresAt: key.expiresAt,+ expiresAt: readableExpiry(key.expiresAt),+ };+ }++ private toResponse(k: ApiKey): ApiKeyResponseDto {+ return {+ id: k.id,+ name: k.name,+ keyPrefix: k.keyPrefix,+ role: k.role,+ allowedIps: k.allowedIps || undefined,+ allowedSessions: k.allowedSessions || undefined,+ allowedChats: k.allowedChats || undefined,+ isActive: k.isActive,+ expiresAt: readableExpiry(k.expiresAt) || undefined,+ lastUsedAt: k.lastUsedAt || undefined,+ usageCount: k.usageCount,+ createdAt: k.createdAt,};}@@ -69,21 +93,7 @@ export class AuthController {scope: this.authzSnapshot(apiKey),},});- return {- id: apiKey.id,- name: apiKey.name,- keyPrefix: apiKey.keyPrefix,- role: apiKey.role,- allowedIps: apiKey.allowedIps || undefined,- allowedSessions: apiKey.allowedSessions || undefined,- allowedChats: apiKey.allowedChats || undefined,- isActive: apiKey.isActive,- expiresAt: apiKey.expiresAt || undefined,- lastUsedAt: apiKey.lastUsedAt || undefined,- usageCount: apiKey.usageCount,- createdAt: apiKey.createdAt,- apiKey: rawKey,- };+ return { ...this.toResponse(apiKey), apiKey: rawKey };}@Get()@@ -96,20 +106,7 @@ export class AuthController {})async findAll(): Promise<ApiKeyResponseDto[]> {const keys = await this.authService.findAll();- return keys.map(k => ({- id: k.id,- name: k.name,- keyPrefix: k.keyPrefix,- role: k.role,- allowedIps: k.allowedIps || undefined,- allowedSessions: k.allowedSessions || undefined,- allowedChats: k.allowedChats || undefined,- isActive: k.isActive,- expiresAt: k.expiresAt || undefined,- lastUsedAt: k.lastUsedAt || undefined,- usageCount: k.usageCount,- createdAt: k.createdAt,- }));+ return keys.map(k => this.toResponse(k));}@Get(':id')@@ -123,20 +120,7 @@ export class AuthController {@ApiResponse({ status: 404, description: 'No API key with this id.' })async findOne(@Param('id') id: string): Promise<ApiKeyResponseDto> {const k = await this.authService.findOne(id);- return {- id: k.id,- name: k.name,- keyPrefix: k.keyPrefix,- role: k.role,- allowedIps: k.allowedIps || undefined,- allowedSessions: k.allowedSessions || undefined,- allowedChats: k.allowedChats || undefined,- isActive: k.isActive,- expiresAt: k.expiresAt || undefined,- lastUsedAt: k.lastUsedAt || undefined,- usageCount: k.usageCount,- createdAt: k.createdAt,- };+ return this.toResponse(k);}@Put(':id')@@ -166,20 +150,7 @@ export class AuthController {after: this.authzSnapshot(k),},});- return {- id: k.id,- name: k.name,- keyPrefix: k.keyPrefix,- role: k.role,- allowedIps: k.allowedIps || undefined,- allowedSessions: k.allowedSessions || undefined,- allowedChats: k.allowedChats || undefined,- isActive: k.isActive,- expiresAt: k.expiresAt || undefined,- lastUsedAt: k.lastUsedAt || undefined,- usageCount: k.usageCount,- createdAt: k.createdAt,- };+ return this.toResponse(k);}@Delete(':id')@@ -221,19 +192,6 @@ export class AuthController {...this.auditContext(req, actor),metadata: { targetKeyId: k.id, targetKeyName: k.name },});- return {- id: k.id,- name: k.name,- keyPrefix: k.keyPrefix,- role: k.role,- allowedIps: k.allowedIps || undefined,- allowedSessions: k.allowedSessions || undefined,- allowedChats: k.allowedChats || undefined,- isActive: k.isActive,- expiresAt: k.expiresAt || undefined,- lastUsedAt: k.lastUsedAt || undefined,- usageCount: k.usageCount,- createdAt: k.createdAt,- };+ return this.toResponse(k);}}