import { Inject, Injectable } from '@nestjs/common'; import { randomUUID } from 'node:crypto'; import { SignJWT } from 'jose'; import { APP_CONFIG } from '../config/app-config.js'; import type { AppConfig } from '../config/app-config.interface.js'; import type { ProcessingTokenDto } from './dto/processing-token.dto.js'; /** Short-lived token the renderer verifies with the shared secret; the issuer marks jobs as Prevision's. */ @Injectable() export class ProcessingTokenService { private readonly key: Uint8Array; constructor(@Inject(APP_CONFIG) private readonly config: AppConfig) { this.key = new TextEncoder().encode(config.processingToken.secret); } async issue(userId: string, sessionId: string): Promise { const { audience, issuer, ttlSeconds } = this.config.processingToken; const now = Math.floor(Date.now() / 1000); const token = await new SignJWT({ role: 'client', sid: sessionId }) .setProtectedHeader({ alg: 'HS256' }) .setIssuer(issuer) .setAudience(audience) .setSubject(userId) .setIssuedAt(now) .setNotBefore(now) .setExpirationTime(now + ttlSeconds) .setJti(randomUUID()) .sign(this.key); return { token, expiresAt: new Date((now + ttlSeconds) * 1000).toISOString() }; } }