Skip to content

Email for professionals and teams

Preserve email styles with isolated rendering and remote content controls

nailao2b918b8285e3
diff --git a/package-lock.json b/package-lock.json
index 38f4daa..bca59ac 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "mailflare",
- "version": "0.4.0",
+ "version": "0.5.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "mailflare",
- "version": "0.4.0",
+ "version": "0.5.0",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@ai-sdk/openai-compatible": "^3.0.55",
@@ -27,13 +27,17 @@
"better-sqlite3": "^13.0.3",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
+ "css-tree": "^3.2.1",
"dayjs": "^1.11.20",
+ "dompurify": "^3.4.16",
"drizzle-orm": "^0.45.2",
"lucide-react": "^1.16.0",
"mimetext": "^3.0.28",
"nanoid": "^5.1.16",
"next": "16.3.3",
"nodemailer": "^10.0.9",
+ "parse-srcset": "^1.0.2",
+ "parse5": "^8.0.1",
"postal-mime": "^2.7.4",
"qrcode": "^1.5.4",
"react": "^19.2.6",
@@ -56,6 +60,7 @@
"@tailwindcss/postcss": "^4",
"@types/bcryptjs": "^2.4.6",
"@types/better-sqlite3": "^9.6.0",
+ "@types/css-tree": "^3.2.0",
"@types/node": "^20.19.41",
"@types/nodemailer": "^8.0.1",
"@types/qrcode": "^1.5.6",
@@ -68,6 +73,7 @@
"esbuild": "^0.28.2",
"eslint": "^9",
"eslint-config-next": "16.3.3",
+ "jsdom": "^30.1.2",
"tailwindcss": "^4",
"tsx": "^4.23.13",
"typescript": "^5.7.4",
@@ -190,6 +196,59 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/@asamuzakjp/css-color": {
+ "version": "7.1.3",
+ "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-7.1.3.tgz",
+ "integrity": "sha512-1t1U8Cm3RBl9vh3RAZhjkPaduzLSvQJRToRrxpGR/eDRW99mOREleuu+mWfiFa795bUzjwht7NgphCKTs2ianQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@csstools/css-calc": "^3.4.2",
+ "@csstools/css-color-parser": "^4.2.5",
+ "@csstools/css-parser-algorithms": "^4.0.2",
+ "@csstools/css-tokenizer": "^4.0.2",
+ "lru-cache": "^11.5.3"
+ },
+ "engines": {
+ "node": "^22.22.2 || ^24.15.0 || >=26.0.0"
+ }
+ },
+ "node_modules/@asamuzakjp/css-color/node_modules/lru-cache": {
+ "version": "11.5.3",
+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz",
+ "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==",
+ "dev": true,
+ "license": "BlueOak-1.0.0",
+ "engines": {
+ "node": "20 || >=22"
+ }
+ },
+ "node_modules/@asamuzakjp/dom-selector": {
+ "version": "9.2.4",
+ "resolved": "https://registry.npmjs.org/@asamuzakjp/dom-selector/-/dom-selector-9.2.4.tgz",
+ "integrity": "sha512-YnVzxDxLaqL0t7Q4wfcgHZjg55Wm6y5EaO7Bhu3q9J7wq/8iw3PhsnWiOQhYekx4VexnbkgWpTT6n+QIV7kczw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "bidi-js": "^1.1.0",
+ "css-tree": "^3.2.1",
+ "is-potential-custom-element-name": "^1.0.1",
+ "lru-cache": "^11.5.3"
+ },
+ "engines": {
+ "node": "^22.22.2 || ^24.15.0 || >=26.0.0"
+ }
+ },
+ "node_modules/@asamuzakjp/dom-selector/node_modules/lru-cache": {
+ "version": "11.5.3",
+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz",
+ "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==",
+ "dev": true,
+ "license": "BlueOak-1.0.0",
+ "engines": {
+ "node": "20 || >=22"
+ }
+ },
"node_modules/@babel/code-frame": {
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz",
@@ -447,6 +506,19 @@
"node": ">=6.9.0"
}
},
+ "node_modules/@bramus/specificity": {
+ "version": "2.4.3",
+ "resolved": "https://registry.npmjs.org/@bramus/specificity/-/specificity-2.4.3.tgz",
+ "integrity": "sha512-0GEz8qJWokkUVYQYRukmkSHIFNoBH8QTreeHrAFbvz1XFYc3Y+puhMs8PQ5x8GNugiC2l5jvDBXKLbBIByeSBw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "css-tree": "^3.2.1"
+ },
+ "bin": {
+ "specificity": "bin/cli.js"
+ }
+ },
"node_modules/@cloudflare/kv-asset-handler": {
"version": "0.5.0",
"resolved": "https://registry.npmjs.org/@cloudflare/kv-asset-handler/-/kv-asset-handler-0.5.0.tgz",
@@ -615,6 +687,146 @@
"@jridgewell/sourcemap-codec": "^1.4.10"
}
},
+ "node_modules/@csstools/color-helpers": {
+ "version": "6.1.2",
+ "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-6.1.2.tgz",
+ "integrity": "sha512-grhRy3OKmniaAEKXMjua5z/EODX0MSqBGjunw8+j/3HQjOnahs2AGhvEOIYVUWcU6ScApbhLhVrQTX8XqrMrow==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/csstools"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/csstools"
+ }
+ ],
+ "license": "MIT-0",
+ "engines": {
+ "node": ">=20.19.0"
+ }
+ },
+ "node_modules/@csstools/css-calc": {
+ "version": "3.4.3",
+ "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-3.4.3.tgz",
+ "integrity": "sha512-iex20d8CHVkyvg6B7UKV7uHnI2Bqo9g+EFfT9E0y+GvTvhZ/DwONJ+9aKb1dlqm0ZiGsL5RXjp0fCoJYnkeDjA==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/csstools"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/csstools"
+ }
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=20.19.0"
+ },
+ "peerDependencies": {
+ "@csstools/css-parser-algorithms": "^4.0.2",
+ "@csstools/css-tokenizer": "^4.0.2"
+ }
+ },
+ "node_modules/@csstools/css-color-parser": {
+ "version": "4.2.6",
+ "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-4.2.6.tgz",
+ "integrity": "sha512-iiPQ3iRWwnJkeEn6RIu6SJPr7hYrLz6XZ9s/QZl+2/LI5KQVjpl2fdmDSZKuD4xP6GMmMPgHFFXg6k1Wkz0Trg==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/csstools"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/csstools"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "@csstools/color-helpers": "^6.1.2",
+ "@csstools/css-calc": "^3.4.3"
+ },
+ "engines": {
+ "node": ">=20.19.0"
+ },
+ "peerDependencies": {
+ "@csstools/css-parser-algorithms": "^4.0.2",
+ "@csstools/css-tokenizer": "^4.0.2"
+ }
+ },
+ "node_modules/@csstools/css-parser-algorithms": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-4.0.2.tgz",
+ "integrity": "sha512-40cSKyMvK+tq4qz6Awrlye2WGuOKt3FwPgtGg6KTfbHOWNw+Rk1rzbAtZnZ6IBhsY491HLRnDXwoyBAijmmILA==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/csstools"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/csstools"
+ }
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=20.19.0"
+ },
+ "peerDependencies": {
+ "@csstools/css-tokenizer": "^4.0.2"
+ }
+ },
+ "node_modules/@csstools/css-syntax-patches-for-csstree": {
+ "version": "1.1.15",
+ "resolved": "https://registry.npmjs.org/@csstools/css-syntax-patches-for-csstree/-/css-syntax-patches-for-csstree-1.1.15.tgz",
+ "integrity": "sha512-J0u7HkVl2nzSlhsiTOp4AmwcUQ3D+mGEEKfBy/7To5/y7F2OHwyLrXfrhR0SMgr4p5Lo+eaMVSeai24zUcBIxA==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/csstools"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/csstools"
+ }
+ ],
+ "license": "MIT-0",
+ "peerDependencies": {
+ "css-tree": "^3.2.1"
+ },
+ "peerDependenciesMeta": {
+ "css-tree": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@csstools/css-tokenizer": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-4.0.2.tgz",
+ "integrity": "sha512-OoKoR0f76dCY666JlcbhmVTs2drYj1GUXZTYTcbUgJjh9Nv41aFfZ21bPQTERm5+L5cBDo466NltB2lplS5GBw==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/csstools"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/csstools"
+ }
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=20.19.0"
+ }
+ },
"node_modules/@drizzle-team/brocli": {
"version": "0.10.2",
"resolved": "https://registry.npmjs.org/@drizzle-team/brocli/-/brocli-0.10.2.tgz",
@@ -1719,6 +1931,24 @@
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
}
},
+ "node_modules/@exodus/bytes": {
+ "version": "1.16.0",
+ "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.16.0.tgz",
+ "integrity": "sha512-IcpW84uEn3N7ETtNZMlxKhfl6Pec8rUNGOTBtWbK1FKhJxIFAptZyVrvVRVBimAJxJCgc3PxepxkdWWG4DVzfA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"
+ },
+ "peerDependencies": {
+ "@noble/hashes": "^1.8.0 || ^2.0.0"
+ },
+ "peerDependenciesMeta": {
+ "@noble/hashes": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@floating-ui/core": {
"version": "1.7.5",
"license": "MIT",
@@ -4482,6 +4712,13 @@
"@types/node": "*"
}
},
+ "node_modules/@types/css-tree": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmjs.org/@types/css-tree/-/css-tree-3.2.0.tgz",
+ "integrity": "sha512-J5KXmk6BFIepOT7280FdFyNs4c5fh0Uee0otjKEvzchrRs38Ii9qminqc4ds0L19X8Zd/rT+brR9jkBthygjWw==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/@types/debug": {
"version": "4.1.13",
"resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.13.tgz",
@@ -4596,6 +4833,13 @@
"@types/nodemailer": "*"
}
},
+ "node_modules/@types/trusted-types": {
+ "version": "2.0.7",
+ "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",
+ "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",
+ "license": "MIT",
+ "optional": true
+ },
"node_modules/@types/unist": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz",
@@ -5980,6 +6224,16 @@
"node": ">=22"
}
},
+ "node_modules/bidi-js": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.1.0.tgz",
+ "integrity": "sha512-fX1Onk0tdVPC7obPWB5EbJ1z7NVhLq4m2xZLq2YXBkxzMXIGRpNMU88n0EPgWseKl12J7zXs7qrDxPK4sRs2fg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "require-from-string": "^2.0.2"
+ }
+ },
"node_modules/blake3-wasm": {
"version": "2.1.5",
"resolved": "https://registry.npmjs.org/blake3-wasm/-/blake3-wasm-2.1.5.tgz",
@@ -6388,6 +6642,19 @@
"postcss-value-parser": "^4.0.2"
}
},
+ "node_modules/css-tree": {
+ "version": "3.2.1",
+ "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-3.2.1.tgz",
+ "integrity": "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==",
+ "license": "MIT",
+ "dependencies": {
+ "mdn-data": "2.27.1",
+ "source-map-js": "^1.2.1"
+ },
+ "engines": {
+ "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0"
+ }
+ },
"node_modules/csstype": {
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
@@ -6401,6 +6668,20 @@
"dev": true,
"license": "BSD-2-Clause"
},
+ "node_modules/data-urls": {
+ "version": "8.0.0",
+ "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-8.0.0.tgz",
+ "integrity": "sha512-JQUCCK+/CAGbGGx618PlFZMXH81Jtj7t73CHv9dd/zVWvxgGT2zLFRjnKb+Ng46GIwcy+f7f88qd4duqllK+WQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "whatwg-mimetype": "^5.0.0",
+ "whatwg-url": "^17.1.2"
+ },
+ "engines": {
+ "node": "^22.14.0 || >=24.0.0"
+ }
+ },
"node_modules/data-view-buffer": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/data-view-buffer/-/data-view-buffer-1.0.2.tgz",
@@ -6485,6 +6766,13 @@
"node": ">=0.10.0"
}
},
+ "node_modules/decimal.js": {
+ "version": "10.6.0",
+ "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz",
+ "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/decode-named-character-reference": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/decode-named-character-reference/-/decode-named-character-reference-1.3.0.tgz",
@@ -6597,6 +6885,15 @@
"node": ">=0.10.0"
}
},
+ "node_modules/dompurify": {
+ "version": "3.4.16",
+ "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.16.tgz",
+ "integrity": "sha512-sqo+pNp3qRhCIpbgRi1y8Tgk27Bo2Ry7w0dC1NBeNTdZChWjz9Xb/KOoZbRP/R6pQZ80Qw8YhXw13hWWBbMRnQ==",
+ "license": "(MPL-2.0 OR Apache-2.0)",
+ "optionalDependencies": {
+ "@types/trusted-types": "^2.0.7"
+ }
+ },
"node_modules/drizzle-kit": {
"version": "0.31.10",
"resolved": "https://registry.npmjs.org/drizzle-kit/-/drizzle-kit-0.31.10.tgz",
@@ -7270,6 +7567,18 @@
"node": ">=10.13.0"
}
},
+ "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/error-stack-parser-es": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/error-stack-parser-es/-/error-stack-parser-es-1.0.5.tgz",
@@ -8593,6 +8902,19 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/html-encoding-sniffer": {
+ "version": "7.0.0",
+ "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-7.0.0.tgz",
+ "integrity": "sha512-UikN5yr7xsCDAq87Or5or0PAlD3HJJOKVzM05az588WnpDJ4Ux7a2A53Qi6gofGg2/EtvF/H4hCi/TXfCW4Y6w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@exodus/bytes": "^1.15.1"
+ },
+ "engines": {
+ "node": "^22.13.0 || >=24.0.0"
+ }
+ },
"node_modules/html-url-attributes": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/html-url-attributes/-/html-url-attributes-3.0.1.tgz",
@@ -9003,6 +9325,13 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/is-potential-custom-element-name": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz",
+ "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/is-regex": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.2.1.tgz",
@@ -9244,6 +9573,66 @@
"js-yaml": "bin/js-yaml.js"
}
},
+ "node_modules/jsdom": {
+ "version": "30.1.2",
+ "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-30.1.2.tgz",
+ "integrity": "sha512-0FFE/jE1rppmVfUrJUgxqXjcwolZYIGtAgj1pTussMhNZxIxi7W/PvfWaMNroGi2B36X1IKHbexpZ9DhkoOPiQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@asamuzakjp/css-color": "^7.1.3",
+ "@asamuzakjp/dom-selector": "^9.2.4",
+ "@bramus/specificity": "^2.4.2",
+ "@csstools/css-syntax-patches-for-csstree": "^1.1.15",
+ "@exodus/bytes": "^1.16.0",
+ "css-tree": "^3.2.1",
+ "data-urls": "^8.0.0",
+ "decimal.js": "^10.6.0",
+ "html-encoding-sniffer": "^7.0.0",
+ "is-potential-custom-element-name": "^1.0.1",
+ "lru-cache": "^11.5.3",
+ "parse5": "^8.0.1",
+ "saxes": "^6.0.0",
+ "tough-cookie": "^6.0.2",
+ "undici": "^8.11.2",
+ "w3c-xmlserializer": "^6.0.0",
+ "webidl-conversions": "^8.0.1",
+ "whatwg-mimetype": "^5.0.0",
+ "whatwg-url": "^17.2.0",
+ "xml-name-validator": "^5.0.0"
+ },
+ "engines": {
+ "node": "^22.22.2 || ^24.15.0 || >=26.0.0"
+ },
+ "peerDependencies": {
+ "canvas": "^3.2.3"
+ },
+ "peerDependenciesMeta": {
+ "canvas": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/jsdom/node_modules/lru-cache": {
+ "version": "11.5.3",
+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz",
+ "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==",
+ "dev": true,
+ "license": "BlueOak-1.0.0",
+ "engines": {
+ "node": "20 || >=22"
+ }
+ },
+ "node_modules/jsdom/node_modules/undici": {
+ "version": "8.11.2",
+ "resolved": "https://registry.npmjs.org/undici/-/undici-8.11.2.tgz",
+ "integrity": "sha512-u4UB2/IrKdU6lFxumHmmo1a3fCQO5tzQllRorfoRS63txhrB7xTpSn1PftwC4qEHkOaqP95fCWW4lJzwErwzhQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=22.19.0"
+ }
+ },
"node_modules/jsesc": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz",
@@ -10024,6 +10413,12 @@
"url": "https://opencollective.com/unified"
}
},
+ "node_modules/mdn-data": {
+ "version": "2.27.1",
+ "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz",
+ "integrity": "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==",
+ "license": "CC0-1.0"
+ },
"node_modules/merge-stream": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz",
@@ -11831,6 +12226,24 @@
"integrity": "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==",
"license": "MIT"
},
+ "node_modules/parse-srcset": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/parse-srcset/-/parse-srcset-1.0.2.tgz",
+ "integrity": "sha512-/2qh0lav6CmI15FzA3i/2Bzk2zCgQhGMkvhOhKNcBVQ1ldgpbfiNTVslmooUmWJcADi1f1kIeynbDRVzNlfR6Q==",
+ "license": "MIT"
+ },
+ "node_modules/parse5": {
+ "version": "8.0.1",
+ "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.0.1.tgz",
+ "integrity": "sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw==",
+ "license": "MIT",
+ "dependencies": {
+ "entities": "^8.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/inikulin/parse5?sponsor=1"
+ }
+ },
"node_modules/path-exists": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz",
@@ -12516,7 +12929,6 @@
"resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
"integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",
"license": "MIT",
- "peer": true,
"engines": {
"node": ">=0.10.0"
}
@@ -12736,6 +13148,19 @@
"node": ">=16"
}
},
+ "node_modules/saxes": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz",
+ "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "xmlchars": "^2.2.0"
+ },
+ "engines": {
+ "node": ">=v12.22.7"
+ }
+ },
"node_modules/scheduler": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz",
@@ -13432,6 +13857,26 @@
"url": "https://github.com/sponsors/SuperchupuDev"
}
},
+ "node_modules/tldts": {
+ "version": "7.4.16",
+ "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.4.16.tgz",
+ "integrity": "sha512-QwBER5KMR86IIjpIiO7H/Z3IMJPsZ1A6RKPAqzTTgOyUQUSt9FdnKcqhTaJmkY6HVrgouZHZR0ncK5QxvmnQeg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "tldts-core": "^7.4.16"
+ },
+ "bin": {
+ "tldts": "bin/cli.js"
+ }
+ },
+ "node_modules/tldts-core": {
+ "version": "7.4.16",
+ "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.4.16.tgz",
+ "integrity": "sha512-MDolfaSJtlSK5Y0A1xl3277ekubZwobpBjugknDizI9O5Rm60a1m8k4ICK+MRsCDzPygT81mp3BBf5RKDlFRfA==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/to-regex-range": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",
@@ -13444,6 +13889,32 @@
"node": ">=8.0"
}
},
+ "node_modules/tough-cookie": {
+ "version": "6.0.2",
+ "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.0.2.tgz",
+ "integrity": "sha512-exgYmnmL/sJpR3upZfXG5PoatXQii55xAiXGXzY+sROLZ/Y+SLcp9PgJNI9Vz37HpQ74WvDcLT8eqm+kV3FzrA==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "tldts": "^7.0.5"
+ },
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/tr46": {
+ "version": "7.0.0",
+ "resolved": "https://registry.npmjs.org/tr46/-/tr46-7.0.0.tgz",
+ "integrity": "sha512-BcDSDW+SIGWVOns1Zm6Yg91q9AEj7eaID0QDY9oIqJD1A8dscNwMcl9Sms2DeuWCNov1X0/oXanHGYQBSLwZsg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "punycode": "^2.3.1"
+ },
+ "engines": {
+ "node": "^22.14.0 || >=24.0.0"
+ }
+ },
"node_modules/trim-lines": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz",
@@ -14474,6 +14945,19 @@
}
}
},
+ "node_modules/w3c-xmlserializer": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-6.0.0.tgz",
+ "integrity": "sha512-4Nsy8K5Tr6SPDH9jhKJOHf7ChDrc1zufZTVSF7x72hwuEXBqxqk9G6cK+K2NRUtB3iELRJqjXb4JPDMBjMTl2Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "xml-name-validator": "^5.0.0"
+ },
+ "engines": {
+ "node": "^22.22.2 || ^24.15.0 || >=26.0.0"
+ }
+ },
"node_modules/watchpack": {
"version": "2.5.2",
"resolved": "https://registry.npmjs.org/watchpack/-/watchpack-2.5.2.tgz",
@@ -14493,6 +14977,16 @@
"integrity": "sha512-r4DIlprAGwJ7YM11VZp4R884m0Vmgr6EAKe3P+kO0PPj3Unqyvv59rczf6UiGcb9Z8QxZVcqKNwv/g0WNdWwsw==",
"license": "Apache-2.0"
},
+ "node_modules/webidl-conversions": {
+ "version": "8.0.1",
+ "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz",
+ "integrity": "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=20"
+ }
+ },
"node_modules/webpack": {
"version": "5.111.1",
"resolved": "https://registry.npmjs.org/webpack/-/webpack-5.111.1.tgz",
@@ -14543,6 +15037,31 @@
"node": ">=10.13.0"
}
},
+ "node_modules/whatwg-mimetype": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-5.0.0.tgz",
+ "integrity": "sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/whatwg-url": {
+ "version": "17.2.0",
+ "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-17.2.0.tgz",
+ "integrity": "sha512-IhLIHNcBrzIixC5XXsbr4DxdjajyA5vQ5RwGZMtrUp+GbtE5Nrsge9QKau7jXrC0aTXLYGV0xiW7Tb4YS2aomw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@exodus/bytes": "^1.16.0",
+ "tr46": "^7.0.0",
+ "webidl-conversions": "^8.0.1"
+ },
+ "engines": {
+ "node": "^22.14.0 || >=24.0.0"
+ }
+ },
"node_modules/which-boxed-primitive": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/which-boxed-primitive/-/which-boxed-primitive-1.1.1.tgz",
@@ -15207,6 +15726,23 @@
}
}
},
+ "node_modules/xml-name-validator": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",
+ "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/xmlchars": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz",
+ "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/yallist": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",
diff --git a/package.json b/package.json
index e97f326..c4c5547 100644
--- a/package.json
+++ b/package.json
@@ -75,13 +75,17 @@
"better-sqlite3": "^13.0.3",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
+ "css-tree": "^3.2.1",
"dayjs": "^1.11.20",
+ "dompurify": "^3.4.16",
"drizzle-orm": "^0.45.2",
"lucide-react": "^1.16.0",
"mimetext": "^3.0.28",
"nanoid": "^5.1.16",
"next": "16.3.3",
"nodemailer": "^10.0.9",
+ "parse-srcset": "^1.0.2",
+ "parse5": "^8.0.1",
"postal-mime": "^2.7.4",
"qrcode": "^1.5.4",
"react": "^19.2.6",
@@ -104,6 +108,7 @@
"@tailwindcss/postcss": "^4",
"@types/bcryptjs": "^2.4.6",
"@types/better-sqlite3": "^9.6.0",
+ "@types/css-tree": "^3.2.0",
"@types/node": "^20.19.41",
"@types/nodemailer": "^8.0.1",
"@types/qrcode": "^1.5.6",
@@ -116,6 +121,7 @@
"esbuild": "^0.28.2",
"eslint": "^9",
"eslint-config-next": "16.3.3",
+ "jsdom": "^30.1.2",
"tailwindcss": "^4",
"tsx": "^4.23.13",
"typescript": "^5.7.4",
diff --git a/src/app/(dashboard)/inbox/[messageId]/email-html-sanitizer.ts b/src/app/(dashboard)/inbox/[messageId]/email-html-sanitizer.ts
index b1de5fa..9b4b972 100644
--- a/src/app/(dashboard)/inbox/[messageId]/email-html-sanitizer.ts
+++ b/src/app/(dashboard)/inbox/[messageId]/email-html-sanitizer.ts
@@ -1,228 +1,2 @@
-import type { SanitizeEmailHtmlOptions } from "./email-html-sanitizer-types";
-
-const ALLOWED_TAGS = new Set([
- "a",
- "abbr",
- "address",
- "b",
- "blockquote",
- "br",
- "caption",
- "code",
- "col",
- "colgroup",
- "dd",
- "del",
- "div",
- "dl",
- "dt",
- "em",
- "figcaption",
- "figure",
- "h1",
- "h2",
- "h3",
- "h4",
- "h5",
- "h6",
- "hr",
- "i",
- "img",
- "ins",
- "kbd",
- "li",
- "ol",
- "p",
- "pre",
- "q",
- "s",
- "samp",
- "small",
- "span",
- "strong",
- "sub",
- "sup",
- "table",
- "tbody",
- "td",
- "tfoot",
- "th",
- "thead",
- "tr",
- "u",
- "ul",
-]);
-
-const DROP_CONTENT_TAGS = new Set([
- "base",
- "button",
- "embed",
- "form",
- "iframe",
- "input",
- "link",
- "math",
- "meta",
- "object",
- "option",
- "script",
- "select",
- "style",
- "svg",
- "textarea",
-]);
-
-const GLOBAL_ATTRIBUTES = new Set(["dir", "lang", "style", "title"]);
-const TAG_ATTRIBUTES: Record<string, Set<string>> = {
- a: new Set(["href"]),
- blockquote: new Set(["cite"]),
- col: new Set(["span", "width"]),
- img: new Set(["alt", "height", "src", "width"]),
- li: new Set(["value"]),
- ol: new Set(["start", "type"]),
- table: new Set(["border", "cellpadding", "cellspacing", "width"]),
- td: new Set(["align", "colspan", "rowspan", "valign", "width"]),
- th: new Set(["align", "colspan", "rowspan", "scope", "valign", "width"]),
-};
-
-const ALLOWED_STYLE_PROPERTIES = new Set([
- "background-color",
- "border",
- "border-bottom",
- "border-color",
- "border-left",
- "border-radius",
- "border-right",
- "border-style",
- "border-top",
- "border-width",
- "color",
- "display",
- "font-family",
- "font-size",
- "font-style",
- "font-weight",
- "height",
- "letter-spacing",
- "line-height",
- "margin",
- "margin-bottom",
- "margin-left",
- "margin-right",
- "margin-top",
- "max-width",
- "min-width",
- "padding",
- "padding-bottom",
- "padding-left",
- "padding-right",
- "padding-top",
- "text-align",
- "text-decoration",
- "text-indent",
- "text-transform",
- "vertical-align",
- "white-space",
- "width",
- "word-break",
- "word-wrap",
-]);
-const APP_FONT_FALLBACK = "var(--font-geist-sans), system-ui, sans-serif";
-
-function isSafeLinkUrl(value: string, options: SanitizeEmailHtmlOptions): boolean {
- try {
- const url = options.forOutgoing ? new URL(value) : new URL(value, window.location.origin);
- return ["http:", "https:", "mailto:", "tel:"].includes(url.protocol);
- } catch {
- return false;
- }
-}
-
-function isSafeImageUrl(value: string, options: SanitizeEmailHtmlOptions): boolean {
- if (!options.forOutgoing && value.startsWith("/api/messages/")) return true;
- if (/^data:image\/(?:gif|jpeg|png|webp);base64,/i.test(value)) return true;
- try {
- const url = options.forOutgoing ? new URL(value) : new URL(value, window.location.origin);
- return options.forOutgoing ? url.protocol === "https:" : url.protocol === "http:" || url.protocol === "https:";
- } catch {
- return false;
- }
-}
-
-function sanitizeStyle(element: HTMLElement, options: SanitizeEmailHtmlOptions): void {
- const safeDeclarations: string[] = [];
- for (const property of Array.from(element.style)) {
- if (!ALLOWED_STYLE_PROPERTIES.has(property)) continue;
- const value = element.style.getPropertyValue(property);
- if (/url\s*\(|expression\s*\(|javascript:|@import|behavior\s*:|-moz-binding/i.test(value)) continue;
- const safeValue = property === "font-family" && !options.forOutgoing
- ? `${value}, ${APP_FONT_FALLBACK}`
- : value;
- safeDeclarations.push(`${property}: ${safeValue}`);
- }
- if (safeDeclarations.length) {
- element.setAttribute("style", safeDeclarations.join("; "));
- } else {
- element.removeAttribute("style");
- }
-}
-
-function sanitizeElement(element: Element, options: SanitizeEmailHtmlOptions): void {
- const tag = element.tagName.toLowerCase();
- if (!ALLOWED_TAGS.has(tag)) {
- if (DROP_CONTENT_TAGS.has(tag)) {
- element.remove();
- return;
- }
- element.replaceWith(...Array.from(element.childNodes));
- return;
- }
-
- for (const attribute of Array.from(element.attributes)) {
- const name = attribute.name.toLowerCase();
- const allowed = GLOBAL_ATTRIBUTES.has(name) || TAG_ATTRIBUTES[tag]?.has(name);
- if (!allowed || name.startsWith("on")) element.removeAttribute(attribute.name);
- }
-
- if (element instanceof HTMLElement) sanitizeStyle(element, options);
-
- if (tag === "a") {
- const href = element.getAttribute("href");
- if (!href || !isSafeLinkUrl(href, options)) {
- element.removeAttribute("href");
- } else {
- element.setAttribute("target", "_blank");
- element.setAttribute("rel", "noopener noreferrer");
- }
- }
-
- if (tag === "img") {
- const src = element.getAttribute("src");
- if (!src || !isSafeImageUrl(src, options)) {
- element.remove();
- return;
- }
- element.setAttribute("loading", "lazy");
- element.setAttribute("referrerpolicy", "no-referrer");
- }
-}
-
-export function sanitizeEmailHtml(html: string | null, options: SanitizeEmailHtmlOptions = {}): string | null {
- if (!html) return null;
- const document = new DOMParser().parseFromString(html, "text/html");
- for (const blockquote of Array.from(document.body.querySelectorAll("blockquote"))) {
- const introduction = blockquote.previousElementSibling;
- if (
- introduction instanceof HTMLElement &&
- /^On\b[\s\S]*\bwrote:\s*$/i.test(introduction.textContent?.trim() ?? "") &&
- !introduction.style.marginTop
- ) {
- introduction.style.marginTop = "1.4em";
- introduction.style.paddingBottom = "0.6em";
- }
- }
- for (const element of Array.from(document.body.querySelectorAll("*"))) {
- sanitizeElement(element, options);
- }
- return document.body.innerHTML;
-}
+// Compatibility export for existing compose callers.
+export { sanitizeEmailHtml } from "@/lib/email/html";
diff --git a/src/app/(dashboard)/inbox/[messageId]/page.tsx b/src/app/(dashboard)/inbox/[messageId]/page.tsx
index 519852b..6bce918 100644
--- a/src/app/(dashboard)/inbox/[messageId]/page.tsx
+++ b/src/app/(dashboard)/inbox/[messageId]/page.tsx
@@ -36,8 +36,7 @@ import {
resolveInlineAttachmentUrls,
} from "./utils";
import { extractCloudAttachments } from "./cloud-attachment-utils";
-import { sanitizeEmailHtml } from "./email-html-sanitizer";
-import { collapseQuotedEmailHtml } from "./quote-collapse-utils";
+import { EmailHtmlRenderer } from "@/components/messages/email-html-renderer";
import clsx from "clsx";
import { useAssistantOpen } from "@/components/agent/assistant-open-state";
import { useMessageContentScroll } from "./use-message-content-scroll";
@@ -137,12 +136,12 @@ export default function MessageDetailPage() {
message.snippet,
ownAddress,
);
- const htmlBody = collapseQuotedEmailHtml(sanitizeEmailHtml(
- resolveInlineAttachmentUrls(bodyDisplay.htmlBody, message.id, attachments),
- ));
- const quotedHtml = collapseQuotedEmailHtml(sanitizeEmailHtml(
- resolveInlineAttachmentUrls(bodyDisplay.quotedHtml, message.id, attachments),
- ), true);
+ const htmlBody = (
+ resolveInlineAttachmentUrls(bodyDisplay.htmlBody, message.id, attachments)
+ );
+ const quotedHtml = (
+ resolveInlineAttachmentUrls(bodyDisplay.quotedHtml, message.id, attachments)
+ );
const cloudAttachmentResult = extractCloudAttachments(
bodyDisplay.latestContent,
);
@@ -271,7 +270,7 @@ export default function MessageDetailPage() {
</div>
<div className="prose max-w-none pl-16 text-neutral-900">
{htmlBody ? (
- <div className="email-body mx-auto" dangerouslySetInnerHTML={{ __html: htmlBody }} />
+ <EmailHtmlRenderer key={message.id} className="mx-auto" html={htmlBody} />
) : (
<pre className="whitespace-pre-wrap text-sm text mx-auto">
{cloudAttachmentResult.content}
diff --git a/src/app/(dashboard)/inbox/[messageId]/quote-collapse-utils.ts b/src/app/(dashboard)/inbox/[messageId]/quote-collapse-utils.ts
index 83d224a..555a9e2 100644
--- a/src/app/(dashboard)/inbox/[messageId]/quote-collapse-utils.ts
+++ b/src/app/(dashboard)/inbox/[messageId]/quote-collapse-utils.ts
@@ -1,6 +1,8 @@
export function collapseQuotedEmailHtml(html: string | null, preserveLeadingQuote = false): string | null {
if (!html) return null;
- const document = new DOMParser().parseFromString(html, "text/html");
+ const template = window.document.createElement("template");
+ template.innerHTML = html;
+ const document = { body: template.content, createElement: window.document.createElement.bind(window.document) };
for (const blockquote of Array.from(document.body.querySelectorAll("blockquote"))) {
const introduction = blockquote.previousElementSibling;
@@ -22,9 +24,11 @@ export function collapseQuotedEmailHtml(html: string | null, preserveLeadingQuot
const content = document.createElement("div");
content.className = "email-quote-content";
introduction.parentNode?.insertBefore(details, introduction);
- content.append(introduction, blockquote);
- details.append(summary, content);
+ content.appendChild(introduction);
+ content.appendChild(blockquote);
+ details.appendChild(summary);
+ details.appendChild(content);
}
- return document.body.innerHTML;
+ return template.innerHTML;
}
diff --git a/src/app/(dashboard)/inbox/[messageId]/utils.ts b/src/app/(dashboard)/inbox/[messageId]/utils.ts
index 084d861..9067182 100644
--- a/src/app/(dashboard)/inbox/[messageId]/utils.ts
+++ b/src/app/(dashboard)/inbox/[messageId]/utils.ts
@@ -5,6 +5,7 @@ import { formatRecipientAddressList } from "@/lib/email/recipient-display";
import { getDisplayNameForAddress } from "@/lib/contacts/utils";
import { htmlToReadableText, splitRepliedEmailContent } from "@/lib/email/reply-content-utils";
import { splitQuotedHtml } from "@/components/compose/rich-text-utils";
+import { resolveEmailCidUrls } from "@/lib/email/html";
import type { Message } from "@/hooks/types";
import type { MessageAttachment, MessageBodyDisplay, MessageDetailResponse } from "./types";
@@ -92,14 +93,11 @@ export function resolveInlineAttachmentUrls(
): string | null {
if (!htmlBody) return null;
- return attachments.reduce((html, attachment) => {
- if (!attachment.contentId) return html;
- const contentId = attachment.contentId.replace(/^<|>$/g, "");
- return html.replaceAll(
- `cid:${contentId}`,
- getAttachmentUrl(messageId, attachment.id),
- );
- }, htmlBody);
+ const urls = new Map<string, string>();
+ for (const attachment of attachments) {
+ if (attachment.contentId) urls.set(attachment.contentId.replace(/^<|>$/g, ""), getAttachmentUrl(messageId, attachment.id));
+ }
+ return resolveEmailCidUrls(htmlBody, urls);
}
export function formatAttachmentSize(size: number): string {
diff --git a/src/components/compose/rich-text-editor.tsx b/src/components/compose/rich-text-editor.tsx
index 0603fda..51a3370 100644
--- a/src/components/compose/rich-text-editor.tsx
+++ b/src/components/compose/rich-text-editor.tsx
@@ -15,6 +15,8 @@ import {
} from "lucide-react";
import { Tooltip } from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";
+import { EmailHtmlRenderer } from "@/components/messages/email-html-renderer";
+import { sanitizeEmailHtml, sanitizeEditorHtml } from "@/lib/email/html";
import type { RichTextEditorProps, ToolbarCommand } from "./rich-text-editor-types";
const COMMANDS: ToolbarCommand[] = [
@@ -54,7 +56,9 @@ export function RichTextEditor({
// Keep the DOM in step with the value without resetting the caret on every keystroke.
useEffect(() => {
const element = editorRef.current;
- if (element && element.innerHTML !== value) element.innerHTML = value;
+ if (!element) return;
+ const safeValue = sanitizeEditorHtml(value);
+ if (element.innerHTML !== safeValue) element.innerHTML = safeValue;
}, [value]);
useEffect(() => {
@@ -76,7 +80,8 @@ export function RichTextEditor({
}, []);
function emit() {
- onChange(editorRef.current?.innerHTML ?? "");
+ // Export validated original resource addresses, never the blocked preview placeholders.
+ onChange(sanitizeEmailHtml(editorRef.current?.innerHTML ?? "", { forOutgoing: true }) ?? "");
}
function run(command: string, commandValue?: string) {
@@ -162,10 +167,7 @@ export function RichTextEditor({
•••
</button>
{showQuoted && (
- <div
- className="email-body mt-2 max-w-none border-l-2 border-neutral-200 pl-3 text-sm text-neutral-600"
- dangerouslySetInnerHTML={{ __html: quotedHtml }}
- />
+ <EmailHtmlRenderer className="mt-2" html={quotedHtml} preserveLeadingQuote />
)}
</div>
)}
diff --git a/src/components/message-actions/utils.ts b/src/components/message-actions/utils.ts
index 58dfd87..4a248e6 100644
--- a/src/components/message-actions/utils.ts
+++ b/src/components/message-actions/utils.ts
@@ -161,7 +161,7 @@ export function buildReplyQuoteHtml(
bodyText: string | null | undefined,
bodyHtml: string | null | undefined,
) {
- const original = bodyHtml ? sanitizeEmailHtml(bodyHtml) : textToHtml(bodyText);
+ const original = bodyHtml ? sanitizeEmailHtml(bodyHtml, { forOutgoing: true }) : textToHtml(bodyText);
if (!original) return null;
const when = sentAt ? formatUserDate(sentAt, { weekday: "short", month: "short", day: "numeric", year: "numeric", hour: "numeric", minute: "2-digit" }) : "an earlier date";
return wrapQuotedHtml(
@@ -244,7 +244,7 @@ export function buildForwardHtml(
];
if (message.ccAddr) lines.push(`Cc: ${message.ccAddr}`);
const header = `<div>---------- Forwarded message ---------<br>${lines.map(escapeHtml).join("<br>")}</div><br>`;
- const original = bodyHtml ? sanitizeEmailHtml(bodyHtml) : textToHtml(bodyText);
+ const original = bodyHtml ? sanitizeEmailHtml(bodyHtml, { forOutgoing: true }) : textToHtml(bodyText);
return wrapQuotedHtml(`${header}${original ?? ""}`);
}
diff --git a/src/components/messages/conversation-thread.tsx b/src/components/messages/conversation-thread.tsx
index 19cc67c..f25516c 100644
--- a/src/components/messages/conversation-thread.tsx
+++ b/src/components/messages/conversation-thread.tsx
@@ -6,8 +6,7 @@ import { ChevronsUpDown, Paperclip } from "lucide-react";
import { ContactAvatar } from "@/components/contacts/contact-avatar";
import { QuotedEmailToggle } from "@/components/messages/quoted-email-toggle";
import { runSingleMessageAction } from "@/components/message-actions/utils";
-import { sanitizeEmailHtml } from "@/app/(dashboard)/inbox/[messageId]/email-html-sanitizer";
-import { collapseQuotedEmailHtml } from "@/app/(dashboard)/inbox/[messageId]/quote-collapse-utils";
+import { EmailHtmlRenderer } from "./email-html-renderer";
import { getMessageBodyDisplay, resolveInlineAttachmentUrls } from "@/app/(dashboard)/inbox/[messageId]/utils";
import { cn } from "@/lib/utils";
@@ -138,9 +137,9 @@ export function ConversationMessageCard({
if (expanded) {
const display = getMessageBodyDisplay(message.textBody, message.htmlBody, message.snippet);
body = {
- html: collapseQuotedEmailHtml(sanitizeEmailHtml(resolveInlineAttachmentUrls(display.htmlBody, message.id, message.attachments))),
+ html: resolveInlineAttachmentUrls(display.htmlBody, message.id, message.attachments),
text: display.latestContent,
- quotedHtml: collapseQuotedEmailHtml(sanitizeEmailHtml(resolveInlineAttachmentUrls(display.quotedHtml, message.id, message.attachments)), true),
+ quotedHtml: resolveInlineAttachmentUrls(display.quotedHtml, message.id, message.attachments),
};
}
@@ -197,7 +196,7 @@ export function ConversationMessageCard({
{expanded && body && (
<div className="pb-4 pl-16 pt-2">
{body.html ? (
- <div className="email-body max-w-none text-sm text-neutral-900" dangerouslySetInnerHTML={{ __html: body.html }} />
+ <EmailHtmlRenderer html={body.html} />
) : (
<pre className="whitespace-pre-wrap font-sans text-sm text-neutral-900">{body.text}</pre>
)}
diff --git a/src/components/messages/email-html-renderer.tsx b/src/components/messages/email-html-renderer.tsx
new file mode 100644
index 0000000..a30d652
--- /dev/null
+++ b/src/components/messages/email-html-renderer.tsx
@@ -0,0 +1,62 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import { prepareEmailHtml } from "@/lib/email/html";
+import { collapseQuotedEmailHtml } from "@/app/(dashboard)/inbox/[messageId]/quote-collapse-utils";
+
+const BASE_STYLE = `
+:host { display:block; min-width:0; isolation:isolate; }
+.email-quote-toggle { margin-top:1.4em; }
+.email-quote-toggle > summary { cursor:pointer; list-style:none; width:26px; border-radius:20px; background:#ececec; text-align:center; }
+.email-quote-toggle > summary::-webkit-details-marker { display:none; }
+.email-quote-toggle > summary::before { content:'•••'; }
+.email-quote-content { display:flow-root; }
+`;
+
+export function EmailHtmlRenderer({ html, className, preserveLeadingQuote = false }: {
+ html: string; className?: string; preserveLeadingQuote?: boolean;
+}) {
+ const host = useRef<HTMLDivElement>(null);
+ const [allowedSource, setAllowedSource] = useState<string | null>(null);
+ const [hasRemote, setHasRemote] = useState(false);
+ const allowRemote = allowedSource === html;
+ useEffect(() => {
+ if (!host.current) return;
+ host.current.dir = document.documentElement.dir || "ltr";
+ const root = host.current.shadowRoot ?? host.current.attachShadow({ mode: "open" });
+ const prepared = prepareEmailHtml(html, { reader: true, allowRemote });
+ setHasRemote(prepared.hasRemote);
+ const base = document.createElement("style");
+ base.textContent = `${BASE_STYLE}\n${prepared.rootTag} { display:block; font:14px/1.5 Arial,sans-serif; color:#202124; background:#fff; color-scheme:light; }\n${prepared.bodyTag} { display:block; }`;
+ const content = document.createElement("template");
+ content.innerHTML = collapseQuotedEmailHtml(prepared.html, preserveLeadingQuote) ?? "";
+ root.replaceChildren(base, content.content);
+ const mailBody = root.querySelector(prepared.bodyTag);
+ // An LTR scroller cannot reach left-side overflow from an RTL email.
+ if (mailBody) host.current.dir = window.getComputedStyle(mailBody).direction;
+ // Document fragment navigation does not automatically find IDs inside a shadow tree.
+ const navigate = (event: Event) => {
+ const target = event.target as Element | null;
+ const anchor = target?.closest("a[href]");
+ const href = anchor?.getAttribute("href");
+ if (!href?.startsWith("#")) return;
+ event.preventDefault();
+ try {
+ const id = decodeURIComponent(href.slice(1));
+ const destination = root.getElementById(id) ?? Array.from(root.querySelectorAll("a[name]")).find(node => node.getAttribute("name") === id);
+ destination?.scrollIntoView({ block: "start" });
+ } catch { /* Ignore malformed fragments. */ }
+ };
+ root.addEventListener("click", navigate);
+ return () => root.removeEventListener("click", navigate);
+ }, [html, allowRemote, preserveLeadingQuote]);
+ return <div className={`min-w-0 max-w-full ${className ?? ""}`}>
+ {hasRemote && <div className="mb-2 flex justify-end">
+ <button type="button" aria-pressed={allowRemote} className="rounded px-2 py-1 text-xs text-blue-600 hover:bg-blue-50"
+ onClick={() => setAllowedSource(allowRemote ? null : html)}>
+ {allowRemote ? "Block remote content" : "Allow remote content"}
+ </button>
+ </div>}
+ <div className="max-w-full overflow-x-auto" ref={host} />
+ </div>;
+}
diff --git a/src/components/messages/quoted-email-toggle.tsx b/src/components/messages/quoted-email-toggle.tsx
index 1ad5c18..c045355 100644
--- a/src/components/messages/quoted-email-toggle.tsx
+++ b/src/components/messages/quoted-email-toggle.tsx
@@ -1,13 +1,11 @@
import type { QuotedEmailToggleProps } from "./quoted-email-toggle-types";
+import { EmailHtmlRenderer } from "./email-html-renderer";
export function QuotedEmailToggle({ html }: QuotedEmailToggleProps) {
return (
<details className="email-quote-toggle">
<summary aria-label="Toggle quoted email" title="Show or hide quoted email" />
- <div
- className="email-body email-quote-content max-w-none text-sm text-neutral-600"
- dangerouslySetInnerHTML={{ __html: html }}
- />
+ <EmailHtmlRenderer html={html} preserveLeadingQuote />
</details>
);
}
diff --git a/src/components/settings/mailbox-signature-form.tsx b/src/components/settings/mailbox-signature-form.tsx
index 6f1e4fb..60da752 100644
--- a/src/components/settings/mailbox-signature-form.tsx
+++ b/src/components/settings/mailbox-signature-form.tsx
@@ -2,7 +2,8 @@
import { useEffect, useState } from "react";
import { useSelectedMailbox } from "@/components/mailbox-provider";
-import { isHtmlSignature, signatureToHtml } from "@/components/compose/rich-text-utils";
+import { isHtmlSignature } from "@/components/compose/rich-text-utils";
+import { EmailHtmlRenderer } from "@/components/messages/email-html-renderer";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
@@ -65,9 +66,9 @@ export function MailboxSignatureForm() {
{isHtmlSignature(signature) && (
<div className="space-y-2">
<p className="text-xs font-medium text-neutral-500">Preview</p>
- <div
+ <EmailHtmlRenderer
className="rounded-md border border-neutral-200 bg-white p-4 text-sm text-neutral-900"
- dangerouslySetInnerHTML={{ __html: signatureToHtml(signature) }}
+ html={signature}
/>
</div>
)}
diff --git a/src/lib/email/html.ts b/src/lib/email/html.ts
new file mode 100644
index 0000000..99fd0f0
--- /dev/null
+++ b/src/lib/email/html.ts
@@ -0,0 +1,355 @@
+import createDOMPurify from "dompurify";
+import * as css from "css-tree";
+import { parse, serialize, type DefaultTreeAdapterTypes } from "parse5";
+import parseSrcset from "parse-srcset";
+import type { SanitizeEmailHtmlOptions } from "@/app/(dashboard)/inbox/[messageId]/email-html-sanitizer-types";
+
+type Options = SanitizeEmailHtmlOptions & {
+ allowRemote?: boolean;
+ reader?: boolean;
+ editor?: boolean;
+};
+
+type MailDocument = { template: HTMLTemplateElement; rootTag: string; bodyTag: string; needsWrapper: boolean };
+const nameOf = (name: string) => css.ident.decode(name).toLowerCase();
+const BLOCKED_IMAGE = "data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=";
+const RESOURCE_ATTRIBUTES = ["src", "background", "poster"];
+const EDITOR_ATTRIBUTES = ["data-mailflare-src", "data-mailflare-background", "data-mailflare-poster", "data-mailflare-srcset", "data-mailflare-style", "data-mailflare-sheet"];
+
+function outgoingScope(source: string): string {
+ // Stable presentation names keep repeated signature generation comparable. These are
+ // not a security boundary; reader containers always use fresh, unpredictable names.
+ let hash = 2166136261;
+ for (let index = 0; index < source.length; index++) hash = Math.imul(hash ^ source.charCodeAt(index), 16777619);
+ return `outgoing${(hash >>> 0).toString(16)}`;
+}
+
+/** Parse without a browser DOM, then populate an inert template. No network is possible. */
+function mailDocument(source: string, outgoing = false): MailDocument {
+ const parsed = parse(source);
+ const html = parsed.childNodes.find((node): node is DefaultTreeAdapterTypes.Element => "tagName" in node && node.tagName === "html")!;
+ const head = html.childNodes.find((node): node is DefaultTreeAdapterTypes.Element => "tagName" in node && node.tagName === "head")!;
+ const body = html.childNodes.find((node): node is DefaultTreeAdapterTypes.Element => "tagName" in node && node.tagName === "body")!;
+ // Fresh element names avoid collisions with mail classes/IDs and never define custom elements.
+ const token = outgoing ? outgoingScope(source) : window.crypto.randomUUID().replaceAll("-", "");
+ const rootTag = `mail-root-${token}`;
+ const bodyTag = `mail-body-${token}`;
+ html.tagName = html.nodeName = rootTag;
+ body.tagName = body.nodeName = bodyTag;
+ const headContent = head.childNodes.filter(node => "tagName" in node && ["style", "base"].includes(node.tagName));
+ html.childNodes = [...headContent, body];
+ for (const child of html.childNodes) child.parentNode = html;
+ const template = document.createElement("template");
+ template.innerHTML = serialize(parsed);
+ return { template, rootTag, bodyTag, needsWrapper: !!html.attrs.length || !!body.attrs.length || headContent.some(node => "tagName" in node && node.tagName === "style") };
+}
+
+const SAFE_AT_RULES = new Set([
+ "media", "supports", "font-face", "keyframes", "-webkit-keyframes", "layer",
+ "container", "scope", "starting-style", "page", "property", "counter-style",
+]);
+
+/** Only remove unsupported syntax at its declaration/rule boundary, not an entire sheet. */
+function transformCss(source: string, inline: boolean, resource: (value: string) => string | null, doc?: MailDocument, classScope = false, allowIndirect = false, onIndirect?: () => void): string {
+ try {
+ const ast = css.parse(source, {
+ context: inline ? "declarationList" : "stylesheet",
+ parseCustomProperty: true,
+ });
+ css.walk(ast, {
+ enter(node, item, list) {
+ const remove = () => { if (item && list) list.remove(item); };
+ if (node.type === "Declaration") {
+ if (["behavior", "-moz-binding"].includes(nameOf(node.property)) || css.find(node.value, child => child.type === "Raw")) {
+ remove(); return css.walk.skip;
+ }
+ }
+ if (node.type === "Rule" && css.find(node.prelude, child => child.type === "Raw")) {
+ remove(); return css.walk.skip;
+ }
+ if (node.type === "Atrule") {
+ const name = nameOf(node.name);
+ if (!SAFE_AT_RULES.has(name) || (node.prelude && css.find(node.prelude, child => child.type === "Raw"))) {
+ remove(); return css.walk.skip;
+ }
+ node.name = name;
+ }
+ if (node.type === "Raw") { remove(); return css.walk.skip; }
+ if (node.type === "Selector" && css.find(node, child =>
+ (child.type === "PseudoClassSelector" && ["host", "host-context"].includes(nameOf(child.name))) ||
+ (child.type === "PseudoElementSelector" && ["slotted", "part"].includes(nameOf(child.name)))
+ )) { remove(); return css.walk.skip; }
+ if (node.type === "Function") {
+ const name = nameOf(node.name);
+ node.name = css.ident.encode(name);
+ if (name === "expression") { remove(); return css.walk.skip; }
+ if (["image", "image-set", "-webkit-image-set", "src"].includes(name)) {
+ if (css.find(node, child => child.type === "Function" && ["var", "attr"].includes(nameOf(child.name)))) {
+ onIndirect?.();
+ if (!allowIndirect) {
+ Object.assign(node, { type: "Url", value: BLOCKED_IMAGE });
+ return css.walk.skip;
+ }
+ }
+ node.children.forEach(child => {
+ if (child.type === "String") child.value = resource(child.value) ?? BLOCKED_IMAGE;
+ });
+ }
+ // Escaped url("...") can be represented as a generic Function by the parser.
+ if (name === "url") {
+ const first = node.children.first;
+ const value = first?.type === "String" ? first.value : css.ident.decode(css.generate(node.children));
+ Object.assign(node, { type: "Url", value: resource(value) ?? BLOCKED_IMAGE });
+ return css.walk.skip;
+ }
+ }
+ if (node.type === "Url") node.value = resource(node.value) ?? BLOCKED_IMAGE;
+ if (doc && node.type === "TypeSelector") {
+ const name = nameOf(node.name);
+ if (name === "html" || name === "body") {
+ if (classScope) doc.needsWrapper = true;
+ Object.assign(node, {
+ type: classScope ? "ClassSelector" : "TypeSelector", name: name === "html" ? doc.rootTag : doc.bodyTag,
+ });
+ }
+ }
+ if (doc && node.type === "PseudoClassSelector" && nameOf(node.name) === "root") {
+ if (classScope) doc.needsWrapper = true;
+ Object.assign(node, { type: classScope ? "ClassSelector" : "TypeSelector", name: doc.rootTag });
+ }
+ },
+ leave(node, item, list) {
+ if (node.type === "Rule" && node.prelude.type === "SelectorList" && node.prelude.children.isEmpty && item && list) list.remove(item);
+ },
+ });
+ return css.generate(ast);
+ } catch { return ""; }
+}
+
+function mapSrcset(source: string, resource: (value: string) => string | null): string {
+ return parseSrcset(source).flatMap(candidate => {
+ const url = resource(candidate.url);
+ return url ? [`${url}${candidate.w ? ` ${candidate.w}w` : candidate.d !== undefined ? ` ${candidate.d}x` : ""}`] : [];
+ }).join(", ");
+}
+
+function restoreEditorStyle(current: string, stored: string): string {
+ try {
+ const original = css.parse(decodeURIComponent(stored), { context: "declarationList", parseCustomProperty: true });
+ const ast = css.parse(current, { context: "declarationList", parseCustomProperty: true });
+ const originals = new Map<string, css.Declaration["value"]>();
+ css.walk(original, node => { if (node.type === "Declaration") originals.set(node.property, node.value); });
+ css.walk(ast, node => {
+ if (node.type === "Declaration" && css.find(node.value, child => child.type === "Url" && child.value === BLOCKED_IMAGE)) {
+ const value = originals.get(node.property);
+ if (value) node.value = value;
+ }
+ });
+ return css.generate(ast);
+ } catch { return current; }
+}
+
+function legacyBodyStyles(element: HTMLDivElement) {
+ const color = element.getAttribute("text");
+ const background = element.getAttribute("bgcolor");
+ const image = element.getAttribute("background");
+ if (color && !element.style.color) element.style.color = color;
+ if (background && !element.style.backgroundColor) element.style.backgroundColor = background;
+ if (image && !element.style.backgroundImage) element.style.backgroundImage = `url(${JSON.stringify(image)})`;
+ for (const [attribute, property] of [["topmargin", "margin-top"], ["bottommargin", "margin-bottom"], ["leftmargin", "margin-left"], ["rightmargin", "margin-right"]]) {
+ const value = element.getAttribute(attribute);
+ if (value && /^\d+$/.test(value) && !element.style.getPropertyValue(property)) element.style.setProperty(property, `${value}px`);
+ }
+}
+
+export function resolveEmailCidUrls(source: string, urls: Map<string, string>): string {
+ if (typeof document === "undefined" || !urls.size) return source;
+ const doc = mailDocument(source);
+ const resolve = (value: string) => {
+ if (!/^cid:/i.test(value)) return value;
+ const id = value.slice(4).replace(/^<|>$/g, "");
+ try { return urls.get(id) ?? urls.get(decodeURIComponent(id)) ?? value; }
+ catch { return urls.get(id) ?? value; }
+ };
+ for (const element of doc.template.content.querySelectorAll("*")) {
+ for (const attr of RESOURCE_ATTRIBUTES) {
+ if (element.hasAttribute(attr)) element.setAttribute(attr, resolve(element.getAttribute(attr)!));
+ }
+ if (element.hasAttribute("srcset")) element.setAttribute("srcset", mapSrcset(element.getAttribute("srcset")!, resolve));
+ if (element.hasAttribute("style")) element.setAttribute("style", transformCss(element.getAttribute("style")!, true, resolve, undefined, false, true));
+ if (element.tagName === "STYLE") element.textContent = transformCss(element.textContent ?? "", false, resolve, undefined, false, true);
+ }
+ // Return a document, not reader-specific containers. Its next consumer may be the sender.
+ return restoreDocument(doc.template, doc, true);
+}
+
+function restoreDocument(template: HTMLTemplateElement, doc: MailDocument, full: boolean): string {
+ const root = template.content.querySelector(doc.rootTag)!;
+ const body = root.querySelector(doc.bodyTag)!;
+ const headNodes = Array.from(root.querySelectorAll("style, base"));
+ if (!full) return body.innerHTML;
+ const html = document.createElement("html");
+ const head = document.createElement("head");
+ const bodyElement = document.createElement("body");
+ for (const attribute of root.attributes) html.setAttribute(attribute.name, attribute.value);
+ for (const attribute of body.attributes) bodyElement.setAttribute(attribute.name, attribute.value);
+ for (const node of headNodes) head.appendChild(node);
+ for (const child of Array.from(body.childNodes)) bodyElement.appendChild(child);
+ html.appendChild(head);
+ html.appendChild(bodyElement);
+ return html.outerHTML;
+}
+
+/** Ordinary divs are portable in signatures and quoted fragments; no nested html/body tags. */
+function outgoingFragment(template: HTMLTemplateElement, doc: MailDocument): string {
+ const root = template.content.querySelector(doc.rootTag)!;
+ const body = root.querySelector(doc.bodyTag)!;
+ if (!doc.needsWrapper) return body.innerHTML;
+ const convert = (element: Element, className: string) => {
+ const replacement = document.createElement("div");
+ for (const attribute of element.attributes) replacement.setAttribute(attribute.name, attribute.value);
+ replacement.classList.add(className);
+ for (const child of Array.from(element.childNodes)) replacement.appendChild(child);
+ element.replaceWith(replacement);
+ };
+ convert(body, doc.bodyTag);
+ convert(root, doc.rootTag);
+ return template.innerHTML;
+}
+
+export function prepareEmailHtml(source: string, options: Options = {}) {
+ const outgoing = !!options.forOutgoing && !options.editor;
+ const doc = mailDocument(source, outgoing);
+ const { template, rootTag, bodyTag } = doc;
+ let hasRemote = false;
+ const allowIndirect = !!options.allowRemote || outgoing;
+ const markIndirect = () => { hasRemote = true; };
+ const base = template.content.querySelector("base[href]")?.getAttribute("href");
+ const resource = (value: string): string | null => {
+ if (/^data:image\/(?:png|jpeg|gif|webp);base64,/i.test(value)) return value;
+ if (!options.forOutgoing && /^\/api\/messages\/[^/]+\/attachments\/[^/?]+\?preview=1$/.test(value)) return value;
+ if (value.startsWith("#")) return value;
+ try {
+ const url = new URL(value, base || "https://invalid.invalid/");
+ if (!["http:", "https:"].includes(url.protocol) || url.hostname === "invalid.invalid") return null;
+ hasRemote = true;
+ return options.allowRemote || (options.forOutgoing && !options.editor) ? url.href : null;
+ } catch { return null; }
+ };
+ const root = template.content.querySelector<HTMLDivElement>(rootTag)!;
+ const body = template.content.querySelector<HTMLDivElement>(bodyTag)!;
+ for (const placeholder of template.content.querySelectorAll("[data-mailflare-sheet]")) {
+ try {
+ const style = document.createElement("style");
+ style.textContent = decodeURIComponent(placeholder.getAttribute("data-mailflare-sheet")!);
+ placeholder.replaceWith(style);
+ } catch { placeholder.remove(); }
+ }
+ legacyBodyStyles(body);
+ const linkColor = body.getAttribute("link");
+ if (linkColor && /^#[a-f\d]{3,8}$/i.test(linkColor)) {
+ const style = document.createElement("style");
+ style.textContent = `body a:link{color:${linkColor}}`;
+ root.insertBefore(style, root.firstChild);
+ }
+ const editorHeadStyles = document.createDocumentFragment();
+ for (const element of template.content.querySelectorAll("*")) {
+ if (element.tagName === "STYLE") {
+ if (options.editor) {
+ // Keep a non-executable copy for sending; never install mail CSS into the editor document.
+ const placeholder = document.createElement("span");
+ placeholder.hidden = true;
+ placeholder.setAttribute("data-mailflare-sheet", encodeURIComponent(transformCss(element.textContent ?? "", false, value => value, undefined, false, true)));
+ if (element.parentElement === root) {
+ editorHeadStyles.appendChild(placeholder);
+ element.remove();
+ } else element.replaceWith(placeholder);
+ continue;
+ }
+ if (!options.reader && !options.forOutgoing) { element.remove(); continue; }
+ element.textContent = transformCss(element.textContent ?? "", false, resource, options.reader || outgoing ? doc : undefined, outgoing, allowIndirect, markIndirect);
+ }
+ // Editor placeholders preserve source addresses without loading them. Validate again on send.
+ for (const attr of [...RESOURCE_ATTRIBUTES, "srcset", "style"]) {
+ const stored = element.getAttribute(`data-mailflare-${attr}`);
+ if (stored !== null) element.setAttribute(attr, attr === "style" ? restoreEditorStyle(element.getAttribute("style") ?? "", stored) : stored);
+ element.removeAttribute(`data-mailflare-${attr}`);
+ }
+ if (element.hasAttribute("style")) {
+ const original = element.getAttribute("style")!;
+ const safe = transformCss(original, true, resource, options.reader ? doc : undefined, false, allowIndirect, markIndirect);
+ if (options.editor && original !== safe) element.setAttribute("data-mailflare-style", encodeURIComponent(transformCss(original, true, value => {
+ try { const url = new URL(value); return ["http:", "https:"].includes(url.protocol) ? url.href : resource(value); }
+ catch { return resource(value); }
+ }, undefined, false, true)));
+ element.setAttribute("style", safe);
+ }
+ for (const attr of RESOURCE_ATTRIBUTES) {
+ if (!element.hasAttribute(attr)) continue;
+ const original = element.getAttribute(attr)!;
+ const value = resource(original);
+ if (value) element.setAttribute(attr, value);
+ else {
+ if (options.editor) element.setAttribute(`data-mailflare-${attr}`, original);
+ element.removeAttribute(attr);
+ }
+ }
+ if (element.hasAttribute("srcset")) {
+ const original = element.getAttribute("srcset")!;
+ const value = mapSrcset(original, resource);
+ if (options.editor) element.setAttribute("data-mailflare-srcset", original);
+ if (value) element.setAttribute("srcset", value); else element.removeAttribute("srcset");
+ }
+ if (element.tagName === "A") {
+ const original = element.getAttribute("href") ?? "";
+ if (original.startsWith("#")) {
+ element.removeAttribute("target");
+ element.removeAttribute("rel");
+ } else {
+ try {
+ const href = new URL(original, base || "https://invalid.invalid/");
+ if (!["https:", "http:", "mailto:", "tel:"].includes(href.protocol) || href.hostname === "invalid.invalid") element.removeAttribute("href");
+ else element.setAttribute("href", href.href);
+ } catch { element.removeAttribute("href"); }
+ element.setAttribute("target", "_blank");
+ element.setAttribute("rel", "noopener noreferrer");
+ }
+ }
+ if (element.tagName === "IMG") {
+ element.setAttribute("referrerpolicy", "no-referrer");
+ element.setAttribute("loading", "lazy");
+ }
+ }
+ if (options.editor) body.insertBefore(editorHeadStyles, body.firstChild);
+ const purifier = createDOMPurify(window);
+ const cleaned = purifier.sanitize(template.content, {
+ USE_PROFILES: { html: true },
+ ADD_TAGS: ["style", rootTag, bodyTag],
+ ADD_ATTR: ["target", "loading", "referrerpolicy", ...(options.forOutgoing || options.editor ? ["data-mailflare-quote", "data-mailflare-signature"] : []), ...(options.editor ? EDITOR_ATTRIBUTES : [])],
+ FORBID_TAGS: ["script", "iframe", "object", "embed", "form", "input", "button", "select", "textarea", "link", "base", "meta", "audio", "video", "source", "template"],
+ FORBID_ATTR: ["is", "slot"],
+ ALLOW_DATA_ATTR: false,
+ RETURN_DOM_FRAGMENT: true,
+ });
+ const result = document.createElement("template");
+ result.content.append(cleaned);
+ // Stable serialization keeps the editor from replacing its DOM just for attribute order.
+ for (const element of result.content.querySelectorAll("*")) {
+ const attributes = Array.from(element.attributes).sort((a, b) => a.name.localeCompare(b.name));
+ for (const attribute of attributes) element.removeAttribute(attribute.name);
+ for (const attribute of attributes) element.setAttribute(attribute.name, attribute.value);
+ }
+ // Metadata on a converted body element needs explicit preservation; DOMPurify may drop
+ // obsolete body-only attributes, whose visual equivalents were translated above.
+ const output = options.reader ? result.innerHTML : outgoing ? outgoingFragment(result, doc) : restoreDocument(result, doc, false);
+ return { html: output, hasRemote, rootTag, bodyTag };
+}
+
+export function sanitizeEmailHtml(html: string | null, options: SanitizeEmailHtmlOptions = {}): string | null {
+ if (!html || typeof window === "undefined") return null;
+ return prepareEmailHtml(html, options).html;
+}
+
+export function sanitizeEditorHtml(html: string): string {
+ return prepareEmailHtml(html, { editor: true }).html;
+}
diff --git a/src/lib/email/parse-srcset.d.ts b/src/lib/email/parse-srcset.d.ts
new file mode 100644
index 0000000..7a61854
--- /dev/null
+++ b/src/lib/email/parse-srcset.d.ts
@@ -0,0 +1,3 @@
+declare module "parse-srcset" {
+ export default function parse(source: string): Array<{ url: string; w?: number; h?: number; d?: number }>;
+}
diff --git a/src/lib/seed-utils.ts b/src/lib/seed-utils.ts
index e150dc2..714e2ca 100644
--- a/src/lib/seed-utils.ts
+++ b/src/lib/seed-utils.ts
@@ -232,7 +232,15 @@ export async function ensureDemoUser(env: CloudflareEnv) {
.from(users)
.where(eq(users.email, demoCredentials.email))
.limit(1);
- if (existing) return existing;
+ const [admin] = await db.select({ id: users.id }).from(users).where(eq(users.role, "admin")).limit(1);
+ if (existing) {
+ // Repair demos seeded before the login page required an admin account.
+ if (!admin) {
+ await db.update(users).set({ role: "admin", isPrimaryAdmin: true }).where(eq(users.id, existing.id));
+ return { ...existing, role: "admin" as const, isPrimaryAdmin: true };
+ }
+ return existing;
+ }
const id = newId("usr");
await db.insert(users).values({
@@ -240,6 +248,8 @@ export async function ensureDemoUser(env: CloudflareEnv) {
email: demoCredentials.email,
passwordHash: hashPassword(demoCredentials.password),
name: "Demo User",
+ role: admin ? "user" : "admin",
+ isPrimaryAdmin: !admin,
});
await ensureBookingUsername(env, id, demoCredentials.email);
diff --git a/tests/email-html.test.mjs b/tests/email-html.test.mjs
new file mode 100644
index 0000000..b024c6b
--- /dev/null
+++ b/tests/email-html.test.mjs
@@ -0,0 +1,193 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { build } from "esbuild";
+import { JSDOM } from "jsdom";
+
+const dom = new JSDOM("", { url: "https://mail.example/" });
+globalThis.window = dom.window;
+globalThis.document = dom.window.document;
+globalThis.HTMLElement = dom.window.HTMLElement;
+const bundle = await build({ entryPoints: ["src/lib/email/html.ts"], bundle: true, write: false, platform: "browser", format: "esm" });
+const { prepareEmailHtml, resolveEmailCidUrls, sanitizeEditorHtml } = await import(`data:text/javascript;base64,${Buffer.from(bundle.outputFiles[0].text).toString("base64")}`);
+
+const message = `<html><head><style>
+@import "https://remote.example/import.css";
+@media (max-width:600px) { body .card { color:red; background:url(https://remote.example/bg); } }
+@font-face {font-family:Mail;src:url(https://remote.example/font.woff2)}
+.other { background:image-set("https://remote.example/set" 1x); }
+:host {display:none}
+</style></head><body bgcolor="#eee"><div class="card" style="display:grid;gap:12px">Hello</div>
+<img src="https://remote.example/image" srcset="https://remote.example/large 2x" onerror="alert(1)">
+<img src="/api/messages/m/attachments/a?preview=1"><script>alert(1)</script>
+<a href="javascript:alert(1)">bad</a></body></html>`;
+
+test("reader preserves layout and local attachments but blocks every remote URL", () => {
+ const result = prepareEmailHtml(message, { reader: true });
+ assert.equal(result.hasRemote, true);
+ assert.doesNotMatch(result.html, /remote\.example|onerror|<script|javascript:|:host|@import/);
+ assert.match(result.html, /@media/);
+ assert.match(result.html, /display:grid/);
+ assert.match(result.html, /class="card"/);
+ assert.match(result.html, /\/api\/messages\/m\/attachments\/a\?preview=1/);
+});
+
+test("authorization restores images, srcset, CSS backgrounds and fonts", () => {
+ const result = prepareEmailHtml(message, { reader: true, allowRemote: true });
+ for (const path of ["image", "large", "bg", "font.woff2", "set"]) assert.ok(result.html.includes(`https://remote.example/${path}`));
+ assert.doesNotMatch(result.html, /@import|:host|onerror|<script/);
+});
+
+test("CSS escaping cannot bypass remote blocking", () => {
+ const result = prepareEmailHtml('<style>.x{background:u\\72l(https://remote.example/escaped)}</style><div class="x">x</div>', { reader: true });
+ assert.doesNotMatch(result.html, /remote\.example/);
+});
+
+test("outgoing quotes retain styles and remote addresses without document tags", () => {
+ const result = prepareEmailHtml(message, { forOutgoing: true });
+ assert.doesNotMatch(result.html, /onerror|javascript:|<html|<body/);
+ assert.match(result.html, /<style/);
+ assert.match(result.html, /https:\/\/remote.example\/image/);
+});
+
+test("CID mapping changes resource attributes and CSS, not visible text", () => {
+ const source = '<style>.x{background:url(cid:logo)}</style><img src="CID:logo"><p>cid:logo</p>';
+ const resolved = resolveEmailCidUrls(source, new Map([["logo", "/api/messages/m/attachments/a?preview=1"]]));
+ assert.match(resolved, /<p>cid:logo<\/p>/);
+ const result = prepareEmailHtml(resolved, { reader: true });
+ assert.equal(result.hasRemote, false);
+ assert.equal((result.html.match(/\/api\/messages\/m\/attachments\/a/g) ?? []).length, 2);
+});
+
+test("escaped function names and URLs cannot bypass resource policy", () => {
+ for (const value of [String.raw`im\61ge-set("https://remote.example/set" 1x)`, String.raw`-webkit-im\61ge-set("https://remote.example/set" 1x)`, String.raw`u\72l("https://remote.example/bg")`, String.raw`image("https://remote.example/bg")`]) {
+ const source = `<style>.x{background:${value}}</style><p class="x">x</p>`;
+ const blocked = prepareEmailHtml(source, { reader: true });
+ assert.doesNotMatch(blocked.html, /remote\.example/, value);
+ assert.equal(blocked.hasRemote, true, value);
+ assert.match(prepareEmailHtml(source, { reader: true, allowRemote: true }).html, /remote\.example/);
+ }
+});
+
+test("escaped shadow boundary selectors are removed without removing normal selectors", () => {
+ const source = String.raw`<style>:h\6fst{display:none}:host-context(.x){color:red}::p\61rt(x){color:blue}.x{color:green}</style><p class="x">x</p>`;
+ const result = prepareEmailHtml(source, { reader: true });
+ assert.doesNotMatch(result.html, /h\\6fst|host-context|p\\61rt/);
+ assert.match(result.html, /\.x\{color:green\}/);
+});
+
+test("CSS variables, keyframes and layers survive and URLs inside variables are handled", () => {
+ const source = '<style>:root{--brand:red;--image:url(https://remote.example/bg)}@layer mail{.x{color:var(--brand);background:var(--image)}}@keyframes spin{to{transform:rotate(1turn)}}</style><p style="color:red;--brand:blue;font-size:20px">x</p>';
+ const result = prepareEmailHtml(source, { reader: true });
+ assert.match(result.html, /--brand:red/);
+ assert.match(result.html, /@layer mail/);
+ assert.match(result.html, /@keyframes spin/);
+ assert.match(result.html, /color:red;--brand:blue;font-size:20px/);
+ assert.doesNotMatch(result.html, /remote\.example/);
+});
+
+test("invalid declaration does not erase unrelated valid declarations", () => {
+ const result = prepareEmailHtml('<style>.x{color:red;background:url("broken);font-size:20px}.y{color:green}</style>', { reader: true });
+ assert.match(result.html, /color:red/);
+});
+
+test("document attributes, body backgrounds and structural selectors are preserved", () => {
+ const source = '<html dir="rtl" class="original-root" style="font-size:20px"><head><style>html.original-root > body.original-body{padding:10px}:root{--brand:red}</style></head><body class="original-body" bgcolor="#ff0000" background="https://remote.example/bg"><p>x</p></body></html>';
+ const result = prepareEmailHtml(source, { reader: true });
+ const template = document.createElement("template");
+ template.innerHTML = result.html;
+ const root = template.content.querySelector(result.rootTag);
+ const body = root.querySelector(result.bodyTag);
+ assert.equal(root.getAttribute("dir"), "rtl");
+ assert.equal(root.style.fontSize, "20px");
+ assert.equal(root.className, "original-root");
+ assert.equal(body.style.backgroundColor, "rgb(255, 0, 0)");
+ assert.match(result.html, new RegExp(`${result.rootTag}\\.original-root>${result.bodyTag}\\.original-body`));
+ assert.doesNotMatch(result.html, /remote\.example/);
+});
+
+test("CID conversion preserves document metadata and does not rewrite text resembling tags", () => {
+ const source = '<html dir="rtl"><head><style>.x:before{content:"<body>"}</style></head><body bgcolor="#eee"><img src="cid:logo"></body></html>';
+ const resolved = resolveEmailCidUrls(source, new Map([["logo", "/api/messages/m/attachments/a?preview=1"]]));
+ assert.match(resolved, /<html dir="rtl">/);
+ assert.match(resolved, /content:"<body>"/);
+ assert.match(resolved, /<body bgcolor="#eee">/);
+});
+
+test("reader containers do not share class names with message content", () => {
+ const result = prepareEmailHtml('<style>.mail-root{display:none}</style><div class="mail-document">x</div>', { reader: true });
+ const template = document.createElement("template");
+ template.innerHTML = result.html;
+ assert.equal(template.content.querySelector(result.rootTag).className, "");
+ assert.equal(template.content.querySelector(result.bodyTag).className, "");
+});
+
+test("fragment links retain IDs and do not open another document", () => {
+ const result = prepareEmailHtml('<a href="#section">jump</a><p id="section">x</p>', { reader: true });
+ assert.match(result.html, /href="#section"/);
+ assert.doesNotMatch(result.html, /target="_blank"/);
+ assert.match(result.html, /id="section"/);
+});
+
+test("editor preview blocks resources, preserves them for send and is stable on roundtrip", () => {
+ const source = '<p style="color:red;--brand:blue;background:url(https://remote.example/bg)">x<img src="https://remote.example/image" srcset="https://remote.example/large 2x"></p>';
+ const preview = sanitizeEditorHtml(source);
+ const template = document.createElement("template");
+ template.innerHTML = preview;
+ assert.equal(template.content.querySelector("img").getAttribute("src"), null);
+ assert.equal(template.content.querySelector("img").getAttribute("srcset"), null);
+ assert.doesNotMatch(template.content.querySelector("p").getAttribute("style"), /remote\.example/);
+ const outgoing = prepareEmailHtml(preview, { forOutgoing: true }).html;
+ for (const path of ["image", "large", "bg"]) assert.ok(outgoing.includes(`https://remote.example/${path}`));
+ assert.doesNotMatch(outgoing, /data-mailflare-(?:src|style)/);
+ assert.equal(sanitizeEditorHtml(outgoing), preview);
+});
+
+test("editor preview never includes stylesheets or loses signature markers", () => {
+ const result = sanitizeEditorHtml('<style>body{display:none}</style><div data-mailflare-signature="1">signature</div>');
+ assert.doesNotMatch(result, /<style/);
+ assert.match(result, /data-mailflare-signature="1"/);
+});
+
+test("ordinary outgoing fragments do not acquire wrappers on each edit", () => {
+ const first = prepareEmailHtml('<p><b>hello</b></p>', { forOutgoing: true }).html;
+ assert.equal(first, '<p><b>hello</b></p>');
+ assert.equal(prepareEmailHtml(first, { forOutgoing: true }).html, first);
+});
+
+test("string variables cannot indirectly trigger image-set requests before authorization", () => {
+ const source = '<style>:root{--image:"https://remote.example/variable"}.x{background:image-set(var(--image) 1x)}</style><p class="x">x</p>';
+ const blocked = prepareEmailHtml(source, { reader: true });
+ assert.equal(blocked.hasRemote, true);
+ assert.doesNotMatch(blocked.html, /background:image-set/);
+ assert.match(prepareEmailHtml(source, { reader: true, allowRemote: true }).html, /background:image-set/);
+});
+
+test("resource placeholders do not revert unrelated formatting edits", () => {
+ const preview = sanitizeEditorHtml('<p style="color:red;background:url(https://remote.example/bg)">x</p>');
+ const template = document.createElement("template");
+ template.innerHTML = preview;
+ template.content.querySelector("p").style.color = "blue";
+ const outgoing = prepareEmailHtml(template.innerHTML, { forOutgoing: true }).html;
+ assert.match(outgoing, /color:blue/);
+ assert.match(outgoing, /remote\.example\/bg/);
+});
+
+test("CID mapping does not discard the base URL used by relative resources", () => {
+ const source = '<html><head><base href="https://remote.example/assets/"></head><body><img src="logo.png"><img src="cid:logo"></body></html>';
+ const resolved = resolveEmailCidUrls(source, new Map([["logo", "/api/messages/m/attachments/a?preview=1"]]));
+ const blocked = prepareEmailHtml(resolved, { reader: true });
+ assert.equal(blocked.hasRemote, true);
+ assert.doesNotMatch(blocked.html, /remote\.example/);
+ assert.match(prepareEmailHtml(resolved, { reader: true, allowRemote: true }).html, /https:\/\/remote\.example\/assets\/logo.png/);
+});
+
+test("styled signatures are deterministic and editor copies are inert but exportable", () => {
+ const source = '<style>.signature{color:red;background:url(https://remote.example/bg)}</style><p class="signature">signature</p>';
+ const outgoing = prepareEmailHtml(source, { forOutgoing: true }).html;
+ assert.equal(prepareEmailHtml(source, { forOutgoing: true }).html, outgoing);
+ const preview = sanitizeEditorHtml(outgoing);
+ assert.doesNotMatch(preview, /<style/);
+ assert.match(preview, /data-mailflare-sheet/);
+ assert.match(prepareEmailHtml(preview, { forOutgoing: true }).html, /\.signature\{color:red;background:url\(https:\/\/remote.example\/bg\)/);
+ assert.equal(sanitizeEditorHtml(prepareEmailHtml(preview, { forOutgoing: true }).html), preview);
+});