import { CanActivate, ExecutionContext, Injectable, UnauthorizedException, } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { timingSafeEqual } from 'crypto'; import { Request } from 'express'; @Injectable() export class SslSyncTokenGuard implements CanActivate { constructor(private readonly config: ConfigService) {} canActivate(context: ExecutionContext): boolean { const expected = this.config.get('SSL_SYNC_TOKEN')?.trim(); if (!expected) { throw new UnauthorizedException('SSL sync is not configured'); } const req = context.switchToHttp().getRequest(); const provided = String(req.headers['x-ssl-sync-token'] ?? '').trim(); if (!provided || provided.length !== expected.length) { throw new UnauthorizedException('Invalid SSL sync token'); } const a = Buffer.from(provided); const b = Buffer.from(expected); if (!timingSafeEqual(a, b)) { throw new UnauthorizedException('Invalid SSL sync token'); } return true; } }