i'm trying to sanitize but it doesn't work

48 Views Asked by At

i'm trying to sanitize html string before sending it into database, i'm using sanitize-html npm package but it doesn't work

if (noteContent) {
  const resultContent = sanitize(noteContent);
  console.log(resultContent);
} else {
  setErrorMessages((prevState) => ["note content cannot be empty"]);
}

here when i'm entering <img src=? onerror="alert('hello')" />
it returns:

<p><img src=? onerror="alert('hello')" /></p>  

i don't get it what am i doing wrong?

2

There are 2 best solutions below

0
Tim Nikischin On

According to the documentation available on Github, the function you are looking for should be called sanitizeHtml() and not sanitize()

However, if you read closely, per default it does allow quite some html tags and attributes listed here: https://github.com/apostrophecms/sanitize-html?tab=readme-ov-file#default-options

In order to be more restrict, follow the example provided in their documentation.

// Allow only a super restricted set of tags and attributes
const clean = sanitizeHtml(dirty, {
  allowedTags: [ 'b', 'i', 'em', 'strong', 'a' ],
  allowedAttributes: {
    'a': [ 'href' ]
  },
  allowedIframeHostnames: ['www.youtube.com']
});

For your example provided this would look something like this:

if (noteContent) {
  const resultContent = sanitizeHtml(noteContent, {
    allowedTags: [], 
    allowedAttributes: {}
  });
  console.log(resultContent);
} else {
  setErrorMessages((prevState) => ["note content cannot be empty"]);
}

See also this part of the documentation.

1
Gak On

Also, There is another option. Dompurify

It is simple.

// return : '<img src=? />'
const clean = DOMPurify.sanitize('<img src=? onerror="alert('hello')" />');