cure53 / DOMPurify

DOMPurify - a DOM-only, super-fast, uber-tolerant XSS sanitizer for HTML, MathML and SVG. DOMPurify works with a secure default, but offers a lot of configurability and hooks. Demo:
https://cure53.de/purify
Other
13.67k stars 698 forks source link

Question regarding local hooks #880

Closed Sushi21 closed 9 months ago

Sushi21 commented 9 months ago

We are currently looking at removing the images nodes that have a src that's matching the current origin.

Hooks like uponSanitizeAttribute seemed to be what we needed. But hooks being global, we want to narrow its usage to one particular spot in our code base.

  const currentOrigin = window.location.origin;

  function uponSanitizeAttribute(node, data) {
    if (node.nodeName === 'IMG' && data.attrName === 'src') {
      if (new URL(data.attrValue)?.origin === currentOrigin) {
        node.remove();
      }
    }
  }

  DOMPurify.addHook('uponSanitizeAttribute', uponSanitizeAttribute);
  var cleaned = DOMPurify.sanitize(parsedHtml);
  DOMPurify.removeHook('uponSanitizeAttribute', uponSanitizeAttribute);
  return cleaned;

is there a way to achieve this without using hooks? but local sanitizing config?

cure53 commented 9 months ago

Hmmm, not sure if this can be achieved without using hooks. Likely you have to add and remove the hook as your example shows. Do you have any ideas how to implement this more elegantly in our code-base?