sanitiny

A small (1368 bytes) HTML sanitiser

Usage no npm install needed!

<script type="module">
  import sanitiny from 'https://cdn.skypack.dev/sanitiny';
</script>

README

Sanitiny

A whitelist-based HTML sanitiser in 1368 bytes.

var html = '<p <img onload=xss()>';

var cleaned = sanitiny(html);

var cleanedWithOptions = sanitiny(html, {
    tags: ['p', 'div'],
    attributes: ['href', 'src', 'width', 'height'],
    schemes: ['http', 'https']
});

The goal of this module is to guard against XSS attacks. All tags in the output will be well-formed, and only tags and attributes in the whitelist will be present.

It doesn't support some features, or correct some semantic ambiguities. If you give it strange or invalid input, it may misinterpret, but it will always misinterpret safely.

Features and limitations

It supports user-supplied whitelists of tags and attributes. It does not support limiting attributes to certain tags.

By default, it filters href and src values to prevent XSS. You can specify your own filters using options.filter.

Unlike most elements, when <script> and <style> are removed, their contents is removed with them.

It is not a full HTML parser, and it is not tolerant. The following features are not supported:

  • it will not fix invalid structures such as <div><blockquote></div> or </br>
  • it will not auto-close opened tags, e.g. <div>foo or <div><p>foo</div>
  • it will misunderstand <![CDATA[...]]> blocks and <!DOCTYPE ...> declarations
  • it will misunderstand comments <!-- ... -->
  • it will not understand namespaces, e.g. <foo:bar>
  • it will permit weird things with close tags, e.g. </div foo="bar"> or </div/>
  • it will not handle unescaped <s. (e.g. most browsers interpret a < b > c as a &lt; b &gt; c)

Syntactically correct HTML containing none of these features will remain correct.

When is it useful?

I originally designed it as a lightweight filter for embedding content using oEmbed.

The HTML fragments obtained using this method should be well-formed, so we don't need a tolerant parser. If I was given weird or invalid HTML, I was happy to produce weird output, as long as it was safe.

In fact, in the browser even unclosed tags and other semantic issues are not a problem if you're setting an element's .innerHTML. The only concern is removing XSS attacks.

If you are on the server-side, there are more comprehensive modules to use, and (with no bandwidth concerns) you should use those as well.

Attribute processing

All src and href attributes are filtered to prevent XSS. The default filter has a whitelist of allowed URI schemes (http/https/ftp/mailto), and if it looks like another scheme is being used, it replaces the value.

Absolute URLs are always fine. Some weirdly-formed relative URLs (e.g. <a href="foo&amp;bar"> - where is the query?) might trip this filter and be replaced. Sensible URLs should be fine.

You can supply your own attribute processing functions using options.filter:

sanitiny(html, {
    filter: {
        href: sanitify.defaults.filter.href,
        src: sanitify.defaults.filter.src,
        width: function (widthValue) {
            // Only allow percentage widths
            if (!/%/.test(widthValue)) return 'auto';
            return widthValue;
        }
    }
})

It also escapes every instance of < in attribute values. This lets you perform further modifications secure in the knowledge that < is only ever used at the start of a tag, e.g.:

// links should open in a new tab
var clean = sanitiny(html).replace(/<a\s/g, '<a target="_blank" ');

(Note: if you have allowed <script> or <style> tags for some inexplicable reason, this is no longer true.)

Defaults

The .tags, .attributes and .schemes options are actually interpreted as strings, and then split using ,. This means you can specify them as either strings or arrays.

The default values (available as sanitiny.defaults) are strings, so you can extend them by adding to their value, or by creating a new array:

var sanitiny = require('sanitiny');
// Append to string
sanitiny.defaults.schemes += ',smb';

var cleanedWithOptions = sanitiny(html, {
    // Include in array
    tags: [sanitiny.defaults.tags, 'iframe', 'img']
});

Why did you write this?

I wanted to safely use oEmbed content. Writing a sanitiser seemed like fun, and I wanted to see if I could get it under a kilobyte.

License

This is released into the public domain (CC0)

Anybody is free to use any part of this code, for any purpose, and can release it under any license they choose.