secureDOMPurify.js 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. import DOMPurify from 'dompurify';
  2. // Centralized secure DOMPurify configuration to prevent XSS and CSS injection attacks
  3. export function getSecureDOMPurifyConfig() {
  4. return {
  5. // Allow common markdown elements including anchor tags
  6. ALLOWED_TAGS: ['a', 'p', 'br', 'strong', 'em', 'u', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ul', 'ol', 'li', 'blockquote', 'pre', 'code', 'img', 'table', 'thead', 'tbody', 'tr', 'th', 'td', 'hr', 'div', 'span'],
  7. // Allow safe attributes including href for anchor tags
  8. ALLOWED_ATTR: ['href', 'title', 'alt', 'src', 'width', 'height', 'target', 'rel'],
  9. // Allow safe protocols for links
  10. ALLOWED_URI_REGEXP: /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i,
  11. // Allow unknown protocols but be cautious
  12. ALLOW_UNKNOWN_PROTOCOLS: false,
  13. // Sanitize DOM for security
  14. SANITIZE_DOM: true,
  15. // Keep content but sanitize it
  16. KEEP_CONTENT: true,
  17. // Block dangerous elements that can cause XSS
  18. FORBID_TAGS: ['script', 'style', 'iframe', 'object', 'embed', 'applet', 'svg', 'defs', 'use', 'g', 'symbol', 'marker', 'pattern', 'mask', 'clipPath', 'linearGradient', 'radialGradient', 'stop', 'animate', 'animateTransform', 'animateMotion', 'set', 'switch', 'foreignObject', 'link', 'meta', 'form', 'input', 'textarea', 'select', 'option', 'button', 'label', 'fieldset', 'legend', 'frameset', 'frame', 'noframes', 'base', 'basefont', 'isindex', 'dir', 'menu', 'menuitem'],
  19. // Block dangerous attributes but allow safe href
  20. FORBID_ATTR: ['xlink:href', 'onload', 'onerror', 'onclick', 'onmouseover', 'onfocus', 'onblur', 'onchange', 'onsubmit', 'onreset', 'onselect', 'onunload', 'onresize', 'onscroll', 'onkeydown', 'onkeyup', 'onkeypress', 'onmousedown', 'onmouseup', 'onmouseover', 'onmouseout', 'onmousemove', 'ondblclick', 'oncontextmenu', 'onwheel', 'ontouchstart', 'ontouchend', 'ontouchmove', 'ontouchcancel', 'onabort', 'oncanplay', 'oncanplaythrough', 'ondurationchange', 'onemptied', 'onended', 'onerror', 'onloadeddata', 'onloadedmetadata', 'onloadstart', 'onpause', 'onplay', 'onplaying', 'onprogress', 'onratechange', 'onseeked', 'onseeking', 'onstalled', 'onsuspend', 'ontimeupdate', 'onvolumechange', 'onwaiting', 'onbeforeunload', 'onhashchange', 'onpagehide', 'onpageshow', 'onpopstate', 'onstorage', 'onunload', 'style', 'class', 'id', 'data-*', 'aria-*'],
  21. // Block data URIs that could contain malicious content
  22. ALLOW_DATA_ATTR: false,
  23. // Custom hooks for additional security
  24. HOOKS: {
  25. uponSanitizeElement: function(node, data) {
  26. // Block any remaining dangerous elements
  27. const dangerousTags = ['svg', 'style', 'script', 'link', 'meta', 'iframe', 'object', 'embed', 'applet'];
  28. if (node.tagName && dangerousTags.includes(node.tagName.toLowerCase())) {
  29. if (process.env.DEBUG === 'true') {
  30. console.warn('Blocked potentially dangerous element:', node.tagName);
  31. }
  32. return false;
  33. }
  34. // Block img tags with SVG data URIs that could contain malicious JavaScript
  35. if (node.tagName && node.tagName.toLowerCase() === 'img') {
  36. const src = node.getAttribute('src');
  37. if (src) {
  38. // Block all SVG data URIs to prevent XSS via embedded JavaScript
  39. if (src.startsWith('data:image/svg') || src.endsWith('.svg')) {
  40. if (process.env.DEBUG === 'true') {
  41. console.warn('Blocked potentially malicious SVG image:', src);
  42. }
  43. return false;
  44. }
  45. // Additional check for base64 encoded SVG with script tags
  46. if (src.startsWith('data:image/svg+xml;base64,')) {
  47. try {
  48. const base64Content = src.split(',')[1];
  49. const decodedContent = atob(base64Content);
  50. if (decodedContent.includes('<script') || decodedContent.includes('javascript:')) {
  51. if (process.env.DEBUG === 'true') {
  52. console.warn('Blocked SVG with embedded JavaScript:', src.substring(0, 100) + '...');
  53. }
  54. return false;
  55. }
  56. } catch (e) {
  57. // If decoding fails, block it as a safety measure
  58. if (process.env.DEBUG === 'true') {
  59. console.warn('Blocked malformed SVG data URI:', src);
  60. }
  61. return false;
  62. }
  63. }
  64. }
  65. }
  66. // Block elements with dangerous attributes
  67. const dangerousAttrs = ['style', 'onload', 'onerror', 'onclick', 'onmouseover', 'onfocus', 'onblur'];
  68. for (const attr of dangerousAttrs) {
  69. if (node.hasAttribute && node.hasAttribute(attr)) {
  70. if (process.env.DEBUG === 'true') {
  71. console.warn('Blocked element with dangerous attribute:', node.tagName, attr);
  72. }
  73. return false;
  74. }
  75. }
  76. return true;
  77. },
  78. uponSanitizeAttribute: function(node, data) {
  79. // Block style attributes completely
  80. if (data.attrName === 'style') {
  81. if (process.env.DEBUG === 'true') {
  82. console.warn('Blocked style attribute');
  83. }
  84. return false;
  85. }
  86. // Block class and id attributes that might be used for CSS injection
  87. if (data.attrName === 'class' || data.attrName === 'id') {
  88. if (process.env.DEBUG === 'true') {
  89. console.warn('Blocked class/id attribute:', data.attrName, data.attrValue);
  90. }
  91. return false;
  92. }
  93. // Block data attributes
  94. if (data.attrName && data.attrName.startsWith('data-')) {
  95. if (process.env.DEBUG === 'true') {
  96. console.warn('Blocked data attribute:', data.attrName);
  97. }
  98. return false;
  99. }
  100. // Allow href attribute for anchor tags only
  101. if (data.attrName === 'href') {
  102. // Only allow href on anchor tags
  103. if (node.tagName && node.tagName.toLowerCase() === 'a') {
  104. return true;
  105. } else {
  106. if (process.env.DEBUG === 'true') {
  107. console.warn('Blocked href attribute on non-anchor element:', node.tagName);
  108. }
  109. return false;
  110. }
  111. }
  112. return true;
  113. }
  114. }
  115. };
  116. }
  117. // Convenience function for secure sanitization
  118. export function sanitizeHTML(html) {
  119. return DOMPurify.sanitize(html, getSecureDOMPurifyConfig());
  120. }
  121. // Convenience function for sanitizing text (no HTML)
  122. export function sanitizeText(text) {
  123. return DOMPurify.sanitize(text, {
  124. ALLOWED_TAGS: [],
  125. ALLOWED_ATTR: [],
  126. KEEP_CONTENT: true
  127. });
  128. }