// Short-lived HMAC tokens for iframe auth so the raw API key never lands in // iframe URLs, browser history, or tunnel logs. import { createHmac, timingSafeEqual } from 'crypto'; // 2min TTL balances security against the frontend rebuilding iframes on every // refresh (NekodoPreviewPanel iframeKey++), which would lose user state on shorter TTLs. export const PROXY_TOKEN_TTL_MS = 2 * 60 * 1000; // Subject-bound HMAC token. `subject` is a caller/session identifier (for // example a stable preview-session UUID) so a leaked token can't be replayed // by another browser session. export function signProxyToken( containerId: string, expiresAt: number, secret: string, subject: string, ): string { if (!subject) { throw new Error('subject is required'); } const subjectEncoded = Buffer.from(subject, 'utf8').toString('base64url'); const payload = `${subjectEncoded}:${containerId}:${expiresAt}`; const sig = createHmac('sha256', secret).update(payload).digest('hex'); return `${payload}:${sig}`; } // Verification requires the same subject that was used to mint the token. export function verifyProxyToken( token: string, containerId: string, secret: string, subject: string, ): boolean { if (!subject) return false; const parts = token.split(':'); if (parts.length !== 4) return false; const [subjectPart, tokenContainerId, expiresAtStr, providedSig] = parts; if (tokenContainerId !== containerId) return false; const expiresAt = parseInt(expiresAtStr, 10); if (isNaN(expiresAt) || Date.now() > expiresAt) return false; const expectedSubject = Buffer.from(subject, 'utf8').toString('base64url'); if (subjectPart !== expectedSubject) return false; const expectedSig = createHmac('sha256', secret) .update(`${subjectPart}:${tokenContainerId}:${expiresAtStr}`) .digest('hex'); try { return timingSafeEqual(Buffer.from(providedSig, 'hex'), Buffer.from(expectedSig, 'hex')); } catch { return false; } }