commit
inital commit
diff --git a/.dev.vars.example b/.dev.vars.example
new file mode 100644
index 0000000..b72d53a
--- /dev/null
+++ b/.dev.vars.example
@@ -0,0 +1,13 @@
+RESEND_API_KEY=
+RESEND_WEBHOOK_SECRET=
+SEND_FROM=
+COOKIE_SECURE=false
+OIDC_ISSUER=
+OIDC_CLIENT_ID=
+OIDC_CLIENT_SECRET=
+OIDC_REDIRECT_URI=
+OIDC_SCOPE=openid profile email
+OIDC_POST_LOGOUT_REDIRECT_URI=
+VAPID_PUBLIC_KEY=
+VAPID_PRIVATE_KEY=
+VAPID_SUBJECT=mailto:[email protected]
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..cdfbe7a
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,5 @@
+node_modules/
+.wrangler/
+.dev.vars
+dist/
+*.log
diff --git a/bun.lock b/bun.lock
new file mode 100644
index 0000000..3d8ee90
--- /dev/null
+++ b/bun.lock
@@ -0,0 +1,220 @@
+{
+ "lockfileVersion": 2,
+ "configVersion": 1,
+ "workspaces": {
+ "": {
+ "name": "doughminaiton-inbox",
+ "dependencies": {
+ "hono": "^4.13.5",
+ "jose": "^6.2.10",
+ "resend": "^6.24.0",
+ },
+ "devDependencies": {
+ "@cloudflare/workers-types": "^5.20260827.0",
+ "typescript": "^5.9.3",
+ "wrangler": "^4.127.0",
+ },
+ },
+ },
+ "packages": {
+ "@cloudflare/kv-asset-handler": ["@cloudflare/[email protected]", "", {}, "sha512-jxQYkj8dSIzc0cD6cMMNdOc1UVjqSqu8BZdor5s8cGjW2I8BjODt/kWPVdY+u9zj3ms75Q5qaZgnxUad83+eAg=="],
+
+ "@cloudflare/unenv-preset": ["@cloudflare/[email protected]", "", { "peerDependencies": { "unenv": "2.0.0-rc.24", "workerd": ">1.20260305.0 <2.0.0-0" }, "optionalPeers": ["workerd"] }, "sha512-ECxObrMfyTl5bhQf/lZCXwo5G6xX9IAUo+nDMKK4SZ8m4Jvvxp52vilxyySSWh2YTZz8+HQ07qGH/2rEom1vDw=="],
+
+ "@cloudflare/workerd-darwin-64": ["@cloudflare/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-8UsGGY8ZUiYHOWdsxBlNsGmaHBGArVwJ3CM4nWpfBhthjjYe4M/OqrTpqKF7NNWb63qQiv1d8Z+Z6/hmUqNKIQ=="],
+
+ "@cloudflare/workerd-darwin-arm64": ["@cloudflare/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-0bLqVQYsQ3v3FdYGmzh23vi9fJeYTBx19o4LUySIsRcgBggGSlR39ml162vTXvZzUISOjVW2qfL7Y+SMrrfXmQ=="],
+
+ "@cloudflare/workerd-linux-64": ["@cloudflare/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-DTC0yWzybX4gUH5Q1pJo3UwEQjp0Gmz0Q71I+39xT9SXBesX5QndOIQv45yHQ86Z84EzK2WwaENdlpmDSvJKmw=="],
+
+ "@cloudflare/workerd-linux-arm64": ["@cloudflare/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-PFerWi+DP2Ckc6eATAS4dhotBt8IeXJjTzIgy18H+uqsswlXc7A8HsnAunHL9v/7/BjCgq46iMo2g4iUAsEpDw=="],
+
+ "@cloudflare/workerd-windows-64": ["@cloudflare/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-X26hulrG2MSSfpRmjZbCq98LNaZnrRqbmGcgo7g1U/U0nJ5npYruPm3fAyZ2y6VDr5CmQo9BLCahxP8VB/QR6A=="],
+
+ "@cloudflare/workers-types": ["@cloudflare/[email protected]", "", {}, "sha512-L5wIIHcgy67AAfe8nNmfcRHLBtO+2jva14zx1HxH2tunlteNmQvo4nYtcfef1n1MKXu3Z3xB98Fvl1BorkjFtg=="],
+
+ "@cspotcode/source-map-support": ["@cspotcode/[email protected]", "", { "dependencies": { "@jridgewell/trace-mapping": "0.3.9" } }, "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw=="],
+
+ "@emnapi/runtime": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="],
+
+ "@esbuild/aix-ppc64": ["@esbuild/[email protected]", "", { "os": "aix", "cpu": "ppc64" }, "sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ=="],
+
+ "@esbuild/android-arm": ["@esbuild/[email protected]", "", { "os": "android", "cpu": "arm" }, "sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ=="],
+
+ "@esbuild/android-arm64": ["@esbuild/[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg=="],
+
+ "@esbuild/android-x64": ["@esbuild/[email protected]", "", { "os": "android", "cpu": "x64" }, "sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng=="],
+
+ "@esbuild/darwin-arm64": ["@esbuild/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q=="],
+
+ "@esbuild/darwin-x64": ["@esbuild/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ=="],
+
+ "@esbuild/freebsd-arm64": ["@esbuild/[email protected]", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw=="],
+
+ "@esbuild/freebsd-x64": ["@esbuild/[email protected]", "", { "os": "freebsd", "cpu": "x64" }, "sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ=="],
+
+ "@esbuild/linux-arm": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ=="],
+
+ "@esbuild/linux-arm64": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g=="],
+
+ "@esbuild/linux-ia32": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "ia32" }, "sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w=="],
+
+ "@esbuild/linux-loong64": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg=="],
+
+ "@esbuild/linux-mips64el": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ=="],
+
+ "@esbuild/linux-ppc64": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "ppc64" }, "sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ=="],
+
+ "@esbuild/linux-riscv64": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ=="],
+
+ "@esbuild/linux-s390x": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "s390x" }, "sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag=="],
+
+ "@esbuild/linux-x64": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA=="],
+
+ "@esbuild/netbsd-arm64": ["@esbuild/[email protected]", "", { "os": "none", "cpu": "arm64" }, "sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw=="],
+
+ "@esbuild/netbsd-x64": ["@esbuild/[email protected]", "", { "os": "none", "cpu": "x64" }, "sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg=="],
+
+ "@esbuild/openbsd-arm64": ["@esbuild/[email protected]", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q=="],
+
+ "@esbuild/openbsd-x64": ["@esbuild/[email protected]", "", { "os": "openbsd", "cpu": "x64" }, "sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw=="],
+
+ "@esbuild/openharmony-arm64": ["@esbuild/[email protected]", "", { "os": "none", "cpu": "arm64" }, "sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg=="],
+
+ "@esbuild/sunos-x64": ["@esbuild/[email protected]", "", { "os": "sunos", "cpu": "x64" }, "sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ=="],
+
+ "@esbuild/win32-arm64": ["@esbuild/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA=="],
+
+ "@esbuild/win32-ia32": ["@esbuild/[email protected]", "", { "os": "win32", "cpu": "ia32" }, "sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg=="],
+
+ "@esbuild/win32-x64": ["@esbuild/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A=="],
+
+ "@img/colour": ["@img/[email protected]", "", {}, "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ=="],
+
+ "@img/sharp-darwin-arm64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-arm64": "1.3.1" }, "os": "darwin", "cpu": "arm64" }, "sha512-eEieHsMksAW4IiO5NzauESRl2D2qz3J/kwUxUrSfV06A93eEaRfMpHXyUb1mAqrR7i8U9A0GRqE9pjn6u1Jjpg=="],
+
+ "@img/sharp-darwin-x64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-x64": "1.3.1" }, "os": "darwin", "cpu": "x64" }, "sha512-BaktuGPCeHJMARpodR8jK4uKiZrPAy9WrfQW0sdI37clracq8Bp01AYS3SZgi5FS/y5twa9t4+LIuuxQjqRrWw=="],
+
+ "@img/sharp-freebsd-wasm32": ["@img/[email protected]", "", { "dependencies": { "@img/sharp-wasm32": "0.35.2" }, "os": "freebsd" }, "sha512-YoAxdnd8hPUkvLHd3bWY+YA8nw3xM/RyRopYucNsWHVSan8NLVM3X2volsfoRDcXdUJPg6tXahSd7HXPK7lRnw=="],
+
+ "@img/sharp-libvips-darwin-arm64": ["@img/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-4V/M3roRMTYjiwZY9IOVQOE8OyeCxFAkYmyZDrZl51uOKjibm3oeEJ4WAmLxutAfzFbC9jqUiPs2gbnGflH+7g=="],
+
+ "@img/sharp-libvips-darwin-x64": ["@img/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-c0/DxItpJv2+dGhgycJBBgotdqruGYDvA79drdh0MD1dFpy7JzJ/PlXwi1H4rFf0eTy8tgbI91aHDnZIceY3jQ=="],
+
+ "@img/sharp-libvips-linux-arm": ["@img/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-aGGy9aWzXgHBG7HNyQPWorZthlp7+x6fDRoPAQbGO3ThcttuTyKIx3NuSHb6zb4gBNq6/yNn9f1cy9nFKS/Vmg=="],
+
+ "@img/sharp-libvips-linux-arm64": ["@img/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-JznefmcK9j1JKPz8AkQDh89kjojubyfOasWBPKfzMIhPwsgDy9evpE/naJTXXXmghS1iFwR8u/kTwh/I2/+GCw=="],
+
+ "@img/sharp-libvips-linux-ppc64": ["@img/[email protected]", "", { "os": "linux", "cpu": "ppc64" }, "sha512-1EkwGNCZk6iWNCMWqrvdJ+r1j0PT1zIz60CNPhYnJlK/zyeWqlsPZIe+ocBVqPF8k/Ssee/NCk+tE9Ryrko6ng=="],
+
+ "@img/sharp-libvips-linux-riscv64": ["@img/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-Ilays+w2bXdnxzxtQdmXR62u8o8GYa3eL4+Gr+1KiE4xperMZUslRaVPJwwPkzlHEjGfXAfRVAa/7CYCtSqsBw=="],
+
+ "@img/sharp-libvips-linux-s390x": ["@img/[email protected]", "", { "os": "linux", "cpu": "s390x" }, "sha512-VfBwVHQTbRoj4XlpA/KLZ7ltgMpz+4WSejFzQ+GnoImjo1PtEJ59QB2qR1xQEeRPYIkNrPIm2L4cICMvz4C2ew=="],
+
+ "@img/sharp-libvips-linux-x64": ["@img/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-+c8ukgwU62DS54nCAjw7keOfHUkmr0B5QHEdcOqRnodF/MNXJbVI8Eopoj4B/0H8Asr65I+A4Amrn7a85/md6A=="],
+
+ "@img/sharp-libvips-linuxmusl-arm64": ["@img/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-qlKb/pwbkAi1WMsJrYHk7CuDrd12s27U2QnRhFYUoJNrRCmkosMTttuRFat/DDB3IlDm5qE1TJgZ4JDnHX8Ldw=="],
+
+ "@img/sharp-libvips-linuxmusl-x64": ["@img/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-yO21HwoUVLN8Qa+/SBjQLMYwBWAVJjeGPNe+hc0OUeMeifEtJqu5a1c4HayE1nNpDih9y3/KkoltfkDodmKAlg=="],
+
+ "@img/sharp-linux-arm": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm": "1.3.1" }, "os": "linux", "cpu": "arm" }, "sha512-SE4kzF2mepn6z+6E7L6lsV8FzuLL6IPQdyX8ZiwROAG/G8td+hP/m7FsFPwidtrF19gvajuC9l6TxAVcsA4S7A=="],
+
+ "@img/sharp-linux-arm64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm64": "1.3.1" }, "os": "linux", "cpu": "arm64" }, "sha512-af12Pnd0ZGu2HfP8NayB0kk6eC/lrfbQE6HlR4jD+34wdJ1Vw9TF6TMn6ZvffT+WgqVsl0hRbmNvz2u/23VmwA=="],
+
+ "@img/sharp-linux-ppc64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-ppc64": "1.3.1" }, "os": "linux", "cpu": "ppc64" }, "sha512-hYSBm7zcNtDCozCxQHYZJiu63b/bXsgRZuOxCIBZsStMM9Vap47iFHdbX4kCvQsblPB/k+clhELpdQJHQLSHvg=="],
+
+ "@img/sharp-linux-riscv64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-riscv64": "1.3.1" }, "os": "linux", "cpu": "none" }, "sha512-qQt0Kc13+Hoan/Awq/qMSQw3L+RI1NCRPgD5cUJ/1WSSmIoysLOc72jlRM3E0OHN9Yr313jgeQ2T+zW+F03QFA=="],
+
+ "@img/sharp-linux-s390x": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-s390x": "1.3.1" }, "os": "linux", "cpu": "s390x" }, "sha512-E4fLLfRPzDLlEeDaTzI98OFLcv++WL5ChLLMwPoVd0CIoZQqupBSNbOisPL5am9XsbQ9T84+iiMpUvbFtkunbA=="],
+
+ "@img/sharp-linux-x64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-x64": "1.3.1" }, "os": "linux", "cpu": "x64" }, "sha512-gi0zFJJRLswfCZmHtJdikXPOc5u7qamSOS3NHedLqLd4W8Q0NqjdBr6TTRIgsfFjqfTsHFgdfvJ9LwqSgcHiAA=="],
+
+ "@img/sharp-linuxmusl-arm64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-arm64": "1.3.1" }, "os": "linux", "cpu": "arm64" }, "sha512-siWbOW1u6HFnFLrp0waKyW7VEf7jYvcDWdrXEFa8AkdAQgEvuu5Fz8/Y70w9EeqAdwDtfU012BhEHHaDqvQNzg=="],
+
+ "@img/sharp-linuxmusl-x64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-x64": "1.3.1" }, "os": "linux", "cpu": "x64" }, "sha512-YBqMMcjDi4QGYiSn4vNOYBhmlC4z5AXqkOUUqI2e0AFA4urNv4ESgOgwNl3K+4etQhha0twXlzeF20bbULm9Yg=="],
+
+ "@img/sharp-wasm32": ["@img/[email protected]", "", { "dependencies": { "@emnapi/runtime": "^1.11.1" } }, "sha512-Mrv4JQNYVQ94xH+jzZ9r+gowleN8mv2FTgKT+PI6bx5C0G8TdNYndu161pg2i7uoBwxy2ImPMHrJOM2LZef7Bw=="],
+
+ "@img/sharp-webcontainers-wasm32": ["@img/[email protected]", "", { "dependencies": { "@img/sharp-wasm32": "0.35.2" }, "cpu": "none" }, "sha512-QNV27pxs9wpApEiCfvHM1RDoP1w1+2KrUWWDPEhEwg+latvOrfuhWrHWZKwdSFwU6jh3myjw/yOCRsUIuOft3g=="],
+
+ "@img/sharp-win32-arm64": ["@img/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-BiVRYc/t6/Vl3e1hBx0hugG4oN9Pydf4fgMSpxTQJmwGUg/YoXTWHiFeRymHfCZzifxu4F4rpk/I67D0LQ20wQ=="],
+
+ "@img/sharp-win32-ia32": ["@img/[email protected]", "", { "os": "win32", "cpu": "ia32" }, "sha512-YYEhx9PImCC7T0tI8JDMi4DB9LwLCXCU5OWNYEXAxh5Q1ShKkyC6byxzoBJ3gEFDnH2lQckWuDe70G7mB2XJog=="],
+
+ "@img/sharp-win32-x64": ["@img/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-imoOyBcoM/iiUr4J6VPpCNjPnjvP/Gks95898yB8YqoGGYmHYbOyCuNv9FMhFgtaiHFGbHW8bxKqRV6VjtXThQ=="],
+
+ "@jridgewell/resolve-uri": ["@jridgewell/[email protected]", "", {}, "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw=="],
+
+ "@jridgewell/sourcemap-codec": ["@jridgewell/[email protected]", "", {}, "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og=="],
+
+ "@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.0.3", "@jridgewell/sourcemap-codec": "^1.4.10" } }, "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ=="],
+
+ "@poppinss/colors": ["@poppinss/[email protected]", "", { "dependencies": { "kleur": "^4.1.5" } }, "sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg=="],
+
+ "@poppinss/dumper": ["@poppinss/[email protected]", "", { "dependencies": { "@poppinss/colors": "^4.1.5", "@sindresorhus/is": "^7.0.2", "supports-color": "^10.0.0" } }, "sha512-NBdYIb90J7LfOI32dOewKI1r7wnkiH6m920puQ3qHUeZkxNkQiFnXVWoE6YtFSv6QOiPPf7ys6i+HWWecDz7sw=="],
+
+ "@poppinss/exception": ["@poppinss/[email protected]", "", {}, "sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw=="],
+
+ "@sindresorhus/is": ["@sindresorhus/[email protected]", "", {}, "sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw=="],
+
+ "@speed-highlight/core": ["@speed-highlight/[email protected]", "", {}, "sha512-qeW2e1l78afw8VhRPfPQ1Gjj+KU5XFQ/OFV5ti6eTa9bruO7mJyZtA4vw0ofqmA3tKCkROE9xLk3VZoeRc98nw=="],
+
+ "@stablelib/base64": ["@stablelib/[email protected]", "", {}, "sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ=="],
+
+ "blake3-wasm": ["[email protected]", "", {}, "sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g=="],
+
+ "cookie": ["[email protected]", "", {}, "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ=="],
+
+ "detect-libc": ["[email protected]", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="],
+
+ "error-stack-parser-es": ["[email protected]", "", {}, "sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA=="],
+
+ "esbuild": ["[email protected]", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.28.1", "@esbuild/android-arm": "0.28.1", "@esbuild/android-arm64": "0.28.1", "@esbuild/android-x64": "0.28.1", "@esbuild/darwin-arm64": "0.28.1", "@esbuild/darwin-x64": "0.28.1", "@esbuild/freebsd-arm64": "0.28.1", "@esbuild/freebsd-x64": "0.28.1", "@esbuild/linux-arm": "0.28.1", "@esbuild/linux-arm64": "0.28.1", "@esbuild/linux-ia32": "0.28.1", "@esbuild/linux-loong64": "0.28.1", "@esbuild/linux-mips64el": "0.28.1", "@esbuild/linux-ppc64": "0.28.1", "@esbuild/linux-riscv64": "0.28.1", "@esbuild/linux-s390x": "0.28.1", "@esbuild/linux-x64": "0.28.1", "@esbuild/netbsd-arm64": "0.28.1", "@esbuild/netbsd-x64": "0.28.1", "@esbuild/openbsd-arm64": "0.28.1", "@esbuild/openbsd-x64": "0.28.1", "@esbuild/openharmony-arm64": "0.28.1", "@esbuild/sunos-x64": "0.28.1", "@esbuild/win32-arm64": "0.28.1", "@esbuild/win32-ia32": "0.28.1", "@esbuild/win32-x64": "0.28.1" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw=="],
+
+ "fast-sha256": ["[email protected]", "", {}, "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ=="],
+
+ "fsevents": ["[email protected]", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
+
+ "hono": ["[email protected]", "", {}, "sha512-O6+/eCYRkzzzy0rPWwKLiGBR1nFuUPZynnwjxN1MBA62NNqbT0wQEzQyK2gSO5yDIDB336sXQleAhOHrzlYyKw=="],
+
+ "jose": ["[email protected]", "", {}, "sha512-iiW7J9qRFlGxvCOIBDBDxFePQSn7ZMAnrYGhrrOo6siO/MIqwfyilLR27pkfDgUk+raLuzADS8A3S/KLBisc0g=="],
+
+ "kleur": ["[email protected]", "", {}, "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ=="],
+
+ "miniflare": ["[email protected]", "", { "dependencies": { "@cspotcode/source-map-support": "0.8.1", "sharp": "0.35.2", "undici": "7.29.0", "workerd": "1.20260826.1", "ws": "8.21.0", "youch": "4.1.0-beta.10" } }, "sha512-ZXR3Bieg+B5MK0T/zYIWaZiCGCb9Z3en4+/TleYKhIGPLx/e0cRcG/ZvvTviUapVBBK2zODB+aiypdIojU3x6Q=="],
+
+ "path-to-regexp": ["[email protected]", "", {}, "sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ=="],
+
+ "pathe": ["[email protected]", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="],
+
+ "postal-mime": ["[email protected]", "", {}, "sha512-GNEXKvWFQnbgO5NlrGzVa0FmWzBZ24PersAWErttSg1Hjpf0ATxTwS5DOMGaOpTG6bUh5cTr7xi0jAD942wCJA=="],
+
+ "resend": ["[email protected]", "", { "dependencies": { "postal-mime": "2.7.5", "standardwebhooks": "1.0.0" }, "peerDependencies": { "@react-email/render": "*" }, "optionalPeers": ["@react-email/render"] }, "sha512-ZG+tRzTtg3usrzMMVK1THPILCDbxE0uefG3XEQro/+jb9hcRb8JiQeyzIo2BphMJk2OomBeciZU3rCgX3XWx5w=="],
+
+ "semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="],
+
+ "sharp": ["[email protected]", "", { "dependencies": { "@img/colour": "^1.1.0", "detect-libc": "^2.1.2", "semver": "^7.8.4" }, "optionalDependencies": { "@img/sharp-darwin-arm64": "0.35.2", "@img/sharp-darwin-x64": "0.35.2", "@img/sharp-freebsd-wasm32": "0.35.2", "@img/sharp-libvips-darwin-arm64": "1.3.1", "@img/sharp-libvips-darwin-x64": "1.3.1", "@img/sharp-libvips-linux-arm": "1.3.1", "@img/sharp-libvips-linux-arm64": "1.3.1", "@img/sharp-libvips-linux-ppc64": "1.3.1", "@img/sharp-libvips-linux-riscv64": "1.3.1", "@img/sharp-libvips-linux-s390x": "1.3.1", "@img/sharp-libvips-linux-x64": "1.3.1", "@img/sharp-libvips-linuxmusl-arm64": "1.3.1", "@img/sharp-libvips-linuxmusl-x64": "1.3.1", "@img/sharp-linux-arm": "0.35.2", "@img/sharp-linux-arm64": "0.35.2", "@img/sharp-linux-ppc64": "0.35.2", "@img/sharp-linux-riscv64": "0.35.2", "@img/sharp-linux-s390x": "0.35.2", "@img/sharp-linux-x64": "0.35.2", "@img/sharp-linuxmusl-arm64": "0.35.2", "@img/sharp-linuxmusl-x64": "0.35.2", "@img/sharp-webcontainers-wasm32": "0.35.2", "@img/sharp-win32-arm64": "0.35.2", "@img/sharp-win32-ia32": "0.35.2", "@img/sharp-win32-x64": "0.35.2" } }, "sha512-FVtFjtBCMiJS6yb5CX7Sop45WFMpeGw6oRKuJnXYgf/f1ms/D7LE/ZUSNxnW7rZ/dbslQWYkoqFHGPaDBtaK4w=="],
+
+ "standardwebhooks": ["[email protected]", "", { "dependencies": { "@stablelib/base64": "^1.0.0", "fast-sha256": "^1.3.0" } }, "sha512-BbHGOQK9olHPMvQNHWul6MYlrRTAOKn03rOe4A8O3CLWhNf4YHBqq2HJKKC+sfqpxiBY52pNeesD6jIiLDz8jg=="],
+
+ "supports-color": ["[email protected]", "", {}, "sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g=="],
+
+ "tslib": ["[email protected]", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
+
+ "typescript": ["[email protected]", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
+
+ "undici": ["[email protected]", "", {}, "sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw=="],
+
+ "unenv": ["[email protected]", "", { "dependencies": { "pathe": "^2.0.3" } }, "sha512-i7qRCmY42zmCwnYlh9H2SvLEypEFGye5iRmEMKjcGi7zk9UquigRjFtTLz0TYqr0ZGLZhaMHl/foy1bZR+Cwlw=="],
+
+ "workerd": ["[email protected]", "", { "optionalDependencies": { "@cloudflare/workerd-darwin-64": "1.20260826.1", "@cloudflare/workerd-darwin-arm64": "1.20260826.1", "@cloudflare/workerd-linux-64": "1.20260826.1", "@cloudflare/workerd-linux-arm64": "1.20260826.1", "@cloudflare/workerd-windows-64": "1.20260826.1" }, "bin": { "workerd": "bin/workerd" } }, "sha512-oTG9ot5zxO9OjjKCskt86+nVrBL0kiUqExHnYaTg4OCkHf/K4zr+9hYvgwmG8DdCWG0TQGErHzD+1h50TM5b+w=="],
+
+ "wrangler": ["[email protected]", "", { "dependencies": { "@cloudflare/kv-asset-handler": "0.5.0", "@cloudflare/unenv-preset": "2.16.1", "blake3-wasm": "2.1.5", "esbuild": "0.28.1", "miniflare": "5.20260826.0-alpha", "path-to-regexp": "6.3.0", "unenv": "2.0.0-rc.24", "workerd": "1.20260826.1" }, "optionalDependencies": { "fsevents": "2.3.3" }, "peerDependencies": { "@cloudflare/workers-types": "^5.20260826.1" }, "optionalPeers": ["@cloudflare/workers-types"], "bin": { "wrangler": "bin/wrangler.js", "wrangler2": "bin/wrangler.js", "cf-wrangler": "bin/cf-wrangler.js" } }, "sha512-4dPqcBEMJfGeZeNnjHT7ThNJs+EiNYxUTg4ywqIdQubcXHBhFeVMQyHV4A9AOhZRFr83cckqdds034KGcr/dtw=="],
+
+ "ws": ["[email protected]", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g=="],
+
+ "youch": ["[email protected]", "", { "dependencies": { "@poppinss/colors": "^4.1.5", "@poppinss/dumper": "^0.6.4", "@speed-highlight/core": "^1.2.7", "cookie": "^1.0.2", "youch-core": "^0.3.3" } }, "sha512-rLfVLB4FgQneDr0dv1oddCVZmKjcJ6yX6mS4pU82Mq/Dt9a3cLZQ62pDBL4AUO+uVrCvtWz3ZFUL2HFAFJ/BXQ=="],
+
+ "youch-core": ["[email protected]", "", { "dependencies": { "@poppinss/exception": "^1.2.2", "error-stack-parser-es": "^1.0.5" } }, "sha512-ho7XuGjLaJ2hWHoK8yFnsUGy2Y5uDpqSTq1FkHLK4/oqKtyUU1AFbOOxY4IpC9f0fTLjwYbslUz0Po5BpD1wrA=="],
+ }
+}
diff --git a/lib/attachments.ts b/lib/attachments.ts
new file mode 100644
index 0000000..aa9f167
--- /dev/null
+++ b/lib/attachments.ts
@@ -0,0 +1,98 @@
+import { kv } from "./kv";
+import type { StoredAttachment } from "./store";
+
+export async function saveAttachment(
+ filename: string,
+ contentType: string,
+ base64Content: string,
+ contentId?: string | null,
+): Promise<StoredAttachment> {
+ const id = crypto.randomUUID();
+ const bytes = Buffer.from(base64Content, "base64");
+ const cid = normalizeContentId(contentId);
+ const name = filename || "attachment";
+ const type = contentType || "application/octet-stream";
+ await kv().put(`att:${id}`, bytes);
+ return { id, filename: name, contentType: type, size: bytes.length, contentId: cid };
+}
+
+async function saveAttachmentMeta(
+ filename: string,
+ contentType: string,
+ contentId: string | null,
+): Promise<StoredAttachment> {
+ const id = crypto.randomUUID();
+ const name = filename || "attachment";
+ const type = contentType || "application/octet-stream";
+ return { id, filename: name, contentType: type, size: 0, contentId };
+}
+
+export function normalizeContentId(raw: unknown): string | null {
+ if (typeof raw !== "string") return null;
+ const trimmed = raw.trim().replace(/^<|>$/g, "").trim();
+ return trimmed || null;
+}
+
+export async function readAttachment(attachmentId: string): Promise<Uint8Array | null> {
+ if (!attachmentId) return null;
+ const buf = await kv().get(`att:${attachmentId}`, "arrayBuffer");
+ return buf ? new Uint8Array(buf) : null;
+}
+
+export async function deleteAttachment(attachmentId: string): Promise<void> {
+ if (!attachmentId) return;
+ await kv().delete(`att:${attachmentId}`);
+}
+
+export async function toResendAttachment(
+ att: StoredAttachment,
+): Promise<{ filename: string; content: string } | null> {
+ const bytes = await readAttachment(att.id);
+ if (!bytes) return null;
+ return {
+ filename: att.filename,
+ content: Buffer.from(bytes).toString("base64"),
+ };
+}
+
+export async function persistInboundAttachments(attachments: unknown): Promise<StoredAttachment[]> {
+ if (!Array.isArray(attachments)) return [];
+
+ const results: StoredAttachment[] = [];
+ for (const raw of attachments) {
+ if (!raw || typeof raw !== "object") continue;
+ const a = raw as Record<string, unknown>;
+ const content = typeof a.content === "string" ? a.content : null;
+ const filename =
+ (typeof a.filename === "string" && a.filename) ||
+ (typeof a.name === "string" && a.name) ||
+ "attachment";
+ const contentType =
+ (typeof a.contentType === "string" && a.contentType) ||
+ (typeof a.content_type === "string" && a.content_type) ||
+ (typeof a.type === "string" && a.type) ||
+ "application/octet-stream";
+ const contentId = normalizeContentId(
+ (typeof a.contentId === "string" && a.contentId) ||
+ (typeof a.content_id === "string" && a.content_id) ||
+ (typeof a.cid === "string" && a.cid) ||
+ null,
+ );
+
+ if (!content) {
+ try {
+ results.push(await saveAttachmentMeta(filename, contentType, contentId));
+ } catch (err) {
+ console.error("Failed to persist inbound attachment metadata", filename, err);
+ }
+ continue;
+ }
+
+ try {
+ results.push(await saveAttachment(filename, contentType, content, contentId));
+ } catch (err) {
+ console.error("Failed to persist inbound attachment", filename, err);
+ }
+ }
+ return results;
+}
diff --git a/lib/auth.ts b/lib/auth.ts
new file mode 100644
index 0000000..5511de1
--- /dev/null
+++ b/lib/auth.ts
@@ -0,0 +1,38 @@
+import { kv } from "./kv";
+import type { Pending } from "./oidc";
+
+const SESSION_TTL_S = 60 * 60 * 24 * 7;
+const PENDING_TTL_S = 60 * 10;
+
+export async function createSession(username: string): Promise<string> {
+ const token = crypto.randomUUID();
+ await kv().put(`session:${token}`, username, { expirationTtl: SESSION_TTL_S });
+ return token;
+}
+
+export async function isValidSession(token: string | undefined): Promise<boolean> {
+ return (await sessionUser(token)) !== null;
+}
+
+export async function sessionUser(token: string | undefined): Promise<string | null> {
+ if (!token) return null;
+ return (await kv().get(`session:${token}`)) ?? null;
+}
+
+export async function destroySession(token: string | undefined): Promise<void> {
+ if (token) await kv().delete(`session:${token}`);
+}
+
+export async function savePending(p: Pending): Promise<string> {
+ const id = crypto.randomUUID();
+ await kv().put(`pending:${id}`, JSON.stringify(p), { expirationTtl: PENDING_TTL_S });
+ return id;
+}
+
+export async function takePending(id: string | undefined): Promise<Pending | null> {
+ if (!id) return null;
+ const raw = await kv().get(`pending:${id}`, "json");
+ if (!raw) return null;
+ await kv().delete(`pending:${id}`);
+ return raw as Pending;
+}
diff --git a/lib/kv.ts b/lib/kv.ts
new file mode 100644
index 0000000..8be8558
--- /dev/null
+++ b/lib/kv.ts
@@ -0,0 +1,35 @@
+export interface Env {
+ MAILBOX_KV: KVNamespace;
+ ASSETS: Fetcher;
+}
+
+let current: Env | null = null;
+
+export function setEnv(e: Env): void {
+ current = e;
+}
+
+export function env(): Env {
+ if (!current) throw new Error("Worker env not initialised");
+ return current;
+}
+
+export function kv(): KVNamespace {
+ return env().MAILBOX_KV;
+}
+
+export async function hashKey(input: string): Promise<string> {
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(input));
+ return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
+}
+
+export async function listNames(prefix: string): Promise<string[]> {
+ const out: string[] = [];
+ let cursor: string | undefined;
+ do {
+ const res: KVNamespaceListResult<unknown> = await kv().list({ prefix, cursor, limit: 1000 });
+ for (const k of res.keys) out.push(k.name);
+ cursor = res.list_complete ? undefined : res.cursor;
+ } while (cursor);
+ return out;
+}
diff --git a/lib/oidc.ts b/lib/oidc.ts
new file mode 100644
index 0000000..6e9ecd9
--- /dev/null
+++ b/lib/oidc.ts
@@ -0,0 +1,166 @@
+import { createRemoteJWKSet, jwtVerify } from "jose";
+
+const OIDC = {
+ issuer: (process.env.OIDC_ISSUER || "").replace(/\/+$/, ""),
+ clientId: process.env.OIDC_CLIENT_ID || "",
+ clientSecret: process.env.OIDC_CLIENT_SECRET || "",
+ redirectUri: process.env.OIDC_REDIRECT_URI || "",
+ scope: process.env.OIDC_SCOPE || "openid profile email",
+ postLogoutRedirectUri: process.env.OIDC_POST_LOGOUT_REDIRECT_URI || "",
+};
+
+interface Discovery {
+ issuer: string;
+ authorization_endpoint: string;
+ token_endpoint: string;
+ jwks_uri: string;
+ end_session_endpoint?: string;
+}
+
+let discovery: Discovery | null = null;
+let jwks: ReturnType<typeof createRemoteJWKSet> | null = null;
+
+async function getDiscovery(): Promise<Discovery> {
+ if (discovery && jwks) return discovery;
+
+ const url = `${OIDC.issuer}/.well-known/openid-configuration`;
+ const res = await fetch(url);
+ if (!res.ok) {
+ throw new Error(`OIDC discovery failed (${res.status}) at ${url}`);
+ }
+
+ discovery = (await res.json()) as Discovery;
+ jwks = createRemoteJWKSet(new URL(discovery.jwks_uri));
+ return discovery;
+}
+
+export async function initOidc(): Promise<void> {
+ const missing = [
+ ["OIDC_ISSUER", OIDC.issuer],
+ ["OIDC_CLIENT_ID", OIDC.clientId],
+ ["OIDC_CLIENT_SECRET", OIDC.clientSecret],
+ ["OIDC_REDIRECT_URI", OIDC.redirectUri],
+ ]
+ .filter(([, v]) => !v)
+ .map(([k]) => k);
+
+ if (missing.length) {
+ throw new Error(`Missing OIDC env vars: ${missing.join(", ")}`);
+ }
+
+ await getDiscovery();
+ console.log(`OIDC ready - issuer ${OIDC.issuer}`);
+}
+
+function b64url(bytes: Uint8Array): string {
+ let binary = "";
+ for (const b of bytes) binary += String.fromCharCode(b);
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
+}
+
+function randomToken(bytes = 32): string {
+ return b64url(crypto.getRandomValues(new Uint8Array(bytes)));
+}
+
+async function sha256(input: string): Promise<Uint8Array> {
+ return new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(input)));
+}
+
+function sanitizeUsername(name: string): string {
+ return name
+ .toLowerCase()
+ .trim()
+ .replace(/[^a-z0-9._-]/g, "-")
+ .replace(/^-+|-+$/g, "");
+}
+
+function pickUsername(claims: Record<string, unknown>): string {
+ const email = typeof claims.email === "string" ? claims.email.split("@")[0] : "";
+ const raw =
+ (typeof claims.preferred_username === "string" && claims.preferred_username) ||
+ email ||
+ (typeof claims.sub === "string" && claims.sub) ||
+ "";
+ return sanitizeUsername(String(raw));
+}
+
+export interface Pending {
+ state: string;
+ nonce: string;
+ codeVerifier: string;
+ returnTo: string;
+}
+
+export async function buildAuthUrl(returnTo: string): Promise<{ url: string; pending: Pending }> {
+ const d = await getDiscovery();
+
+ const state = randomToken();
+ const nonce = randomToken();
+ const codeVerifier = randomToken(32);
+ const codeChallenge = b64url(await sha256(codeVerifier));
+
+ const url = new URL(d.authorization_endpoint);
+ url.searchParams.set("response_type", "code");
+ url.searchParams.set("client_id", OIDC.clientId);
+ url.searchParams.set("redirect_uri", OIDC.redirectUri);
+ url.searchParams.set("scope", OIDC.scope);
+ url.searchParams.set("state", state);
+ url.searchParams.set("nonce", nonce);
+ url.searchParams.set("code_challenge", codeChallenge);
+ url.searchParams.set("code_challenge_method", "S256");
+
+ return {
+ url: url.toString(),
+ pending: { state, nonce, codeVerifier, returnTo: returnTo.startsWith("/") ? returnTo : "/inbox" },
+ };
+}
+
+export async function completeLogin(
+ code: string,
+ pending: Pending,
+): Promise<{ username: string; sub: string }> {
+ const d = await getDiscovery();
+
+ const body = new URLSearchParams({
+ grant_type: "authorization_code",
+ code,
+ redirect_uri: OIDC.redirectUri,
+ client_id: OIDC.clientId,
+ client_secret: OIDC.clientSecret,
+ code_verifier: pending.codeVerifier,
+ });
+
+ const tokenRes = await fetch(d.token_endpoint, {
+ method: "POST",
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
+ body,
+ });
+
+ if (!tokenRes.ok) {
+ const text = await tokenRes.text();
+ throw new Error(`token exchange failed (${tokenRes.status}): ${text}`);
+ }
+
+ const tokens = (await tokenRes.json()) as { id_token?: string };
+ if (!tokens.id_token) throw new Error("no id_token returned");
+
+ const { payload } = await jwtVerify(tokens.id_token, jwks!, {
+ issuer: d.issuer,
+ audience: OIDC.clientId,
+ });
+
+ if (payload.nonce !== pending.nonce) throw new Error("nonce mismatch");
+
+ const username = pickUsername(payload as Record<string, unknown>);
+ if (!username) throw new Error("no usable username in token");
+
+ return { username, sub: String(payload.sub || "") };
+}
+
+export function endSessionUrl(): string | null {
+ if (!discovery?.end_session_endpoint || !OIDC.postLogoutRedirectUri) return null;
+ const url = new URL(discovery.end_session_endpoint);
+ url.searchParams.set("post_logout_redirect_uri", OIDC.postLogoutRedirectUri);
+ url.searchParams.set("client_id", OIDC.clientId);
+ return url.toString();
+}
diff --git a/lib/owners.ts b/lib/owners.ts
new file mode 100644
index 0000000..aa0eaf8
--- /dev/null
+++ b/lib/owners.ts
@@ -0,0 +1,196 @@
+import { kv } from "./kv";
+import { bareAddress } from "./settings";
+import ownersSeed from "../owners.json";
+
+interface OwnersConfig {
+ domain: string;
+ admins: string[];
+ catchAll: string;
+ owners: Record<string, string[]>;
+}
+
+function normalize(raw: Partial<OwnersConfig>): OwnersConfig {
+ const domain = (raw.domain || "").toLowerCase();
+ const owners: Record<string, string[]> = {};
+ for (const [user, entries] of Object.entries(raw.owners || {})) {
+ owners[user.toLowerCase()] = Array.from(
+ new Set((entries || []).map((e) => e.trim().toLowerCase()).filter(Boolean)),
+ );
+ }
+ return {
+ domain,
+ admins: (raw.admins || []).map((a) => a.toLowerCase()),
+ catchAll: (raw.catchAll || "").toLowerCase(),
+ owners,
+ };
+}
+
+function loadSeed(): OwnersConfig {
+ return normalize(ownersSeed as Partial<OwnersConfig>);
+}
+
+let cfg: OwnersConfig | null = null;
+
+function state(): OwnersConfig {
+ if (!cfg) cfg = loadSeed();
+ return cfg;
+}
+
+async function save(): Promise<void> {
+ const s = state();
+ await kv().put("owners:config", JSON.stringify(s));
+}
+
+export async function initOwners(): Promise<void> {
+ const stored = (await kv().get("owners:config", "json")) as Partial<OwnersConfig> | null;
+ if (stored) {
+ cfg = normalize(stored);
+ return;
+ }
+ cfg = loadSeed();
+ await kv().put("owners:config", JSON.stringify(cfg));
+}
+
+function expand(entry: string): string {
+ const e = entry.trim().toLowerCase();
+ if (!e) return "";
+ return e.includes("@") ? e : `${e}@${state().domain}`;
+}
+
+function autoAddress(username: string): string {
+ return `${username.toLowerCase()}@${state().domain}`;
+}
+
+function knownUsers(): string[] {
+ const s = state();
+ return Array.from(new Set([...Object.keys(s.owners), ...s.admins, s.catchAll].filter(Boolean)));
+}
+
+function ownerIndex(): Map<string, string> {
+ const s = state();
+ const map = new Map<string, string>();
+ for (const user of knownUsers()) {
+ map.set(bareAddress(autoAddress(user)), user);
+ }
+ for (const [user, entries] of Object.entries(s.owners)) {
+ for (const entry of entries) map.set(bareAddress(expand(entry)), user);
+ }
+ return map;
+}
+
+export function isAdmin(username: string): boolean {
+ return state().admins.includes(username.toLowerCase());
+}
+
+export function ownerOf(address: string): string {
+ return ownerIndex().get(bareAddress(address)) ?? state().catchAll;
+}
+
+export function ownerForRecipients(recipients: string[]): string {
+ const idx = ownerIndex();
+ for (const r of recipients) {
+ const owner = idx.get(bareAddress(r));
+ if (owner) return owner;
+ }
+ return state().catchAll;
+}
+
+export function addressesFor(username: string): string[] {
+ const s = state();
+ const u = username.toLowerCase();
+ if (s.admins.includes(u)) return allAddresses();
+ const extras = (s.owners[u] ?? []).map(expand);
+ return Array.from(new Set([autoAddress(u), ...extras].filter(Boolean)));
+}
+
+export function allAddresses(): string[] {
+ return Array.from(new Set(ownerIndex().keys()));
+}
+
+export function canSendAs(username: string, address: string): boolean {
+ const bare = bareAddress(address);
+ return addressesFor(username).some((a) => bareAddress(a) === bare);
+}
+
+export function canAccessOwner(username: string, owner: string): boolean {
+ const u = username.toLowerCase();
+ return isAdmin(u) || u === (owner || "").toLowerCase();
+}
+
+export function resolveFromFor(username: string, requested?: string | null): string {
+ const owned = addressesFor(username);
+ if (requested) {
+ const bare = bareAddress(requested);
+ const match = owned.find((a) => bareAddress(a) === bare);
+ if (match) return match;
+ }
+ return owned[0] ?? "";
+}
+
+export async function ensureUser(username: string): Promise<void> {
+ const s = state();
+ const u = username.toLowerCase();
+ if (!u) return;
+ if (s.admins.includes(u) || u === s.catchAll || u in s.owners) return;
+ s.owners[u] = [];
+ await save();
+}
+
+export async function assignAddress(username: string, address: string): Promise<OwnersState> {
+ const s = state();
+ const u = username.toLowerCase();
+ const full = expand(address);
+ if (!full || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(full)) {
+ throw new Error("Invalid email address");
+ }
+ if (!(u in s.owners) && !s.admins.includes(u) && u !== s.catchAll) {
+ s.owners[u] = [];
+ }
+ for (const key of Object.keys(s.owners)) {
+ s.owners[key] = (s.owners[key] ?? []).filter(
+ (e) => bareAddress(expand(e)) !== bareAddress(full),
+ );
+ }
+ if (bareAddress(full) !== bareAddress(autoAddress(u))) {
+ (s.owners[u] ??= []).push(full);
+ }
+ await save();
+ return dashboardState();
+}
+
+export async function unassignAddress(username: string, address: string): Promise<OwnersState> {
+ const s = state();
+ const u = username.toLowerCase();
+ const bare = bareAddress(expand(address));
+ const list = s.owners[u];
+ if (list) {
+ s.owners[u] = list.filter((e) => bareAddress(expand(e)) !== bare);
+ }
+ await save();
+ return dashboardState();
+}
+
+export interface OwnersUser {
+ username: string;
+ isAdmin: boolean;
+ auto: string;
+ reserved: string[];
+ addresses: string[];
+}
+export interface OwnersState {
+ domain: string;
+ catchAll: string;
+ users: OwnersUser[];
+}
+
+export function dashboardState(): OwnersState {
+ const s = state();
+ const users = knownUsers().map((u) => ({
+ username: u,
+ isAdmin: s.admins.includes(u),
+ auto: autoAddress(u),
+ reserved: (s.owners[u] ?? []).map(expand),
+ addresses: addressesFor(u),
+ }));
+ return { domain: s.domain, catchAll: s.catchAll, users };
+}
diff --git a/lib/push.ts b/lib/push.ts
new file mode 100644
index 0000000..4f257a4
--- /dev/null
+++ b/lib/push.ts
@@ -0,0 +1,76 @@
+import { kv, hashKey, listNames } from "./kv";
+import { sendWebPush, type PushSubscription, type VapidKeys } from "./webpush";
+
+function vapid(): VapidKeys {
+ return {
+ public: process.env.VAPID_PUBLIC_KEY ?? "",
+ private: process.env.VAPID_PRIVATE_KEY ?? "",
+ subject: process.env.VAPID_SUBJECT ?? "mailto:admin@localhost",
+ };
+}
+
+export function pushConfigured(): boolean {
+ const v = vapid();
+ return Boolean(v.public && v.private);
+}
+
+export function vapidPublicKey(): string {
+ return vapid().public;
+}
+
+export type PushPayload = { title: string; body: string; url?: string; tag?: string };
+
+function isSubscription(x: unknown): x is PushSubscription {
+ if (!x || typeof x !== "object") return false;
+ const s = x as Record<string, unknown>;
+ return typeof s.endpoint === "string" && !!s.keys && typeof s.keys === "object";
+}
+
+export async function addSubscription(sub: PushSubscription): Promise<void> {
+ if (!isSubscription(sub)) throw new Error("Invalid subscription");
+ await kv().put(`push:${await hashKey(sub.endpoint)}`, JSON.stringify(sub));
+}
+
+export async function removeSubscription(endpoint: string): Promise<void> {
+ await kv().delete(`push:${await hashKey(endpoint)}`);
+}
+
+export async function listSubscriptions(): Promise<PushSubscription[]> {
+ const names = await listNames("push:");
+ const rows = await Promise.all(names.map((n) => kv().get(n, "json")));
+ return rows.filter(isSubscription);
+}
+
+export async function subscriptionCount(): Promise<number> {
+ return (await listNames("push:")).length;
+}
+
+export async function sendToAll(payload: PushPayload): Promise<{ sent: number; pruned: number }> {
+ const keys = vapid();
+ if (!keys.public || !keys.private) return { sent: 0, pruned: 0 };
+
+ const subs = await listSubscriptions();
+ const data = JSON.stringify(payload);
+ const dead: string[] = [];
+ let sent = 0;
+
+ await Promise.all(
+ subs.map(async (sub) => {
+ try {
+ const res = await sendWebPush(sub, data, keys);
+ if (res.status >= 200 && res.status < 300) {
+ sent++;
+ } else if (res.status === 404 || res.status === 410) {
+ dead.push(sub.endpoint);
+ } else {
+ console.error("Push send failed", res.status, await res.text().catch(() => ""));
+ }
+ } catch (err) {
+ console.error("Push send error", err);
+ }
+ }),
+ );
+
+ for (const endpoint of dead) await removeSubscription(endpoint);
+ return { sent, pruned: dead.length };
+}
diff --git a/lib/settings.ts b/lib/settings.ts
new file mode 100644
index 0000000..947f361
--- /dev/null
+++ b/lib/settings.ts
@@ -0,0 +1,124 @@
+import { kv } from "./kv";
+
+export type Settings = {
+ fromAddresses: string[];
+ defaultFrom: string | null;
+};
+
+export function bareAddress(input: string | undefined | null): string {
+ if (!input) return "";
+ const match = input.match(/<([^>]+)>/);
+ return (match?.[1] ? match[1] : input).trim().toLowerCase();
+}
+
+export function isValidAddress(input: string): boolean {
+ const bare = bareAddress(input);
+ return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(bare);
+}
+
+export function parseAddressList(raw: string | undefined | null): string[] {
+ if (!raw) return [];
+ return raw
+ .split(/[,\n]/)
+ .map((s) => s.trim())
+ .filter(Boolean);
+}
+
+function dedupe(list: string[]): string[] {
+ const seen = new Set<string>();
+ const out: string[] = [];
+ for (const a of list) {
+ const key = bareAddress(a);
+ if (!key || seen.has(key)) continue;
+ seen.add(key);
+ out.push(a);
+ }
+ return out;
+}
+
+function seedFromEnv(): Settings {
+ const seeded = dedupe(parseAddressList(process.env.SEND_FROM));
+ return {
+ fromAddresses: seeded,
+ defaultFrom: seeded[0] ?? null,
+ };
+}
+
+function normalize(raw: unknown): Settings {
+ const r = (raw ?? {}) as Record<string, unknown>;
+ const fromAddresses = Array.isArray(r.fromAddresses)
+ ? dedupe(r.fromAddresses.filter((x): x is string => typeof x === "string"))
+ : [];
+
+ let defaultFrom = typeof r.defaultFrom === "string" ? r.defaultFrom : null;
+ const df = defaultFrom;
+ if (df && !fromAddresses.some((a) => bareAddress(a) === bareAddress(df))) {
+ defaultFrom = null;
+ }
+ if (!defaultFrom && fromAddresses.length) defaultFrom = fromAddresses[0] ?? null;
+
+ return { fromAddresses, defaultFrom };
+}
+
+export async function getSettings(): Promise<Settings> {
+ const raw = await kv().get("settings", "json");
+ return raw ? normalize(raw) : seedFromEnv();
+}
+
+async function mutate(fn: (s: Settings) => void): Promise<Settings> {
+ const s = await getSettings();
+ fn(s);
+ const next = normalize(s);
+ await kv().put("settings", JSON.stringify(next));
+ return next;
+}
+
+export function addFromAddress(address: string): Promise<Settings> {
+ const clean = address.trim();
+ if (!isValidAddress(clean)) return Promise.reject(new Error("Invalid email address"));
+ return mutate((s) => {
+ if (!s.fromAddresses.some((a) => bareAddress(a) === bareAddress(clean))) {
+ s.fromAddresses.push(clean);
+ }
+ if (!s.defaultFrom) s.defaultFrom = s.fromAddresses[0] ?? null;
+ });
+}
+
+export function removeFromAddress(address: string): Promise<Settings> {
+ const key = bareAddress(address);
+ return mutate((s) => {
+ s.fromAddresses = s.fromAddresses.filter((a) => bareAddress(a) !== key);
+ if (s.defaultFrom && bareAddress(s.defaultFrom) === key) {
+ s.defaultFrom = s.fromAddresses[0] ?? null;
+ }
+ });
+}
+
+export function setDefaultFrom(address: string): Promise<Settings> {
+ return mutate((s) => {
+ const match = s.fromAddresses.find((a) => bareAddress(a) === bareAddress(address));
+ if (!match) throw new Error("Address is not in the list");
+ s.defaultFrom = match;
+ });
+}
+
+export async function resolveFrom(requested?: string | null): Promise<string> {
+ const s = await getSettings();
+ if (requested) {
+ const match = s.fromAddresses.find((a) => bareAddress(a) === bareAddress(requested));
+ if (match) return match;
+ }
+ if (s.defaultFrom) return s.defaultFrom;
+ if (s.fromAddresses[0]) return s.fromAddresses[0];
+ return parseAddressList(process.env.SEND_FROM)[0] ?? "";
+}
+
+export async function getMyAddresses(): Promise<string[]> {
+ const s = await getSettings();
+ const set = new Set<string>();
+ for (const a of [...s.fromAddresses, ...parseAddressList(process.env.SEND_FROM)]) {
+ const bare = bareAddress(a);
+ if (bare) set.add(bare);
+ }
+ return [...set];
+}
diff --git a/lib/store.ts b/lib/store.ts
new file mode 100644
index 0000000..026a862
--- /dev/null
+++ b/lib/store.ts
@@ -0,0 +1,224 @@
+import { kv, hashKey, listNames } from "./kv";
+import { deleteAttachment } from "./attachments";
+
+export type StoredAttachment = {
+ id: string;
+ filename: string;
+ contentType: string;
+ size: number;
+ contentId?: string | null;
+};
+
+export type Folder = "inbox" | "sent" | "drafts";
+
+export type StoredEmail = {
+ id: string;
+ from: string;
+ to: string[];
+ subject: string;
+ html: string | null;
+ text: string | null;
+ receivedAt: string;
+ attachments: StoredAttachment[];
+ direction: "inbound" | "outbound";
+ status: "sent" | "draft";
+ messageId: string | null;
+ inReplyTo: string | null;
+ references: string | null;
+ threadKey: string;
+ owner: string;
+};
+
+export type DraftInput = {
+ to: string[];
+ subject: string;
+ html: string;
+ attachments: StoredAttachment[];
+ from?: string;
+ inReplyTo?: string | null;
+ references?: string | null;
+ threadKey?: string | null;
+ owner: string;
+};
+
+type Rec = StoredEmail & { _seq: string; _inv: string };
+
+const EPOCH_CAP = 10_000_000_000_000;
+
+export function folderOf(email: Pick<StoredEmail, "direction" | "status">): Folder {
+ if (email.status === "draft") return "drafts";
+ return email.direction === "inbound" ? "inbox" : "sent";
+}
+
+function newOrder(): { seq: string; inv: string } {
+ const ms = Date.now();
+ const rand = crypto.randomUUID().replace(/-/g, "").slice(0, 8);
+ return {
+ seq: `${String(ms).padStart(13, "0")}-${rand}`,
+ inv: `${String(EPOCH_CAP - ms).padStart(13, "0")}-${rand}`,
+ };
+}
+
+function toEmail(rec: Rec): StoredEmail {
+ const { _seq, _inv, ...rest } = rec;
+ return rest;
+}
+
+async function readRecord(id: string): Promise<Rec | null> {
+ return (await kv().get(`email:${id}`, "json")) as Rec | null;
+}
+
+async function writeIndexes(rec: Rec): Promise<void> {
+ const jobs: Promise<unknown>[] = [
+ kv().put(`ix:f:${folderOf(rec)}:${rec._inv}:${rec.id}`, ""),
+ hashKey(rec.threadKey).then((h) => kv().put(`ix:t:${h}:${rec._seq}:${rec.id}`, "")),
+ ];
+ if (rec.messageId) {
+ jobs.push(hashKey(rec.messageId).then((h) => kv().put(`ix:m:${h}`, rec.id)));
+ }
+ await Promise.all(jobs);
+}
+
+async function deleteIndexes(rec: Rec): Promise<void> {
+ const jobs: Promise<unknown>[] = [
+ kv().delete(`ix:f:${folderOf(rec)}:${rec._inv}:${rec.id}`),
+ hashKey(rec.threadKey).then((h) => kv().delete(`ix:t:${h}:${rec._seq}:${rec.id}`)),
+ ];
+ if (rec.messageId) {
+ jobs.push(hashKey(rec.messageId).then((h) => kv().delete(`ix:m:${h}`)));
+ }
+ await Promise.all(jobs);
+}
+
+function idFromKey(name: string): string {
+ return name.slice(name.lastIndexOf(":") + 1);
+}
+
+export async function addEmail(email: StoredEmail): Promise<StoredEmail> {
+ const existing = await readRecord(email.id);
+ if (existing) return toEmail(existing);
+
+ const { seq, inv } = newOrder();
+ const rec: Rec = { ...email, _seq: seq, _inv: inv };
+ await kv().put(`email:${email.id}`, JSON.stringify(rec));
+ await writeIndexes(rec);
+ return email;
+}
+
+export async function listEmails(folder?: Folder, owner?: string) {
+ const prefixes = folder
+ ? [`ix:f:${folder}:`]
+ : ["ix:f:inbox:", "ix:f:sent:", "ix:f:drafts:"];
+
+ const names: string[] = [];
+ for (const p of prefixes) names.push(...(await listNames(p)));
+ names.sort();
+
+ const key = owner?.toLowerCase() ?? null;
+ const records = await Promise.all(names.map((n) => readRecord(idFromKey(n))));
+
+ const out = [];
+ for (const rec of records) {
+ if (!rec) continue;
+ if (key && rec.owner.toLowerCase() !== key) continue;
+ const { html, text, _seq, _inv, ...meta } = rec;
+ out.push(meta);
+ }
+ return out;
+}
+
+export async function getEmail(id: string): Promise<StoredEmail | null> {
+ const rec = await readRecord(id);
+ return rec ? toEmail(rec) : null;
+}
+
+export async function findByMessageId(messageId: string): Promise<StoredEmail | null> {
+ const id = await kv().get(`ix:m:${await hashKey(messageId)}`);
+ return id ? getEmail(id) : null;
+}
+
+export async function listByThreadKey(threadKey: string, owner?: string): Promise<StoredEmail[]> {
+ const names = await listNames(`ix:t:${await hashKey(threadKey)}:`);
+ const ids = [...new Set(names.map(idFromKey))];
+ const key = owner?.toLowerCase() ?? null;
+ const records = await Promise.all(ids.map(readRecord));
+
+ return records
+ .filter((rec): rec is Rec => !!rec && (!key || rec.owner.toLowerCase() === key))
+ .sort((a, b) => a.receivedAt.localeCompare(b.receivedAt))
+ .map(toEmail);
+}
+
+export async function createDraft(input: DraftInput): Promise<StoredEmail> {
+ const draft: StoredEmail = {
+ id: crypto.randomUUID(),
+ from: input.from ?? "",
+ to: input.to,
+ subject: input.subject,
+ html: input.html,
+ text: null,
+ receivedAt: new Date().toISOString(),
+ attachments: input.attachments,
+ direction: "outbound",
+ status: "draft",
+ messageId: null,
+ inReplyTo: input.inReplyTo ?? null,
+ references: input.references ?? null,
+ threadKey: input.threadKey ?? `draft::${crypto.randomUUID()}`,
+ owner: input.owner,
+ };
+ await addEmail(draft);
+ return draft;
+}
+
+export async function updateDraft(id: string, input: DraftInput): Promise<StoredEmail | null> {
+ const rec = await readRecord(id);
+ if (!rec || rec.status !== "draft") return null;
+
+ const keep = new Set(input.attachments.map((a) => a.id).filter(Boolean));
+ await Promise.all(
+ rec.attachments
+ .filter((a) => a.id && !keep.has(a.id))
+ .map((a) => deleteAttachment(a.id)),
+ );
+
+ const updated: Rec = {
+ ...rec,
+ from: input.from ?? rec.from,
+ to: input.to,
+ subject: input.subject,
+ html: input.html,
+ attachments: input.attachments,
+ receivedAt: new Date().toISOString(),
+ };
+ await kv().put(`email:${id}`, JSON.stringify(updated));
+ return toEmail(updated);
+}
+
+export async function deleteDraft(id: string): Promise<boolean> {
+ const rec = await readRecord(id);
+ if (!rec || rec.status !== "draft") return false;
+ await deleteIndexes(rec);
+ await kv().delete(`email:${id}`);
+ return true;
+}
+
+export async function deleteEmail(id: string): Promise<StoredEmail | null> {
+ const rec = await readRecord(id);
+ if (!rec) return null;
+ await deleteIndexes(rec);
+ await kv().delete(`email:${id}`);
+ return toEmail(rec);
+}
+
+export async function deleteByThreadKey(threadKey: string): Promise<StoredEmail[]> {
+ const names = await listNames(`ix:t:${await hashKey(threadKey)}:`);
+ const ids = [...new Set(names.map(idFromKey))];
+ const records = (await Promise.all(ids.map(readRecord))).filter((rec): rec is Rec => !!rec);
+ if (records.length === 0) return [];
+
+ await Promise.all(
+ records.flatMap((rec) => [deleteIndexes(rec), kv().delete(`email:${rec.id}`)]),
+ );
+ return records.map(toEmail);
+}
diff --git a/lib/webpush.ts b/lib/webpush.ts
new file mode 100644
index 0000000..8d9d936
--- /dev/null
+++ b/lib/webpush.ts
@@ -0,0 +1,183 @@
+export type PushSubscription = {
+ endpoint: string;
+ keys: { p256dh: string; auth: string };
+};
+
+export type VapidKeys = {
+ public: string;
+ private: string;
+ subject: string;
+};
+
+const textEncoder = new TextEncoder();
+
+function b64urlToBytes(input: string): Uint8Array {
+ const normalized = input.replace(/-/g, "+").replace(/_/g, "/");
+ const padded = normalized + "=".repeat((4 - (normalized.length % 4)) % 4);
+ const binary = atob(padded);
+ const out = new Uint8Array(binary.length);
+ for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
+ return out;
+}
+
+function bytesToB64url(bytes: Uint8Array): string {
+ let binary = "";
+ for (const b of bytes) binary += String.fromCharCode(b);
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
+}
+
+function concat(...parts: Uint8Array[]): Uint8Array {
+ const total = parts.reduce((n, p) => n + p.length, 0);
+ const out = new Uint8Array(total);
+ let offset = 0;
+ for (const p of parts) {
+ out.set(p, offset);
+ offset += p.length;
+ }
+ return out;
+}
+
+async function hmac(key: Uint8Array, data: Uint8Array): Promise<Uint8Array> {
+ const k = await crypto.subtle.importKey(
+ "raw",
+ key,
+ { name: "HMAC", hash: "SHA-256" },
+ false,
+ ["sign"],
+ );
+ return new Uint8Array(await crypto.subtle.sign("HMAC", k, data));
+}
+
+async function hkdf(
+ salt: Uint8Array,
+ ikm: Uint8Array,
+ info: Uint8Array,
+ length: number,
+): Promise<Uint8Array> {
+ const prk = await hmac(salt, ikm);
+ const expanded = await hmac(prk, concat(info, new Uint8Array([1])));
+ return expanded.slice(0, length);
+}
+
+async function vapidAuthorization(endpoint: string, vapid: VapidKeys): Promise<string> {
+ const url = new URL(endpoint);
+ const header = bytesToB64url(textEncoder.encode(JSON.stringify({ typ: "JWT", alg: "ES256" })));
+ const payload = bytesToB64url(
+ textEncoder.encode(
+ JSON.stringify({
+ aud: `${url.protocol}//${url.host}`,
+ exp: Math.floor(Date.now() / 1000) + 12 * 60 * 60,
+ sub: vapid.subject,
+ }),
+ ),
+ );
+ const unsigned = `${header}.${payload}`;
+
+ const pub = b64urlToBytes(vapid.public);
+ const priv = b64urlToBytes(vapid.private);
+ const jwk: JsonWebKey = {
+ kty: "EC",
+ crv: "P-256",
+ x: bytesToB64url(pub.slice(1, 33)),
+ y: bytesToB64url(pub.slice(33, 65)),
+ d: bytesToB64url(priv),
+ ext: true,
+ };
+ const key = await crypto.subtle.importKey(
+ "jwk",
+ jwk,
+ { name: "ECDSA", namedCurve: "P-256" },
+ false,
+ ["sign"],
+ );
+ const signature = new Uint8Array(
+ await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, key, textEncoder.encode(unsigned)),
+ );
+
+ return `vapid t=${unsigned}.${bytesToB64url(signature)}, k=${vapid.public}`;
+}
+
+async function encryptPayload(sub: PushSubscription, payload: string): Promise<Uint8Array> {
+ const clientPublic = b64urlToBytes(sub.keys.p256dh);
+ const authSecret = b64urlToBytes(sub.keys.auth);
+ const plaintext = textEncoder.encode(payload);
+
+ const ephemeral = (await crypto.subtle.generateKey(
+ { name: "ECDH", namedCurve: "P-256" },
+ true,
+ ["deriveBits"],
+ )) as CryptoKeyPair;
+ const ephemeralPublic = new Uint8Array(
+ (await crypto.subtle.exportKey("raw", ephemeral.publicKey)) as ArrayBuffer,
+ );
+
+ const clientKey = await crypto.subtle.importKey(
+ "raw",
+ clientPublic,
+ { name: "ECDH", namedCurve: "P-256" },
+ false,
+ [],
+ );
+ const sharedSecret = new Uint8Array(
+ await crypto.subtle.deriveBits(
+ { name: "ECDH", public: clientKey } as unknown as SubtleCryptoDeriveKeyAlgorithm,
+ ephemeral.privateKey,
+ 256,
+ ),
+ );
+
+ const keyInfo = concat(
+ textEncoder.encode("WebPush: info\0"),
+ clientPublic,
+ ephemeralPublic,
+ );
+ const ikm = await hkdf(authSecret, sharedSecret, keyInfo, 32);
+
+ const salt = crypto.getRandomValues(new Uint8Array(16));
+ const cek = await hkdf(salt, ikm, textEncoder.encode("Content-Encoding: aes128gcm\0"), 16);
+ const nonce = await hkdf(salt, ikm, textEncoder.encode("Content-Encoding: nonce\0"), 12);
+
+ const aesKey = await crypto.subtle.importKey("raw", cek, { name: "AES-GCM" }, false, ["encrypt"]);
+ const ciphertext = new Uint8Array(
+ await crypto.subtle.encrypt(
+ { name: "AES-GCM", iv: nonce },
+ aesKey,
+ concat(plaintext, new Uint8Array([2])),
+ ),
+ );
+
+ const recordSize = 4096;
+ const header = concat(
+ salt,
+ new Uint8Array([
+ (recordSize >>> 24) & 0xff,
+ (recordSize >>> 16) & 0xff,
+ (recordSize >>> 8) & 0xff,
+ recordSize & 0xff,
+ ]),
+ new Uint8Array([ephemeralPublic.length]),
+ ephemeralPublic,
+ );
+
+ return concat(header, ciphertext);
+}
+
+export async function sendWebPush(
+ sub: PushSubscription,
+ payload: string,
+ vapid: VapidKeys,
+): Promise<Response> {
+ const body = await encryptPayload(sub, payload);
+ const authorization = await vapidAuthorization(sub.endpoint, vapid);
+
+ return fetch(sub.endpoint, {
+ method: "POST",
+ headers: {
+ Authorization: authorization,
+ "Content-Encoding": "aes128gcm",
+ "Content-Type": "application/octet-stream",
+ TTL: "2419200",
+ },
+ body,
+ });
+}
diff --git a/owners.json b/owners.json
new file mode 100644
index 0000000..9d72237
--- /dev/null
+++ b/owners.json
@@ -0,0 +1,9 @@
+{
+ "domain": "doughmination.win",
+ "admins": ["clove"],
+ "catchAll": "clove",
+ "owners": {
+ "clove": ["admin", "ctf", "universal-credit", "clove"],
+ "ari": ["ari"]
+ }
+}
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..5cc9aa6
--- /dev/null
+++ b/package.json
@@ -0,0 +1,20 @@
+{
+ "name": "doughminaiton-inbox",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "dev": "wrangler dev",
+ "deploy": "wrangler deploy",
+ "typecheck": "tsc --noEmit"
+ },
+ "devDependencies": {
+ "@cloudflare/workers-types": "^5.20260827.0",
+ "typescript": "^5.9.3",
+ "wrangler": "^4.127.0"
+ },
+ "dependencies": {
+ "hono": "^4.13.5",
+ "jose": "^6.2.10",
+ "resend": "^6.24.0"
+ }
+}
diff --git a/public/app.js b/public/app.js
new file mode 100644
index 0000000..602a2c9
--- /dev/null
+++ b/public/app.js
@@ -0,0 +1,805 @@
+/* mailbox/public/app.js
+ * Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+ * Licensed under the DASL-1.0 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+const listEl = document.getElementById("list");
+const detailEl = document.getElementById("detailContent");
+const backBtn = document.getElementById("backBtn");
+const layoutEl = document.querySelector(".layout");
+const composeModal = document.getElementById("composeModal");
+const composeForm = document.getElementById("composeForm");
+const composeError = document.getElementById("composeError");
+const composeTitle = composeForm.querySelector("h2");
+const messageLabel = composeForm.html.closest("label");
+const attachmentsInput = composeForm.attachments;
+const attachmentListEl = document.getElementById("attachmentList");
+const attachmentWarning = document.getElementById("attachmentWarning");
+const saveDraftBtn = document.getElementById("saveDraftBtn");
+const deleteDraftBtn = document.getElementById("deleteDraftBtn");
+const folderNav = document.getElementById("folderNav");
+const lightbox = document.getElementById("lightbox");
+const lightboxImg = document.getElementById("lightboxImg");
+const fromRow = document.getElementById("fromRow");
+const fromSelect = composeForm.from;
+const toastHost = document.getElementById("toastHost");
+
+let emails = [];
+let activeId = null;
+let activeFolder = "inbox";
+// Messages of the thread currently open in the detail pane, so a per-message
+// delete can figure out whether anything is left to keep showing.
+let currentThread = [];
+// Configured send-from addresses, fetched once at startup for the compose picker.
+let fromOptions = { fromAddresses: [], defaultFrom: null };
+// Ids optimistically hidden while an undo toast is still up. Nothing is deleted
+// on the server until the toast expires, so these are just visually suppressed.
+const pendingDeleteIds = new Set();
+const UNDO_MS = 6000;
+// Resend rejects emails whose total size (all attachments) tops ~40 MB.
+const RESEND_LIMIT = 40 * 1024 * 1024;
+
+function bareAddr(s) {
+ if (!s) return "";
+ const m = String(s).match(/<([^>]+)>/);
+ return (m ? m[1] : s).trim().toLowerCase();
+}
+
+// The compose modal is reused for "new message", "reply", "forward", and
+// "edit draft". This holds whatever async submit logic applies right now.
+let currentSubmitHandler = null;
+// Set only while editing an existing draft, so Save/Delete know what to act on.
+let editingDraftId = null;
+// Attachments staged for the message currently open in the compose modal.
+let stagedAttachments = [];
+
+function fmtTime(iso) {
+ const d = new Date(iso);
+ return d.toLocaleString(undefined, {
+ month: "short",
+ day: "numeric",
+ hour: "2-digit",
+ minute: "2-digit",
+ });
+}
+
+function fmtSize(bytes) {
+ if (bytes < 1024) return `${bytes} B`;
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
+}
+
+function escapeHtml(str) {
+ const div = document.createElement("div");
+ div.textContent = str ?? "";
+ return div.innerHTML;
+}
+
+function isImageAttachment(a) {
+ return !!a.id && typeof a.contentType === "string" && a.contentType.startsWith("image/");
+}
+
+function fileToBase64(file) {
+ return new Promise((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onload = () => {
+ // dataURL looks like "data:<type>;base64,<content>" — we only want the payload
+ const result = reader.result;
+ const comma = result.indexOf(",");
+ resolve(comma === -1 ? result : result.slice(comma + 1));
+ };
+ reader.onerror = reject;
+ reader.readAsDataURL(file);
+ });
+}
+
+// Shrinks large photos in the browser before they're uploaded: downscale to a
+// sane max dimension and re-encode as JPEG. Keeps the result a normal, openable
+// image (unlike gzip, which would give the recipient a file they can't read).
+// Non-images, small images, and GIFs/HEIC that won't decode are left as-is.
+function compressImageFile(file, { maxDim = 2000, quality = 0.82, minBytes = 800 * 1024 } = {}) {
+ return new Promise((resolve) => {
+ if (!file.type.startsWith("image/") || file.type === "image/gif" || file.size <= minBytes) {
+ resolve(file);
+ return;
+ }
+ const url = URL.createObjectURL(file);
+ const img = new Image();
+ img.onload = () => {
+ URL.revokeObjectURL(url);
+ const scale = Math.min(1, maxDim / Math.max(img.width, img.height));
+ const width = Math.round(img.width * scale);
+ const height = Math.round(img.height * scale);
+ const canvas = document.createElement("canvas");
+ canvas.width = width;
+ canvas.height = height;
+ canvas.getContext("2d").drawImage(img, 0, 0, width, height);
+ canvas.toBlob(
+ (blob) => {
+ // If re-encoding didn't actually help, keep the original.
+ if (!blob || blob.size >= file.size) {
+ resolve(file);
+ return;
+ }
+ const name = file.name.replace(/\.[^.]+$/, "") + ".jpg";
+ resolve(new File([blob], name, { type: "image/jpeg" }));
+ },
+ "image/jpeg",
+ quality
+ );
+ };
+ img.onerror = () => {
+ // Formats the browser can't decode (often HEIC) — send them untouched.
+ URL.revokeObjectURL(url);
+ resolve(file);
+ };
+ img.src = url;
+ });
+}
+
+// Best-effort size of everything staged: uploaded refs carry a real `size`,
+// while inline-fallback items only have base64 (~4/3 of the real bytes).
+function stagedTotalBytes() {
+ return stagedAttachments.reduce((sum, a) => {
+ if (typeof a.size === "number") return sum + a.size;
+ if (typeof a.content === "string") return sum + Math.floor(a.content.length * 0.75);
+ return sum;
+ }, 0);
+}
+
+function updateAttachmentWarning() {
+ if (!attachmentWarning) return;
+ const total = stagedTotalBytes();
+ if (total > RESEND_LIMIT) {
+ attachmentWarning.textContent = `Attachments total ${fmtSize(total)} — over the 40 MB email limit, so this will likely bounce. Remove a file or split it across two emails.`;
+ attachmentWarning.classList.remove("hidden");
+ } else if (total > RESEND_LIMIT * 0.6) {
+ attachmentWarning.textContent = `Attachments total ${fmtSize(total)} — getting close to the 40 MB email limit.`;
+ attachmentWarning.classList.remove("hidden");
+ } else {
+ attachmentWarning.classList.add("hidden");
+ }
+}
+
+function pathForFolder(folder) {
+ return `/${folder}`;
+}
+
+function folderForPath(pathname) {
+ const clean = pathname.replace(/\/+$/, "");
+ if (clean === "/sent") return "sent";
+ if (clean === "/drafts") return "drafts";
+ return "inbox"; // covers "/" and "/inbox"
+}
+
+function setActiveFolderButton(folder) {
+ folderNav.querySelectorAll(".folder-item").forEach((b) => {
+ b.classList.toggle("active", b.dataset.folder === folder);
+ });
+}
+
+function goToFolder(folder, { push = true } = {}) {
+ setActiveFolderButton(folder);
+ activeId = null;
+ detailEl.innerHTML = '<p class="muted">Select an email to read it.</p>';
+ layoutEl.classList.remove("show-detail");
+ if (push) history.pushState(null, "", pathForFolder(folder));
+ loadEmails(folder);
+}
+
+async function loadEmails(folder = activeFolder) {
+ activeFolder = folder;
+ const res = await fetch(`/api/emails?folder=${encodeURIComponent(folder)}`);
+ emails = await res.json();
+ renderList();
+}
+
+function renderList() {
+ const visible = emails.filter((e) => !pendingDeleteIds.has(e.id));
+ if (visible.length === 0) {
+ listEl.innerHTML = '<p class="muted">Nothing here.</p>';
+ return;
+ }
+
+ listEl.innerHTML = visible
+ .map(
+ (e) => `
+ <div class="list-item ${e.id === activeId ? "active" : ""}" data-id="${e.id}">
+ <div class="list-item-main">
+ <div class="from">${escapeHtml(activeFolder === "drafts" ? (e.to || []).join(", ") || "(no recipient)" : e.from)}</div>
+ <div class="subject">${escapeHtml(e.subject || "(no subject)")}</div>
+ <div class="time">${fmtTime(e.receivedAt)}</div>
+ </div>
+ <button class="row-delete" data-id="${e.id}" title="Delete" aria-label="Delete">✕</button>
+ </div>
+ `
+ )
+ .join("");
+
+ listEl.querySelectorAll(".list-item").forEach((el) => {
+ el.addEventListener("click", () => {
+ if (activeFolder === "drafts") {
+ openDraft(el.dataset.id);
+ } else {
+ openEmail(el.dataset.id);
+ }
+ });
+ });
+
+ listEl.querySelectorAll(".row-delete").forEach((btn) => {
+ btn.addEventListener("click", (ev) => {
+ ev.stopPropagation(); // don't also open the email
+ deleteMessage(btn.dataset.id);
+ });
+ });
+}
+
+function attachmentsHtml(email) {
+ if (!email.attachments || email.attachments.length === 0) return "";
+
+ // Images the server already stitched into the body (cid: inline) are flagged
+ // `inline` — don't repeat them here.
+ const shown = email.attachments.filter((a) => !a.inline);
+ const images = shown.filter(isImageAttachment);
+ const files = shown.filter((a) => !isImageAttachment(a));
+
+ let html = "";
+
+ if (images.length) {
+ const thumbs = images
+ .map((a) => {
+ const url = `/api/emails/${email.id}/attachments/${a.id}?inline=1`;
+ return `<a class="image-thumb" href="${url}" data-full="${url}" title="${escapeHtml(a.filename)}">
+ <img src="${url}" alt="${escapeHtml(a.filename)}" loading="lazy" />
+ </a>`;
+ })
+ .join("");
+ html += `<div class="image-grid">${thumbs}</div>`;
+ }
+
+ if (files.length) {
+ const items = files
+ .map((a) =>
+ a.id
+ ? `<li><a class="file-download" href="/api/emails/${email.id}/attachments/${a.id}" data-url="/api/emails/${email.id}/attachments/${a.id}" data-name="${escapeHtml(a.filename)}" download="${escapeHtml(a.filename)}">${escapeHtml(a.filename)}</a> <span class="muted-inline">(${fmtSize(a.size)})</span></li>`
+ : `<li>${escapeHtml(a.filename)} <span class="muted-inline">(unavailable)</span></li>`
+ )
+ .join("");
+ html += `<ul class="attachment-list">${items}</ul>`;
+ }
+
+ return html;
+}
+
+async function openEmail(id) {
+ activeId = id;
+ renderList();
+ layoutEl.classList.add("show-detail");
+
+ const res = await fetch(`/api/emails/${id}/thread`);
+ if (!res.ok) {
+ detailEl.innerHTML = '<p class="muted">Could not load this email.</p>';
+ return;
+ }
+ const thread = await res.json();
+ currentThread = thread;
+ const last = thread[thread.length - 1];
+
+ const messagesHtml = thread
+ .map(
+ (email) => `
+ <article class="message">
+ <div class="msg-head">
+ <span class="dir-badge ${email.direction}">${email.direction === "inbound" ? "received" : "sent"}</span>
+ <strong>${escapeHtml(email.from)}</strong>
+ <span class="muted-inline">to ${escapeHtml((email.to || []).join(", "))}</span>
+ <button class="msg-delete" data-id="${email.id}" title="Delete this message" aria-label="Delete this message">🗑</button>
+ </div>
+ <div class="meta">${fmtTime(email.receivedAt)}</div>
+ <div class="body">
+ ${email.html ?? `<pre style="white-space: pre-wrap;">${escapeHtml(email.text ?? "(empty message)")}</pre>`}
+ </div>
+ ${attachmentsHtml(email)}
+ </article>
+ `
+ )
+ .join("");
+
+ detailEl.innerHTML = `
+ ${messagesHtml}
+ <div class="thread-actions">
+ <button class="btn-accent" id="replyBtn">Reply</button>
+ <button class="btn-ghost" id="forwardBtn">Forward</button>
+ <button class="btn-danger" id="deleteThreadBtn">Delete conversation</button>
+ </div>
+ `;
+
+ document.getElementById("replyBtn").addEventListener("click", () => openReply(last));
+ document.getElementById("forwardBtn").addEventListener("click", () => openForward(last));
+ document.getElementById("deleteThreadBtn").addEventListener("click", () => deleteThread(id));
+
+ detailEl.querySelectorAll(".msg-delete").forEach((btn) => {
+ btn.addEventListener("click", () => deleteMessage(btn.dataset.id));
+ });
+
+ detailEl.querySelectorAll(".image-thumb").forEach((thumb) => {
+ thumb.addEventListener("click", (ev) => {
+ ev.preventDefault();
+ openLightbox(thumb.dataset.full);
+ });
+ });
+
+ detailEl.querySelectorAll(".file-download").forEach((link) => {
+ link.addEventListener("click", (ev) => {
+ ev.preventDefault();
+ downloadFile(link.dataset.url, link.dataset.name);
+ });
+ });
+}
+
+// iOS and installed (standalone) PWAs ignore the <a download> attribute — a tap
+// just does nothing. So fetch the bytes ourselves and trigger the save via an
+// object URL; if that's blocked, fall back to opening the file in a new tab so
+// the OS viewer's share/save sheet can take over.
+async function downloadFile(url, filename) {
+ try {
+ const res = await fetch(url, { credentials: "same-origin" });
+ if (!res.ok) throw new Error("download failed");
+ const blob = await res.blob();
+ const objUrl = URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = objUrl;
+ a.download = filename || "download";
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+ setTimeout(() => URL.revokeObjectURL(objUrl), 10000);
+ } catch (_) {
+ window.open(url, "_blank");
+ }
+}
+
+async function openDraft(id) {
+ activeId = id;
+ renderList();
+ layoutEl.classList.add("show-detail");
+
+ const draft = emails.find((e) => e.id === id);
+ if (!draft) return;
+
+ // Draft list items omit html/text (list endpoint strips bodies), so fetch the full record.
+ const res = await fetch(`/api/emails/${id}/thread`).catch(() => null);
+ // Drafts aren't part of a real thread; fall back to what we already have if this 404s.
+ const full = res && res.ok ? (await res.json())[0] : draft;
+
+ editingDraftId = id;
+ stagedAttachments = full.attachments ?? [];
+ openComposeModal({
+ title: "Edit draft",
+ toValue: (full.to || []).join(", "),
+ subjectValue: full.subject ?? "",
+ htmlValue: full.html ?? "",
+ fromPreferred: full.from || null,
+ subjectReadOnly: false,
+ showMessage: true,
+ showDeleteDraft: true,
+ submitHandler: (fields) => sendDraft(id, fields),
+ });
+}
+
+function renderAttachmentList() {
+ updateAttachmentWarning();
+ if (stagedAttachments.length === 0) {
+ attachmentListEl.innerHTML = "";
+ return;
+ }
+ attachmentListEl.innerHTML = stagedAttachments
+ .map((a, i) => `<li>${escapeHtml(a.filename)} <span class="muted-inline">(${fmtSize(a.size ?? a.content?.length ?? 0)})</span> <button type="button" data-idx="${i}" class="btn-ghost remove-attachment">Remove</button></li>`)
+ .join("");
+ attachmentListEl.querySelectorAll(".remove-attachment").forEach((btn) => {
+ btn.addEventListener("click", () => {
+ stagedAttachments.splice(Number(btn.dataset.idx), 1);
+ renderAttachmentList();
+ });
+ });
+}
+
+attachmentsInput.addEventListener("change", async () => {
+ const files = Array.from(attachmentsInput.files ?? []);
+ for (const rawFile of files) {
+ // Shrink big photos before doing anything else with them.
+ const file = await compressImageFile(rawFile);
+ const content = await fileToBase64(file);
+ // Upload each file on its own right away, so the eventual send/draft
+ // request only carries a small reference (id) instead of every file's
+ // base64 at once. That keeps requests under the proxy's size limit — the
+ // reason attaching several files used to fail while a single one worked.
+ try {
+ const res = await fetch("/api/uploads", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ filename: file.name, contentType: file.type, content }),
+ });
+ if (res.ok) {
+ stagedAttachments.push(await res.json());
+ continue;
+ }
+ } catch (_) {
+ /* fall through to inline content below */
+ }
+ // Fallback: keep the bytes inline so send still works if upload failed.
+ stagedAttachments.push({
+ filename: file.name,
+ contentType: file.type,
+ content,
+ size: file.size,
+ });
+ }
+ attachmentsInput.value = "";
+ renderAttachmentList();
+});
+
+// Fills the From <select> from the configured addresses. Hides the whole row
+// when nothing is configured (the server then falls back to its default/env).
+function populateFromSelect(preferred) {
+ if (!fromSelect) return;
+ const list = fromOptions.fromAddresses || [];
+ if (list.length === 0) {
+ fromSelect.innerHTML = "";
+ fromRow.style.display = "none";
+ return;
+ }
+ fromRow.style.display = "";
+ const match = preferred && list.find((a) => bareAddr(a) === bareAddr(preferred));
+ const selected = match || fromOptions.defaultFrom || list[0];
+ fromSelect.innerHTML = list
+ .map(
+ (a) =>
+ `<option value="${escapeHtml(a)}"${bareAddr(a) === bareAddr(selected) ? " selected" : ""}>${escapeHtml(a)}</option>`
+ )
+ .join("");
+}
+
+// For replies/forwards, prefer sending from whichever of our addresses the
+// original message actually involved.
+function preferredFromFor(email) {
+ const list = fromOptions.fromAddresses || [];
+ const candidates = email.direction === "inbound" ? email.to || [] : [email.from];
+ for (const c of candidates) {
+ const m = list.find((a) => bareAddr(a) === bareAddr(c));
+ if (m) return m;
+ }
+ return null;
+}
+
+function openComposeModal({
+ title,
+ toValue,
+ subjectValue,
+ htmlValue,
+ fromPreferred,
+ subjectReadOnly,
+ showMessage,
+ showDeleteDraft,
+ submitHandler,
+}) {
+ composeError.classList.add("hidden");
+ composeForm.reset();
+ composeTitle.textContent = title;
+ composeForm.to.value = toValue ?? "";
+ composeForm.subject.value = subjectValue ?? "";
+ composeForm.html.value = htmlValue ?? "";
+ composeForm.subject.readOnly = !!subjectReadOnly;
+ messageLabel.style.display = showMessage ? "" : "none";
+ composeForm.html.required = showMessage;
+ deleteDraftBtn.classList.toggle("hidden", !showDeleteDraft);
+ currentSubmitHandler = submitHandler;
+ if (!showDeleteDraft) editingDraftId = null;
+ populateFromSelect(fromPreferred);
+ renderAttachmentList();
+ composeModal.classList.remove("hidden");
+}
+
+function currentFields() {
+ return {
+ to: composeForm.to.value,
+ subject: composeForm.subject.value,
+ html: composeForm.html.value,
+ from: fromSelect && fromRow.style.display !== "none" ? fromSelect.value : undefined,
+ attachments: stagedAttachments,
+ };
+}
+
+function openNewMessage() {
+ editingDraftId = null;
+ stagedAttachments = [];
+ openComposeModal({
+ title: "New message",
+ toValue: "",
+ subjectValue: "",
+ htmlValue: "",
+ subjectReadOnly: false,
+ showMessage: true,
+ submitHandler: (fields) =>
+ fetch("/api/send", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ to: fields.to,
+ from: fields.from,
+ subject: fields.subject,
+ html: `<p>${escapeHtml(fields.html).replace(/\n/g, "<br>")}</p>`,
+ attachments: fields.attachments,
+ }),
+ }),
+ });
+}
+
+function openReply(email) {
+ const replyTo = email.direction === "inbound" ? email.from : (email.to || [])[0] ?? "";
+ editingDraftId = null;
+ stagedAttachments = [];
+ openComposeModal({
+ title: "Reply",
+ toValue: replyTo,
+ subjectValue: /^\s*re\s*:/i.test(email.subject) ? email.subject : `Re: ${email.subject}`,
+ htmlValue: "",
+ fromPreferred: preferredFromFor(email),
+ subjectReadOnly: false,
+ showMessage: true,
+ submitHandler: (fields) =>
+ fetch(`/api/emails/${email.id}/reply`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ to: fields.to,
+ from: fields.from,
+ html: `<p>${escapeHtml(fields.html).replace(/\n/g, "<br>")}</p>`,
+ attachments: fields.attachments,
+ }),
+ }),
+ });
+}
+
+function openForward(email) {
+ editingDraftId = null;
+ stagedAttachments = [];
+ openComposeModal({
+ title: "Forward",
+ toValue: "",
+ subjectValue: /^\s*fwd?\s*:/i.test(email.subject) ? email.subject : `Fwd: ${email.subject}`,
+ htmlValue: "",
+ fromPreferred: preferredFromFor(email),
+ subjectReadOnly: true,
+ showMessage: false,
+ submitHandler: (fields) =>
+ fetch(`/api/emails/${email.id}/forward`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ to: composeForm.to.value, from: fields.from }),
+ }),
+ });
+}
+
+async function sendDraft(id, fields) {
+ // Make sure any edits (including attachments just added) are persisted
+ // before asking the server to send — /api/drafts/:id/send uses whatever
+ // is already saved, it doesn't take a body.
+ await fetch(`/api/drafts/${id}`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ to: fields.to,
+ from: fields.from,
+ subject: fields.subject,
+ html: `<p>${escapeHtml(fields.html).replace(/\n/g, "<br>")}</p>`,
+ attachments: fields.attachments,
+ }),
+ });
+
+ return fetch(`/api/drafts/${id}/send`, { method: "POST" });
+}
+
+async function saveDraft() {
+ const fields = currentFields();
+ const payload = JSON.stringify({
+ to: fields.to,
+ from: fields.from,
+ subject: fields.subject,
+ html: fields.html,
+ attachments: fields.attachments,
+ });
+
+ const res = editingDraftId
+ ? await fetch(`/api/drafts/${editingDraftId}`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: payload,
+ })
+ : await fetch("/api/drafts", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: payload,
+ });
+
+ if (!res.ok) {
+ composeError.textContent = "Couldn't save draft.";
+ composeError.classList.remove("hidden");
+ return;
+ }
+
+ composeModal.classList.add("hidden");
+ if (activeFolder === "drafts") loadEmails();
+}
+
+async function deleteDraftAndClose() {
+ if (!editingDraftId) return;
+ await fetch(`/api/drafts/${editingDraftId}`, { method: "DELETE" });
+ composeModal.classList.add("hidden");
+ closeDetail();
+ loadEmails();
+}
+
+function closeDetail() {
+ activeId = null;
+ currentThread = [];
+ layoutEl.classList.remove("show-detail");
+ detailEl.innerHTML = '<p class="muted">Select an email to read it.</p>';
+}
+
+// Delete is optimistic + undoable: we hide the affected rows immediately and
+// only hit the server once the toast times out. Undo just cancels — so nothing
+// is actually removed on the server during the grace window.
+function deleteMessage(id) {
+ performUndoableDelete([id], "Message deleted", () =>
+ fetch(`/api/emails/${id}`, { method: "DELETE" })
+ );
+}
+
+function deleteThread(id) {
+ const ids = currentThread.length ? currentThread.map((m) => m.id) : [id];
+ performUndoableDelete(ids, "Conversation deleted", () =>
+ fetch(`/api/emails/${id}/thread`, { method: "DELETE" })
+ );
+}
+
+function performUndoableDelete(ids, message, commit) {
+ ids.forEach((x) => pendingDeleteIds.add(x));
+
+ // If the open detail shows anything we're removing, close it for now.
+ if (ids.includes(activeId) || currentThread.some((m) => ids.includes(m.id))) {
+ closeDetail();
+ }
+ renderList();
+ showUndoToast(message, ids, commit);
+}
+
+function showUndoToast(message, ids, commit) {
+ const el = document.createElement("div");
+ el.className = "toast";
+
+ const span = document.createElement("span");
+ span.textContent = message;
+
+ const undoBtn = document.createElement("button");
+ undoBtn.className = "toast-undo";
+ undoBtn.textContent = "Undo";
+
+ el.append(span, undoBtn);
+ toastHost.appendChild(el);
+
+ let settled = false;
+ const settle = async (undo) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ el.classList.add("leaving");
+ setTimeout(() => el.remove(), 200);
+
+ if (undo) {
+ ids.forEach((x) => pendingDeleteIds.delete(x));
+ await loadEmails();
+ } else {
+ try {
+ await commit();
+ } catch (_) {
+ /* If the real delete fails, the next poll will just show it again. */
+ }
+ ids.forEach((x) => pendingDeleteIds.delete(x));
+ await loadEmails();
+ }
+ };
+
+ undoBtn.addEventListener("click", () => settle(true));
+ const timer = setTimeout(() => settle(false), UNDO_MS);
+}
+
+function openLightbox(src) {
+ if (!src) return;
+ lightboxImg.src = src;
+ lightbox.classList.remove("hidden");
+}
+
+function closeLightbox() {
+ lightbox.classList.add("hidden");
+ lightboxImg.src = "";
+}
+
+document.getElementById("composeBtn").addEventListener("click", openNewMessage);
+
+backBtn.addEventListener("click", () => {
+ layoutEl.classList.remove("show-detail");
+});
+
+document.getElementById("logoutBtn").addEventListener("click", async () => {
+ await fetch("/api/logout", { method: "POST" });
+ window.location.href = "/login";
+});
+
+document.getElementById("cancelBtn").addEventListener("click", () => {
+ composeModal.classList.add("hidden");
+});
+
+saveDraftBtn.addEventListener("click", saveDraft);
+deleteDraftBtn.addEventListener("click", deleteDraftAndClose);
+
+lightbox.addEventListener("click", closeLightbox);
+document.addEventListener("keydown", (ev) => {
+ if (ev.key === "Escape" && !lightbox.classList.contains("hidden")) closeLightbox();
+});
+
+folderNav.querySelectorAll(".folder-item").forEach((btn) => {
+ btn.addEventListener("click", () => goToFolder(btn.dataset.folder));
+});
+
+window.addEventListener("popstate", () => {
+ goToFolder(folderForPath(location.pathname), { push: false });
+});
+
+composeForm.addEventListener("submit", async (ev) => {
+ ev.preventDefault();
+ if (!currentSubmitHandler) return;
+
+ const fields = currentFields();
+ const res = await currentSubmitHandler(fields);
+
+ if (!res.ok) {
+ const err = await res.json().catch(() => ({}));
+ composeError.textContent = err.error ?? "That didn't go through.";
+ composeError.classList.remove("hidden");
+ return;
+ }
+
+ // Sending a draft removes it from disk server-side; make sure we don't
+ // try to resave it as a draft if the modal gets reopened before a reload.
+ if (editingDraftId) editingDraftId = null;
+
+ composeModal.classList.add("hidden");
+ loadEmails();
+ if (activeId && activeFolder !== "drafts") openEmail(activeId);
+});
+
+// Load the configured send-from addresses for the compose picker.
+async function loadFromOptions() {
+ try {
+ const res = await fetch("/api/settings");
+ if (res.ok) fromOptions = await res.json();
+ } catch (_) {
+ /* Leave defaults; compose just hides the From row. */
+ }
+}
+
+// Register the push service worker so notifications work once the user opts in
+// from Settings. Registration itself is silent and permission-free.
+if ("serviceWorker" in navigator) {
+ navigator.serviceWorker.register("/sw.js").catch(() => {});
+}
+
+const initialFolder = folderForPath(location.pathname);
+setActiveFolderButton(initialFolder);
+// Normalize "/" to "/inbox" in the address bar without adding a history entry.
+history.replaceState(null, "", pathForFolder(initialFolder));
+loadFromOptions();
+loadEmails(initialFolder);
+// Poll for new mail every 15s — simple and good enough for a personal inbox
+setInterval(() => loadEmails(), 15000);
\ No newline at end of file
diff --git a/public/apple-touch-icon.png b/public/apple-touch-icon.png
new file mode 100644
index 0000000..fa7ac1b
Binary files /dev/null and b/public/apple-touch-icon.png differ
diff --git a/public/favicon.ico b/public/favicon.ico
new file mode 100644
index 0000000..d4f056c
Binary files /dev/null and b/public/favicon.ico differ
diff --git a/public/index.html b/public/index.html
new file mode 100644
index 0000000..90ce733
--- /dev/null
+++ b/public/index.html
@@ -0,0 +1,102 @@
+<!-- mailbox/public/index.html
+ Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+ Licensed under the DASL-1.0 Licence.
+ See LICENCE.md in the project root for full licence information. -->
+<!-- mailbox/public/index.html -->
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <meta name="theme-color" content="#0a0b10" />
+ <meta name="apple-mobile-web-app-capable" content="yes" />
+ <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
+ <title>Inbox</title>
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
+ <link rel="manifest" href="/manifest.webmanifest" />
+ <link rel="stylesheet" href="/style.css" />
+</head>
+<body>
+ <div class="app">
+ <header class="topbar">
+ <h1>Inbox</h1>
+ <div class="topbar-right">
+ <button id="composeBtn" class="btn-accent">New message</button>
+ <a href="/settings" class="btn-ghost">Settings</a>
+ <button id="logoutBtn" class="btn-ghost">Log out</button>
+ </div>
+ </header>
+
+ <div class="layout">
+ <nav id="folderNav" class="folder-nav">
+ <button class="folder-item active" data-folder="inbox">Inbox</button>
+ <button class="folder-item" data-folder="sent">Sent</button>
+ <button class="folder-item" data-folder="drafts">Drafts</button>
+ </nav>
+
+ <aside id="list" class="list">
+ <p class="muted">Loading…</p>
+ </aside>
+
+ <main id="detail" class="detail">
+ <button id="backBtn" class="back-btn hidden">‹ Back to list</button>
+ <div id="detailContent">
+ <p class="muted">Select an email to read it.</p>
+ </div>
+ </main>
+ </div>
+ </div>
+
+ <div id="composeModal" class="modal hidden">
+ <form id="composeForm" class="compose">
+ <h2>New message</h2>
+
+ <label id="fromRow" style="display: none">
+ From
+ <select name="from"></select>
+ </label>
+
+ <label>
+ To
+ <input name="to" type="email" required />
+ </label>
+
+ <label>
+ Subject
+ <input name="subject" type="text" required />
+ </label>
+
+ <label>
+ Message
+ <textarea name="html" rows="8" required></textarea>
+ </label>
+
+ <label>
+ Attachments
+ <input name="attachments" type="file" multiple />
+ </label>
+ <ul id="attachmentList" class="attachment-list"></ul>
+ <p id="attachmentWarning" class="warn hidden"></p>
+
+ <p id="composeError" class="error hidden"></p>
+
+ <div class="actions">
+ <button type="button" id="deleteDraftBtn" class="btn-ghost hidden">Delete draft</button>
+ <button type="button" id="saveDraftBtn" class="btn-ghost">Save draft</button>
+ <button type="button" id="cancelBtn" class="btn-ghost">Cancel</button>
+ <button type="submit" class="btn-accent">Send</button>
+ </div>
+ </form>
+ </div>
+
+ <div id="lightbox" class="lightbox hidden">
+ <img id="lightboxImg" src="" alt="" />
+ </div>
+
+ <div id="toastHost" class="toast-host"></div>
+
+ <script src="/app.js"></script>
+ <script src="/sfx.js"></script>
+</body>
+</html>
\ No newline at end of file
diff --git a/public/login.html b/public/login.html
new file mode 100644
index 0000000..ead2683
--- /dev/null
+++ b/public/login.html
@@ -0,0 +1,38 @@
+<!-- mailbox/public/login.html
+ Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+ Licensed under the DASL-1.0 Licence.
+ See LICENCE.md in the project root for full licence information. -->
+<!-- mailbox/public/login.html -->
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>Sign in — Inbox</title>
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="Inbox" />
+ <meta property="og:title" content="Inbox" />
+ <meta property="og:description" content="Clove Twilight's private mailbox." />
+ <meta property="og:url" content="https://doughmination.tech" />
+ <meta property="og:image" content="https://m.doughmination.gay/img/avatars/favicon.png" />
+ <meta name="twitter:card" content="summary" />
+ <meta name="twitter:title" content="Inbox" />
+ <meta name="twitter:description" content="Clove Twilight's private mailbox." />
+ <meta name="twitter:image" content="https://m.doughmination.gay/img/avatars/favicon.png" />
+ <meta name="theme-color" content="#f5a9b8" />
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
+ <link rel="stylesheet" href="/style.css" />
+</head>
+<body class="login-body">
+ <div class="compose login-card">
+ <h2>Sign in</h2>
+ <p>Use your passkey to sign in to the inbox.</p>
+
+ <div class="actions">
+ <a href="/auth/login" class="btn-accent">🔑 Sign in with SSO</a>
+ </div>
+ </div>
+ <script src="/sfx.js"></script>
+</body>
+</html>
diff --git a/public/login.js b/public/login.js
new file mode 100644
index 0000000..fe9cde8
--- /dev/null
+++ b/public/login.js
@@ -0,0 +1,39 @@
+/* mailbox/public/login.js
+ * Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+ * Licensed under the DASL-1.0 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+const form = document.getElementById("loginForm");
+const errorEl = document.getElementById("loginError");
+
+form.addEventListener("submit", async (ev) => {
+ ev.preventDefault();
+ errorEl.classList.add("hidden");
+
+ const formData = new FormData(form);
+
+ const res = await fetch("/api/login", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ username: formData.get("username"),
+ password: formData.get("password"),
+ // Turnstile injects this hidden field into the widget's container div
+ // once a challenge is solved.
+ turnstileToken: formData.get("cf-turnstile-response"),
+ // Honeypot — should always be empty for a real visitor.
+ website: formData.get("website"),
+ }),
+ });
+
+ if (!res.ok) {
+ const err = await res.json().catch(() => ({}));
+ errorEl.textContent = err.error ?? "Sign in failed.";
+ errorEl.classList.remove("hidden");
+ // Turnstile tokens are single-use — get a fresh one for the next attempt.
+ if (window.turnstile) window.turnstile.reset();
+ return;
+ }
+
+ window.location.href = "/";
+});
\ No newline at end of file
diff --git a/public/manifest.webmanifest b/public/manifest.webmanifest
new file mode 100644
index 0000000..0b9e8c2
--- /dev/null
+++ b/public/manifest.webmanifest
@@ -0,0 +1,18 @@
+{
+ "name": "Inbox",
+ "short_name": "Inbox",
+ "description": "Personal mailbox",
+ "start_url": "/inbox",
+ "scope": "/",
+ "display": "standalone",
+ "background_color": "#1e1e2e",
+ "theme_color": "#1e1e2e",
+ "icons": [
+ {
+ "src": "/apple-touch-icon.png",
+ "sizes": "180x180",
+ "type": "image/png",
+ "purpose": "any"
+ }
+ ]
+}
diff --git a/public/settings.html b/public/settings.html
new file mode 100644
index 0000000..9d1a675
--- /dev/null
+++ b/public/settings.html
@@ -0,0 +1,87 @@
+<!-- mailbox/public/settings.html
+ Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+ Licensed under the DASL-1.0 Licence.
+ See LICENCE.md in the project root for full licence information. -->
+<!-- mailbox/public/settings.html -->
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <meta name="theme-color" content="#0a0b10" />
+ <meta name="apple-mobile-web-app-capable" content="yes" />
+ <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
+ <title>Settings</title>
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
+ <link rel="manifest" href="/manifest.webmanifest" />
+ <link rel="stylesheet" href="/style.css" />
+</head>
+<body>
+ <div class="app">
+ <header class="topbar">
+ <h1>Settings</h1>
+ <div class="topbar-right">
+ <a href="/inbox" class="btn-ghost">‹ Inbox</a>
+ <button id="logoutBtn" class="btn-ghost">Log out</button>
+ </div>
+ </header>
+
+ <main class="settings-page">
+ <!-- Send-from addresses (read-only; managed via reservations) -->
+ <section class="settings-card">
+ <h2>Your addresses</h2>
+ <p class="settings-hint">
+ Addresses you can send as. Everyone owns their own
+ <code>[email protected]</code>; extra addresses are reserved
+ for you by an admin below.
+ </p>
+
+ <ul id="fromList" class="from-list">
+ <li class="muted">Loading…</li>
+ </ul>
+ </section>
+
+ <!-- Address reservations (admin only) -->
+ <section class="settings-card hidden" id="ownersCard">
+ <h2>Address reservations</h2>
+ <p class="settings-hint">
+ Reserve extra addresses for a user. Each user always keeps their own
+ <code>[email protected]</code>. Unreserved mail goes to the
+ catch-all owner.
+ </p>
+
+ <div id="ownersList" class="from-list"><span class="muted">Loading…</span></div>
+
+ <form id="assignForm" class="add-from">
+ <input id="assignUser" type="text" placeholder="username (e.g. clove)" autocomplete="off" />
+ <input id="assignAddr" type="text" placeholder="address or local-part (e.g. ctf)" autocomplete="off" />
+ <button type="submit" class="btn-accent">Reserve</button>
+ </form>
+ <p id="ownersError" class="error hidden"></p>
+ </section>
+
+ <!-- Notifications -->
+ <section class="settings-card">
+ <h2>Push notifications</h2>
+ <p class="settings-hint">
+ Get a notification on this device when new mail arrives. On iPhone/iPad
+ you must first add this site to your Home Screen (Share → Add to Home
+ Screen), open it from there, then enable notifications.
+ </p>
+
+ <div id="pushStatus" class="push-status muted">Checking…</div>
+
+ <div class="push-actions">
+ <button id="pushToggleBtn" class="btn-accent" disabled>Enable notifications</button>
+ <button id="pushTestBtn" class="btn-ghost hidden">Send test</button>
+ </div>
+ <p id="pushError" class="error hidden"></p>
+ </section>
+ </main>
+ </div>
+
+ <script src="/settings.js"></script>
+ <script src="/sfx.js"></script>
+</body>
+</html>
diff --git a/public/settings.js b/public/settings.js
new file mode 100644
index 0000000..4421ac2
--- /dev/null
+++ b/public/settings.js
@@ -0,0 +1,291 @@
+/* mailbox/public/settings.js
+ * Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+ * Licensed under the DASL-1.0 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+// --- Settings page logic: send-from addresses + Web Push enrolment ---
+
+const fromListEl = document.getElementById("fromList");
+
+// Admin reservations panel
+const ownersCard = document.getElementById("ownersCard");
+const ownersListEl = document.getElementById("ownersList");
+const assignForm = document.getElementById("assignForm");
+const assignUser = document.getElementById("assignUser");
+const assignAddr = document.getElementById("assignAddr");
+const ownersError = document.getElementById("ownersError");
+
+const pushStatusEl = document.getElementById("pushStatus");
+const pushToggleBtn = document.getElementById("pushToggleBtn");
+const pushTestBtn = document.getElementById("pushTestBtn");
+const pushError = document.getElementById("pushError");
+
+function escapeHtml(str) {
+ const div = document.createElement("div");
+ div.textContent = str ?? "";
+ return div.innerHTML;
+}
+
+function bareAddr(s) {
+ if (!s) return "";
+ const m = String(s).match(/<([^>]+)>/);
+ return (m ? m[1] : s).trim().toLowerCase();
+}
+
+// --- Your addresses (read-only) ---
+
+function renderFromList(settings) {
+ const list = settings.fromAddresses || [];
+ if (list.length === 0) {
+ fromListEl.innerHTML = '<li class="muted">No addresses yet.</li>';
+ return;
+ }
+ fromListEl.innerHTML = list
+ .map(
+ (addr) => `
+ <li class="from-row">
+ <span class="from-addr">${escapeHtml(addr)}</span>
+ </li>`,
+ )
+ .join("");
+}
+
+async function loadSettings() {
+ const res = await fetch("/api/settings");
+ renderFromList(await res.json());
+}
+
+// --- Address reservations (admin only) ---
+
+function showOwnersError(msg) {
+ ownersError.textContent = msg;
+ ownersError.classList.remove("hidden");
+}
+
+function renderOwners(state) {
+ const users = state.users || [];
+ ownersListEl.innerHTML = users
+ .map((u) => {
+ const auto = `<span class="from-addr" title="Automatic — can't be removed">${escapeHtml(u.auto)}</span>`;
+ const extras = (u.reserved || [])
+ .map(
+ (addr) => `
+ <span class="from-addr">
+ ${escapeHtml(addr)}
+ <button class="btn-ghost owner-remove" data-user="${escapeHtml(u.username)}" data-addr="${escapeHtml(addr)}">✕</button>
+ </span>`,
+ )
+ .join("");
+ const badge = u.isAdmin ? ' <span class="muted">(admin — sees all)</span>' : "";
+ return `
+ <div class="from-row" style="flex-direction:column;align-items:flex-start;gap:4px">
+ <strong>${escapeHtml(u.username)}${badge}</strong>
+ <div style="display:flex;flex-wrap:wrap;gap:6px">${auto}${extras}</div>
+ </div>`;
+ })
+ .join("");
+
+ ownersListEl.querySelectorAll(".owner-remove").forEach((btn) => {
+ btn.addEventListener("click", () => unassign(btn.dataset.user, btn.dataset.addr));
+ });
+}
+
+async function loadOwners() {
+ const res = await fetch("/api/owners");
+ if (!res.ok) return; // 403 for non-admins — leave the panel hidden
+ ownersCard.classList.remove("hidden");
+ renderOwners(await res.json());
+}
+
+async function assign(username, address) {
+ ownersError.classList.add("hidden");
+ const res = await fetch("/api/owners/assign", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ username, address }),
+ });
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ showOwnersError(data.error || "Couldn't reserve that address.");
+ return;
+ }
+ renderOwners(data);
+ assignUser.value = "";
+ assignAddr.value = "";
+}
+
+async function unassign(username, address) {
+ const res = await fetch("/api/owners/unassign", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ username, address }),
+ });
+ if (res.ok) renderOwners(await res.json());
+}
+
+assignForm.addEventListener("submit", (ev) => {
+ ev.preventDefault();
+ const u = assignUser.value.trim();
+ const a = assignAddr.value.trim();
+ if (u && a) assign(u, a);
+});
+
+document.getElementById("logoutBtn").addEventListener("click", async () => {
+ await fetch("/api/logout", { method: "POST" });
+ window.location.href = "/login";
+});
+
+// --- Web Push ---
+
+function urlBase64ToUint8Array(base64String) {
+ const padding = "=".repeat((4 - (base64String.length % 4)) % 4);
+ const base64 = (base64String + padding).replace(/-/g, "+").replace(/_/g, "/");
+ const raw = atob(base64);
+ const out = new Uint8Array(raw.length);
+ for (let i = 0; i < raw.length; i++) out[i] = raw.charCodeAt(i);
+ return out;
+}
+
+const pushSupported =
+ "serviceWorker" in navigator && "PushManager" in window && "Notification" in window;
+
+// iOS only allows Web Push from an installed (Home Screen) PWA.
+const isIos = /iphone|ipad|ipod/i.test(navigator.userAgent);
+const isStandalone =
+ window.matchMedia("(display-mode: standalone)").matches || window.navigator.standalone === true;
+
+let serverPush = { configured: false, publicKey: "", count: 0 };
+let swReg = null;
+
+function setPushStatus(msg, kind) {
+ pushStatusEl.textContent = msg;
+ pushStatusEl.className = "push-status" + (kind ? " " + kind : "");
+}
+
+function showPushError(msg) {
+ pushError.textContent = msg;
+ pushError.classList.remove("hidden");
+}
+
+async function initPush() {
+ pushError.classList.add("hidden");
+
+ if (!pushSupported) {
+ setPushStatus("This browser doesn't support notifications.", "muted");
+ pushToggleBtn.disabled = true;
+ return;
+ }
+
+ if (isIos && !isStandalone) {
+ setPushStatus(
+ "Add this site to your Home Screen first (Share → Add to Home Screen), then open it from there to enable notifications.",
+ "muted"
+ );
+ pushToggleBtn.disabled = true;
+ return;
+ }
+
+ try {
+ serverPush = await (await fetch("/api/push/status")).json();
+ } catch (_) {
+ setPushStatus("Couldn't reach the server.", "muted");
+ return;
+ }
+
+ if (!serverPush.configured) {
+ setPushStatus("Push isn't configured on the server (missing VAPID keys).", "muted");
+ pushToggleBtn.disabled = true;
+ return;
+ }
+
+ swReg = await navigator.serviceWorker.register("/sw.js");
+ await navigator.serviceWorker.ready;
+
+ const sub = await swReg.pushManager.getSubscription();
+ reflectSubscription(!!sub);
+}
+
+function reflectSubscription(isSubscribed) {
+ pushToggleBtn.disabled = false;
+ if (isSubscribed) {
+ setPushStatus("Notifications are on for this device.", "ok");
+ pushToggleBtn.textContent = "Disable notifications";
+ pushToggleBtn.classList.remove("btn-accent");
+ pushToggleBtn.classList.add("btn-ghost");
+ pushTestBtn.classList.remove("hidden");
+ } else {
+ setPushStatus("Notifications are off for this device.", "muted");
+ pushToggleBtn.textContent = "Enable notifications";
+ pushToggleBtn.classList.add("btn-accent");
+ pushToggleBtn.classList.remove("btn-ghost");
+ pushTestBtn.classList.add("hidden");
+ }
+}
+
+async function enablePush() {
+ pushError.classList.add("hidden");
+ const permission = await Notification.requestPermission();
+ if (permission !== "granted") {
+ showPushError("Notification permission was not granted.");
+ return;
+ }
+
+ const sub = await swReg.pushManager.subscribe({
+ userVisibleOnly: true,
+ applicationServerKey: urlBase64ToUint8Array(serverPush.publicKey),
+ });
+
+ const res = await fetch("/api/push/subscribe", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ subscription: sub }),
+ });
+ if (!res.ok) {
+ showPushError("Couldn't save the subscription on the server.");
+ return;
+ }
+ reflectSubscription(true);
+}
+
+async function disablePush() {
+ const sub = await swReg.pushManager.getSubscription();
+ if (sub) {
+ await fetch("/api/push/unsubscribe", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ endpoint: sub.endpoint }),
+ });
+ await sub.unsubscribe();
+ }
+ reflectSubscription(false);
+}
+
+pushToggleBtn.addEventListener("click", async () => {
+ pushToggleBtn.disabled = true;
+ try {
+ const sub = await swReg.pushManager.getSubscription();
+ if (sub) await disablePush();
+ else await enablePush();
+ } catch (err) {
+ showPushError("Something went wrong: " + (err && err.message ? err.message : err));
+ } finally {
+ pushToggleBtn.disabled = false;
+ }
+});
+
+pushTestBtn.addEventListener("click", async () => {
+ pushError.classList.add("hidden");
+ pushTestBtn.disabled = true;
+ try {
+ const res = await fetch("/api/push/test", { method: "POST" });
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok) showPushError(data.error || "Test failed.");
+ else setPushStatus(`Test sent to ${data.sent} device(s).`, "ok");
+ } finally {
+ pushTestBtn.disabled = false;
+ }
+});
+
+loadSettings();
+loadOwners();
+initPush();
diff --git a/public/sfx.js b/public/sfx.js
new file mode 100644
index 0000000..e6fd330
--- /dev/null
+++ b/public/sfx.js
@@ -0,0 +1,124 @@
+/* sfx.js
+ * Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+ * Licensed under the DASL-1.0 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ *
+ * UI sounds: hover, click, toggle. On by default, muteable (persisted),
+ * silenced under prefers-reduced-motion. Set window.SFX_BASE to point at the
+ * folder holding hover.mp3 / click.mp3 / toggle.mp3 (defaults to "/sfx/").
+ */
+(function () {
+ var base = window.SFX_BASE || "https://m.doughmination.gay/sfx/";
+
+ var reduceMotion = window.matchMedia
+ ? window.matchMedia("(prefers-reduced-motion: reduce)").matches
+ : false;
+
+ var STORE_KEY = "sfx-muted";
+
+ function readMuted() {
+ if (reduceMotion) return true;
+ try {
+ return localStorage.getItem(STORE_KEY) === "1";
+ } catch (e) {
+ return false;
+ }
+ }
+
+ var muted = readMuted();
+
+ var names = ["hover", "click", "toggle"];
+
+ var sounds = {};
+ names.forEach(function (name) {
+ var audio = new Audio(base + name + ".mp3");
+ audio.preload = "auto";
+ audio.volume = 0.3;
+ sounds[name] = audio;
+ });
+
+ var lastHover = 0;
+
+ function play(name) {
+ if (muted) return;
+ var audio = sounds[name];
+ if (!audio) return;
+ try {
+ audio.currentTime = 0;
+ var attempt = audio.play();
+ if (attempt && attempt.catch) attempt.catch(function () {});
+ } catch (e) {}
+ }
+
+ var interactive = 'a,button,[role="button"],summary,.row,.copy,.zip';
+ var toggleable = 'input[type="checkbox"],input[type="radio"],[role="switch"]';
+
+ document.addEventListener(
+ "pointerover",
+ function (event) {
+ var el = event.target.closest(interactive);
+ if (!el) return;
+ var now = Date.now();
+ if (now - lastHover < 90) return;
+ lastHover = now;
+ play("hover");
+ },
+ true,
+ );
+
+ document.addEventListener(
+ "click",
+ function (event) {
+ if (event.target.closest(toggleable)) {
+ play("toggle");
+ return;
+ }
+ if (event.target.closest(interactive)) play("click");
+ },
+ true,
+ );
+
+ document.addEventListener(
+ "change",
+ function (event) {
+ if (event.target.matches(toggleable + ",select")) play("toggle");
+ },
+ true,
+ );
+
+ function label() {
+ return muted ? "Unmute interface sounds" : "Mute interface sounds";
+ }
+
+ function glyph() {
+ return muted ? "🔇" : "🔊";
+ }
+
+ function mount() {
+ var button = document.querySelector(".sfx-toggle");
+ if (!button) {
+ button = document.createElement("button");
+ button.className = "sfx-toggle";
+ document.body.appendChild(button);
+ }
+ button.type = "button";
+ button.textContent = glyph();
+ button.setAttribute("aria-label", label());
+
+ button.addEventListener("click", function () {
+ muted = !muted;
+ try {
+ localStorage.setItem(STORE_KEY, muted ? "1" : "0");
+ } catch (e) {}
+ button.textContent = glyph();
+ button.setAttribute("aria-label", label());
+ if (!muted) play("toggle");
+ });
+ }
+
+ if (document.readyState === "loading") {
+ document.addEventListener("DOMContentLoaded", mount);
+ } else {
+ mount();
+ }
+})();
diff --git a/public/style.css b/public/style.css
new file mode 100644
index 0000000..c2411f1
--- /dev/null
+++ b/public/style.css
@@ -0,0 +1,854 @@
+/* mailbox/public/style.css
+ * Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+ * Licensed under the DASL-1.0 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+/* mailbox/public/style.css */
+
+/* Comic Code — the shared face across every site, served from the same CDN the
+ personal + info sites use. */
+@font-face {
+ font-family: "Comic Code";
+ src: url("https://m.doughmination.gay/f/Comic-Code/woff2/ComicCode-Regular.woff2") format("woff2"),
+ url("https://m.doughmination.gay/f/Comic-Code/woff/ComicCode-Regular.woff") format("woff");
+ font-weight: 400;
+ font-style: normal;
+ font-display: swap;
+}
+@font-face {
+ font-family: "Comic Code";
+ src: url("https://m.doughmination.gay/f/Comic-Code/woff2/ComicCode-Italic.woff2") format("woff2"),
+ url("https://m.doughmination.gay/f/Comic-Code/woff/ComicCode-Italic.woff") format("woff");
+ font-weight: 400;
+ font-style: italic;
+ font-display: swap;
+}
+@font-face {
+ font-family: "Comic Code";
+ src: url("https://m.doughmination.gay/f/Comic-Code/woff2/ComicCode-Medium.woff2") format("woff2"),
+ url("https://m.doughmination.gay/f/Comic-Code/woff/ComicCode-Medium.woff") format("woff");
+ font-weight: 500;
+ font-style: normal;
+ font-display: swap;
+}
+@font-face {
+ font-family: "Comic Code";
+ src: url("https://m.doughmination.gay/f/Comic-Code/woff2/ComicCode-Bold.woff2") format("woff2"),
+ url("https://m.doughmination.gay/f/Comic-Code/woff/ComicCode-Bold.woff") format("woff");
+ font-weight: 700;
+ font-style: normal;
+ font-display: swap;
+}
+
+:root {
+ /* Unified dark palette — derived from the info site's colours so every site
+ matches. bg #0a0b10, surface #12141c, surfaceHover #1b1e2a, text #f4f6fb,
+ muted #9aa3c2, border #232838, accent #f5a9b8. */
+ --base: #0a0b10;
+ --mantle: #12141c;
+ --crust: #05060a;
+ --surface0: #1b1e2a;
+ --surface1: #232838;
+ --surface2: #2c3346;
+ --text: #f4f6fb;
+ --subtext0: #9aa3c2;
+ --subtext1: #c9cfe0;
+ --overlay0: #5b6480;
+ --red: #d15f8c;
+ --pink: #f5a9b8; /* accent */
+ --yellow: #f5a9b8; /* warnings — kept on-palette */
+}
+
+* {
+ box-sizing: border-box;
+}
+
+body {
+ margin: 0;
+ background: var(--base);
+ color: var(--text);
+ font-family: "Comic Code", ui-monospace, monospace;
+ font-size: 15px;
+}
+
+.app {
+ display: flex;
+ flex-direction: column;
+ height: 100vh;
+}
+
+.topbar {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 0.75rem 1.25rem;
+ background: var(--mantle);
+ border-bottom: 1px solid var(--surface0);
+}
+
+.topbar h1 {
+ font-size: 1.1rem;
+ margin: 0;
+ font-weight: 600;
+}
+
+.topbar-right {
+ display: flex;
+ align-items: center;
+ gap: 0.75rem;
+}
+
+.layout {
+ flex: 1;
+ display: grid;
+ grid-template-columns: 140px 320px 1fr;
+ overflow: hidden;
+}
+
+.folder-nav {
+ display: flex;
+ flex-direction: column;
+ gap: 0.15rem;
+ padding: 0.75rem 0.5rem;
+ background: var(--crust);
+ border-right: 1px solid var(--surface0);
+}
+
+.folder-item {
+ background: transparent;
+ border: none;
+ color: var(--subtext1);
+ text-align: left;
+ padding: 0.5rem 0.75rem;
+ border-radius: 6px;
+ font: inherit;
+ cursor: pointer;
+}
+
+.folder-item:hover {
+ background: var(--surface0);
+}
+
+.folder-item.active {
+ background: var(--surface0);
+ color: var(--text);
+ font-weight: 600;
+}
+
+.list {
+ overflow-y: auto;
+ border-right: 1px solid var(--surface0);
+ background: var(--mantle);
+}
+
+.list-item {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ padding: 0.85rem 1rem;
+ border-bottom: 1px solid var(--surface0);
+ cursor: pointer;
+}
+
+.list-item:hover {
+ background: var(--surface0);
+}
+
+.list-item-main {
+ flex: 1;
+ min-width: 0;
+}
+
+.row-delete {
+ flex: 0 0 auto;
+ padding: 0.25rem 0.5rem;
+ background: transparent;
+ border: none;
+ color: var(--overlay0);
+ font-size: 0.9rem;
+ line-height: 1;
+ opacity: 0;
+ transition: opacity 0.12s ease, color 0.12s ease;
+}
+
+.list-item:hover .row-delete {
+ opacity: 1;
+}
+
+.row-delete:hover {
+ color: var(--red);
+}
+
+.list-item.active {
+ background: var(--surface0);
+ border-left: 3px solid var(--pink);
+}
+
+.list-item .from {
+ font-weight: 600;
+ color: var(--text);
+}
+
+.list-item .subject {
+ color: var(--subtext1);
+ font-size: 0.9rem;
+ margin-top: 0.15rem;
+}
+
+.list-item .time {
+ color: var(--overlay0);
+ font-size: 0.75rem;
+ margin-top: 0.35rem;
+}
+
+.detail {
+ padding: 1.5rem 2rem;
+ overflow-y: auto;
+}
+
+.detail h2 {
+ margin: 0 0 0.25rem 0;
+}
+
+.detail .meta {
+ color: var(--subtext0);
+ font-size: 0.85rem;
+ margin-bottom: 1.25rem;
+}
+
+.detail .body {
+ border-top: 1px solid var(--surface0);
+ padding-top: 1.25rem;
+ line-height: 1.6;
+}
+
+/* Email bodies often carry inline color/background/font styles from the
+ sender's mail client (signatures, quoted replies, etc). Those inline
+ styles beat our stylesheet by specificity, so on a dark theme you can
+ end up with invisible black-on-black or washed-out white-on-white text.
+ Force every element inside a message body back to the theme's palette,
+ regardless of what the original HTML tried to set. */
+.detail .body,
+.detail .body * {
+ color: var(--text) !important;
+ background-color: transparent !important;
+ font-family: inherit !important;
+ text-shadow: none !important;
+}
+
+.detail .body a {
+ color: var(--pink) !important;
+ text-decoration: underline;
+}
+
+.detail .body img {
+ max-width: 100%;
+ height: auto;
+}
+
+.muted {
+ color: var(--overlay0);
+ padding: 1rem;
+}
+
+.muted-inline {
+ color: var(--overlay0);
+ font-size: 0.85rem;
+}
+
+.message {
+ border: 1px solid var(--surface0);
+ border-radius: 8px;
+ padding: 1rem 1.25rem;
+ margin-bottom: 1rem;
+}
+
+.msg-head {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ flex-wrap: wrap;
+}
+
+.msg-delete {
+ margin-left: auto;
+ padding: 0.2rem 0.45rem;
+ background: transparent;
+ border: none;
+ color: var(--overlay0);
+ font-size: 0.9rem;
+ line-height: 1;
+}
+
+.msg-delete:hover {
+ color: var(--red);
+}
+
+.dir-badge {
+ font-size: 0.7rem;
+ text-transform: uppercase;
+ letter-spacing: 0.03em;
+ padding: 0.15rem 0.45rem;
+ border-radius: 4px;
+ background: var(--surface1);
+ color: var(--subtext1);
+}
+
+.dir-badge.outbound {
+ background: var(--pink);
+ color: var(--crust);
+}
+
+.thread-actions {
+ display: flex;
+ gap: 0.5rem;
+ margin-top: 0.5rem;
+}
+
+button {
+ font: inherit;
+ border-radius: 6px;
+ padding: 0.5rem 1rem;
+ border: 1px solid transparent;
+ cursor: pointer;
+}
+
+/* Anchors used as buttons (topbar links, settings back link). */
+a.btn-accent,
+a.btn-ghost,
+a.btn-danger {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ font: inherit;
+ border-radius: 6px;
+ padding: 0.5rem 1rem;
+ border: 1px solid transparent;
+ cursor: pointer;
+ text-decoration: none;
+}
+
+.btn-accent {
+ background: var(--pink);
+ color: var(--crust);
+ font-weight: 600;
+}
+
+.btn-accent:hover {
+ filter: brightness(1.05);
+}
+
+.btn-ghost {
+ background: transparent;
+ border-color: var(--surface2);
+ color: var(--text);
+}
+
+.btn-ghost:hover {
+ background: var(--surface0);
+}
+
+.btn-danger {
+ background: transparent;
+ border-color: var(--red);
+ color: var(--red);
+}
+
+.btn-danger:hover {
+ background: var(--red);
+ color: var(--crust);
+}
+
+.modal {
+ position: fixed;
+ inset: 0;
+ background: rgba(17, 17, 27, 0.7);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+}
+
+.modal.hidden {
+ display: none;
+}
+
+.compose {
+ background: var(--mantle);
+ border: 1px solid var(--surface0);
+ border-radius: 10px;
+ padding: 1.5rem;
+ width: 420px;
+ max-width: 90vw;
+ display: flex;
+ flex-direction: column;
+ gap: 0.75rem;
+}
+
+.compose h2 {
+ margin: 0 0 0.25rem 0;
+}
+
+.compose label {
+ display: flex;
+ flex-direction: column;
+ gap: 0.35rem;
+ font-size: 0.85rem;
+ color: var(--subtext1);
+}
+
+.compose input,
+.compose textarea,
+.compose select {
+ background: var(--surface0);
+ border: 1px solid var(--surface1);
+ border-radius: 6px;
+ padding: 0.5rem 0.6rem;
+ color: var(--text);
+ font: inherit;
+ resize: vertical;
+}
+
+.compose input:focus,
+.compose textarea:focus,
+.compose select:focus {
+ outline: 2px solid var(--pink);
+ outline-offset: 1px;
+}
+
+.compose .actions {
+ display: flex;
+ justify-content: flex-end;
+ gap: 0.5rem;
+ margin-top: 0.5rem;
+}
+
+.error {
+ color: var(--red);
+ font-size: 0.85rem;
+}
+
+.error.hidden {
+ display: none;
+}
+
+.warn {
+ color: var(--yellow, #e5c890);
+ font-size: 0.85rem;
+}
+
+.warn.hidden {
+ display: none;
+}
+
+.attachment-list {
+ list-style: none;
+ margin: 0.25rem 0 0 0;
+ padding: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 0.35rem;
+}
+
+.attachment-list li {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ background: var(--surface0);
+ border-radius: 6px;
+ padding: 0.35rem 0.6rem;
+ font-size: 0.85rem;
+}
+
+.attachment-list a {
+ color: var(--pink);
+ text-decoration: none;
+}
+
+.attachment-list a:hover {
+ text-decoration: underline;
+}
+
+.attachment-list .remove-attachment {
+ margin-left: auto;
+ padding: 0.2rem 0.5rem;
+ font-size: 0.75rem;
+}
+
+/* ---------- Image attachment previews ---------- */
+.image-grid {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.5rem;
+ margin-top: 0.75rem;
+}
+
+.image-thumb {
+ display: block;
+ width: 120px;
+ height: 120px;
+ border-radius: 8px;
+ overflow: hidden;
+ border: 1px solid var(--surface1);
+ background: var(--surface0);
+ cursor: zoom-in;
+}
+
+.image-thumb img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ display: block;
+}
+
+.image-thumb:hover {
+ border-color: var(--pink);
+}
+
+/* ---------- Lightbox ---------- */
+.lightbox {
+ position: fixed;
+ inset: 0;
+ background: rgba(17, 17, 27, 0.9);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 2rem;
+ cursor: zoom-out;
+ z-index: 50;
+}
+
+.lightbox.hidden {
+ display: none;
+}
+
+.lightbox img {
+ max-width: 95vw;
+ max-height: 95vh;
+ border-radius: 8px;
+ box-shadow: 0 8px 40px rgba(0, 0, 0, 0.5);
+}
+
+.hidden {
+ display: none !important;
+}
+
+.login-body {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ min-height: 100vh;
+}
+
+.login-card {
+ position: static;
+}
+
+.hp-field {
+ position: absolute;
+ left: -9999px;
+ top: -9999px;
+ height: 0;
+ width: 0;
+ overflow: hidden;
+}
+
+.back-btn {
+ display: none;
+ background: transparent;
+ border: none;
+ color: var(--pink);
+ font: inherit;
+ font-weight: 600;
+ padding: 0.25rem 0;
+ margin-bottom: 0.75rem;
+ cursor: pointer;
+}
+
+/* ---------- Settings page ---------- */
+.settings-page {
+ flex: 1;
+ overflow-y: auto;
+ padding: 1.5rem;
+ display: flex;
+ flex-direction: column;
+ gap: 1.25rem;
+ max-width: 640px;
+ width: 100%;
+ margin: 0 auto;
+}
+
+.settings-card {
+ background: var(--mantle);
+ border: 1px solid var(--surface0);
+ border-radius: 10px;
+ padding: 1.25rem 1.5rem;
+}
+
+.settings-card h2 {
+ margin: 0 0 0.35rem 0;
+ font-size: 1rem;
+}
+
+.settings-hint {
+ color: var(--subtext0);
+ font-size: 0.85rem;
+ margin: 0 0 1rem 0;
+ line-height: 1.5;
+}
+
+.from-list {
+ list-style: none;
+ margin: 0 0 0.85rem 0;
+ padding: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 0.4rem;
+}
+
+.from-row {
+ display: flex;
+ align-items: center;
+ gap: 0.6rem;
+ background: var(--surface0);
+ border-radius: 6px;
+ padding: 0.4rem 0.6rem;
+}
+
+.from-row .from-addr {
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ font-size: 0.9rem;
+}
+
+.star {
+ background: transparent;
+ border: none;
+ color: var(--overlay0);
+ font-size: 1.1rem;
+ line-height: 1;
+ padding: 0.1rem 0.25rem;
+}
+
+.star.on {
+ color: var(--pink);
+}
+
+.from-remove {
+ padding: 0.25rem 0.6rem;
+ font-size: 0.8rem;
+}
+
+.add-from {
+ display: flex;
+ gap: 0.5rem;
+}
+
+.add-from input {
+ flex: 1;
+ min-width: 0;
+ background: var(--surface0);
+ border: 1px solid var(--surface1);
+ border-radius: 6px;
+ padding: 0.5rem 0.6rem;
+ color: var(--text);
+ font: inherit;
+}
+
+.add-from input:focus {
+ outline: 2px solid var(--pink);
+ outline-offset: 1px;
+}
+
+.push-status {
+ font-size: 0.9rem;
+ margin-bottom: 0.85rem;
+ line-height: 1.5;
+}
+
+.push-status.ok {
+ color: var(--pink);
+}
+
+.push-actions {
+ display: flex;
+ gap: 0.5rem;
+ flex-wrap: wrap;
+}
+
+/* ---------- Undo toast ---------- */
+.toast-host {
+ position: fixed;
+ left: 50%;
+ bottom: 1.25rem;
+ transform: translateX(-50%);
+ display: flex;
+ flex-direction: column;
+ gap: 0.5rem;
+ z-index: 60;
+ pointer-events: none;
+}
+
+.toast {
+ display: flex;
+ align-items: center;
+ gap: 1rem;
+ background: var(--surface1);
+ color: var(--text);
+ border: 1px solid var(--surface2);
+ border-radius: 8px;
+ padding: 0.6rem 0.9rem;
+ box-shadow: 0 6px 24px rgba(0, 0, 0, 0.4);
+ font-size: 0.9rem;
+ pointer-events: auto;
+ animation: toast-in 0.16s ease;
+}
+
+.toast.leaving {
+ opacity: 0;
+ transition: opacity 0.2s ease;
+}
+
+.toast-undo {
+ background: transparent;
+ border: none;
+ color: var(--pink);
+ font-weight: 600;
+ padding: 0.1rem 0.3rem;
+}
+
+.toast-undo:hover {
+ text-decoration: underline;
+}
+
+@keyframes toast-in {
+ from {
+ opacity: 0;
+ transform: translateY(8px);
+ }
+ to {
+ opacity: 1;
+ transform: translateY(0);
+ }
+}
+
+/* ---------- Mobile ---------- */
+@media (max-width: 768px) {
+ .topbar {
+ padding: 0.6rem 0.85rem;
+ flex-wrap: wrap;
+ gap: 0.5rem;
+ }
+
+ .topbar h1 {
+ font-size: 1rem;
+ }
+
+ .topbar-right {
+ gap: 0.5rem;
+ }
+
+ .topbar-right button {
+ padding: 0.45rem 0.7rem;
+ font-size: 0.85rem;
+ }
+
+ .layout {
+ display: flex;
+ flex-direction: column;
+ flex: 1;
+ min-height: 0;
+ }
+
+ .folder-nav {
+ flex: 0 0 auto;
+ flex-direction: row;
+ overflow-x: auto;
+ padding: 0.5rem;
+ gap: 0.4rem;
+ border-right: none;
+ border-bottom: 1px solid var(--surface0);
+ -webkit-overflow-scrolling: touch;
+ }
+
+ .folder-item {
+ flex: 0 0 auto;
+ white-space: nowrap;
+ }
+
+ .list,
+ .detail {
+ flex: 1;
+ min-height: 0;
+ border-right: none;
+ overflow-y: auto;
+ }
+
+ /* Only one of list/detail is visible at a time; .show-detail toggles which. */
+ .detail {
+ display: none;
+ padding: 1rem 1.1rem;
+ }
+
+ .layout.show-detail .list {
+ display: none;
+ }
+
+ .layout.show-detail .detail {
+ display: block;
+ }
+
+ .back-btn {
+ display: inline-block;
+ }
+
+ .msg-head {
+ font-size: 0.9rem;
+ }
+
+ .modal {
+ align-items: flex-end;
+ }
+
+ .compose {
+ width: 100%;
+ max-width: 100%;
+ max-height: 92vh;
+ overflow-y: auto;
+ border-radius: 14px 14px 0 0;
+ }
+
+ .compose .actions {
+ flex-wrap: wrap;
+ }
+
+ .compose .actions button {
+ flex: 1 1 auto;
+ }
+
+ .login-card {
+ width: 100%;
+ max-width: 360px;
+ }
+
+ .list-item {
+ padding: 0.9rem 1rem;
+ }
+
+ /* No hover on touch — keep the row delete affordance visible. */
+ .row-delete {
+ opacity: 1;
+ }
+
+ /* iOS Safari zooms in on focus if an input's font-size is under 16px */
+ .compose input,
+ .compose textarea {
+ font-size: 16px;
+ }
+
+ button {
+ min-height: 40px;
+ }
+}
\ No newline at end of file
diff --git a/public/sw.js b/public/sw.js
new file mode 100644
index 0000000..8610e72
--- /dev/null
+++ b/public/sw.js
@@ -0,0 +1,55 @@
+/* mailbox/public/sw.js
+ * Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+ * Licensed under the DASL-1.0 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+// Service worker for the mailbox PWA. Its main job is Web Push: show a
+// notification when the server sends one, and focus/open the inbox when the
+// user taps it. Deliberately minimal — no offline caching.
+
+self.addEventListener("install", () => {
+ self.skipWaiting();
+});
+
+self.addEventListener("activate", (event) => {
+ event.waitUntil(self.clients.claim());
+});
+
+self.addEventListener("push", (event) => {
+ let data = {};
+ try {
+ data = event.data ? event.data.json() : {};
+ } catch (_) {
+ data = { body: event.data ? event.data.text() : "" };
+ }
+
+ const title = data.title || "New email";
+ const options = {
+ body: data.body || "",
+ icon: "/apple-touch-icon.png",
+ badge: "/apple-touch-icon.png",
+ tag: data.tag || undefined,
+ data: { url: data.url || "/inbox" },
+ };
+
+ event.waitUntil(self.registration.showNotification(title, options));
+});
+
+self.addEventListener("notificationclick", (event) => {
+ event.notification.close();
+ const url = (event.notification.data && event.notification.data.url) || "/inbox";
+
+ event.waitUntil(
+ self.clients.matchAll({ type: "window", includeUncontrolled: true }).then((wins) => {
+ for (const win of wins) {
+ // Reuse an already-open tab if we have one.
+ if ("focus" in win) {
+ if ("navigate" in win) win.navigate(url).catch(() => {});
+ return win.focus();
+ }
+ }
+ if (self.clients.openWindow) return self.clients.openWindow(url);
+ return undefined;
+ })
+ );
+});
diff --git a/server.ts b/server.ts
new file mode 100644
index 0000000..5bceb04
--- /dev/null
+++ b/server.ts
@@ -0,0 +1,767 @@
+import { Hono } from "hono";
+import { getCookie, setCookie, deleteCookie } from "hono/cookie";
+import { Resend } from "resend";
+import {
+ addEmail,
+ getEmail,
+ listEmails,
+ listByThreadKey,
+ createDraft,
+ updateDraft,
+ deleteDraft,
+ deleteEmail,
+ deleteByThreadKey,
+ type Folder,
+ type StoredEmail,
+ type StoredAttachment,
+} from "./lib/store";
+import {
+ readAttachment,
+ saveAttachment,
+ deleteAttachment,
+ toResendAttachment,
+ persistInboundAttachments,
+} from "./lib/attachments";
+import {
+ createSession,
+ sessionUser,
+ destroySession,
+ savePending,
+ takePending,
+} from "./lib/auth";
+import {
+ initOidc,
+ buildAuthUrl,
+ completeLogin,
+ endSessionUrl,
+} from "./lib/oidc";
+import {
+ isAdmin,
+ ensureUser,
+ addressesFor,
+ allAddresses,
+ ownerForRecipients,
+ canAccessOwner,
+ resolveFromFor,
+ dashboardState,
+ assignAddress,
+ unassignAddress,
+ initOwners,
+} from "./lib/owners";
+import { bareAddress } from "./lib/settings";
+import {
+ pushConfigured,
+ vapidPublicKey,
+ addSubscription,
+ removeSubscription,
+ subscriptionCount,
+ sendToAll,
+} from "./lib/push";
+import { setEnv, env, type Env } from "./lib/kv";
+import type { PushSubscription } from "./lib/webpush";
+
+type UploadedAttachment = { filename: string; contentType: string; content: string };
+
+async function persistUploads(uploads: UploadedAttachment[] | undefined): Promise<StoredAttachment[]> {
+ if (!uploads?.length) return [];
+ return Promise.all(uploads.map((u) => saveAttachment(u.filename, u.contentType, u.content)));
+}
+
+type MixedAttachment =
+ | { id: string; filename: string; contentType: string; size: number }
+ | UploadedAttachment;
+
+async function resolveAttachments(items: MixedAttachment[] | undefined): Promise<StoredAttachment[]> {
+ if (!items?.length) return [];
+ const resolved = await Promise.all(
+ items.map((item) =>
+ "id" in item && item.id
+ ? Promise.resolve(item as StoredAttachment)
+ : saveAttachment(
+ (item as UploadedAttachment).filename,
+ (item as UploadedAttachment).contentType,
+ (item as UploadedAttachment).content,
+ ),
+ ),
+ );
+ return resolved;
+}
+
+async function toResendAttachments(attachments: StoredAttachment[]) {
+ const resolved = await Promise.all(attachments.map(toResendAttachment));
+ return resolved.filter((a): a is { filename: string; content: string } => a !== null);
+}
+
+function parseFolder(value: string | undefined): Folder | undefined {
+ return value === "inbox" || value === "sent" || value === "drafts" ? value : undefined;
+}
+
+const resend = new Resend(process.env.RESEND_API_KEY);
+const webhookSecret = process.env.RESEND_WEBHOOK_SECRET ?? "";
+const sendFrom = (process.env.SEND_FROM ?? "").split(/[,\n]/)[0]?.trim() ?? "";
+const cookieSecure = process.env.COOKIE_SECURE === "true";
+
+function computeThreadKey(subject: string, from: string, to: string[], myAddresses: string[]): string {
+ const cleanSubject = (subject || "")
+ .replace(/^\s*(re|fwd?)\s*:\s*/i, "")
+ .trim()
+ .toLowerCase();
+
+ const me = new Set(myAddresses);
+ const participants = [bareAddress(from), ...to.map(bareAddress)]
+ .filter((addr) => addr && !me.has(addr))
+ .sort();
+
+ const counterpart = participants[0] ?? bareAddress(from);
+ return `${cleanSubject}::${counterpart}`;
+}
+
+function pickReplyFrom(user: string, original: StoredEmail, requested?: string | null): string {
+ const owned = addressesFor(user);
+ const inOwned = (addr: string | undefined | null) =>
+ owned.find((a) => bareAddress(a) === bareAddress(addr));
+
+ if (requested) {
+ const match = inOwned(requested);
+ if (match) return match;
+ }
+ const targets = original.direction === "inbound" ? original.to : [original.from];
+ for (const t of targets) {
+ const match = inOwned(t);
+ if (match) return match;
+ }
+ return owned[0] ?? sendFrom;
+}
+
+function buildReferences(original: { references: string | null; messageId: string | null }): string {
+ const prior = original.references ? original.references.split(/\s+/).filter(Boolean) : [];
+ if (original.messageId) prior.push(original.messageId);
+ return prior.join(" ");
+}
+
+async function purgeAttachmentFiles(emails: StoredEmail[]): Promise<void> {
+ const ids = emails.flatMap((e) => e.attachments).map((a) => a.id).filter(Boolean);
+ await Promise.all(ids.map((id) => deleteAttachment(id)));
+}
+
+type ServableAttachment = StoredAttachment & { inline?: boolean };
+type ServableEmail = Omit<StoredEmail, "attachments"> & { attachments: ServableAttachment[] };
+
+function inlineCidImages(email: StoredEmail): ServableEmail {
+ const attachments: ServableAttachment[] = email.attachments.map((a) => ({ ...a }));
+
+ const byContentId = new Map<string, StoredAttachment>();
+ for (const a of email.attachments) {
+ if (a.id && a.contentId) byContentId.set(a.contentId.toLowerCase(), a);
+ }
+
+ if (!email.html || !email.html.includes("cid:") || byContentId.size === 0) {
+ return { ...email, attachments };
+ }
+
+ const usedIds = new Set<string>();
+ const html = email.html.replace(/cid:([^"'\s>)]+)/gi, (whole, rawId: string) => {
+ const key = rawId.replace(/^<|>$/g, "").trim().toLowerCase();
+ const match = byContentId.get(key);
+ if (!match) return whole;
+ usedIds.add(match.id);
+ return `/api/emails/${email.id}/attachments/${match.id}?inline=1`;
+ });
+
+ return {
+ ...email,
+ html,
+ attachments: attachments.map((a) => (usedIds.has(a.id) ? { ...a, inline: true } : a)),
+ };
+}
+
+function sendAsset(req: Request, file: string): Promise<Response> {
+ return env().ASSETS.fetch(new Request(new URL(file, req.url)));
+}
+
+const app = new Hono<{ Variables: { user: string } }>();
+
+const PUBLIC_PATHS = new Set([
+ "/login",
+ "/login.html",
+ "/login.js",
+ "/style.css",
+ "/favicon.ico",
+ "/apple-touch-icon.png",
+ "/auth/login",
+ "/auth/callback",
+ "/sw.js",
+ "/manifest.webmanifest",
+]);
+
+app.use("/*", async (c, next) => {
+ const path = c.req.path;
+ if (path === "/webhook/inbound" || PUBLIC_PATHS.has(path)) {
+ return next();
+ }
+
+ const token = getCookie(c, "session");
+ const user = await sessionUser(token);
+ if (!user) {
+ if (path.startsWith("/api/")) return c.json({ error: "Unauthorized" }, 401);
+ return c.redirect("/login");
+ }
+
+ c.set("user", user);
+ return next();
+});
+
+app.get("/login", (c) => sendAsset(c.req.raw, "/login.html"));
+
+app.get("/auth/login", async (c) => {
+ try {
+ const from = c.req.query("from") || "/inbox";
+ const { url, pending } = await buildAuthUrl(from);
+ const id = await savePending(pending);
+ setCookie(c, "login", id, {
+ httpOnly: true,
+ sameSite: "Lax",
+ secure: cookieSecure,
+ path: "/",
+ maxAge: 600,
+ });
+ return c.redirect(url);
+ } catch (err) {
+ console.error("OIDC login start failed", err);
+ return c.text("Login is temporarily unavailable.", 500);
+ }
+});
+
+app.get("/auth/callback", async (c) => {
+ const code = c.req.query("code");
+ const stateParam = c.req.query("state");
+ const err = c.req.query("error");
+ if (err) return c.text(`Login failed: ${err}`, 401);
+
+ const pending = await takePending(getCookie(c, "login"));
+ deleteCookie(c, "login", { path: "/" });
+
+ if (!pending || !code || !stateParam || stateParam !== pending.state) {
+ return c.redirect("/login");
+ }
+
+ try {
+ const { username } = await completeLogin(code, pending);
+ await ensureUser(username);
+ const token = await createSession(username);
+ setCookie(c, "session", token, {
+ httpOnly: true,
+ sameSite: "Lax",
+ secure: cookieSecure,
+ path: "/",
+ maxAge: 60 * 60 * 24 * 7,
+ });
+ return c.redirect(pending.returnTo);
+ } catch (e) {
+ console.error("OIDC callback error", e);
+ return c.text("Login failed.", 401);
+ }
+});
+
+app.get("/", (c) => sendAsset(c.req.raw, "/index.html"));
+app.get("/inbox", (c) => sendAsset(c.req.raw, "/index.html"));
+app.get("/sent", (c) => sendAsset(c.req.raw, "/index.html"));
+app.get("/drafts", (c) => sendAsset(c.req.raw, "/index.html"));
+app.get("/settings", (c) => sendAsset(c.req.raw, "/settings.html"));
+
+app.post("/api/logout", async (c) => {
+ await destroySession(getCookie(c, "session"));
+ deleteCookie(c, "session", { path: "/" });
+ return c.json({ ok: true, endSession: endSessionUrl() });
+});
+
+app.get("/api/me", (c) => {
+ const user = c.get("user");
+ return c.json({
+ username: user,
+ displayName: user,
+ isAdmin: isAdmin(user),
+ addresses: addressesFor(user),
+ });
+});
+
+app.post("/webhook/inbound", async (c) => {
+ const payload = await c.req.text();
+
+ let event: any;
+ try {
+ event = resend.webhooks.verify({
+ payload,
+ headers: {
+ id: c.req.header("svix-id") ?? "",
+ timestamp: c.req.header("svix-timestamp") ?? "",
+ signature: c.req.header("svix-signature") ?? "",
+ },
+ webhookSecret,
+ });
+ } catch (err) {
+ console.error("Webhook signature verification failed", err);
+ return c.text("Invalid signature", 401);
+ }
+
+ if (event.type !== "email.received") {
+ return c.json({ ok: true, ignored: event.type });
+ }
+
+ const emailId = event.data.email_id;
+
+ const { data: full, error } = await resend.emails.receiving.get(emailId);
+ if (error || !full) {
+ console.error("Failed to fetch received email content", error);
+ return c.json({ ok: false }, 500);
+ }
+
+ const subject = full.subject ?? "(no subject)";
+ const to = full.to ?? [];
+ const inReplyTo = full.headers?.["in-reply-to"] ?? null;
+ const references = full.headers?.["references"] ?? null;
+ const attachments = await persistInboundAttachments(full.attachments ?? []);
+ const myAddresses = allAddresses().map(bareAddress);
+ const owner = ownerForRecipients(to);
+
+ await addEmail({
+ id: full.id,
+ from: full.from,
+ to,
+ subject,
+ html: full.html ?? null,
+ text: full.text ?? null,
+ receivedAt: full.created_at,
+ attachments,
+ direction: "inbound",
+ status: "sent",
+ messageId: full.message_id ?? null,
+ inReplyTo,
+ references,
+ threadKey: computeThreadKey(subject, full.from, to, myAddresses),
+ owner,
+ });
+
+ try {
+ await sendToAll({
+ title: full.from ? `New email from ${full.from}` : "New email",
+ body: subject,
+ url: "/inbox",
+ tag: full.id,
+ });
+ } catch (err) {
+ console.error("Push notification failed", err);
+ }
+
+ return c.json({ ok: true });
+});
+
+app.get("/api/emails", async (c) => {
+ const user = c.get("user");
+ const folder = parseFolder(c.req.query("folder"));
+ const emails = await listEmails(folder, isAdmin(user) ? undefined : user);
+ return c.json(emails);
+});
+
+app.get("/api/emails/:id/attachments/:attachmentId", async (c) => {
+ const email = await getEmail(c.req.param("id"));
+ if (!email || !canAccessOwner(c.get("user"), email.owner)) {
+ return c.json({ error: "Not found" }, 404);
+ }
+
+ const attachmentId = c.req.param("attachmentId");
+ const meta = email.attachments.find((a) => a.id === attachmentId);
+ if (!meta || !meta.id) return c.json({ error: "Not found" }, 404);
+
+ const bytes = await readAttachment(meta.id);
+ if (!bytes) return c.json({ error: "Not found" }, 404);
+
+ const disposition = c.req.query("inline") === "1" ? "inline" : "attachment";
+
+ return new Response(bytes, {
+ headers: {
+ "Content-Type": meta.contentType,
+ "Content-Disposition": `${disposition}; filename="${meta.filename.replace(/"/g, "")}"`,
+ "Content-Length": String(meta.size),
+ },
+ });
+});
+
+app.get("/api/emails/:id", async (c) => {
+ const email = await getEmail(c.req.param("id"));
+ if (!email || !canAccessOwner(c.get("user"), email.owner)) {
+ return c.json({ error: "Not found" }, 404);
+ }
+ return c.json(inlineCidImages(email));
+});
+
+app.delete("/api/emails/:id", async (c) => {
+ const email = await getEmail(c.req.param("id"));
+ if (!email || !canAccessOwner(c.get("user"), email.owner)) {
+ return c.json({ error: "Not found" }, 404);
+ }
+ const removed = await deleteEmail(email.id);
+ if (removed) await purgeAttachmentFiles([removed]);
+ return c.json({ ok: true });
+});
+
+app.delete("/api/emails/:id/thread", async (c) => {
+ const original = await getEmail(c.req.param("id"));
+ if (!original || !canAccessOwner(c.get("user"), original.owner)) {
+ return c.json({ error: "Not found" }, 404);
+ }
+ const removed = await deleteByThreadKey(original.threadKey);
+ await purgeAttachmentFiles(removed);
+ return c.json({ ok: true, count: removed.length });
+});
+
+app.post("/api/uploads", async (c) => {
+ const body = await c.req.json().catch(() => null);
+ if (!body?.content || typeof body.content !== "string") {
+ return c.json({ error: "content is required" }, 400);
+ }
+ const stored = await saveAttachment(
+ typeof body.filename === "string" ? body.filename : "attachment",
+ typeof body.contentType === "string" ? body.contentType : "application/octet-stream",
+ body.content,
+ );
+ return c.json(stored);
+});
+
+app.post("/api/send", async (c) => {
+ const body = await c.req.json().catch(() => null);
+ if (!body?.to || !body?.subject || !body?.html) {
+ return c.json({ error: "to, subject, and html are required" }, 400);
+ }
+
+ const user = c.get("user");
+ const from = resolveFromFor(user, body.from);
+ if (!from) return c.json({ error: "You have no send-from address." }, 400);
+ const stored = await resolveAttachments(body.attachments);
+ const resendAttachments = await toResendAttachments(stored);
+
+ const { data, error } = await resend.emails.send({
+ from,
+ to: body.to,
+ subject: body.subject,
+ html: body.html,
+ attachments: resendAttachments.length ? resendAttachments : undefined,
+ });
+
+ if (error) return c.json({ error: error.message }, 400);
+
+ const to = [body.to];
+ const myAddresses = allAddresses().map(bareAddress);
+ await addEmail({
+ id: data.id,
+ from,
+ to,
+ subject: body.subject,
+ html: body.html,
+ text: null,
+ receivedAt: new Date().toISOString(),
+ attachments: stored,
+ direction: "outbound",
+ status: "sent",
+ messageId: null,
+ inReplyTo: null,
+ references: null,
+ threadKey: computeThreadKey(body.subject, from, to, myAddresses),
+ owner: user,
+ });
+
+ return c.json(data);
+});
+
+app.post("/api/emails/:id/reply", async (c) => {
+ const user = c.get("user");
+ const original = await getEmail(c.req.param("id"));
+ if (!original || !canAccessOwner(user, original.owner)) {
+ return c.json({ error: "Not found" }, 404);
+ }
+
+ const body = await c.req.json().catch(() => null);
+ if (!body?.html) return c.json({ error: "html is required" }, 400);
+
+ const to = body.to ?? original.from;
+ const subject = /^\s*re\s*:/i.test(original.subject)
+ ? original.subject
+ : `Re: ${original.subject}`;
+
+ const headers: Record<string, string> = {};
+ if (original.messageId) {
+ headers["In-Reply-To"] = original.messageId;
+ headers["References"] = buildReferences(original);
+ }
+
+ const from = pickReplyFrom(user, original, body.from);
+ const stored = await resolveAttachments(body.attachments);
+ const resendAttachments = await toResendAttachments(stored);
+
+ const { data, error } = await resend.emails.send({
+ from,
+ to,
+ subject,
+ html: body.html,
+ headers,
+ attachments: resendAttachments.length ? resendAttachments : undefined,
+ });
+
+ if (error) return c.json({ error: error.message }, 400);
+
+ await addEmail({
+ id: data.id,
+ from,
+ to: [to],
+ subject,
+ html: body.html,
+ text: null,
+ receivedAt: new Date().toISOString(),
+ attachments: stored,
+ direction: "outbound",
+ status: "sent",
+ messageId: null,
+ inReplyTo: original.messageId,
+ references: headers["References"] ?? null,
+ threadKey: original.threadKey,
+ owner: original.owner,
+ });
+
+ return c.json(data);
+});
+
+app.post("/api/emails/:id/forward", async (c) => {
+ const user = c.get("user");
+ const original = await getEmail(c.req.param("id"));
+ if (!original || !canAccessOwner(user, original.owner)) {
+ return c.json({ error: "Not found" }, 404);
+ }
+
+ const body = await c.req.json().catch(() => null);
+ if (!body?.to) return c.json({ error: "to is required" }, 400);
+
+ const from = pickReplyFrom(user, original, body.from);
+
+ if (original.direction === "inbound") {
+ const { data, error } = await resend.emails.receiving.forward({
+ emailId: original.id,
+ to: body.to,
+ from,
+ });
+ if (error) return c.json({ error: error.message }, 400);
+ return c.json(data);
+ }
+
+ const { data, error } = await resend.emails.send({
+ from,
+ to: body.to,
+ subject: /^\s*fwd?\s*:/i.test(original.subject) ? original.subject : `Fwd: ${original.subject}`,
+ html: original.html ?? `<pre>${original.text ?? ""}</pre>`,
+ });
+ if (error) return c.json({ error: error.message }, 400);
+ return c.json(data);
+});
+
+app.get("/api/emails/:id/thread", async (c) => {
+ const user = c.get("user");
+ const original = await getEmail(c.req.param("id"));
+ if (!original || !canAccessOwner(user, original.owner)) {
+ return c.json({ error: "Not found" }, 404);
+ }
+ const thread = await listByThreadKey(original.threadKey, isAdmin(user) ? undefined : user);
+ return c.json(thread.map(inlineCidImages));
+});
+
+app.post("/api/drafts", async (c) => {
+ const body = await c.req.json().catch(() => null);
+ if (!body?.subject && !body?.html && !body?.to) {
+ return c.json({ error: "Nothing to save" }, 400);
+ }
+
+ const stored = await resolveAttachments(body.attachments);
+ const draft = await createDraft({
+ to: body.to ? [body.to].flat() : [],
+ subject: body.subject ?? "",
+ html: body.html ?? "",
+ from: typeof body.from === "string" ? body.from : undefined,
+ attachments: stored,
+ owner: c.get("user"),
+ });
+
+ return c.json(draft);
+});
+
+app.put("/api/drafts/:id", async (c) => {
+ const user = c.get("user");
+ const body = await c.req.json().catch(() => null);
+ if (!body) return c.json({ error: "Invalid body" }, 400);
+
+ const existing = await getEmail(c.req.param("id"));
+ if (!existing || existing.status !== "draft" || !canAccessOwner(user, existing.owner)) {
+ return c.json({ error: "Not found" }, 404);
+ }
+
+ const stored = await resolveAttachments(body.attachments);
+ const draft = await updateDraft(c.req.param("id"), {
+ to: body.to ? [body.to].flat() : [],
+ subject: body.subject ?? "",
+ html: body.html ?? "",
+ from: typeof body.from === "string" ? body.from : undefined,
+ attachments: stored,
+ owner: existing.owner,
+ });
+
+ if (!draft) return c.json({ error: "Not found" }, 404);
+ return c.json(draft);
+});
+
+app.delete("/api/drafts/:id", async (c) => {
+ const draft = await getEmail(c.req.param("id"));
+ if (!draft || draft.status !== "draft" || !canAccessOwner(c.get("user"), draft.owner)) {
+ return c.json({ error: "Not found" }, 404);
+ }
+ await deleteDraft(draft.id);
+ await purgeAttachmentFiles([draft]);
+ return c.json({ ok: true });
+});
+
+app.post("/api/drafts/:id/send", async (c) => {
+ const user = c.get("user");
+ const draft = await getEmail(c.req.param("id"));
+ if (!draft || draft.status !== "draft" || !canAccessOwner(user, draft.owner)) {
+ return c.json({ error: "Not found" }, 404);
+ }
+ if (!draft.to.length || !draft.subject || !draft.html) {
+ return c.json({ error: "to, subject, and html are required" }, 400);
+ }
+
+ const from = resolveFromFor(draft.owner, draft.from || undefined);
+ const resendAttachments = await toResendAttachments(draft.attachments);
+
+ const { data, error } = await resend.emails.send({
+ from,
+ to: draft.to,
+ subject: draft.subject,
+ html: draft.html,
+ attachments: resendAttachments.length ? resendAttachments : undefined,
+ });
+
+ if (error) return c.json({ error: error.message }, 400);
+
+ const myAddresses = allAddresses().map(bareAddress);
+ await deleteDraft(draft.id);
+ await addEmail({
+ id: data.id,
+ from,
+ to: draft.to,
+ subject: draft.subject,
+ html: draft.html,
+ text: null,
+ receivedAt: new Date().toISOString(),
+ attachments: draft.attachments,
+ direction: "outbound",
+ status: "sent",
+ messageId: null,
+ inReplyTo: null,
+ references: null,
+ threadKey: computeThreadKey(draft.subject, from, draft.to, myAddresses),
+ owner: draft.owner,
+ });
+
+ return c.json(data);
+});
+
+app.get("/api/settings", (c) => {
+ const addrs = addressesFor(c.get("user"));
+ return c.json({ fromAddresses: addrs, defaultFrom: addrs[0] ?? null });
+});
+
+app.get("/api/owners", (c) => {
+ if (!isAdmin(c.get("user"))) return c.json({ error: "Forbidden" }, 403);
+ return c.json(dashboardState());
+});
+
+app.post("/api/owners/assign", async (c) => {
+ if (!isAdmin(c.get("user"))) return c.json({ error: "Forbidden" }, 403);
+ const body = await c.req.json().catch(() => null);
+ if (!body?.username || !body?.address) {
+ return c.json({ error: "username and address are required" }, 400);
+ }
+ try {
+ return c.json(await assignAddress(String(body.username), String(body.address)));
+ } catch (err) {
+ return c.json({ error: (err as Error).message }, 400);
+ }
+});
+
+app.post("/api/owners/unassign", async (c) => {
+ if (!isAdmin(c.get("user"))) return c.json({ error: "Forbidden" }, 403);
+ const body = await c.req.json().catch(() => null);
+ if (!body?.username || !body?.address) {
+ return c.json({ error: "username and address are required" }, 400);
+ }
+ return c.json(await unassignAddress(String(body.username), String(body.address)));
+});
+
+app.get("/api/push/status", async (c) =>
+ c.json({
+ configured: pushConfigured(),
+ publicKey: vapidPublicKey(),
+ count: await subscriptionCount(),
+ }),
+);
+
+app.post("/api/push/subscribe", async (c) => {
+ const body = await c.req.json().catch(() => null);
+ const sub = body?.subscription ?? body;
+ if (!sub?.endpoint || !sub?.keys) return c.json({ error: "Invalid subscription" }, 400);
+ await addSubscription(sub as PushSubscription);
+ return c.json({ ok: true });
+});
+
+app.post("/api/push/unsubscribe", async (c) => {
+ const body = await c.req.json().catch(() => null);
+ const endpoint = body?.endpoint ?? body?.subscription?.endpoint;
+ if (!endpoint || typeof endpoint !== "string") {
+ return c.json({ error: "endpoint is required" }, 400);
+ }
+ await removeSubscription(endpoint);
+ return c.json({ ok: true });
+});
+
+app.post("/api/push/test", async (c) => {
+ if (!pushConfigured()) {
+ return c.json({ error: "Push is not configured on the server." }, 400);
+ }
+ const result = await sendToAll({
+ title: "Test notification",
+ body: "Your inbox notifications are working.",
+ url: "/inbox",
+ tag: "mailbox-test",
+ });
+ return c.json(result);
+});
+
+app.get("/*", (c) => env().ASSETS.fetch(c.req.raw));
+
+let ready: Promise<void> | null = null;
+function init(): Promise<void> {
+ if (!ready) {
+ ready = (async () => {
+ await initOwners();
+ await initOidc();
+ })().catch((err) => {
+ ready = null;
+ throw err;
+ });
+ }
+ return ready;
+}
+
+export default {
+ async fetch(request: Request, binding: Env, ctx: ExecutionContext): Promise<Response> {
+ setEnv(binding);
+ await init();
+ return app.fetch(request, binding, ctx);
+ },
+};
diff --git a/tsconfig.json b/tsconfig.json
new file mode 100644
index 0000000..9d91c02
--- /dev/null
+++ b/tsconfig.json
@@ -0,0 +1,20 @@
+{
+ "compilerOptions": {
+ "lib": ["ESNext"],
+ "target": "ESNext",
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "moduleDetection": "force",
+ "types": ["@cloudflare/workers-types"],
+ "allowJs": true,
+ "resolveJsonModule": true,
+ "allowImportingTsExtensions": true,
+ "verbatimModuleSyntax": true,
+ "noEmit": true,
+ "strict": true,
+ "skipLibCheck": true,
+ "noFallthroughCasesInSwitch": true,
+ "noUncheckedIndexedAccess": true,
+ "noImplicitOverride": true
+ }
+}
diff --git a/wrangler.jsonc b/wrangler.jsonc
new file mode 100644
index 0000000..e77f56c
--- /dev/null
+++ b/wrangler.jsonc
@@ -0,0 +1,29 @@
+{
+ "$schema": "node_modules/wrangler/config-schema.json",
+ "name": "inbox",
+ "main": "server.ts",
+ "compatibility_date": "2026-08-01",
+ "compatibility_flags": [
+ "nodejs_compat"
+ ],
+ "observability": {
+ "enabled": true
+ },
+ "assets": {
+ "directory": "./public",
+ "binding": "ASSETS",
+ "run_worker_first": true
+ },
+ "kv_namespaces": [
+ {
+ "binding": "MAILBOX_KV",
+ "id": "9f2023123d284292b796806f5f314338",
+ "preview_id": "REPLACE_WITH_KV_PREVIEW_NAMESPACE_ID"
+ }
+ ],
+ "vars": {
+ "OIDC_SCOPE": "openid profile email",
+ "VAPID_SUBJECT": "mailto:[email protected]",
+ "COOKIE_SECURE": "true"
+ }
+}
\ No newline at end of file