prevision / apps /prevision-api /src /generations /guards /internal-token.guard.ts
github-actions[bot]
Automated Deploy: 23110475c742a5d4f03930b55bca09042215c1dd
1fe7075
Raw History Blame Contribute Delete
1.24 kB
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<boolean> {
const token = bearerToken(context.switchToHttp().getRequest<Request>());
if (!token) throw unauthenticated();
try {
await jwtVerify(token, this.key, {
algorithms: ['HS256'],
audience: this.config.internalTokenAudience,
requiredClaims: ['exp', 'iat'],
});
} catch {
throw unauthenticated();
}
return true;
}
}