Thursday, December 3, 2026

js-xss for whitelist-based HTML sanitization in Node.js and browser applications

js-xss for whitelist-based HTML sanitization in Node.js and browser applications

xss is a Node.js and browser library that sanitizes untrusted HTML against XSS by allowing only whitelisted tags and attributes, with deep customization for authorized application hardening.

Toolleizongmin/js-xss — HTML sanitizer module published on npm as xss, built for XSS prevention via whitelist configuration
CategoryInput sanitization / secure coding library (JavaScript)
Primary UseFiltering user-supplied HTML before rendering in Node.js or browser apps, using a configurable whiteList of tags and attributes
Safe UseDefensive library for developers and authorized security teams hardening their own applications, web labs, and code review engagements against XSS
Telemetry NotePure library with no network calls; runs entirely in-process. filterXSSWithResult exposes which tags and attributes were removed, giving defenders a built-in audit signal

leizongmin/js-xss is one of the older and more widely deployed HTML sanitization libraries in the Node.js ecosystem, published on npm under the package name xss and sitting at roughly 5,300 stars on GitHub. Its core premise is simple and defensible: rather than trying to detect and strip known-bad patterns, it applies a whitelist that defines exactly which HTML tags and which attributes on those tags are permitted to survive filtering. Everything outside that whitelist is either escaped or removed depending on configuration. The README positions it explicitly as a module to filter user input to prevent XSS attacks, and it is that framing — treat all input as hostile, allow only the minimum markup — that makes it relevant reading for offensive and defensive professionals alike.

Installation follows the standard npm pattern, and the project also ships a bower path and a prebuilt browser bundle in dist/. The basic invocation on Node.js is require("xss") followed by calling the exported xss() function on an untrusted string; the README's canonical example passes a script tag and receives escaped output. On the browser side, the library exposes a global filterXSS function in shim mode or loads through requirejs in AMD mode. Notably, the README itself warns against pointing production code at the raw CDN bundle URL, which is the kind of honest operational note you want to see from a security library.

Architecturally, the interesting surface is the options object accepted as the second argument to xss(), or materialized once via new xss.FilterXSS(options) for repeated use. The FilterXSS class approach lets you build a configured filter instance and call .process() repeatedly without re-parsing the ruleset, which matters for throughput on hot paths. The README benchmarks the module at 22.53 MB/s, roughly three times the figure it cites for validator@0.3.7 at 6.9 MB/s, with test code in the benchmark directory — a claim worth re-verifying against current versions rather than trusting wholesale, since that comparison is clearly dated.

The whitelist itself is expressed as a map of tag names to arrays of allowed attributes, for example { a: ["href", "title", "target"] }. Under that rule, an anchor tag keeps its safe attributes while an onclick handler is stripped and an i tag outside the whitelist is escaped to <i>. The default ruleset is exposed as xss.whiteList for inspection, and allowList is accepted as a synonym — a small but meaningful concession to modern naming conventions. This default-then-override model is the right mental model for the library: you inherit a conservative baseline and tighten or selectively loosen it per context.

Where js-xss distinguishes itself from simpler sanitizers is the event-handler customization layer. onTag fires for every tag encountered and receives the tag name, its raw HTML, and metadata including isWhite, isClosing, position, and sourcePosition — the latter pair enabling precise source-to-output mapping, which is genuinely useful for logging and debugging filters. Returning a string from onTag replaces the tag entirely; returning nothing defers to the default policy, which routes whitelisted tags to onTagAttr and non-whitelisted ones to onIgnoreTag. The parallel onTagAttr, onIgnoreTag, and onIgnoreTagAttr callbacks give the same control at attribute granularity.

Attribute value safety is handled by safeAttrValue, and the README documents a subtle but important behavior: when action or formaction are explicitly allowed by a custom whitelist, the default value checker permits only HTTP(S) or relative URLs for form destinations, explicitly rejecting javascript: and data: schemes, and noting that the data:image/ exception allowed for href and src does not extend to form targets. This is exactly the class of nuance where sanitizers historically fail, and it signals that the maintainers have reasoned about scheme-based bypasses rather than only tag-name matching. You can override safeAttrValue entirely, though doing so shifts responsibility for scheme validation onto your own code.

The CSS path is delegated to a sibling module, js-css-filter, when the style attribute is permitted. Its options object accepts its own whiteList of CSS properties, using patterns like position: /^fixed|relative$/ to constrain values, and setting css: false disables CSS filtering entirely for cases where the style content is trusted. Escaping behavior is also tunable: the default escapeHtml replaces angle brackets with entities, and singleQuotedAttributeValue switches output attribute quoting from double to single quotes. The README's caution that modifying the escaping function is not recommended is worth heeding, since escaping is where most filter regressions originate.

Global filtering behavior is controlled by three boolean-ish options. stripIgnoreTag chooses between escaping non-whitelisted tags (the default) and removing them outright. stripIgnoreTagBody extends removal to tag contents — set to true or '*' to strip bodies of all non-whitelisted tags, or pass an array like ['script'] to target specific ones. allowCommentTag defaults to stripping HTML comments, which is the correct posture since comments have historically served as parsing-differential and conditional-comment attack vehicles. These three switches effectively let you choose between an escape-heavy output that preserves visible text and a strip-heavy output that surgically deletes content.

For defenders and code auditors, the standout capability is filterXSSWithResult, which returns both the sanitized HTML and a structured removed array describing what was filtered: entries carry a type of tag or attr, the offending tag and attr names, the raw html fragment, and an isClosing flag. Wiring that into application logging turns the sanitizer into a detection sensor — a spike in removed onclick or script entries is a direct signal that someone is probing your input surfaces. The README's worked example shows a script tag pair and an onclick attribute being reported precisely, which makes the telemetry easy to consume.

The project also ships a command line tool for offline inspection: xss -i origin.html -o target.html processes a file in place, and xss -t opens an interactive mode where you type HTML and watch the filtered output, with xss -h documenting the rest. This makes it convenient to sanity-check a ruleset against edge cases before deploying it, and the README's reference section points at the OWASP XSS Filter Evasion Cheat Sheet and Data URI scheme documentation as background reading — a sensible curriculum for anyone building filter rules. An online playground is available at the project homepage, jsxss.com, for quick experimentation.

The README also lists known adopters, including nodeclub (a Node.js forum running on MongoDB), the private npm registry platform cnpmjs.org, and the collaborative computing site cocalc.com — deployments that all share the pattern of accepting user-authored rich content and rendering it back to other users, which is precisely the stored-XSS threat model this library targets. The repository shows a Node.js CI workflow, Coveralls coverage tracking, and dependency monitoring badges, along with a Chinese-language README, and the license field is flagged as NOASSERTION in the repo metadata — worth verifying against the npm package before commercial adoption.

For an authorized assessment workflow, js-xss is best understood as a reference implementation of whitelist-based filtering: application teams use it to harden rendering of untrusted markup, and security reviewers use its callback surface and result reporting to reason about what a filter actually does to hostile input rather than assuming it. The limits are the ones inherent to any sanitizer — it is one layer, not a substitute for output encoding at the framework level or a Content-Security-Policy — and the documentation's own references to filter evasion techniques are a reminder that sanitization is an ongoing arms race. Used as documented, with a minimal whitelist and the safeAttrValue scheme checks intact, it remains a solid defensive component for any system that must render HTML it did not generate.

Official project repository for leizongmin/js-xss.
Download Tool

Educational analysis for authorized security professionals. Use only in controlled, authorized environments.

Sponsored
Share articleFacebookXLinkedIn

Continue exploring

Browse all articles →

0 comentários:

Post a Comment

Note: Only a member of this blog may post a comment.