Command Palette

Search for a command to run...

Hectal
Phase 21: Security in React Apps
React · Exercise 3 of 5 PreviousNext
Intermediate

Write an allow-list sanitiser

A CMS sends blog posts as HTML, and Post renders them with dangerouslySetInnerHTML. Right now sanitize returns the HTML unchanged.

Implement sanitize(html) as an allow-list: parse the HTML in an inert document (new DOMParser().parseFromString(html, "text/html")), then walk every element. Keep only the tags P, B, STRONG, I, EM, UL, LI and A. Remove SCRIPT, STYLE and IFRAME elements together with their content; for any other tag, keep its text (and its allowed children) but drop the tag. Remove every attribute, except href on A when it parses (against https://example.com) to an https: or http: URL. Return the body's innerHTML.

This is for learning: in a real app you'd use DOMPurify.

What Check tests

  1. Dangerous elements are gone
  2. Nothing ran
  3. No attributes survive except safe link hrefs
  4. Allowed formatting is kept
  5. The https link keeps its href; the javascript: link loses it
  6. Unknown tags are unwrapped, their text kept

Stuck? One hint at a time

The solution unlocks after your first Check. Try first: that is where the learning happens.

Runs in your browser. Your code is saved here.

Your page

Press Run to see the page.

Console

Nothing logged yet.