An allow-list sanitizer

When users may post a little formatting, a sanitizer keeps only known-safe tags and turns everything else into harmless text. An allow-list (keep only these) is far safer than a block-list.

What to build

Sanitize lines of HTML, keeping only a few bare formatting tags.

Requirements

  • A tag is a <, an optional /, a name of letters, anything up to the next >, and the >.
  • Keep a tag only if its name (any case) is b, i, em, strong or p AND it has nothing after the name (no attributes, spaces allowed). Write kept tags in lower case, for example <B > becomes <b> and </P> becomes </p>.
  • Every other character, including the characters of tags that are not kept and any < that does not start a complete tag, is escaped: & to &, < to <, > to >, " to ", ' to '.
  • Print each sanitized line.

Input

Lines of HTML.

Output

Each line, sanitized.

Constraints

1 to 30 lines of up to 300 characters.

Example

Input:

<b>bold</b> and <i>italic</i>
<script>alert(1)</script>

Output:

<b>bold</b> and <i>italic</i>
&lt;script&gt;alert(1)&lt;/script&gt;

Why it works

Only tags on the list, with no attributes, survive, so there is nowhere left for a script, an event attribute or a javascript: link; everything else is shown as text, which can never run.

Examples

Example 1 · Input
<b>bold</b> and <i>italic</i>
<script>alert(1)</script>
Expected output
<b>bold</b> and <i>italic</i>
&lt;script&gt;alert(1)&lt;/script&gt;
Example 2 · Input
<p onclick="go()">x</p>
Expected output
&lt;p onclick=&quot;go()&quot;&gt;x</p>

Hints

Hint 1

Scan left to right. At a <, try to match /^<(\/?)([A-Za-z]+)([^>]*)>/ on the rest of the line.

Hint 2

Escape one character at a time when nothing matches.

Solution

Show one correct solution (try it yourself first)
const allowed = ["b", "i", "em", "strong", "p"];
const esc = (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c] ?? c;
let line = prompt();
while (line !== null) {
  let out = "";
  let i = 0;
  while (i < line.length) {
    if (line[i] === "<") {
      const m = /^<(\/?)([A-Za-z]+)([^>]*)>/.exec(line.slice(i));
      if (m && allowed.includes(m[2].toLowerCase()) && m[3].trim() === "") {
        out += `<${m[1]}${m[2].toLowerCase()}>`;
        i += m[0].length;
        continue;
      }
    }
    out += esc(line[i]);
    i++;
  }
  console.log(out);
  line = prompt();
}

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Cross-site scripting (XSS) →