import { Inject, Injectable, Logger } from '@nestjs/common'; import { createClerkClient, verifyToken, type ClerkClient } from '@clerk/backend'; import { AppException, unauthenticated } from '../common/exceptions/app.exception.js'; import { APP_CONFIG, isOriginAllowed } from '../config/app-config.js'; import type { AppConfig } from '../config/app-config.interface.js'; import type { ClerkProfile, ClerkSession } from './interfaces/clerk.interface.js'; interface ClerkInstance { secretKey: string; client: ClerkClient; } @Injectable() export class ClerkService { private readonly logger = new Logger(ClerkService.name); private readonly instances: ClerkInstance[]; constructor(@Inject(APP_CONFIG) private readonly config: AppConfig) { this.instances = config.clerk.secretKeys.map((secretKey) => ({ secretKey, client: createClerkClient({ secretKey }) })); } /** Signature, expiry and `azp` (the frontend origin that requested the token). */ async verifySessionToken(token: string): Promise { const claims = await this.verifyWithAnyInstance(token); if (!claims?.sub || !claims.sid || !isOriginAllowed(this.config, claims.azp)) throw unauthenticated(); return { userId: claims.sub, sessionId: claims.sid }; } async getVerifiedProfile(clerkUserId: string): Promise { const user = await this.findUser(clerkUserId); const email = user.primaryEmailAddress; if (!email || email.verification?.status !== 'verified') { throw new AppException(403, 'EMAIL_NOT_VERIFIED', 'Please verify your email address to continue.'); } const name = [user.firstName, user.lastName].filter(Boolean).join(' ').trim(); return { email: email.emailAddress.trim().toLowerCase(), name: name || null }; } private async verifyWithAnyInstance(token: string) { for (const { secretKey } of this.instances) { try { return await verifyToken(token, { secretKey, jwtKey: this.config.clerk.jwtKey }); } catch { // Signed by another instance (or invalid); try the next one. } } return null; } private async findUser(clerkUserId: string) { let failure: unknown; for (const { client } of this.instances) { try { return await client.users.getUser(clerkUserId); } catch (error) { failure = error; } } this.logger.error(`Clerk user lookup failed: ${failure instanceof Error ? failure.message : String(failure)}`); throw new AppException(503, 'AUTH_UNAVAILABLE', 'Sign-in is temporarily unavailable. Please try again.'); } }