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

How to allow tags with specific attr? #852

Closed ShahriarKh closed 1 year ago

ShahriarKh commented 1 year ago

This is not an issue; I have a question. Is it possible to allow tags like iframe or script only if they have a specific src attribute? I tried searching in the docs and some googling, but wasn't able to find the answer.

I want to do something like

DOMPurify.sanitize(content, {ADD_TAGS: ['iframe', {src: "example.com"}]});

so only iframes coming from example.com are allowed. However, I can't find the correct syntax.

cure53 commented 1 year ago

No core feature but you can easily do that with a hook, here are many examples:

https://github.com/cure53/DOMPurify/blob/main/demos/ https://github.com/cure53/DOMPurify/blob/main/demos/hooks-link-proxy-demo.html

ShahriarKh commented 6 months ago

Can you please give a full example on how to do this? Should the hook return the element? and what hook should I use?

This is what I tried:

const fakeContent = `<div><div>testing</div><script src="no.com"></script><script src="yes.com"></script><p>some text</p></div>`;

const whitelistedDomains = ['yes.com'];

DOMPurify.addHook('uponSanitizeElement', (currentNode) => {
  if (currentNode.tagName == 'SCRIPT') {
    if (whitelistedDomains.includes(currentNode.getAttribute('src'))) {
      // what should I do here to allow the currentNode?
    }
  }
});

DOMPurify.sanitize(fakeContent);

console.log(DOMPurify.removed);