import sanitizeHtml from 'sanitize-html'; // Server-side input sanitization to prevent CSS injection and XSS attacks export function sanitizeInput(input) { if (typeof input !== 'string') { return input; } // Remove any HTML tags and dangerous content // DOMPurify needs a browser window. On Node its default export is a // factory without .sanitize(), which aborted JSON exports on the first // HTML-bearing card. Parse on the server without a DOM or network access. const sanitized = sanitizeHtml(input, { allowedTags: [], allowedAttributes: {}, }); // Additional check for CSS injection patterns const cssInjectionPatterns = [ /]*>[\s\S]*?<\/style\b[^>]*>/gi, /style\s*=\s*["'][^"']*["']/gi, /@import\s+[^;]+;/gi, /url\s*\(\s*[^)]+\s*\)/gi, /expression\s*\(/gi, /javascript\s*:/gi, /vbscript\s*:/gi, /data\s*:/gi ]; let cleaned = sanitized; for (const pattern of cssInjectionPatterns) { if (pattern.test(cleaned)) { if (process.env.DEBUG === 'true') { console.warn('Blocked potential CSS injection in input:', cleaned.substring(0, 100) + '...'); } // Remove the dangerous content cleaned = cleaned.replace(pattern, ''); } } return cleaned.trim(); } // Specific function for sanitizing titles export function sanitizeTitle(title) { if (typeof title !== 'string') { return title; } // First sanitize the input let sanitized = sanitizeInput(title); // Additional title-specific sanitization // Remove any remaining HTML entities that might be dangerous sanitized = sanitized.replace(/&[#\w]+;/g, ''); // Remove any remaining angle brackets sanitized = sanitized.replace(/[<>]/g, ''); // Limit length to prevent abuse if (sanitized.length > 1000) { sanitized = sanitized.substring(0, 1000); if (process.env.DEBUG === 'true') { console.warn('Truncated long title input:', title.length, 'characters'); } } return sanitized.trim(); }