import type { ExecutionContext } from '@nestjs/common'; import { SignJWT } from 'jose'; import type { AppConfig } from '../../config/app-config.interface.js'; import { InternalTokenGuard } from './internal-token.guard.js'; const SECRET = 'test-processing-secret-0123456789abcdef012'; const guard = new InternalTokenGuard({ processingToken: { secret: SECRET }, internalTokenAudience: 'prevision-internal' } as AppConfig); const sign = (audience: string, expiresIn = 60) => { const now = Math.floor(Date.now() / 1000); return new SignJWT({}).setProtectedHeader({ alg: 'HS256' }).setAudience(audience).setIssuedAt(now).setExpirationTime(now + expiresIn).sign(new TextEncoder().encode(SECRET)); }; const check = (token?: string) => guard.canActivate({ switchToHttp: () => ({ getRequest: () => ({ headers: token ? { authorization: `Bearer ${token}` } : {} }) }), } as ExecutionContext); describe('InternalTokenGuard', () => { it('accepts the renderer token', async () => { expect(await check(await sign('prevision-internal'))).toBe(true); }); it.each([ ['missing', async () => undefined], ['browser processing token', () => sign('prevision-processing')], ['expired', () => sign('prevision-internal', -120)], ])('refuses a %s token', async (_, token) => { await expect(check(await token())).rejects.toMatchObject({ status: 401 }); }); });