Agent Skills › Prastavna/cfw-mailbox › cfw-mailbox

cfw-mailbox

GitHub

提供 Cloudflare Workers 自托管 Webmail 项目的架构、开发及部署指南,涵盖 React UI、Hono API、Durable Objects 状态管理及邮件收发流程。

skills/cfw-mailbox/SKILL.md Prastavna/cfw-mailbox

Trigger Scenarios

询问项目架构设计 排查邮件收发问题 配置 Cloudflare Access 认证 执行 Durable Object 迁移

Install

npx skills add Prastavna/cfw-mailbox --skill cfw-mailbox -g -y
More Options

Use without installing

npx skills use Prastavna/cfw-mailbox@cfw-mailbox

指定 Agent (Claude Code)

npx skills add Prastavna/cfw-mailbox --skill cfw-mailbox -a claude-code -g -y

安装 repo 全部 skill

npx skills add Prastavna/cfw-mailbox --all -g -y

预览 repo 内 skill

npx skills add Prastavna/cfw-mailbox --list

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.ts sends /api/* to the Hono app, /t/* to the public tracking pixel, /internal/import to the import API (enabled only when IMPORT_TOKEN is 32+ characters), /mcp to the MCP handler, and everything else to React Router (workers/app.ts). withSecurityHeaders wraps every response.
  • Auth — every API request verifies a Cloudflare Access JWT in workers/auth/access.ts. Local development uses AUTH_MODE=dev from vite.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 MailboxDO per mailbox (getMailbox(env, id)). Everything is a label (INBOX, SENT, DRAFT, OUTBOX, SPAM, TRASH, UNREAD, STARRED, IMPORTANT, SNOOZED, MUTED), and threads keep the union in thread_labels. The DO uses SQLite directly.
  • Registry — one RegistryDO for domains, mailboxes, members, user extension settings and server keys (VAPID).
  • Inbound — workers/email/inbound.ts parses with postal-mime, writes raw/attachments to R2, and calls MailboxDO.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. sendDraft moves it to OUTBOX, sets an alarm for the undo window or schedule, and deliver calls transport.send (env.EMAIL.send). Success becomes SENT; temporary failures retry at 1/5/15 minutes; permanent failures return to DRAFT with sendError.
  • Extensions — each user's settings live in registry.user_extensions (enabled, JSON settings, encrypted secret). The UI is in app/components/extensions/; the backend is in extensions/<id>/.

Hard rules

  • Never edit or reorder a shipped migration. Append a new version in workers/mailbox/schema.ts or workers/registry/schema.ts.
  • Delete children explicitly. Foreign keys may not be enforced; follow the existing deleteMessages and discardDraft patterns, 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_KEY encrypts user API keys; TRACKING_SECRET signs pixel URLs. Never return a stored key to the browser. Compare secret tokens with tokensMatch() in workers/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

  1. Add it to the right router in workers/api/index.ts (global, admin, or per-mailbox). Validate the body with a Zod schema and parseBody.
  2. Define request/response types in shared/api.ts if the browser needs them.
  3. Add the client call in app/lib/* and a test in test/api.test.ts or the relevant suite. Prefer apiFetch; raw fetch calls need the API_REDIRECT option and the isSessionExpired check from app/lib/session.ts.

Add a mailbox schema change

  1. Append { version: N + 1, name, sql } to MAILBOX_MIGRATIONS in workers/mailbox/schema.ts. Existing mailboxes run it on the next DO start.
  2. Update the row types and the queries that build API objects.
  3. Test a fresh mailbox and, for risky changes, simulate an older schema with runInDurableObject and runMigrations.

Add or change an extension

  1. Add the id and metadata to shared/extensions.ts (ExtensionId, EXTENSIONS) and the settings type.
  2. Put backend routes/settings under extensions/<id>/; store per-user state in registry.user_extensions.
  3. Add the launcher icon in app/components/extensions/ExtensionsLauncher.tsx and a settings dialog; route the dialog from app/routes/mailbox.tsx.
  4. Add hooks to app/lib/extensions.ts and E2E coverage.
  5. Gate every API call on enabled (and ready, 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.send is replaced to capture outbound messages (see test/send.test.ts).
  • Use runInDurableObject and runDurableObjectAlarm from cloudflare:test to inspect DO SQL or force alarms/purges.
  • E2E tests run against pnpm dev with 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_DOMAIN and ACCESS_AUD are required.
  • Email Routing sends inbound mail to the Worker; Email Service must be enabled per sending domain.
  • R2 bucket cfw-mailbox stores 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/import migration 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; see docs/deploying.md.

Pitfalls

  • Do not put secrets in wrangler.jsonc; declare optional secrets in workers/env.d.ts so Env is typed.
  • wrangler types only knows vars and bindings, not secrets.
  • Alarm-driven work must re-arm scheduleAlarm(); one alarm handles sends, snoozes and Trash/Spam purges.
  • ctx.id.name is the mailbox ID because getMailbox uses idFromName.
  • Mailbox roles are checked in workers/api/index.ts; a new route under /mailboxes/:id inherits it automatically.
  • Keep docs/architecture.md and docs/api.md in sync with behaviour changes.

Version History

  • d9871cd Current 2026-12-01 07:51

Same Skill Collection

.agents/skills/react-router/SKILL.md
skills/cfw-mailbox-ai-assistant/SKILL.md
skills/cfw-mailbox-open-tracking/SKILL.md

Metadata

Files
0
Version
ef83d0b
Hash
bcef960b
Indexed
2026-12-01 07:51

Accueil - Wiki
Copyright © 2011-2026 iteam. Current version is 2.156.0. UTC+08:00, 2026-12-02 02:18
浙ICP备14020137号-1