import { CanActivate, ExecutionContext, Inject, Injectable } from '@nestjs/common'; import type { Request } from 'express'; import { jwtVerify } from 'jose'; import { unauthenticated } from '../../common/exceptions/app.exception.js'; import { bearerToken } from '../../common/utils/bearer-token.js'; import { APP_CONFIG } from '../../config/app-config.js'; import type { AppConfig } from '../../config/app-config.interface.js'; /** The renderer in the same pod: a short HS256 token for the internal audience (never a browser token). */ @Injectable() export class InternalTokenGuard implements CanActivate { private readonly key: Uint8Array; constructor(@Inject(APP_CONFIG) private readonly config: AppConfig) { this.key = new TextEncoder().encode(config.processingToken.secret); } async canActivate(context: ExecutionContext): Promise { const token = bearerToken(context.switchToHttp().getRequest()); if (!token) throw unauthenticated(); try { await jwtVerify(token, this.key, { algorithms: ['HS256'], audience: this.config.internalTokenAudience, requiredClaims: ['exp', 'iat'], }); } catch { throw unauthenticated(); } return true; } }