Sanitize HTML

What it's for

A comment box with a rich text editor, an import of HTML from somewhere else, the output of Markdown: any HTML a user controls can carry a <script>, an onerror= or a javascript: link. Showing it as is lets one user run code in another's browser. ammonia parses the HTML the way a browser does (html5ever) and keeps only an allow list of tags and attributes. Links get rel="noopener noreferrer".

The route

A comments collection with an html text field, cleaned before it's saved:

// pb_pages/comments.ts: comments arrive as HTML from a rich text editor
export async function post(ctx: any) {
  if (!ctx.auth) throw ctx.httpError(401, "Sign in to comment")
  const { html } = ctx.req.body()
  const comment = new Record(ctx.app.findCollectionByNameOrId("comments"))
  comment.set("html", String((await $wasm.run.async<string | null>("sanitize-html", html || "")) ?? ""))
  ctx.app.save(comment)
  return ctx.res.json(201, { id: comment.id })
}

Clean edits too if comments can be edited: the route that saves an edit makes the same call.

String(...) is there because a module's output comes back parsed when it's JSON: a comment that's just 42 comes back as the number 42.

What it does to a hostile comment:

<p onclick="steal()">Hi <a href="javascript:alert(1)">there</a><script>alert(1)</script></p>
<p>Hi <a rel="noopener noreferrer">there</a></p>

The module

The whole program is one call to ammonia's defaults (src/main.rs):

let mut input = String::new();
if let Err(e) = std::io::stdin().read_to_string(&mut input) {
    fail("bad_input", &format!("the input isn't UTF-8 text: {e}"));
}
let clean = ammonia::clean(&input);
std::io::stdout().write_all(clean.as_bytes()).unwrap();

For your own rules (allow class on <code>, drop images), build an ammonia::Builder in its place.

Build

cd ext/wasm/example/sanitize-html
cargo build --release --target wasm32-wasip1   # rustup target add wasm32-wasip1 first
cp target/wasm32-wasip1/release/sanitize-html.wasm pb_hooks/sanitize-html.pb.wasm

Cost

803 KB, most of it a full HTML parser. The first call compiles it (about 120 ms); later calls load it from the cache in about 5 ms and clean a comment in under 1 ms.

Limits

  • Input and output are each at most 4 MB (MaxPayload).
  • style attributes are removed, not filtered; allow them only with your own CSS rules in the builder.