/** * Security utilities for HTML sanitization. * All DOM writes are sanitized by default to prevent XSS attacks. * * @module bquery/security */ import { sanitizeHtmlCore } from './sanitize-core'; import { toSanitizedHtml } from './trusted-html'; import type { SanitizedHtml } from './trusted-html'; import type { SanitizeOptions } from './types'; export { generateNonce } from './csp'; export { isTrustedTypesSupported } from './trusted-types'; export { trusted } from './trusted-html'; export type { SanitizedHtml, TrustedHtml } from './trusted-html'; /** * Sanitize HTML string, removing dangerous elements and attributes. * Uses Trusted Types when available for CSP compliance. * * @param html - The HTML string to sanitize * @param options - Sanitization options * @returns Sanitized HTML string * * @example * ```ts * const safe = sanitizeHtml('
Hello
'); * // Returns: '
Hello
' * ``` */ export const sanitizeHtml = (html: string, options: SanitizeOptions = {}): SanitizedHtml => { return toSanitizedHtml(sanitizeHtmlCore(html, options)); }; /** * Escape HTML entities to prevent XSS. * Use this for displaying user content as text. * * @param text - The text to escape * @returns Escaped HTML string * * @example * ```ts * escapeHtml(''); * // Returns: '<script>alert(1)</script>' * ``` */ export const escapeHtml = (text: string): string => { const escapeMap: Record = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''', '`': '`', }; return text.replace(/[&<>"'`]/g, (char) => escapeMap[char]); }; /** * Strip all HTML tags and return plain text. * * @param html - The HTML string to strip * @returns Plain text content */ export const stripTags = (html: string): string => { return sanitizeHtmlCore(html, { stripAllTags: true }); }; export type { SanitizeOptions } from './types';