Rich text is a frequent source of stored cross-site scripting when editor input is treated as trusted HTML. Even trusted accounts can be compromised, and content may arrive through imports or APIs.
Choose a constrained content format
If the platform can use Markdown or structured blocks, prefer that over accepting arbitrary HTML. Define supported elements and attributes. If HTML is required, sanitize it with a maintained allowlist-based sanitizer on the server.
Do not attempt to secure HTML with regular expressions or a few string replacements. HTML parsing rules are complex and browser behavior can differ from simplistic filters.
Encode output by context
Escape ordinary text for its output context. HTML text, attributes, URLs, CSS, and JavaScript require different handling. Avoid placing editor-controlled values into inline scripts or event-handler attributes.
For links, validate schemes and reject dangerous protocols. For embeds, use a strict provider allowlist and safe iframe attributes.
Defend the whole pipeline
Sanitize at a clearly defined boundary and keep the original source only if there is a secure reason to do so. Re-sanitize when policy changes. Use a restrictive Content Security Policy as an additional layer, not as a replacement for sanitization.
Implementation checklist
- Prefer Markdown or structured blocks where possible.
- Use a maintained HTML sanitizer with an allowlist.
- Encode output for its exact context.
- Validate URL schemes and embed providers.
- Test malicious payloads from imports and APIs.