cfw-mailbox
GitHub提供 Cloudflare Workers 自托管 Webmail 项目的架构、开发及部署指南,涵盖 React UI、Hono API、Durable Objects 状态管理及邮件收发流程。
Trigger Scenarios
Install
npx skills add Prastavna/cfw-mailbox --skill cfw-mailbox -g -y
SKILL.md
Frontmatter
{
"name": "cfw-mailbox",
"license": "Apache-2.0",
"description": "Work in the cfw-mailbox repository, a self-hosted Gmail-style webmail on Cloudflare Workers. Use for architecture questions, React Router routes, Hono API endpoints, Durable Object migrations, inbound\/outbound email, Cloudflare Access auth, R2 storage, tests, or deployment."
}
cfw-mailbox
Self-hosted, Gmail-style webmail on Cloudflare Workers: React Router 8 (framework mode) for the UI, Hono for the API, two Durable Objects for state, R2 for blobs, Email Routing for inbound mail, Email Service for outbound mail, and Cloudflare Access for sign-in.
Read first
docs/architecture.md— how receiving, sending, notifications, security and open tracking work.docs/development.md— layout and local commands.docs/api.md— every API route and who may call it.docs/deploying.md— Access, Email Routing/Service, secrets and limits.
Read the installed package versions before using framework APIs; this app tracks recent React Router 8 and AI SDK 7 releases.
Layout
app/ React UI
routes/mailbox.tsx The signed-in shell: header, sidebar, dialogs, shortcuts
routes/ /, /mail/:mailboxId/:folder[/:threadId], admin, contacts
components/mail/ Header, sidebar, thread list, conversation view, settings
components/extensions Extensions launcher and each extension's UI
lib/ API client, compose store, sanitising, PWA, hooks
shared/ Types and helpers used by both browser and Worker
workers/
app.ts Worker entry; /api → Hono, else React Router
index.ts Dispatch: /api, /t/ (tracking), /internal/import, /mcp
api/ Hono API and per-mailbox role middleware
auth/access.ts Cloudflare Access JWT verification (+ local dev mode)
mailbox/ MailboxDO, schema migrations, search, keys
registry/ RegistryDO: domains, mailboxes, members, user extensions
email/ inbound, outbound, MIME, mbox/zip export, reply webhook
push/ Web Push (VAPID, encrypted payloads)
lib/ crypto, migrations, HTTP errors, security headers
extensions/ Optional features, one folder per extension
ai/ AI Assistant backend
tracking/ Open Tracking backend
skills/ Agent skills (installable with `npx skills add`)
test/ Vitest tests running in workerd
e2e/ Playwright tests against `pnpm dev`
Runtime map
- Request dispatch —
workers/index.tssends/api/*to the Hono app,/t/*to the public tracking pixel,/internal/importto the import API (enabled only whenIMPORT_TOKENis 32+ characters),/mcpto the MCP handler, and everything else to React Router (workers/app.ts).withSecurityHeaderswraps every response. - Auth — every API request verifies a Cloudflare Access JWT in
workers/auth/access.ts. Local development usesAUTH_MODE=devfromvite.config.ts. Mailbox access is checked per route by role (owner/member/viewer); unknown mailboxes answer 404, and viewers cannot mutate anything except read-only AI routes. - Mailbox data — one
MailboxDOper mailbox (getMailbox(env, id)). Everything is a label (INBOX,SENT,DRAFT,OUTBOX,SPAM,TRASH,UNREAD,STARRED,IMPORTANT,SNOOZED,MUTED), and threads keep the union inthread_labels. The DO uses SQLite directly. - Registry — one
RegistryDOfor domains, mailboxes, members, user extension settings and server keys (VAPID). - Inbound —
workers/email/inbound.tsparses withpostal-mime, writes raw/attachments to R2, and callsMailboxDO.ingest. Redeliveries are skipped by Message-ID. Failed stores delete the R2 uploads and rethrow so delivery retries. - Outbound — a draft is a message with
DRAFT.sendDraftmoves it toOUTBOX, sets an alarm for the undo window or schedule, anddelivercallstransport.send(env.EMAIL.send). Success becomesSENT; temporary failures retry at 1/5/15 minutes; permanent failures return toDRAFTwithsendError. - Extensions — each user's settings live in
registry.user_extensions(enabled, JSONsettings, encryptedsecret). The UI is inapp/components/extensions/; the backend is inextensions/<id>/.
Hard rules
- Never edit or reorder a shipped migration. Append a new version in
workers/mailbox/schema.tsorworkers/registry/schema.ts. - Delete children explicitly. Foreign keys may not be enforced; follow the
existing
deleteMessagesanddiscardDraftpatterns, or add a trigger. - R2 cleanup is the caller's job. If a DB write fails after uploads, delete the uploaded keys; on success, delete removed attachment keys.
- Writes must be JSON (
parseBody) so cross-site form posts cannot pass the CORS preflight. State-changing requests are also origin-checked. - No mail HTML in the app origin. Inbound HTML is sanitised with DOMPurify and rendered in a sandboxed iframe with its own CSP. Keep remote images blocked by default.
- Keep secrets server-side.
ENCRYPTION_KEYencrypts user API keys;TRACKING_SECRETsigns pixel URLs. Never return a stored key to the browser. Compare secret tokens withtokensMatch()inworkers/lib/crypto.ts, not===. - Rate limits are per user for authenticated routes (
API_LIMITER,HEAVY_LIMITER,AI_LIMITER) and per IP for/t/(TRACK_LIMITER). - Viewers are read-only. Any new mutating route is covered by the mailbox middleware; AI routes are the deliberate exception.
- Extensions are off until a user enables them, and their API routes must refuse to run while off.
Common tasks
Add an API route
- Add it to the right router in
workers/api/index.ts(global, admin, or per-mailbox). Validate the body with a Zod schema andparseBody. - Define request/response types in
shared/api.tsif the browser needs them. - Add the client call in
app/lib/*and a test intest/api.test.tsor the relevant suite. PreferapiFetch; rawfetchcalls need theAPI_REDIRECToption and theisSessionExpiredcheck fromapp/lib/session.ts.
Add a mailbox schema change
- Append
{ version: N + 1, name, sql }toMAILBOX_MIGRATIONSinworkers/mailbox/schema.ts. Existing mailboxes run it on the next DO start. - Update the row types and the queries that build API objects.
- Test a fresh mailbox and, for risky changes, simulate an older schema with
runInDurableObjectandrunMigrations.
Add or change an extension
- Add the id and metadata to
shared/extensions.ts(ExtensionId,EXTENSIONS) and the settings type. - Put backend routes/settings under
extensions/<id>/; store per-user state inregistry.user_extensions. - Add the launcher icon in
app/components/extensions/ExtensionsLauncher.tsxand a settings dialog; route the dialog fromapp/routes/mailbox.tsx. - Add hooks to
app/lib/extensions.tsand E2E coverage. - Gate every API call on
enabled(andready, if the feature needs a secret or provider).
Change the send path
MailboxDO.sendDraft → deliver → buildEmail → transport.send. Keep
buildEmail the only place that shapes the Email Service payload. Retries call
deliver again, so anything added there must be idempotent.
Commands
pnpm dev # React Router + Worker, dev auth as dev@example.com
pnpm typecheck # wrangler types + react-router typegen + tsc -b
pnpm test # Vitest in workerd
pnpm test:e2e # Playwright against pnpm dev
pnpm build # production build
pnpm deploy # build + wrangler deploy
pnpm cf-typegen # regenerate worker-configuration.d.ts
Local dev secrets live in .dev.vars (gitignored); .dev.vars.example lists
them. vite.config.ts supplies development defaults for AUTH_MODE,
DEV_USER_EMAIL, ADMIN_EMAILS, ENCRYPTION_KEY, TRACKING_SECRET, and
raises rate limits when E2E=1.
Testing
- Unit/integration tests run the real Worker in workerd via
test/worker.ts.makeMailbox()creates a fresh domain + mailbox;transport.sendis replaced to capture outbound messages (seetest/send.test.ts). - Use
runInDurableObjectandrunDurableObjectAlarmfromcloudflare:testto inspect DO SQL or force alarms/purges. - E2E tests run against
pnpm devwith a single dev user in.wrangler/e2e-state. Each test creates its own mailbox. Shared user settings (AI, tracking) need serial tests and a reset. - The local email simulator captures outbound mail but does not expose the sent MIME; test payload shaping in Vitest instead.
Deployment
- Cloudflare Access protects the Worker;
ACCESS_TEAM_DOMAINandACCESS_AUDare required. - Email Routing sends inbound mail to the Worker; Email Service must be enabled per sending domain.
- R2 bucket
cfw-mailboxstores raw mail, large HTML and attachments. - Required secrets:
ACCESS_TEAM_DOMAIN,ACCESS_AUD,ADMIN_EMAILS,ENCRYPTION_KEY. Optional:IMPORT_TOKEN(32+ random characters, enables the one-off/internal/importmigration API; delete it afterwards),TRACKING_SECRET,APP_ORIGIN,MCP_TOKEN,MCP_USER_EMAIL,REPLY_WEBHOOK_*. - The public tracking pixel needs an Access Bypass policy for
/t/*and a Bot Fight Mode decision; seedocs/deploying.md.
Pitfalls
- Do not put secrets in
wrangler.jsonc; declare optional secrets inworkers/env.d.tssoEnvis typed. wrangler typesonly knows vars and bindings, not secrets.- Alarm-driven work must re-arm
scheduleAlarm(); one alarm handles sends, snoozes and Trash/Spam purges. ctx.id.nameis the mailbox ID becausegetMailboxusesidFromName.- Mailbox roles are checked in
workers/api/index.ts; a new route under/mailboxes/:idinherits it automatically. - Keep
docs/architecture.mdanddocs/api.mdin sync with behaviour changes.
Version History
- d9871cd Current 2026-12-01 07:51


