$ show flavorjones/loofah
Loofah is a Ruby library for manipulating and transforming HTML/XML documents and fragments, built on top of Nokogiri. In production it functions primarily as the HTML sanitization engine behind Rails (via rails-html-sanitizer) and countless other Ruby web applications: it parses untrusted user-supplied HTML and scrubs out unsafe tags, attributes, URLs, CSS properties, and protocols while preserving safe markup. The library combines a general-purpose transformation framework (custom 'scrubbers') with a specific html5lib-derived sanitizer safelist covering HTML, MathML, and SVG elements, ARIA attributes, CSS properties/functions, and URI protocols. The codebase deliberately supports both HTML4 (libxml2) and HTML5 (gumbo) parsing paths, and is the de facto standard for server-side HTML sanitization in the Ruby ecosystem.
The LLM identified 3 files worth highlighting for reuse:
The core sanitization engine. `allowed_uri?` is a pure string-based URI safety validator that normalizes browser-decoding quirks attackers exploit: entity-encoded colons (`javascript:`), semicolon-less numeric character references (`javascript:alert(1)`), named whitespace references (`java	script:`), control-character stripping, and `:` handling — then enforces a protocol allowlist and validates `data:` URI mediatypes per the WHATWG data: URL spec. `scrub_css` uses the crass tokenizer to filter CSS properties/functions while preserving whitespace fidelity. Because these methods operate on plain strings with zero DOM/Nokogiri coupling, they could be lifted directly into any web framework needing URL or inline-CSS validation.
Base class for document transformations implementing a clean visitor-style tree traversal with configurable direction (`:top_down` or `:bottom_up`), frozen `CONTINUE`/`STOP` sentinels for subtree termination, and extension via either a block or a subclass implementing `#scrub`. Also provides `append_attribute` for set-based attribute merging. The traversal abstraction is parser-agnostic and could be extracted to power any recursive tree-rewriting DSL beyond HTML/XML sanitization.
A library of composable built-in scrubbers demonstrating the extension pattern: sanitization strategies (`:strip`, `:prune`, `:escape`, `:whitewash`), link-attribute modifiers (`:nofollow`, `:noopener`, `:noreferrer`, `:targetblank`), text cleanup (`:unprintable`), and the notably non-obvious `:double_breakpoint` scrubber, which uses an XPath query (`//p[br[following-sibling::br]]`) and careful sibling-node juggling to convert `<br><br>` sequences into closing/opening `<p>` boundaries. The link-modifier scrubbers in particular are self-contained, composable transformations adaptable to any HTML-rewriting task.