import { CanActivate, ExecutionContext, Injectable, HttpException } from '@nestjs/common'; import { WidgetKeysService } from '../config/widget-keys.service'; @Injectable() export class WidgetKeyGuard implements CanActivate { constructor(private readonly keys: WidgetKeysService) {} async canActivate(context: ExecutionContext): Promise { const request = context.switchToHttp().getRequest(); const key = request.query?.key ?? request.headers['x-widget-key']; if (!key) throw new HttpException('Widget key required', 401); const siteKey = await this.keys.validateKey(key); if (!siteKey) throw new HttpException('Invalid widget key', 403); const origin = request.headers.origin ?? request.headers.referer; if (!this.keys.validateOrigin(siteKey, origin)) { throw new HttpException('Origin not allowed', 403); } request.widgetSiteKey = siteKey; return true; } }