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

cfw-mailbox

GitHub

用于处理cfw-mailbox仓库的Agent技能,涵盖基于Cloudflare Workers的自托管Webmail应用。支持架构咨询、React UI开发、Hono API接口、Durable Object状态管理、邮件收发、R2存储及部署调试等全栈任务。

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

触发场景

询问Webmail应用架构或组件逻辑 需要编写或修改Hono API端点 进行Durable Object迁移或状态管理 配置或调试Cloudflare Workers部署 处理邮件路由、R2存储或认证相关代码

安装

npx skills add Prastavna/cfw-mailbox --skill cfw-mailbox -g -y
更多选项

不安装直接使用

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, local commands and the extension checklist.
  • docs/extensions.md — what the six optional features do and where each lives.
  • 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], ext/:extensionId, admin
  components/mail/      Header, sidebar, thread list, conversation view, settings, compose
  components/extensions Launcher, ExtensionHost and each extension's UI and surfaces
  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
  mcp/                  MCP server served at /mcp
  push/                 Web Push (VAPID, encrypted payloads)
  lib/                  crypto, migrations, HTTP errors, security headers
extensions/             Optional features, one folder per extension
  ai/  tracking/  templates/  followups/  unsubscribe/  calendar/
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 (EXTENSIONS) and its settings/limit types; ExtensionId is derived from that object.
  2. Backend: extensions/<id>/ with routes (mounted at /api/extensions/<id>) and status(env, email); register both in extensions/registry.ts's SERVERS. Store per-user state in registry.user_extensions.
  3. UI: add the tile (icon, tone, lazy Settings) and any surfaces to EXTENSION_UI in app/components/extensions/registry.ts. Surfaces are composer, thread, page (served by app/routes/extension-page.tsx) and sidebar. ExtensionHost opens settings, so mailbox.tsx needs no change.
  4. Add hooks to app/lib/extensions.ts, a status to app/demo/server.ts, and tests (Vitest plus E2E for the serial per-user settings).
  5. Gate every API call on enabled (and ready, if the feature needs a secret or provider), and every surface on useExtensionReady.

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.

版本历史

  • 26fa6dd 当前 2026-12-02 08:04

    新增 extensions.md 文档,详细说明六个可选功能的定义及代码位置;修复文档漂移问题。

  • d9871cd 2026-12-01 07:51

同 Skill 集合

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

元信息

文件数
0
版本
6ea7c14
Hash
87ef4c5d
收录时间
2026-12-01 07:51

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