Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

65 rader
1.1 KiB

  1. import DOMPurify from 'dompurify';
  2. const ALLOWED_TAGS = [
  3. 'a',
  4. 'b',
  5. 'blockquote',
  6. 'br',
  7. 'caption',
  8. 'col',
  9. 'colgroup',
  10. 'div',
  11. 'em',
  12. 'h1',
  13. 'h2',
  14. 'h3',
  15. 'h4',
  16. 'h5',
  17. 'h6',
  18. 'hr',
  19. 'i',
  20. 'img',
  21. 'li',
  22. 'ol',
  23. 'p',
  24. 'span',
  25. 'strong',
  26. 'style',
  27. 'sub',
  28. 'sup',
  29. 'table',
  30. 'tbody',
  31. 'td',
  32. 'tfoot',
  33. 'th',
  34. 'thead',
  35. 'tr',
  36. 'u',
  37. 'ul'
  38. ];
  39. const ALLOWED_ATTR = ['href', 'title', 'target', 'rel', 'src', 'alt', 'width', 'height', 'colspan', 'rowspan', 'scope', 'class', 'style'];
  40. if (typeof window !== 'undefined') {
  41. DOMPurify.addHook('afterSanitizeAttributes', (node) => {
  42. if (node.tagName === 'A' && node.getAttribute('target') === '_blank') {
  43. node.setAttribute('rel', 'noopener noreferrer');
  44. }
  45. });
  46. }
  47. /**
  48. * Strict allow-list sanitize for API / i18n HTML before innerHTML.
  49. * Scripts, event handlers, iframes, and javascript: URLs are dropped.
  50. */
  51. export function sanitizeHtml(dirty) {
  52. if (dirty == null) {
  53. return '';
  54. }
  55. return DOMPurify.sanitize(String(dirty), {
  56. ALLOWED_TAGS,
  57. ALLOWED_ATTR,
  58. ALLOWED_URI_REGEXP: /^(?:(?:(?:f|ht)tps?|mailto):|[^a-z]|[a-z+.-]+(?:[^a-z+.-:]|$))/i
  59. });
  60. }