// src/server/shared/lib/sanitize.ts
// XSS Protection utility for sanitizing HTML content

/**
 * Allowed HTML tags for rich text content
 * These are safe tags that can be used in notes and comments
 */
const ALLOWED_TAGS = [
  'p', 'br', 'b', 'i', 'u', 'em', 'strong',
  'a', 'ul', 'ol', 'li',
  'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
  'blockquote', 'code', 'pre',
];

/**
 * Sanitize HTML string by removing dangerous tags and attributes
 * @param html - HTML string to sanitize
 * @returns Sanitized HTML string
 */
export function sanitizeHtml(html: string): string {
  if (!html || typeof html !== 'string') {
    return '';
  }

  // Remove script tags and content
  let sanitized = html.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '');

  // Remove iframe tags
  sanitized = sanitized.replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi, '');

  // Remove object tags
  sanitized = sanitized.replace(/<object\b[^<]*(?:(?!<\/object>)<[^<]*)*<\/object>/gi, '');

  // Remove embed tags
  sanitized = sanitized.replace(/<embed\b[^<]*(?:(?!<\/embed>)<[^<]*)*<\/embed>/gi, '');

  // Remove style tags with content
  sanitized = sanitized.replace(/<style\b[^<]*(?:(?!<\/style>)<[^<]*)*<\/style>/gi, '');

  // Remove on* event handlers from all tags
  sanitized = sanitized.replace(/\s*on\w+\s*=\s*["'][^"']*["']/gi, '');
  sanitized = sanitized.replace(/\s*on\w+\s*=\s*["'][^"']*["']/gi, '');
  sanitized = sanitized.replace(/\s*on\w+\s*=\s*[^\s>]*/gi, '');

  // Remove javascript: protocol
  sanitized = sanitized.replace(/javascript:/gi, '');
  sanitized = sanitized.replace(/data:/gi, '');

  // Remove vbscript:
  sanitized = sanitized.replace(/vbscript:/gi, '');

  return sanitized;
}

/**
 * Sanitize plain text by removing HTML tags
 * @param text - Plain text string to sanitize
 * @returns Sanitized plain text string
 */
export function sanitizeText(text: string): string {
  if (!text || typeof text !== 'string') {
    return '';
  }

  // Remove all HTML tags
  return text.replace(/<[^>]*>/g, '');
}

/**
 * Check if HTML contains only allowed tags
 * @param html - HTML string to check
 * @returns true if HTML contains only allowed tags
 */
export function isSafeHtml(html: string): boolean {
  if (!html || typeof html !== 'string') {
    return false;
  }

  // Check for dangerous tags
  const dangerousTags = ['script', 'iframe', 'object', 'embed', 'style'];
  const lowerHtml = html.toLowerCase();

  for (const tag of dangerousTags) {
    if (lowerHtml.includes(`<${tag}`)) {
      return false;
    }
  }

  return true;
}
