Repository Public
1// Assainisseur HTML sans dépendance, par liste blanche stricte. Le HTML fourni par un appelant d'API n'est jamais digne de confiance :2// la sortie est RECONSTRUITE à partir des seuls éléments et attributs permis (rien de l'entrée n'est recopié tel quel).34const ALLOWED = new Set(("a b i u s em strong p br div span ul ol li blockquote pre code h1 h2 h3 h4 h5 h6 hr table thead tbody tfoot tr td th caption colgroup col img font center small big sub sup del ins mark abbr cite q dl dt dd").split(" "))5const VOID = new Set(["br", "hr", "img", "col"])6// Éléments supprimés AVEC leur contenu.7const DROP_CONTENT = new Set(("script style iframe frame frameset object embed applet noscript template svg math title head textarea select option button canvas audio video xmp plaintext noembed noframes").split(" "))8const GLOBAL_ATTRS = new Set(["title", "dir", "lang", "align", "style"])9const TAG_ATTRS: Record<string, Set<string>> = {10 a: new Set(["href"]), img: new Set(["src", "alt", "width", "height"]),11 td: new Set(["colspan", "rowspan", "valign", "width", "height", "bgcolor"]), th: new Set(["colspan", "rowspan", "valign", "width", "height", "bgcolor"]),12 table: new Set(["border", "cellpadding", "cellspacing", "width", "bgcolor"]), tr: new Set(["valign", "bgcolor"]),13 font: new Set(["color", "face", "size"]), ol: new Set(["start", "type"]), col: new Set(["span", "width"]), colgroup: new Set(["span"]),14}15const CSS_PROPS = new Set(("color background-color font-size font-family font-weight font-style text-align text-decoration line-height vertical-align white-space " +16 "margin margin-top margin-right margin-bottom margin-left padding padding-top padding-right padding-bottom padding-left " +17 "border border-top border-right border-bottom border-left border-color border-style border-width border-collapse border-spacing border-radius " +18 "width height max-width min-width list-style-type display").split(" "))1920const NAMED: Record<string, string> = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: "\u00a0", colon: ":", tab: "\t", newline: "\n", sol: "/", lpar: "(", rpar: ")" }21export function decodeEntities(s: string): string {22 return s.replace(/&(#x[0-9a-f]{1,6}|#[0-9]{1,7}|[a-z][a-z0-9]{1,30});?/gi, (m, e: string) => {23 if (e[0] === "#") {24 const n = e[1].toLowerCase() === "x" ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10)25 return n > 0 && n <= 0x10ffff && !(n >= 0xd800 && n <= 0xdfff) ? String.fromCodePoint(n) : ""26 }27 return NAMED[e.toLowerCase()] ?? m28 })29}30export const escapeHtml = (s: string) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """)31// Texte : les entités bien formées sont gardées, tout « & » nu est échappé.32const escapeText = (s: string) => s.replace(/&(?!(#x[0-9a-f]{1,6}|#[0-9]{1,7}|[a-z][a-z0-9]{1,30});)/gi, "&").replace(/</g, "<").replace(/>/g, ">")3334function safeUrl(raw: string, kind: "href" | "src"): string | null {35 const v = decodeEntities(raw).replace(/[\u0000-\u0020\u007f-\u009f\u200b-\u200f\u2028\u2029\ufeff]/g, "")36 if (v.length > 4096 && !v.startsWith("data:")) return null37 if (kind === "href") return /^(https?:\/\/|mailto:)[^"<>\\`]+$/i.test(v) ? v : null38 if (/^cid:[\w.!#$%&'*+/=?^`{|}~@-]{1,300}$/i.test(v)) return v39 if (/^https?:\/\/[^"<>\\`]+$/i.test(v)) return v40 if (/^data:image\/(png|jpeg|gif|webp);base64,[a-z0-9+/=]+$/i.test(v) && v.length <= 2_000_000) return v41 return null42}43function safeStyle(raw: string): string {44 const out: string[] = []45 for (const decl of decodeEntities(raw).split(";")) {46 const i = decl.indexOf(":")47 if (i < 1) continue48 const prop = decl.slice(0, i).trim().toLowerCase()49 const val = decl.slice(i + 1).trim()50 if (!CSS_PROPS.has(prop) || val.length > 200) continue51 if (!/^[\w\s#%.,\-+!'/()]*$/.test(val)) continue // ni \ ni " ni @ ni : (donc pas d'url(), d'expression(), d'échappement CSS)52 if (/\(/.test(val) && !/^[^()]*((rgb|rgba|hsl|hsla)\([\d\s.,%/]+\)[^()]*)+$/i.test(val)) continue53 if (/expression|javascript|behavior|binding|url/i.test(val)) continue54 if (prop === "display" && !/^(block|inline|inline-block|table|table-row|table-cell|list-item|none)$/i.test(val)) continue55 out.push(`${prop}: ${val}`)56 }57 return out.join("; ")58}59function safeAttr(tag: string, name: string, raw: string): string | null {60 if (name === "href") return safeUrl(raw, "href")61 if (name === "src") return safeUrl(raw, "src")62 if (name === "style") return safeStyle(raw) || null63 const v = decodeEntities(raw).replace(/[\u0000-\u001f\u007f]/g, " ").trim()64 if (v.length > 300) return null65 if (["width", "height", "colspan", "rowspan", "border", "cellpadding", "cellspacing", "span", "start", "size"].includes(name)) return /^[+-]?\d{1,4}%?$/.test(v) ? v : null66 if (["color", "bgcolor"].includes(name)) return /^(#[0-9a-f]{3,8}|[a-z]{3,20})$/i.test(v) ? v : null67 if (["align", "valign", "dir", "type"].includes(name)) return /^[a-z0-9]{1,10}$/i.test(v) ? v : null68 return v69}7071const ATTR_RE = /([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'<>`]+)))?/g7273/** Rend un fragment HTML sûr (aucun script, gestionnaire d'événement, URL active, formulaire, cadre, SVG ni CSS dangereux). */74export function sanitizeHtml(input: string): string {75 const src = String(input).replace(/\u0000/g, "")76 const out: string[] = []77 const stack: string[] = []78 let i = 079 const n = src.length80 while (i < n) {81 const lt = src.indexOf("<", i)82 if (lt < 0) { out.push(escapeText(src.slice(i))); break }83 if (lt > i) out.push(escapeText(src.slice(i, lt)))84 if (src.startsWith("<!--", lt)) { const e = src.indexOf("-->", lt + 4); i = e < 0 ? n : e + 3; continue }85 if (src[lt + 1] === "!" || src[lt + 1] === "?") { const e = src.indexOf(">", lt); i = e < 0 ? n : e + 1; continue }86 const m = /^<(\/?)([a-zA-Z][a-zA-Z0-9:-]*)/.exec(src.slice(lt, lt + 80))87 if (!m) { out.push("<"); i = lt + 1; continue }88 // fin de balise : premier « > » hors guillemets89 let j = lt + m[0].length, quote = ""90 while (j < n) {91 const ch = src[j]92 if (quote) { if (ch === quote) quote = "" } else if (ch === '"' || ch === "'") quote = ch93 else if (ch === ">") break94 j++95 }96 if (j >= n) { i = n; break } // balise jamais fermée : le reste est abandonné97 const closing = m[1] === "/"98 const tag = m[2].toLowerCase()99 const attrText = src.slice(lt + m[0].length, j)100 i = j + 1101 if (DROP_CONTENT.has(tag)) {102 if (!closing && !/\/\s*$/.test(attrText)) {103 const re = new RegExp(`</${tag.replace(/[^a-z0-9]/g, "")}\\s*>`, "ig")104 re.lastIndex = i105 const e = re.exec(src)106 i = e ? e.index + e[0].length : n107 }108 continue109 }110 if (!ALLOWED.has(tag)) continue // balise inconnue retirée, son contenu textuel est gardé (échappé)111 if (closing) {112 const k = stack.lastIndexOf(tag)113 if (k >= 0) while (stack.length > k) out.push(`</${stack.pop()}>`)114 continue115 }116 const attrs: string[] = []117 const seen = new Set<string>()118 let hasHref = false119 ATTR_RE.lastIndex = 0120 for (let a = ATTR_RE.exec(attrText); a; a = ATTR_RE.exec(attrText)) {121 const name = a[1].toLowerCase()122 if (seen.has(name) || !(GLOBAL_ATTRS.has(name) || TAG_ATTRS[tag]?.has(name))) continue123 seen.add(name)124 const v = safeAttr(tag, name, a[2] ?? a[3] ?? a[4] ?? "")125 if (v === null) continue126 if (name === "href") hasHref = true127 attrs.push(` ${name}="${escapeHtml(v)}"`)128 }129 if (tag === "img" && !seen.has("src")) continue130 if (tag === "img" && !attrs.some((x) => x.startsWith(" src="))) continue131 if (tag === "a" && hasHref) attrs.push(' rel="noopener noreferrer" target="_blank"')132 out.push(`<${tag}${attrs.join("")}>`)133 if (!VOID.has(tag)) {134 stack.push(tag)135 if (stack.length > 200) break136 }137 }138 while (stack.length) out.push(`</${stack.pop()}>`)139 return out.join("")140}141142/** Version texte d'un HTML (pour la partie text/plain quand l'appelant ne fournit que du HTML). */143export function htmlToText(html: string): string {144 const safe = sanitizeHtml(html)145 return decodeEntities(146 safe.replace(/<br>/g, "\n").replace(/<\/(p|div|li|tr|h[1-6]|blockquote|pre|table)>/g, "\n").replace(/<li[^>]*>/g, "- ").replace(/<[^>]+>/g, ""),147 ).replace(/[ \t]+\n/g, "\n").replace(/\n{3,}/g, "\n\n").trim()148}149