|
| 1 | +import sanitizeHtml from "sanitize-html" |
| 2 | + |
| 3 | +/** |
| 4 | + * Strip every HTML tag and script-bearing construct from a string while |
| 5 | + * leaving the human-readable text intact. |
| 6 | + * |
| 7 | + * "<b>Hello</b> <script>alert(1)</script> world" -> "Hello world" |
| 8 | + * "<a href='javascript:bad()'>click</a>" -> "click" |
| 9 | + * "café — naïve" -> "café — naïve" |
| 10 | + * |
| 11 | + * The sanitiser is configured to strip — not encode — tags so the |
| 12 | + * persisted value never carries entity-encoded markup that downstream |
| 13 | + * consumers would have to re-decode. Whitespace inside discarded tags |
| 14 | + * is preserved so adjacent words don't merge. |
| 15 | + */ |
| 16 | +const SANITIZE_OPTIONS: sanitizeHtml.IOptions = { |
| 17 | + allowedTags: [], |
| 18 | + allowedAttributes: {}, |
| 19 | + // `disallowedTagsMode: "discard"` (the default) strips the tag and |
| 20 | + // keeps the text content. We further block <style> / <script> body |
| 21 | + // text via `nonTextTags` so an inline <script>…</script> doesn't |
| 22 | + // leave its contents behind. |
| 23 | + nonTextTags: ["style", "script", "textarea", "option", "noscript"], |
| 24 | + // Preserve raw text characters without HTML-entity encoding so e.g. |
| 25 | + // an ampersand round-trips as "&" rather than "&". |
| 26 | + disallowedTagsMode: "discard", |
| 27 | + parser: { decodeEntities: true }, |
| 28 | + allowedSchemes: [], |
| 29 | + allowedSchemesByTag: {}, |
| 30 | +} |
| 31 | + |
| 32 | +/** |
| 33 | + * Decode the small set of HTML entities that `sanitize-html` re-emits |
| 34 | + * on output. We intentionally limit the set to characters the user |
| 35 | + * obviously typed as plain text (e.g. `&`, `<`, `>`, single + double |
| 36 | + * quotes) so the round-trip stays lossless for normal prose without |
| 37 | + * re-introducing the very markup we just stripped. |
| 38 | + */ |
| 39 | +function decodeBasicEntities(text: string): string { |
| 40 | + return text |
| 41 | + .replace(/&/g, "&") |
| 42 | + .replace(/</g, "<") |
| 43 | + .replace(/>/g, ">") |
| 44 | + .replace(/"/g, '"') |
| 45 | + .replace(/'/g, "'") |
| 46 | + .replace(/'/g, "'") |
| 47 | +} |
| 48 | + |
| 49 | +export function sanitizeUserText(input: string): string { |
| 50 | + if (typeof input !== "string") return "" |
| 51 | + const stripped = sanitizeHtml(input, SANITIZE_OPTIONS) |
| 52 | + return decodeBasicEntities(stripped) |
| 53 | + // collapse the runs of whitespace introduced where tags used to be |
| 54 | + .replace(/[\s\u00a0]+/g, " ") |
| 55 | + .trim() |
| 56 | +} |
0 commit comments