Preserve HTML email layouts and adapt dark mode with Dark Reader
Some checks failed
Tests und Docker-Image / Tests und Frontend-Build (push) Successful in 51s
Tests und Docker-Image / Leeres Produktionsimage bauen und veröffentlichen (push) Has been cancelled

This commit is contained in:
Weapie 2026-11-05 17:54:57 +01:00
parent 02a28f4ee9
commit c72c72e41e
19 changed files with 995 additions and 192 deletions

View File

@ -2,6 +2,8 @@
## Aktueller Stand
- Überarbeiteter HTML-Mail-Renderer mit eingebetteten Stylesheets, Tabellen-/Zellenlayout, responsiven Media Queries und erhaltenen Outlook-/Word-Abständen.
- Dark Reader für farberhaltenden Dunkelmodus, umschaltbare Originalfarben, zusätzliche Bildquellen einschließlich CSS-Hintergründen und `srcset`; vollständiges Scrollen großer Originalansichten.
- Eingehende IMAP-Mails bis 50 MiB einschließlich MIME-Kodierung, mit passenden Speichergrenzen für Originalmail, HTML und eingehende Anhänge. Ausgehende Anhangsgrenzen bleiben bei 10 MiB je Datei und 20 MiB insgesamt.
- Mails an mehrere Queues in An/Cc erzeugen je Queue eine eigene Kopie, mit queue-spezifischer Duplikaterkennung, Antwortzuordnung, Tags, Benachrichtigungen und optionalen Eingangsbestätigungen. Gemeinsame Postfächer werden vor dem Gelesen-Markieren vollständig verteilt.
- Transaktionale Migration bestehender Message-IDs unter Erhalt von Originalen, Anhängen, Historie, Suchindizes und Verknüpfungen; Abrufprotokoll zählt zusätzliche Queue-Zuordnungen.

View File

@ -88,6 +88,21 @@ Unter **Ticketdetails → Kundenkontakt ändern** können Name und E-Mail-Adress
Neu empfangene HTML-Mails werden standardmäßig formatiert angezeigt. Die Ansicht passt ihre Höhe an den Inhalt und nachgeladene Bilder an; zusätzliche Leerstreifen und ein technischer Vorschau-Footer entfallen. **Original ansehen** öffnet eine größere Ansicht mit Klartext-Umschalter und, sofern vorhanden, Download der ursprünglichen MIME-Datei als `.eml`. Eingebettete CID-Bilder in PNG, JPEG, GIF und WebP werden ausschließlich aus den Anhängen derselben Nachricht aufgelöst. Externe HTTPS-Bilder werden automatisch geladen und lassen sich pro Nachricht über **Externe Bilder anzeigen** ausblenden. Diese Abrufe erfolgen im Browser ohne Referrer; der Bildserver erhält dabei die übliche Verbindungsinformation. HTML-Ansicht und Signaturvorschau folgen dem gewählten Hell-/Dunkelmodus; im Dunkelmodus werden weiße Hintergründe und unlesbare Textfarben angepasst. Die Farben eingebetteter Bilddateien bleiben erhalten.
Der Mail-Renderer erhält eingebettete Stylesheets, CSS-Klassen, Tabellenbreiten, Zellen-Ausrichtungen, Hintergründe und responsive Media Queries. Outlook-/Word-Absatzabstände und Schriftgrößen mit Nachkommastellen bleiben erhalten. Tabellen werden nicht pauschal umformatiert; breite Vorlagen werden bei Bedarf verkleinert oder innerhalb der Mail gescrollt. Die große Originalansicht lässt sich vollständig scrollen.
Der Dunkelmodus verwendet die lokal mitgelieferte [Dark-Reader-API](https://github.com/darkreader/darkreader#using-dark-reader-on-a-website), statt alle Hintergründe und Textfarben pauschal zu überschreiben. **Originalfarben** zeigt die Farbgebung der bereinigten Mail ohne zusätzliche Dunkelmodus-Anpassung. Bilder bleiben ohne automatische Farbfilter. Ein CDN oder zusätzliche Fetch-/Proxy-Abrufe für die Farbanpassung sind nicht erforderlich.
Bildquellen unterstützen auch `srcset`, CSS-/Tabellen-Hintergründe, protokollrelative URLs und lokale CID-/Dateinamenreferenzen aus derselben Nachricht. HTTP-Bildadressen werden auf HTTPS normalisiert. Abgelaufene, beschädigte oder vom Bildserver gesperrte Bilder können weiterhin fehlen; die Vorschau weist darauf hin. Externe Stylesheets und Webfonts werden nicht nachgeladen. CSS wird mit Parsern gefiltert und auf den Mailbereich begrenzt; Skripte, Eventhandler, Formularelemente und aktive Einbettungen werden entfernt. Die Sandbox und die strikte Hauptseiten-CSP bleiben bestehen.
<details>
<summary>Newsletter und Outlook-Layout im neuen Renderer ansehen</summary>
![Newsletter mit ausgerichteten Spalten, geladenen CID-Bildern und erhaltenen Schaltflächenfarben im Dunkelmodus](docs/images/html-newsletter-renderer.jpg)
![Outlook-Mail mit erhaltenen Absatzabständen und Tabellen-Signatur in der isolierten Demo](docs/images/html-outlook-renderer.jpg)
</details>
<details>
<summary>HTML-Nachricht ohne Vorschau-Footer und mit geladenem externem Bild</summary>
@ -97,7 +112,7 @@ Neu empfangene HTML-Mails werden standardmäßig formatiert angezeigt. Die Ansic
![Originalansicht mit eingebettetem Bild im Dunkelmodus](docs/images/message-original.jpg)
HTML und MIME-Originale werden erst seit diesem Update beim Empfang gespeichert. Für bereits früher importierte Nachrichten lässt sich ein verworfener HTML-Teil nicht nachträglich rekonstruieren; dort wird der bisher gespeicherte Inhalt angezeigt. Die HTML-Vorschau sehr großer Nachrichten wird auf 2 MiB begrenzt, während die gespeicherte Originaldatei vollständig heruntergeladen werden kann. Aktive Inhalte, Skripte und unsichere Bildformate werden nicht ausgeführt.
HTML und MIME-Originale werden seit dem HTML-Update beim Empfang gespeichert. Bereits gespeicherte HTML-Originale profitieren direkt vom neuen Renderer; ein erneuter Import ist nicht erforderlich. Für ältere Nachrichten ohne gespeicherten HTML-Teil lässt sich verworfene Formatierung nicht nachträglich rekonstruieren. Die HTML-Vorschau sehr großer Nachrichten wird auf 2 MiB begrenzt, eingebettete Bilddaten auf insgesamt 20 MiB pro Darstellung einschließlich mehrfacher Referenzen. Die gespeicherte Originaldatei und Anhänge bleiben vollständig herunterladbar. Aktive Inhalte, Skripte und unsichere Bildformate werden nicht ausgeführt.
![Ticketverlauf mit interner Notiz, empfangenem Anhang und Antworteditor](docs/images/ticket-detail.png)
@ -495,7 +510,7 @@ Der Runner benötigt `ubuntu-latest`, Node-Action-Unterstützung, Docker CLI und
React 19, Park UI/Ark UI und Panda CSS im Frontend; Express 5, Node.js 22 und SQLite im Backend. Der App-Prozess liefert die Oberfläche aus und betreibt Versandworker sowie IMAP-Scheduler. Das ist ein vollständiger Dienst und kein rein statischer Webauftritt.
Produktionskonfiguration: App als Benutzer `node`, Root-Dateisystem read-only, keine Linux-Capabilities, `no-new-privileges`, temporäres `/tmp`, Ressourcenlimits, begrenzte Logs, Healthcheck und geregeltes Herunterfahren. Sitzungscookies sind HttpOnly, SameSite=Strict und Secure. Anmeldeversuche werden pro Client-IP begrenzt; Rechte werden serverseitig geprüft. Die Hauptseite erlaubt keine Inline-Skripte oder externen Bilder. HTML-Vorschauen laufen als eigene Dokumente in einer Sandbox ohne Same-Origin-Zugriff; nur die eigene, per Nonce freigegebene Größenanpassung darf dort Skriptcode ausführen. Skripte und Eventhandler aus Mails werden entfernt, die CSP blockiert weitere aktive Inhalte. Audit-Trigger verhindern Änderungen über normale Anwendungsaktionen.
Produktionskonfiguration: App als Benutzer `node`, Root-Dateisystem read-only, keine Linux-Capabilities, `no-new-privileges`, temporäres `/tmp`, Ressourcenlimits, begrenzte Logs, Healthcheck und geregeltes Herunterfahren. Sitzungscookies sind HttpOnly, SameSite=Strict und Secure. Anmeldeversuche werden pro Client-IP begrenzt; Rechte werden serverseitig geprüft. Die Hauptseite erlaubt keine Inline-Skripte oder externen Bilder. HTML-Vorschauen laufen als eigene Dokumente in einer Sandbox ohne Same-Origin-Zugriff; nur die per Nonce freigegebene Integration für Größenanpassung und Farbumrechnung einschließlich des lokal gebündelten Dark Readers darf dort Skriptcode ausführen. Skripte und Eventhandler aus Mails werden entfernt, die CSP blockiert weitere aktive Inhalte. Audit-Trigger verhindern Änderungen über normale Anwendungsaktionen.
Die unterstützte Betriebsform ist eine einzelne Instanz mit lokalem persistentem SQLite-Volume hinter einem vertrauenswürdigen TLS-Proxy. Es gibt noch keine horizontale Skalierung, MFA/SSO, Passwort-Selbstzurücksetzung, OAuth2-Mailkonten, POP3 oder integrierten Virenscanner. Klassisches SMTP kann keine transaktionale Exactly-once-Zustellung mit SQLite garantieren. Diese Grenzen und das Verhalten bei unklaren Versandzuständen sind bewusst dokumentiert.

Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

328
package-lock.json generated
View File

@ -11,13 +11,20 @@
"@ark-ui/react": "^5.0.0",
"better-sqlite3": "^11.10.0",
"cron-parser": "^5.10.3",
"darkreader": "4.9.134",
"dom-serializer": "2.0.0",
"dotenv": "^18.0.9",
"express": "^5.1.0",
"html-to-text": "^10.0.1",
"htmlparser2": "12.0.0",
"imapflow": "^1.0.0",
"lucide-react": "^0.468.0",
"mailparser": "^3.7.0",
"nodemailer": "^10.3.1",
"parse-srcset": "1.0.2",
"postcss": "8.5.31",
"postcss-selector-parser": "7.1.6",
"postcss-value-parser": "4.2.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"sanitize-html": "^2.17.5"
@ -3549,7 +3556,6 @@
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz",
"integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==",
"dev": true,
"license": "MIT",
"bin": {
"cssesc": "bin/cssesc"
@ -3564,6 +3570,49 @@
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
"license": "MIT"
},
"node_modules/darkreader": {
"version": "4.9.134",
"resolved": "https://registry.npmjs.org/darkreader/-/darkreader-4.9.134.tgz",
"integrity": "sha512-HAyEz97vK/UFLO6kcjxojji5OKr0+pwgGLrBzyg67xD2p6ySrSyCBvNxb+0KTSMYk9qNz9Hq85JR3TaKyqEV1w==",
"license": "MIT",
"dependencies": {
"malevic": "0.20.3"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/darkreader/donate"
},
"optionalDependencies": {
"@rollup/rollup-linux-x64-gnu": "4.63.5",
"@rollup/rollup-win32-x64-msvc": "4.63.5"
}
},
"node_modules/darkreader/node_modules/@rollup/rollup-linux-x64-gnu": {
"version": "4.63.5",
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.63.5.tgz",
"integrity": "sha512-3W9bTFcQNJn71cSJVM9RKIiZOy8DO/XLDii8Uv/Pm6WKqDRj7JV3ZfuXIEfyuy5LXpIzAbB/1M4Ukp9GKNa7nA==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
]
},
"node_modules/darkreader/node_modules/@rollup/rollup-win32-x64-msvc": {
"version": "4.63.5",
"resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.63.5.tgz",
"integrity": "sha512-ypfC34F3RKXvCXBglGqGMsUSMKlgwd1HX9AOAlx9RoZZ6GaI42YHVeKpzg3JG+wpBUJYTG+NNZhqbDWL8tBZkw==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"win32"
]
},
"node_modules/dayjs": {
"version": "1.11.23",
"resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.23.tgz",
@ -3690,19 +3739,84 @@
}
},
"node_modules/domutils": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz",
"integrity": "sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==",
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/domutils/-/domutils-4.0.2.tgz",
"integrity": "sha512-qI4JLRKnSzqFqr7hAlS5xQDusBCjKSEG4t4+7aNrIQMHBcsC2TGEhuyABJdYkgSewL57PNLYEiibY2iPKhKpaA==",
"license": "BSD-2-Clause",
"dependencies": {
"dom-serializer": "^2.0.0",
"domelementtype": "^2.3.0",
"domhandler": "^5.0.3"
"dom-serializer": "^3.0.0",
"domelementtype": "^3.0.0",
"domhandler": "^6.0.0"
},
"engines": {
"node": ">=20.19.0"
},
"funding": {
"type": "github",
"url": "https://github.com/fb55/domutils?sponsor=1"
}
},
"node_modules/domutils/node_modules/dom-serializer": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-3.1.1.tgz",
"integrity": "sha512-4MEa38/QexBob6gFNwu+EGdWvhJ1OKuNwdYY3Y3NyeWDQfnGeDYQUDfIRzWu5B5gsv03so2Uxd28YC6zrsx3Lw==",
"license": "MIT",
"dependencies": {
"domelementtype": "^3.0.0",
"domhandler": "^6.0.0",
"entities": "^8.0.0"
},
"engines": {
"node": ">=20.19.0"
},
"funding": {
"type": "github",
"url": "https://github.com/cheeriojs/dom-serializer?sponsor=1"
}
},
"node_modules/domutils/node_modules/domelementtype": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-3.0.0.tgz",
"integrity": "sha512-umCQid3jKbDmVjx8jGaW7uUykm4DEUeyV21hPxNMo2nV955DhUThwqyOIDtreepP31hl84X7G5U9ZfsWvIB3Pg==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/fb55"
}
],
"license": "BSD-2-Clause",
"engines": {
"node": ">=20.19.0"
}
},
"node_modules/domutils/node_modules/domhandler": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/domhandler/-/domhandler-6.0.1.tgz",
"integrity": "sha512-gYzvtM72ZtxQO0T048kd6HWSbbGCNOUwcnfQ01cqIJ4X2IYKFFHZ5mKvrQETcFXxsRObZulDaKmy//R7TPtsBg==",
"license": "BSD-2-Clause",
"dependencies": {
"domelementtype": "^3.0.0"
},
"engines": {
"node": ">=20.19.0"
},
"funding": {
"type": "github",
"url": "https://github.com/fb55/domhandler?sponsor=1"
}
},
"node_modules/domutils/node_modules/entities": {
"version": "8.1.0",
"resolved": "https://registry.npmjs.org/entities/-/entities-8.1.0.tgz",
"integrity": "sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA==",
"license": "BSD-2-Clause",
"engines": {
"node": ">=20.19.0"
},
"funding": {
"url": "https://github.com/fb55/entities?sponsor=1"
}
},
"node_modules/dotenv": {
"version": "18.0.9",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-18.0.9.tgz",
@ -4352,7 +4466,33 @@
"url": "https://github.com/sponsors/KillyMXI"
}
},
"node_modules/htmlparser2": {
"node_modules/html-to-text/node_modules/domutils": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz",
"integrity": "sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==",
"license": "BSD-2-Clause",
"dependencies": {
"dom-serializer": "^2.0.0",
"domelementtype": "^2.3.0",
"domhandler": "^5.0.3"
},
"funding": {
"url": "https://github.com/fb55/domutils?sponsor=1"
}
},
"node_modules/html-to-text/node_modules/entities": {
"version": "7.0.1",
"resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz",
"integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==",
"license": "BSD-2-Clause",
"engines": {
"node": ">=0.12"
},
"funding": {
"url": "https://github.com/fb55/entities?sponsor=1"
}
},
"node_modules/html-to-text/node_modules/htmlparser2": {
"version": "10.1.0",
"resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-10.1.0.tgz",
"integrity": "sha512-VTZkM9GWRAtEpveh7MSF6SjjrpNVNNVJfFup7xTY3UpFtm67foy9HDVXneLtFVt4pMz5kZtgNcvCniNFb1hlEQ==",
@ -4371,13 +4511,66 @@
"entities": "^7.0.1"
}
},
"node_modules/htmlparser2/node_modules/entities": {
"version": "7.0.1",
"resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz",
"integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==",
"node_modules/htmlparser2": {
"version": "12.0.0",
"resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-12.0.0.tgz",
"integrity": "sha512-Tz7u1i95/g2x2jz81+x0FBVhBhY5aRTvD3tXXdFaljuNdzDLJ8UGNRrTcj2cgQvAg3iW/h77Fz15nLW0L0CrZw==",
"funding": [
"https://github.com/fb55/htmlparser2?sponsor=1",
{
"type": "github",
"url": "https://github.com/sponsors/fb55"
}
],
"license": "MIT",
"dependencies": {
"domelementtype": "^3.0.0",
"domhandler": "^6.0.0",
"domutils": "^4.0.2",
"entities": "^8.0.0"
},
"engines": {
"node": ">=20.19.0"
}
},
"node_modules/htmlparser2/node_modules/domelementtype": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-3.0.0.tgz",
"integrity": "sha512-umCQid3jKbDmVjx8jGaW7uUykm4DEUeyV21hPxNMo2nV955DhUThwqyOIDtreepP31hl84X7G5U9ZfsWvIB3Pg==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/fb55"
}
],
"license": "BSD-2-Clause",
"engines": {
"node": ">=0.12"
"node": ">=20.19.0"
}
},
"node_modules/htmlparser2/node_modules/domhandler": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/domhandler/-/domhandler-6.0.1.tgz",
"integrity": "sha512-gYzvtM72ZtxQO0T048kd6HWSbbGCNOUwcnfQ01cqIJ4X2IYKFFHZ5mKvrQETcFXxsRObZulDaKmy//R7TPtsBg==",
"license": "BSD-2-Clause",
"dependencies": {
"domelementtype": "^3.0.0"
},
"engines": {
"node": ">=20.19.0"
},
"funding": {
"type": "github",
"url": "https://github.com/fb55/domhandler?sponsor=1"
}
},
"node_modules/htmlparser2/node_modules/entities": {
"version": "8.1.0",
"resolved": "https://registry.npmjs.org/entities/-/entities-8.1.0.tgz",
"integrity": "sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA==",
"license": "BSD-2-Clause",
"engines": {
"node": ">=20.19.0"
},
"funding": {
"url": "https://github.com/fb55/entities?sponsor=1"
@ -5069,6 +5262,12 @@
"node": ">=20.0.0"
}
},
"node_modules/malevic": {
"version": "0.20.3",
"resolved": "https://registry.npmjs.org/malevic/-/malevic-0.20.3.tgz",
"integrity": "sha512-DzUDSf5MkW0Bjrk7l5j6hIN4uxMRGLKmblKvZ84Nu3V5bwAu4tzYX7Mds5HM5Vk1oZaTIeEPFbHaUU1YSWwOnw==",
"license": "MIT"
},
"node_modules/math-intrinsics": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
@ -5660,7 +5859,6 @@
"version": "7.1.6",
"resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.6.tgz",
"integrity": "sha512-7qASPzhKF2l2KLboRZux8CCTRMdGiV08vWmyKzPz22qZ7ZjQBOeY7rNzNoCLSUiftJ7HUq0GERHmxw/t0dCdMw==",
"dev": true,
"license": "MIT",
"dependencies": {
"cssesc": "^3.0.0",
@ -5674,7 +5872,6 @@
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz",
"integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==",
"dev": true,
"license": "MIT"
},
"node_modules/prebuild-install": {
@ -6131,107 +6328,6 @@
"node": ">=22.12.0"
}
},
"node_modules/sanitize-html/node_modules/dom-serializer": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-3.1.1.tgz",
"integrity": "sha512-4MEa38/QexBob6gFNwu+EGdWvhJ1OKuNwdYY3Y3NyeWDQfnGeDYQUDfIRzWu5B5gsv03so2Uxd28YC6zrsx3Lw==",
"license": "MIT",
"dependencies": {
"domelementtype": "^3.0.0",
"domhandler": "^6.0.0",
"entities": "^8.0.0"
},
"engines": {
"node": ">=20.19.0"
},
"funding": {
"type": "github",
"url": "https://github.com/cheeriojs/dom-serializer?sponsor=1"
}
},
"node_modules/sanitize-html/node_modules/domelementtype": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-3.0.0.tgz",
"integrity": "sha512-umCQid3jKbDmVjx8jGaW7uUykm4DEUeyV21hPxNMo2nV955DhUThwqyOIDtreepP31hl84X7G5U9ZfsWvIB3Pg==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/fb55"
}
],
"license": "BSD-2-Clause",
"engines": {
"node": ">=20.19.0"
}
},
"node_modules/sanitize-html/node_modules/domhandler": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/domhandler/-/domhandler-6.0.1.tgz",
"integrity": "sha512-gYzvtM72ZtxQO0T048kd6HWSbbGCNOUwcnfQ01cqIJ4X2IYKFFHZ5mKvrQETcFXxsRObZulDaKmy//R7TPtsBg==",
"license": "BSD-2-Clause",
"dependencies": {
"domelementtype": "^3.0.0"
},
"engines": {
"node": ">=20.19.0"
},
"funding": {
"type": "github",
"url": "https://github.com/fb55/domhandler?sponsor=1"
}
},
"node_modules/sanitize-html/node_modules/domutils": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/domutils/-/domutils-4.0.2.tgz",
"integrity": "sha512-qI4JLRKnSzqFqr7hAlS5xQDusBCjKSEG4t4+7aNrIQMHBcsC2TGEhuyABJdYkgSewL57PNLYEiibY2iPKhKpaA==",
"license": "BSD-2-Clause",
"dependencies": {
"dom-serializer": "^3.0.0",
"domelementtype": "^3.0.0",
"domhandler": "^6.0.0"
},
"engines": {
"node": ">=20.19.0"
},
"funding": {
"type": "github",
"url": "https://github.com/fb55/domutils?sponsor=1"
}
},
"node_modules/sanitize-html/node_modules/entities": {
"version": "8.1.0",
"resolved": "https://registry.npmjs.org/entities/-/entities-8.1.0.tgz",
"integrity": "sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA==",
"license": "BSD-2-Clause",
"engines": {
"node": ">=20.19.0"
},
"funding": {
"url": "https://github.com/fb55/entities?sponsor=1"
}
},
"node_modules/sanitize-html/node_modules/htmlparser2": {
"version": "12.0.0",
"resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-12.0.0.tgz",
"integrity": "sha512-Tz7u1i95/g2x2jz81+x0FBVhBhY5aRTvD3tXXdFaljuNdzDLJ8UGNRrTcj2cgQvAg3iW/h77Fz15nLW0L0CrZw==",
"funding": [
"https://github.com/fb55/htmlparser2?sponsor=1",
{
"type": "github",
"url": "https://github.com/sponsors/fb55"
}
],
"license": "MIT",
"dependencies": {
"domelementtype": "^3.0.0",
"domhandler": "^6.0.0",
"domutils": "^4.0.2",
"entities": "^8.0.0"
},
"engines": {
"node": ">=20.19.0"
}
},
"node_modules/scheduler": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz",

View File

@ -7,7 +7,7 @@
"dev": "concurrently -k \"node --watch server/index.js\" \"vite --host 127.0.0.1\"",
"start": "node server/index.js",
"build": "panda codegen && tsc --noEmit && vite build",
"test": "node --test tests/service.test.js tests/mail-connections.test.js tests/collaboration.test.js tests/organization.test.js tests/pagination.test.js tests/inbound-resilience.test.js tests/multi-queue-mail.test.js",
"test": "node --test tests/service.test.js tests/mail-connections.test.js tests/collaboration.test.js tests/organization.test.js tests/pagination.test.js tests/inbound-resilience.test.js tests/multi-queue-mail.test.js tests/html-rendering.test.js",
"prepare": "panda codegen",
"test:docker": "node tests/docker-smoke.mjs",
"test:image": "node tests/image-smoke.mjs",
@ -18,13 +18,20 @@
"@ark-ui/react": "^5.0.0",
"better-sqlite3": "^11.10.0",
"cron-parser": "^5.10.3",
"darkreader": "4.9.134",
"dom-serializer": "2.0.0",
"dotenv": "^18.0.9",
"express": "^5.1.0",
"html-to-text": "^10.0.1",
"htmlparser2": "12.0.0",
"imapflow": "^1.0.0",
"lucide-react": "^0.468.0",
"mailparser": "^3.7.0",
"nodemailer": "^10.3.1",
"parse-srcset": "1.0.2",
"postcss": "8.5.31",
"postcss-selector-parser": "7.1.6",
"postcss-value-parser": "4.2.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"sanitize-html": "^2.17.5"

View File

@ -7,6 +7,7 @@ import { signatureValue } from './content.js'
import { signatureTokens, signatureContext } from './signature-placeholders.js'
import { proxyHops } from './runtime.js'
import { htmlPreviewDocument } from './html-preview.js'
import { darkReaderPath, darkReaderSource } from './preview-assets.js'
export function createApp(db) {
const app = express(),
s = new Service(db)
@ -38,6 +39,14 @@ export function createApp(db) {
next()
})
app.use(express.json({ limit: '30mb' }))
// Public, immutable vendor code contains no mail or session data. Opaque-origin
// sandboxed previews can load it without cookies; execution still requires a nonce.
app.get(darkReaderPath, (req, res) =>
res
.set('Cache-Control', 'public, max-age=31536000, immutable')
.type('js')
.send(darkReaderSource),
)
app.get('/healthz', (req, res) => {
s.get('SELECT 1 ok')
res.json({ status: 'ok' })

View File

@ -2,6 +2,8 @@ import sanitizeHtml from 'sanitize-html'
import { convert } from 'html-to-text'
import { HttpError } from './service.js'
import { expandSignature } from './signature-placeholders.js'
import { inlineMailCss } from './mail-css.js'
import { safeImageUrl } from './mail-html.js'
export const escapeHtml = (value) =>
String(value).replace(
/[&<>"']/g,
@ -48,7 +50,7 @@ export function safeHtml(html, options = {}) {
'font',
],
allowedAttributes: {
'*': ['style'],
'*': ['style', 'class', 'title', 'align', 'valign', 'bgcolor', 'width', 'height', 'dir'],
a: ['href', 'title'],
img: ['src', 'alt', 'width', 'height'],
td: ['colspan', 'rowspan'],
@ -59,22 +61,17 @@ export function safeHtml(html, options = {}) {
allowedSchemes: ['https', 'http', 'mailto', 'tel'],
allowedSchemesByTag: { img: options.cid ? ['https', 'data', 'cid'] : ['https', 'data'] },
allowProtocolRelative: false,
allowedStyles: {
'*': {
color: [/^#[0-9a-f]{3,8}$/i, /^[a-z]+$/i, /^rgb\([\d\s,]+\)$/i],
'background-color': [/^#[0-9a-f]{3,8}$/i, /^[a-z]+$/i],
'font-family': [/^[a-z\s,\-']+$/i],
'font-size': [/^\d{1,2}(px|pt)$/],
'font-weight': [/^(normal|bold|[1-9]00)$/],
'text-align': [/^(left|right|center|justify)$/],
'text-decoration': [/^(none|underline|line-through)$/],
'line-height': [/^[\d.]+(px|em|%)?$/],
padding: [/^[\d\s.]+(px|pt)$/],
'border-collapse': [/^(collapse|separate)$/],
},
},
parseStyleAttributes: false,
transformTags: {
'*': (tag, attrs) => ({
tagName: tag,
attribs: {
...attrs,
...(attrs.style ? { style: inlineMailCss(attrs.style, safeImageUrl) } : {}),
},
}),
img: (tag, attribs) => {
if (attribs.style) attribs.style = inlineMailCss(attribs.style, safeImageUrl)
if (
attribs.src?.startsWith('data:') &&
!/^data:image\/(png|jpeg|gif|webp);base64,[a-z\d+/=]+$/i.test(attribs.src)

View File

@ -1,7 +1,9 @@
import { randomBytes } from 'node:crypto'
import { darkReaderPath } from './preview-assets.js'
// A separate document keeps the main application's strict image/script policy intact.
// The sandbox has no same-origin access; only this nonce-protected sizing bridge runs.
// The sandbox has no same-origin access. Only the nonce-protected integration and
// the locally bundled Dark Reader code can execute; scripts from mail are removed.
export function htmlPreviewDocument({ dark = false, remoteImages = false } = {}) {
const nonce = randomBytes(24).toString('base64')
const background = dark ? '#222225' : '#ffffff',
@ -10,25 +12,50 @@ export function htmlPreviewDocument({ dark = false, remoteImages = false } = {})
const csp = `default-src 'none'; img-src data:${remoteImages ? ' https:' : ''}; style-src 'unsafe-inline'; script-src 'nonce-${nonce}'; base-uri 'none'; form-action 'none'; frame-ancestors 'self'; sandbox allow-scripts`
const html = `<!doctype html><html><head><meta charset="utf-8"><meta name="color-scheme" content="${dark ? 'dark' : 'light'}"><style>
html,body{margin:0;background:${background};color:${foreground};color-scheme:${dark ? 'dark' : 'light'}}
body{font:14px/1.6 Arial,sans-serif;overflow-wrap:anywhere}
body{font:14px Arial,sans-serif;overflow-wrap:break-word}
#mail-viewport{width:100%;overflow-x:auto;overflow-y:hidden}
#mail-content{display:flow-root;padding:16px;box-sizing:border-box;min-width:0}
#mail-content>:first-child{margin-top:0}#mail-content>:last-child{margin-bottom:0}
img{max-width:100%;height:auto}table{max-width:100%;border-collapse:collapse}pre{white-space:pre-wrap}
blockquote{border-left:3px solid ${accent};margin-left:0;padding-left:16px}a{color:${accent}}
${dark ? `#mail-content,#mail-content *:not(img){color:${foreground}!important;background-color:transparent!important;border-color:#494950!important}#mail-content a,#mail-content a *{color:${accent}!important}` : ''}
</style></head><body><div id="mail-content"></div><script nonce="${nonce}">
img{max-width:100%}pre{white-space:pre-wrap}a{color:${accent}}
.syncova-image-unavailable{background:#8882;outline:1px solid #8885;object-fit:contain}
</style>${dark ? `<script nonce="${nonce}" src="${darkReaderPath}"></script>` : ''}</head><body><div id="mail-viewport"><div id="mail-content"></div></div><script nonce="${nonce}">
(() => {
const channel = location.hash.slice(1), root = document.getElementById('mail-content');
let scheduled = false, lastHeight = 0;
let scheduled = false, lastHeight = 0, lastFailed = -1, failedImages = 0, width = 0;
function fit() {
width = document.documentElement.clientWidth;
root.style.zoom = '1'; root.style.width = 'auto';
const natural = Math.min(20000, Math.max(width, root.scrollWidth));
if (natural > width + 2) {
root.style.width = natural + 'px';
root.style.zoom = String(Math.max(0.5, width / natural));
}
}
function darken() {
if (!${dark ? 'true' : 'false'} || !window.DarkReader) return;
// No CSS/image proxy fetches: remote-content policy belongs exclusively to CSP.
DarkReader.setFetchMethod(() => Promise.reject(new Error('Preview fetch disabled')));
const create = document.createElement;
// The trusted library synchronously installs its own fixed stylesheet observer
// script. Give only that synchronous call the preview nonce; mail scripts remain removed.
document.createElement = function(name, options) {
const element = create.call(this, name, options);
if (String(name).toLowerCase() === 'script') element.nonce = '${nonce}';
return element;
};
try {
DarkReader.enable({brightness:100,contrast:100,sepia:0,darkSchemeBackgroundColor:'#222225',darkSchemeTextColor:'#eeeef0'},
{ignoreImageAnalysis:['*'],disableStyleSheetsProxy:true,disableCustomElementRegistryProxy:true});
} finally { document.createElement = create; }
}
function report() {
if (scheduled) return;
scheduled = true;
requestAnimationFrame(() => {
scheduled = false;
const height = Math.max(1, Math.ceil(root.getBoundingClientRect().height));
if (height !== lastHeight) {
lastHeight = height;
parent.postMessage({ type: 'syncova-preview-size', channel, height }, '*');
const height = Math.max(1, Math.ceil(Math.max(root.getBoundingClientRect().height, root.scrollHeight * (Number(root.style.zoom) || 1))));
if (height !== lastHeight || failedImages !== lastFailed) {
lastHeight = height; lastFailed = failedImages;
parent.postMessage({ type: 'syncova-preview-size', channel, height, failedImages }, '*');
}
});
}
@ -36,16 +63,28 @@ ${dark ? `#mail-content,#mail-content *:not(img){color:${foreground}!important;b
const data = event.data;
if (event.source !== parent || data?.type !== 'syncova-preview-content' ||
data.channel !== channel || typeof data.html !== 'string') return;
failedImages = 0;
if (window.DarkReader?.isEnabled()) DarkReader.disable();
root.innerHTML = data.html;
root.querySelectorAll('img').forEach(image => {
image.referrerPolicy = 'no-referrer';
image.addEventListener('load', report);
image.addEventListener('error', report);
image.addEventListener('load', () => { fit(); report(); });
const unavailable = () => {
if (image.classList.contains('syncova-image-unavailable')) return;
if (image.hasAttribute('width') && image.hasAttribute('height') && image.width <= 2 && image.height <= 2 && !image.alt) {image.style.display='none';return;}
failedImages++;
image.classList.add('syncova-image-unavailable');
image.alt ||= 'Bild nicht verfügbar';
report();
};
image.addEventListener('error', unavailable);
if (!image.getAttribute('src') && !image.getAttribute('srcset')) unavailable();
else if (image.complete && !image.naturalWidth) unavailable();
});
report();
darken(); fit(); report();
});
new ResizeObserver(report).observe(root);
addEventListener('resize', report);
addEventListener('resize', () => {if (width !== document.documentElement.clientWidth) fit(); report();});
})();
</script></body></html>`
return { html, csp }

171
server/mail-css.js Normal file
View File

@ -0,0 +1,171 @@
import postcss from 'postcss'
import selectorParser from 'postcss-selector-parser'
import valueParser from 'postcss-value-parser'
const properties = new Set(
`color background background-color background-image background-position background-size background-repeat
font font-family font-size font-style font-weight font-variant font-stretch line-height letter-spacing word-spacing
text-align text-decoration text-decoration-line text-decoration-color text-indent text-transform text-overflow text-size-adjust -webkit-text-size-adjust
white-space word-break overflow-wrap word-wrap vertical-align direction unicode-bidi
width height min-width min-height max-width max-height margin margin-top margin-right margin-bottom margin-left
padding padding-top padding-right padding-bottom padding-left box-sizing
border border-top border-right border-bottom border-left border-width border-style border-color border-radius
border-top-width border-right-width border-bottom-width border-left-width border-top-style border-right-style border-bottom-style border-left-style
border-top-color border-right-color border-bottom-color border-left-color border-collapse border-spacing
display visibility opacity overflow overflow-x overflow-y float clear position top right bottom left z-index
list-style list-style-type list-style-position list-style-image table-layout caption-side empty-cells
object-fit object-position flex flex-basis flex-direction flex-wrap flex-grow flex-shrink align-items align-self align-content justify-content
gap row-gap column-gap grid-template-columns grid-template-rows grid-column grid-row order`.split(
/\s+/,
),
)
const functions = new Set([
'rgb',
'rgba',
'hsl',
'hsla',
'calc',
'min',
'max',
'clamp',
'var',
'linear-gradient',
'radial-gradient',
'repeating-linear-gradient',
'repeating-radial-gradient',
])
const unescapeCss = (value) =>
value.replace(/\\([\da-f]{1,6}\s?|[^\r\n])/gi, (_, code) =>
/^[\da-f]/i.test(code)
? String.fromCodePoint(Math.min(parseInt(code, 16) || 0xfffd, 0x10ffff))
: code,
)
const safeText = (value) => !/[<>\x00-\x08\x0b\x0c\x0e-\x1f]/.test(value)
function declaration(node, resolveImage) {
const property = unescapeCss(node.prop).toLowerCase()
if (!properties.has(property) && !/^--[a-z\d-]{1,64}$/.test(property)) return ''
if (
property === 'position' &&
!/^(static|relative|absolute|inherit|initial)$/i.test(node.value.trim())
)
return ''
const tree = valueParser(node.value)
let valid = true
tree.walk((part) => {
if (part.type === 'comment') {
part.value = ''
return
}
if (part.type === 'function') {
const name = unescapeCss(part.value).toLowerCase()
if (name === 'url') {
const raw =
part.nodes.length === 1 && part.nodes[0].type === 'string'
? part.nodes[0].value
: valueParser.stringify(part.nodes)
const url = resolveImage(unescapeCss(raw).trim())
if (!url) valid = false
else {
part.value = 'url'
part.nodes = [
{
type: 'string',
quote: '"',
value: url.replaceAll('"', '%22').replaceAll('\\', '%5C'),
},
]
}
return false
}
if (!functions.has(name)) valid = false
}
if (part.type === 'word' || part.type === 'string') {
const decoded = unescapeCss(part.value)
if (
!safeText(decoded) ||
/(?:expression|javascript|vbscript|behavior|binding)\s*[:(]/i.test(decoded)
)
valid = false
}
})
const value = tree.toString().trim()
if (!valid || !safeText(value) || value.length > 200000) return ''
return `${property}:${value}${node.important ? '!important' : ''};`
}
export function inlineMailCss(css = '', resolveImage = () => null) {
if (css.length > 200000) return ''
try {
const rule = postcss.parse(`a{${css}}`, { from: undefined }).first
return (rule?.nodes || [])
.filter((node) => node.type === 'decl')
.map((node) => declaration(node, resolveImage))
.join('')
} catch {
return ''
}
}
function scopeSelectors(selector) {
return selectorParser((root) => {
root.each((item) => {
// HTML/body styles refer to the mail's wrappers, never the preview's own document.
item.walkTags((tag) => {
if (tag.value.toLowerCase() === 'html' || tag.value.toLowerCase() === 'body')
tag.replaceWith(
selectorParser.attribute({ attribute: `data-mail-${tag.value.toLowerCase()}` }),
)
})
item.walkPseudos((pseudo) => {
if (pseudo.value === ':root')
pseudo.replaceWith(selectorParser.attribute({ attribute: 'data-mail-html' }))
})
item.walkIds((id) => {
id.value = 'email-' + id.value
})
if (item.toString().length > 2000 || /[<>\x00-\x1f]/.test(item.toString())) {
item.remove()
return
}
item.prepend(selectorParser.combinator({ value: ' ' }))
item.prepend(selectorParser.id({ value: 'mail-content' }))
})
}).processSync(selector)
}
export function stylesheetMailCss(css = '', resolveImage = () => null) {
if (css.length > 500000) return ''
try {
const ast = postcss.parse(css, { from: undefined })
const render = (nodes, depth = 0) =>
depth > 5
? ''
: nodes
.map((node) => {
if (node.type === 'atrule') {
// Remote stylesheets, fonts, keyframes and browser-specific executable rules are discarded.
if (
node.name.toLowerCase() !== 'media' ||
!safeText(node.params) ||
/[;{}@\\]/.test(node.params) ||
node.params.length > 1000
)
return ''
const content = render(node.nodes || [], depth + 1)
return content ? `@media ${node.params}{${content}}` : ''
}
if (node.type !== 'rule') return ''
const selector = scopeSelectors(node.selector)
const content = (node.nodes || [])
.filter((child) => child.type === 'decl')
.map((child) => declaration(child, resolveImage))
.join('')
return selector && content ? `${selector}{${content}}` : ''
})
.join('')
return render(ast.nodes)
} catch {
return ''
}
}

167
server/mail-html.js Normal file
View File

@ -0,0 +1,167 @@
import sanitizeHtml from 'sanitize-html'
import { parseDocument } from 'htmlparser2'
import render from 'dom-serializer'
import parseSrcset from 'parse-srcset'
import { inlineMailCss, stylesheetMailCss } from './mail-css.js'
const tags =
`a abbr acronym address b bdi bdo big blockquote br caption center cite code col colgroup dd del dfn div dl dt em
font h1 h2 h3 h4 h5 h6 hr i img ins kbd li mark nobr ol p pre q s samp small span strike strong sub sup
table tbody td tfoot th thead tr tt u ul var wbr`.split(/\s+/)
const globalAttrs = [
'style',
'class',
'id',
'title',
'dir',
'lang',
'align',
'valign',
'bgcolor',
'background',
'width',
'height',
'role',
'aria-label',
]
const attributes = {
'*': globalAttrs,
a: ['href', 'name', 'target', 'rel'],
img: ['src', 'srcset', 'sizes', 'alt', 'border', 'hspace', 'vspace', 'loading', 'referrerpolicy'],
td: ['colspan', 'rowspan', 'nowrap'],
th: ['colspan', 'rowspan', 'nowrap', 'scope'],
table: ['cellpadding', 'cellspacing', 'border', 'summary'],
col: ['span'],
colgroup: ['span'],
ol: ['start', 'type', 'reversed'],
li: ['value', 'type'],
font: ['face', 'color', 'size'],
hr: ['size', 'noshade'],
}
export function safeImageUrl(value) {
const url = String(value || '').trim()
if (/^data:image\/(png|jpeg|gif|webp);base64,[a-z\d+/=]+$/i.test(url)) return url
if (!/^(https?:\/\/|\/\/)/i.test(url)) return null
try {
const parsed = new URL(url.startsWith('//') ? 'https:' + url : url.replace(/^http:/i, 'https:'))
if (parsed.protocol !== 'https:' || parsed.username || parsed.password) return null
return parsed.href
} catch {
return null
}
}
export function mailHtml(html, { resolveImage = safeImageUrl } = {}) {
const doc = parseDocument(html, { decodeEntities: true })
let body, htmlNode
const sheets = []
function walk(nodes) {
const pending = [...nodes].reverse().map((node) => ({ node, depth: 0 }))
while (pending.length) {
const { node, depth } = pending.pop()
if (depth > 100) {
node.children = []
continue
}
if (node.name === 'style') {
sheets.push(
stylesheetMailCss(
(node.children || []).map((child) => child.data || '').join(''),
resolveImage,
),
)
node.children = []
}
if (node.name === 'body') body = node
if (node.name === 'html') htmlNode = node
for (const child of [...(node.children || [])].reverse())
pending.push({ node: child, depth: depth + 1 })
}
}
walk(doc.children)
const transform = (tag, attrs) => {
if (attrs.id) attrs.id = 'email-' + attrs.id
if (attrs.class)
attrs.class = attrs.class
.split(/\s+/)
.filter((name) => !name.startsWith('syncova-') && !name.startsWith('darkreader'))
.join(' ')
if (attrs.style) attrs.style = inlineMailCss(attrs.style, resolveImage)
if (attrs.background) {
const image = resolveImage(attrs.background)
if (image) attrs.background = image
else delete attrs.background
}
if (tag === 'img') {
const src = resolveImage(attrs.src)
if (src) attrs.src = src
else {
delete attrs.src
attrs.alt ||= 'Bild nicht verfügbar'
}
if (attrs.srcset) {
try {
attrs.srcset = parseSrcset(attrs.srcset)
.map((item) => {
const url = resolveImage(item.url)
return url ? url + (item.w ? ` ${item.w}w` : item.d ? ` ${item.d}x` : '') : ''
})
.filter(Boolean)
.join(', ')
} catch {
delete attrs.srcset
}
}
attrs.referrerpolicy = 'no-referrer'
attrs.loading = 'eager'
}
if (tag === 'a') {
if (attrs.href?.startsWith('//')) attrs.href = 'https:' + attrs.href
attrs.target = '_blank'
attrs.rel = 'noopener noreferrer'
}
if (tag === 'o:p') tag = 'span'
return { tagName: tag, attribs: attrs }
}
const options = {
allowedTags: tags,
allowedAttributes: attributes,
allowProtocolRelative: false,
allowedSchemes: ['https', 'http', 'mailto', 'tel'],
allowedSchemesByTag: { img: ['https', 'data'] },
parseStyleAttributes: false,
transformTags: { '*': transform },
nonTextTags: [
'style',
'script',
'textarea',
'option',
'noscript',
'title',
'iframe',
'object',
'template',
],
enforceHtmlBoundary: false,
}
const clean = sanitizeHtml(
render(body?.children || doc.children.filter((node) => !['head'].includes(node.name))),
options,
)
const wrapper = (node, kind, content) => {
const attrs = { ...(node?.attribs || {}) }
const serialized = Object.entries(attrs)
.map(
([name, value]) =>
` ${name}="${String(value).replaceAll('&', '&amp;').replaceAll('"', '&quot;').replaceAll('<', '&lt;')}"`,
)
.join('')
const shell = sanitizeHtml(`<div${serialized}></div>`, options)
return shell.replace(/^<div/, `<div data-mail-${kind}`).replace('</div>', content + '</div>')
}
const styled = sheets
.filter(Boolean)
.map((css) => `<style>${css}</style>`)
.join('')
return styled + wrapper(htmlNode, 'html', wrapper(body, 'body', clean))
}

View File

@ -1,5 +1,5 @@
import sanitizeHtml from 'sanitize-html'
import { safeHtml, escapeHtml } from './content.js'
import { escapeHtml } from './content.js'
import { mailHtml, safeImageUrl } from './mail-html.js'
function raster(mime, content) {
if (mime === 'image/png')
@ -21,49 +21,56 @@ export function messageView(s, m) {
original?.html || s.get('SELECT html FROM message_html WHERE message_id=?', m.id)?.html
const markup = source ? Buffer.from(source, 'utf8') : null
const truncated = !!markup && markup.length > 2 * 1024 * 1024
const clean = source
? safeHtml(markup.subarray(0, 2 * 1024 * 1024).toString('utf8'), { cid: true })
: `<div style="white-space:pre-wrap">${escapeHtml(m.body).replace(/\n/g, '<br>')}</div>`
const attachments = s.all(
'SELECT a.mime,a.content,i.content_id FROM attachment_inline i JOIN attachments a ON a.id=i.attachment_id WHERE a.message_id=?',
"SELECT a.name,a.mime,a.content,i.content_id FROM attachments a LEFT JOIN attachment_inline i ON a.id=i.attachment_id WHERE a.message_id=? AND a.mime IN ('image/png','image/jpeg','image/gif','image/webp')",
m.id,
)
let bytes = 0,
blockedInline = 0,
remoteImages = 0
const html = sanitizeHtml(clean, {
allowedTags: false,
allowedAttributes: false,
allowVulnerableTags: true,
allowedSchemes: ['https', 'http', 'mailto', 'tel', 'data'],
allowedSchemesByTag: { img: ['https', 'data'] },
allowProtocolRelative: false,
transformTags: {
img: (tag, attrs) => {
if (attrs.src?.startsWith('cid:')) {
let cid = attrs.src.slice(4)
try {
cid = decodeURIComponent(cid)
} catch {}
const matching = attachments.filter((a) => a.content_id === cid)
const a = matching.length === 1 ? matching[0] : null
if (a && raster(a.mime, a.content) && bytes + a.content.length <= 20 * 1024 * 1024) {
bytes += a.content.length
attrs.src = `data:${a.mime};base64,${a.content.toString('base64')}`
} else {
delete attrs.src
attrs.alt = attrs.alt || 'Eingebettetes Bild nicht verfügbar'
blockedInline++
}
} else if (attrs.src?.startsWith('https:')) remoteImages++
return { tagName: tag, attribs: attrs }
},
a: (tag, attrs) => ({
tagName: tag,
attribs: { ...attrs, target: '_blank', rel: 'noopener noreferrer' },
}),
},
})
const cache = new Map()
const resolveImage = (value) => {
const raw = String(value || '').trim()
if (!raw) return null
if (cache.has(raw)) {
const cached = cache.get(raw)
if (cached.bytes && bytes + cached.bytes > 20 * 1024 * 1024) {
blockedInline++
return null
}
bytes += cached.bytes
return cached.url
}
let embeddedBytes = 0
let result = safeImageUrl(raw)
if (result?.startsWith('https:')) remoteImages++
if (!result && !/^(https?:|\/\/|data:)/i.test(raw)) {
let name = raw.replace(/^cid:/i, '').replace(/^<|>$/g, '')
try {
name = decodeURIComponent(name)
} catch {}
name = name.replace(/^<|>$/g, '')
if (!/^cid:/i.test(raw)) name = name.replace(/^\.\//, '')
const matching = attachments.filter((a) =>
/^cid:/i.test(raw) ? a.content_id === name : a.name === name,
)
const image = matching.length === 1 ? matching[0] : null
if (
image &&
raster(image.mime, image.content) &&
bytes + image.content.length <= 20 * 1024 * 1024
) {
bytes += image.content.length
embeddedBytes = image.content.length
result = `data:${image.mime};base64,${image.content.toString('base64')}`
} else blockedInline++
}
cache.set(raw, { url: result, bytes: embeddedBytes })
return result
}
const html = source
? mailHtml(markup.subarray(0, 2 * 1024 * 1024).toString('utf8'), { resolveImage })
: `<div style="white-space:pre-wrap">${escapeHtml(m.body).replace(/\n/g, '<br>')}</div>`
return {
html,
text: m.body,

6
server/preview-assets.js Normal file
View File

@ -0,0 +1,6 @@
import { readFileSync } from 'node:fs'
import { createRequire } from 'node:module'
import { createHash } from 'node:crypto'
const require = createRequire(import.meta.url)
export const darkReaderSource = readFileSync(require.resolve('darkreader'), 'utf8')
export const darkReaderPath = `/mail-preview-assets/darkreader-${createHash('sha256').update(darkReaderSource).digest('hex').slice(0, 16)}.js`

View File

@ -7,17 +7,20 @@ export function HtmlPreview({
title = 'HTML-Vorschau',
remoteImages = false,
expanded = false,
originalColors = false,
}: {
html: string
title?: string
remoteImages?: boolean
expanded?: boolean
originalColors?: boolean
}) {
const [dark, setDark] = useState(() => document.documentElement.classList.contains('dark'))
const [channel] = useState(() => crypto.randomUUID())
const [height, setHeight] = useState(120)
const [failedImages, setFailedImages] = useState(0)
const frame = useRef<HTMLIFrameElement>(null)
const source = `/api/html-preview?theme=${dark ? 'dark' : 'light'}&images=${remoteImages ? '1' : '0'}#${channel}`
const source = `/api/html-preview?theme=${dark && !originalColors ? 'dark' : 'light'}&images=${remoteImages ? '1' : '0'}#${channel}`
const sendContent = () =>
frame.current?.contentWindow?.postMessage(
{ type: 'syncova-preview-content', channel, html },
@ -35,6 +38,9 @@ export function HtmlPreview({
)
return
setHeight(Math.min(50000, Math.ceil(data.height)))
setFailedImages(
Number.isSafeInteger(data.failedImages) && data.failedImages > 0 ? data.failedImages : 0,
)
}
window.addEventListener('message', resize)
return () => window.removeEventListener('message', resize)
@ -58,6 +64,12 @@ export function HtmlPreview({
style={{ height }}
onLoad={sendContent}
/>
{remoteImages && failedImages > 0 && (
<p className="html-image-status" role="status">
{failedImages} Bild(er) nicht verfügbar. Die Bildadresse kann abgelaufen oder der Zugriff
eingeschränkt sein.
</p>
)}
</div>
)
}

View File

@ -11,6 +11,7 @@ export function MessageContent({ message: m }: any) {
[open, setOpen] = useState(false),
[text, setText] = useState(false),
[remote, setRemote] = useState(true)
const [originalColors, setOriginalColors] = useState(false)
const rich = !!(m.has_html || m.html)
useEffect(() => {
if (!rich && !open) return
@ -44,8 +45,8 @@ export function MessageContent({ message: m }: any) {
)}
{view.blockedInline > 0 && (
<p className="muted">
{view.blockedInline} eingebettete Bildreferenz(en) fehlen oder haben ein nicht
unterstütztes Format.
{view.blockedInline} eingebettete Bildreferenz(en) sind nicht verfügbar, zu groß oder
haben ein nicht unterstütztes Format.
</p>
)}
{text ? (
@ -56,6 +57,7 @@ export function MessageContent({ message: m }: any) {
title={expanded ? 'Originalansicht der Nachricht' : 'Formatierte Nachricht'}
remoteImages={remote}
expanded={expanded}
originalColors={originalColors}
/>
)}
</>
@ -77,6 +79,16 @@ export function MessageContent({ message: m }: any) {
Externe Bilder anzeigen
</label>
)}
{rich && !text && (
<label className="check-label">
<input
type="checkbox"
checked={originalColors}
onChange={(e) => setOriginalColors(e.target.checked)}
/>
Originalfarben
</label>
)}
</div>
)
return (

View File

@ -2274,6 +2274,7 @@ input[type='color'] {
font-size: 12px;
}
.html-preview {
flex-shrink: 0;
border: 1px solid var(--border);
background: var(--surface);
border-radius: 3px;
@ -2288,6 +2289,13 @@ input[type='color'] {
background: var(--surface);
min-width: 0;
}
.html-image-status {
margin: 0;
padding: 8px 16px;
color: var(--muted);
font-size: 11px;
overflow-wrap: anywhere;
}
.message .html-preview {
border: 0;
border-radius: 0;

31
tests/fixtures/mail-newsletter.html vendored Normal file
View File

@ -0,0 +1,31 @@
<!doctype html>
<html><head><meta charset="utf-8">
<style>
body{margin:0;padding:0;background:#f1f3f8;color:#222;font-family:Arial,sans-serif}
.card{width:640px;max-width:640px;background:#fff;border:1px solid #dfe3eb;border-radius:8px}
.content{padding:28px 32px;font-size:15px;line-height:1.5}
.headline{font-size:26px;line-height:1.2;margin:0 0 12px;font-weight:700}
.avatar{display:block;width:64px;height:64px;border-radius:50%;margin:0 auto 12px}
.action{display:inline-block;background:#6750c9;color:#fff;border-radius:4px;padding:12px 24px;text-decoration:none;font-weight:700}
.footer{font-size:12px;line-height:1.5;color:#667085;padding:20px 32px;border-top:1px solid #e4e7ed}
.preheader{display:none!important;height:0;max-height:0;overflow:hidden;opacity:0}
@media only screen and (max-width:600px){.card{width:100%!important}.content{padding:20px!important}.headline{font-size:22px}.avatar{width:48px;height:48px}}
</style>
</head><body>
<span class="preheader">Dieser Vorschautext darf nicht sichtbar erscheinen.</span>
<table role="presentation" width="100%" cellpadding="0" cellspacing="0"><tr><td align="center" style="padding:16px 0">
<table class="card" role="presentation" width="640" align="center" cellpadding="0" cellspacing="0">
<tr><td bgcolor="#6750c9" style="padding:22px 32px;color:#fff;font-weight:700;font-size:20px">SYNCOVA · TEAM-UPDATE</td></tr>
<tr><td class="content"><h1 class="headline">Bleib mit deinem Team auf dem neuesten Stand.</h1>
<p style="margin:0 0 24px">Anna, Michael und Sarah haben neue Beiträge für dich.</p>
<table role="presentation" width="100%" cellpadding="0" cellspacing="0"><tr>
<td align="center" valign="top" width="33%"><img class="avatar" src="cid:avatar-anna" width="64" height="64" alt="Anna"><strong>Anna</strong><p style="margin:4px 0 20px;color:#667085;font-size:12px">Service</p></td>
<td align="center" valign="top" width="33%"><img class="avatar" src="cid:avatar-michael" width="64" height="64" alt="Michael"><strong>Michael</strong><p style="margin:4px 0 20px;color:#667085;font-size:12px">Technik</p></td>
<td align="center" valign="top" width="33%"><img class="avatar" src="cid:avatar-sarah" width="64" height="64" alt="Sarah"><strong>Sarah</strong><p style="margin:4px 0 20px;color:#667085;font-size:12px">Vertrieb</p></td>
</tr></table>
<div style="text-align:center;margin:8px 0"><a class="action" href="https://example.invalid/team">Neuigkeiten ansehen</a></div>
</td></tr>
<tr><td class="footer">Diese Nachricht wurde für die Layoutprüfung erstellt.<br>Syncova Demo · Beispielstraße 12 · 23800 Beispielstadt</td></tr>
</table>
</td></tr></table>
</body></html>

15
tests/fixtures/mail-outlook.html vendored Normal file
View File

@ -0,0 +1,15 @@
<html><head><style>
p.MsoNormal{margin:0cm;margin-bottom:.0001pt;font-size:11.0pt;font-family:Calibri,Arial,sans-serif;line-height:normal;color:#222}
p.signature{margin:0cm;font-size:10pt;line-height:15pt;font-family:Calibri,Arial,sans-serif}
@media screen and (max-width:480px){.contact{width:100%!important}}
</style></head><body lang="DE" style="margin:0cm;background-color:#ffffff;color:#222">
<div class="WordSection1">
<p class="MsoNormal">Hallo Anna,<o:p></o:p></p><p class="MsoNormal">&nbsp;</p>
<p class="MsoNormal">bitte prüfe folgende Vorgänge:</p><p class="MsoNormal">&nbsp;</p>
<p class="MsoNormal">VO/2026/008/180</p><p class="MsoNormal">VO/2026/008/186</p><p class="MsoNormal">VO/2026/008/232</p>
<p class="MsoNormal">&nbsp;</p><p class="MsoNormal">Vielen Dank.</p><p class="MsoNormal">&nbsp;</p>
<p class="MsoNormal">Mit freundlichen Grüßen</p><p class="MsoNormal">Im Auftrag</p><p class="MsoNormal">&nbsp;</p>
<table class="contact" width="440" cellpadding="0" cellspacing="0" role="presentation" style="border-collapse:collapse">
<tr><td width="62" valign="top"><img src="cid:avatar-anna" alt="Logo" width="48" height="48"></td>
<td valign="top"><p class="signature"><b>Anna Beispiel</b></p><p class="signature">Zentrale Dienste</p><p class="signature">Demo-Verwaltung</p><p class="signature">Beispielstraße 12 · 23800 Beispielstadt</p><p class="signature">Tel.: 01234 567-89</p><p class="signature"><a href="mailto:anna@example.invalid">anna@example.invalid</a></p></td></tr>
</table></div></body></html>

View File

@ -0,0 +1,209 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { mailHtml } from '../server/mail-html.js'
import { stylesheetMailCss, inlineMailCss } from '../server/mail-css.js'
import { safeHtml } from '../server/content.js'
import { openDb, seed, uid } from '../server/db.js'
import { Service } from '../server/service.js'
import { createApp } from '../server/app.js'
import { htmlPreviewDocument } from '../server/html-preview.js'
import { darkReaderPath } from '../server/preview-assets.js'
const fixture = (name) => readFileSync(new URL('./fixtures/' + name, import.meta.url), 'utf8')
const png =
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a3ioAAAAASUVORK5CYII='
test('Newsletter rendering preserves stylesheets, responsive rules, hidden preheaders, table geometry and source order', () => {
const clean = mailHtml(fixture('mail-newsletter.html'))
assert.match(clean, /<style>/)
assert.match(clean, /#mail-content \[data-mail-body\]/)
assert.match(clean, /\.card\{width:640px;max-width:640px;background:#fff;/)
assert.match(clean, /@media only screen and \(max-width:600px\)/)
assert.match(clean, /width:100%!important/)
assert.match(clean, /\.preheader\{display:none!important;/)
assert.match(clean, /align="center"/)
assert.match(clean, /valign="top" width="33%"/)
assert.match(clean, /cellpadding="0" cellspacing="0"/)
assert.match(clean, /bgcolor="#6750c9"/)
const cascade = mailHtml(
'<style>.x{color:red}</style><style>.x{color:blue}</style><p class="x">Text</p>',
)
assert(cascade.indexOf('color:red') < cascade.indexOf('color:blue'))
})
test('Outlook paragraph spacing, decimal point sizes, Word tags and inline signature styles survive filtering', () => {
const clean = mailHtml(fixture('mail-outlook.html'))
assert.match(clean, /margin:0cm;margin-bottom:.0001pt;font-size:11.0pt/)
assert.match(clean, /line-height:normal/)
assert.match(clean, /class="MsoNormal"/)
assert.match(clean, /<span><\/span>/)
const signature = safeHtml(
'<table width="440"><tr><td align="left" valign="top" width="300"><p style="margin:0cm;font-size:10.5pt;line-height:14pt;padding:0 12px">Anna Beispiel</p></td></tr></table>',
)
assert.match(signature, /margin:0cm;font-size:10.5pt;line-height:14pt;padding:0 12px;/)
assert.match(signature, /align="left" valign="top" width="300"/)
})
test('Embedded class/ID selectors are scoped to the email, including body selectors inside media queries', () => {
const clean = mailHtml(
'<style>html,body,#brand,.a:is(.b,.c){color:red}@media screen{body p{margin:0}}</style><p id="brand" class="a darkreader syncova-image-unavailable">Text</p>',
)
assert.match(
clean,
/#mail-content \[data-mail-html\],#mail-content \[data-mail-body\],#mail-content #email-brand/,
)
assert.match(clean, /id="email-brand" class="a"/)
assert.match(clean, /@media screen\{#mail-content \[data-mail-body\] p/)
assert(!clean.includes('class="a darkreader'))
})
test('Stylesheet and inline CSS reject executable rules, imports, fonts, unsafe URL schemes and escaped URL tricks', () => {
const payload =
'@import "https://evil.invalid/css";@font-face{font-family:x;src:url(https://evil.invalid/font)}body{color:#123;margin:0;background:url(\\6a avascript:evil());behavior:url(https://evil.invalid/x);-moz-binding:url(https://evil.invalid/x);position:fixed;width:expression(alert(1))}.ok{background-image:u\\72l(\\6a avascript:evil())}'
const clean = stylesheetMailCss(payload)
assert.match(clean, /color:#123;margin:0/)
for (const forbidden of [
'@import',
'@font-face',
'javascript',
'expression',
'behavior',
'binding',
'position:fixed',
'evil.invalid',
])
assert(!clean.includes(forbidden), forbidden)
assert.equal(
inlineMailCss('color:red;background-image:u\\72l(javascript:alert(1));-moz-binding:url(x);'),
'color:red;',
)
assert.equal(stylesheetMailCss('.broken{'), '')
assert.equal(inlineMailCss('width:10px; invalid }{'), '')
})
test('HTML active content, tracking styles outside the mail and malicious raw-text reparse payloads are removed', () => {
const input =
'<html><head><base href="https://evil.invalid"><meta http-equiv="refresh" content="0;url=https://evil.invalid"><link rel="stylesheet" href="https://evil.invalid/a.css"></head><body onload="evil()"><script>evil()</script><iframe srcdoc="<script>evil()</script>"></iframe><object data="x"></object><svg onload="evil()"></svg><a href="javascript:evil()" onclick="evil()">Link</a><img src="data:image/svg+xml;base64,AAAA" onerror="evil()"><textarea><img src=x onerror=evil()></textarea><p style="background:url(file:///etc/passwd)">Text</p></body></html>'
const clean = mailHtml(input)
for (const forbidden of [
'<script',
'<iframe',
'<object',
'<svg',
'<base',
'<meta',
'<link',
'<textarea',
'onload',
'onclick',
'onerror',
'javascript:',
'file:///',
])
assert(!clean.includes(forbidden), forbidden)
assert.match(clean, />Text<\/p>/)
assert(!clean.includes('src="data:'))
})
test('Image URL normalization covers protocol-relative, HTTP, srcset and CSS backgrounds without introducing relative requests', () => {
const clean = mailHtml(
'<style>.banner{background-image:url(//images.example.org/bg.png)}</style><table background="//images.example.org/table.png"><tr><td>Test</td></tr></table><img src="http://images.example.org/a.png" srcset="//images.example.org/b.png 2x, javascript:evil() 3x"><img src="/api/private"><p style="background:url(http://images.example.org/c.png)">Bild</p>',
)
for (const asset of ['bg.png', 'table.png', 'a.png', 'b.png', 'c.png'])
assert(clean.includes('https://images.example.org/' + asset))
assert(!clean.includes('javascript:'))
assert(!clean.includes('/api/private'))
assert.match(clean, /referrerpolicy="no-referrer"/)
})
test('CID images, filename images, srcset and CSS backgrounds resolve only within the owning message', () => {
const db = openDb(':memory:')
seed(db)
const s = new Service(db),
admin = s.user('admin')
try {
const ticket = s.ingest({
messageId: `<${uid()}@example.org>`,
from: 'anna@example.org',
to: ['support@syncova.local'],
body: 'HTML',
html: '<style>.logo{background-image:url(cid:logo)}</style><img src="cid:logo"><img src="./logo.png"><img src="cid:%3Clogo%3E"><img srcset="cid:logo 2x"><img src="cid:foreign">',
attachments: [{ name: 'logo.png', mime: 'image/png', content: png, contentId: 'logo' }],
}).ticket_id
const m = s.detail(admin, ticket).messages[0],
view = s.viewMessage(admin, m.id)
assert.equal(view.blockedInline, 1)
assert(view.html.includes('background-image:url("data:image/png;base64,'))
assert.match(view.html, /srcset="data:image\/png;base64,[^"]+ 2x"/)
assert(!view.html.includes('cid:'))
assert(!view.html.includes('src="logo.png"'))
assert(view.html.includes('Bild nicht verfügbar'))
} finally {
db.close()
}
})
test('Preview uses nonce-scoped Dark Reader without blanket color overrides or same-origin sandbox access', () => {
const dark = htmlPreviewDocument({ dark: true, remoteImages: false })
assert(dark.html.includes(darkReaderPath))
assert(dark.html.includes('ignoreImageAnalysis'))
assert(dark.html.includes('Preview fetch disabled'))
assert(!dark.html.includes('background-color:transparent!important'))
assert(!dark.csp.includes('allow-same-origin'))
assert(!dark.csp.includes("script-src 'unsafe-inline'"))
assert(!dark.csp.includes('https:'))
assert(!htmlPreviewDocument({ dark: false }).html.includes(`src="${darkReaderPath}"`))
})
test('Repeated CID references cannot expand an email beyond the inline image budget', () => {
const db = openDb(':memory:')
seed(db)
const s = new Service(db),
admin = s.user('admin')
try {
const image = Buffer.alloc(2 * 1024 * 1024)
Buffer.from(png, 'base64').copy(image)
const id = s.ingest({
messageId: `<${uid()}@example.org>`,
from: 'anna@example.org',
to: ['support@syncova.local'],
body: 'Bilder',
html: '<img src="cid:large">'.repeat(12),
attachments: [
{
name: 'large.png',
mime: 'image/png',
content: image.toString('base64'),
contentId: 'large',
},
],
}).ticket_id
const view = s.viewMessage(admin, s.detail(admin, id).messages[0].id)
assert.equal(view.blockedInline, 2)
assert.equal((view.html.match(/src="data:image/g) || []).length, 10)
assert(Buffer.byteLength(view.html) < 29 * 1024 * 1024)
} finally {
db.close()
}
})
test('Dark Reader is a public immutable vendor asset while the actual preview document remains authenticated', async () => {
const db = openDb(':memory:')
seed(db)
const { app } = createApp(db),
server = app.listen(0, '127.0.0.1')
await new Promise((resolve) => server.once('listening', resolve))
const base = `http://127.0.0.1:${server.address().port}`
try {
const asset = await fetch(base + darkReaderPath)
assert.equal(asset.status, 200)
assert.match(asset.headers.get('content-type'), /javascript/)
assert.match(asset.headers.get('cache-control'), /immutable/)
assert((await asset.text()).includes('DarkReader'))
assert.equal((await fetch(base + '/api/html-preview')).status, 401)
} finally {
server.closeAllConnections()
await new Promise((resolve) => server.close(resolve))
db.close()
}
})