import crypto from 'crypto'; /** * HMAC Authentication for Slidev Control Commands * * Provides cryptographic authentication for control API requests using HMAC-SHA256. * Prevents unauthorized control commands from being executed on Slidev presentations. * * Security features: * - SHA256 HMAC for strong cryptographic signing * - Timing-safe comparison to prevent timing attacks * - Secret key loaded from environment variable * * @module slidev/auth */ /** * Gets the HMAC secret from environment variable * @throws Error if SLIDEV_HMAC_SECRET is not set */ function getHmacSecret(): string { const secret = process.env.SLIDEV_HMAC_SECRET; if (!secret) { throw new Error('SLIDEV_HMAC_SECRET environment variable is not set'); } return secret; } /** * Generates an HMAC signature for a control command * * The HMAC is calculated over the payload: `${deckId}:${command}:${slideId || ''}` * This ensures that the signature is unique for each combination of deck, command, and slide. * * @param deckId - The deck identifier (format: xxxx-xxxx-xxxx) * @param command - The command type ('next', 'prev', 'goto') * @param slideId - Optional slide identifier (required for 'goto' commands) * @returns 64-character hex string representing the HMAC-SHA256 signature * * @example * const hmac = generateHMAC('a1b2-c3d4-e5f6', 'next'); * // Returns: '3d4f5e6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3d4e5f6' * * @example * const hmac = generateHMAC('a1b2-c3d4-e5f6', 'goto', '5'); * // Returns: '9f8e7d6c5b4a3e2d1c0b9a8f7e6d5c4b3a2e1d0c9b8a7f6e5d4c3b2a1e0d9c8b7' */ export function generateHMAC( deckId: string, command: string, slideId?: string ): string { const secret = getHmacSecret(); const payload = `${deckId}:${command}:${slideId || ''}`; return crypto .createHmac('sha256', secret) .update(payload) .digest('hex'); } /** * Verifies an HMAC signature for a control command * * Uses timing-safe comparison to prevent timing attacks that could leak * information about the correct HMAC value. * * @param deckId - The deck identifier * @param command - The command type * @param slideId - Optional slide identifier * @param providedHmac - The HMAC signature to verify * @returns true if the HMAC is valid, false otherwise * * @example * const isValid = verifyHMAC('a1b2-c3d4-e5f6', 'next', undefined, hmac); * if (!isValid) { * throw new Error('Invalid HMAC signature'); * } */ export function verifyHMAC( deckId: string, command: string, slideId: string | undefined, providedHmac: string ): boolean { try { const expectedHmac = generateHMAC(deckId, command, slideId); // Ensure both buffers are the same length before comparison if (expectedHmac.length !== providedHmac.length) { return false; } // Use timing-safe comparison to prevent timing attacks return crypto.timingSafeEqual( Buffer.from(expectedHmac, 'hex'), Buffer.from(providedHmac, 'hex') ); } catch (error) { // Handle any errors (e.g., invalid hex strings) by returning false return false; } }