/**
* HTML Sanitization utilities to prevent XSS attacks
*/
import { createSanitizeHtmlConfig, FORBID_TAGS, stripSvgDataUrls } from '@cio/utils/functions';
import DOMPurify from 'dompurify';
const browser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
/**
* Sanitizes HTML content using DOMPurify to prevent XSS attacks
* This provides robust client-side protection against XSS attacks
*/
export function sanitizeHtml(html: string): string {
if (typeof html !== 'string') return '';
// Only run DOMPurify in the browser
if (!browser) {
return fallbackSanitize(html);
}
let sanitized = String(DOMPurify.sanitize(html, createSanitizeHtmlConfig()));
// Additional post-processing to remove any SVG data URLs that might have slipped through
sanitized = stripSvgDataUrls(sanitized);
return sanitized;
}
/**
* Fallback sanitization for server-side rendering
*/
function fallbackSanitize(html: string): string {
if (typeof html !== 'string') return '';
// Remove SVG tags and their content completely
html = html.replace(/