diff --git a/README.en.md b/README.en.md index f2a2779..f2d9383 100644 --- a/README.en.md +++ b/README.en.md @@ -14,7 +14,7 @@ The repository is pinned to Bun `1.4.0`. The application preserves the existing - D1/R2 persistence for inbound mail, attachments, ownership, read/star state, archive/trash actions, drafts, sent mail, delivery state, and event timelines. Downloads verify ownership, size, and checksum before returning bytes. - Resend outbound delivery with stable idempotency keys, reply/RFC headers, streamed R2 attachments, error classification, retries, and separate submitted/delivered semantics. - Explicit `AUTH_MODE=local|cloudflare-access` authentication: a non-email local username and PBKDF2 password, or a verified Cloudflare Access identity mapped to the same stable Owner. Both modes retain revocable D1 sessions, secure cookies, Origin/CSRF validation, login rate limiting, and security headers. When Access expires, the browser keeps the active compose buffer in that tab and refreshes only safe GETs after reauthentication; it never blindly replays writes. -- Multi-domain mail identities: domains enter through a controlled configuration flow, and address routing uses exact Cloudflare Email Routing Rules in explicitly selected zones. Inbound ownership is resolved from the envelope recipient before body parsing or R2 writes. Inbox filters apply server-side to mail, drafts, search, counts, and pagination. Bulk actions default to selected loaded messages; filtered-thread and Owner-wide thread expansion require an explicit choice. Trash is always an Owner-wide view. +- Multi-domain mail identities: domains can be verified and connected in the browser, with enable/disable and unknown-recipient settings plus editable address names/signatures ([Preview setup](./docs/PREVIEW.md)). Address routing uses exact Cloudflare Email Routing Rules in explicitly selected zones. Inbound ownership is resolved from the envelope recipient before body parsing or R2 writes. Inbox filters apply server-side to mail, drafts, search, counts, and pagination. Bulk actions default to selected loaded messages; filtered-thread and Owner-wide thread expansion require an explicit choice. Trash is always an Owner-wide view. - Multiple sender identities: new mail prefers a ready exact address selected by the current address filter, while other views use the ready global default; replies and drafts keep their original identity. The server checks Owner, address state, and the domain's Resend sending verification, then freezes the From/signature snapshot. The compose UI explains disabled, unverified, stale, and failed sender states. Legacy `OUTBOUND_FROM_EMAIL` / `MAIL_FROM` values are only for system auto-replies and notifications. - Compose UI: the desktop floating window supports dragging, keyboard resizing, minimizing, and maximizing; phones retain full-screen compose. To offers recent contacts from messages already loaded in this browser session; Cc/Bcc chips, autosave, and attachments remain available. The optional HTML source starts collapsed. See [the UI/UX review](./docs/UI_UE_REVIEW.md) for the current scope and pending acceptance work. - The compose editor loads on first use; if its download fails, the workspace remains available and prompts a page refresh before retrying. @@ -27,7 +27,7 @@ The repository is pinned to Bun `1.4.0`. The application preserves the existing | Environment | Outbound provider | Data and credentials | Constraint | | --- | --- | --- | --- | | development/test | Explicit `demo`/fake | Local D1/R2; bootstrap required | Set `ALLOW_FAKE_SERVICES=true` | -| preview | Private configuration | Isolated preview resources | Do not reuse production credentials or D1 | +| preview | Private configuration | Production D1/R2 and Owner account | Code deploys independently; writes affect production; native Previews need separate secrets, while Version URLs retain production secrets ([Preview guide](./docs/PREVIEW.md)) | | production | `resend` only | Real D1/R2 and Wrangler secrets | Missing bindings/secrets fail closed | The repository contains no fixed login password. Use `scripts/bootstrap-admin.ts` with `FLAREMAIL_ADMIN_USERNAME` and environment variables in the current shell; an optional `FLAREMAIL_PROFILE_EMAIL` is profile data and grants no mail identity. Access-only initialization uses `bun run auth:bootstrap:access` and does not require a local password. diff --git a/README.md b/README.md index f47e573..bb98d73 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ FlareMail 是一个部署在 Cloudflare Workers 上的个人自托管邮件工 - Resend 出站:稳定幂等键、`reply_to`/RFC headers、R2 流式附件上传与完整性校验、错误分类、重试,以及 `submitted` 与 `delivered` 的严格语义区分。 - Resend webhook:Svix 签名与时间窗口校验、事件去重、乱序保护、未知事件保留,以及退信/投诉/抑制等终态。 - 明确的 `AUTH_MODE=local|cloudflare-access` 认证:本地用户名(无需邮箱)和 PBKDF2 密码,或验签后的 Cloudflare Access 身份映射到相同稳定 Owner;两种模式共用 D1 会话吊销、Cookie、Origin/CSRF、登录限速和安全响应头。Access 过期时,浏览器保留当前标签中的写信内容,重新认证后只刷新安全 GET,不盲重放写请求。 -- 多域名邮件身份:域名通过受控配置显式加入;地址路由只使用限定 zone 的 Cloudflare Email Routing Rules API 精确规则。收件在读取正文/R2 前按信封收件人解析地址,统一邮箱支持服务端域名/地址筛选,搜索、计数、分页和草稿使用同一筛选范围。批量操作默认只修改已选的已加载邮件;筛选内会话和跨 Owner 地址的完整会话均需明确选择,回收站始终是 Owner 全局视图。 +- 多域名邮件身份:进入域名或邮箱地址页面时自动同步 Cloudflare 中指向本应用的已有域名和邮箱规则,无需重复填写 Zone ID;也支持手动接入其他域名、启停域名和设置未知地址策略。地址支持名称与签名编辑,详见 [Preview 与接入配置](./docs/PREVIEW.md)。同步不改动远程规则,保留本地设置及删除状态。地址路由只使用限定 zone 的 Cloudflare Email Routing Rules API 精确规则。收件在读取正文/R2 前按信封收件人解析地址,统一邮箱支持服务端域名/地址筛选,搜索、计数、分页和草稿使用同一筛选范围。批量操作默认只修改已选的已加载邮件;筛选内会话和跨 Owner 地址的完整会话均需明确选择,回收站始终是 Owner 全局视图。 - 多发件身份:新邮件优先采用当前精确地址筛选中的可发信地址,其他视图使用可发信的全局默认;回复和草稿保留各自原有身份。服务端检查 Owner、地址状态和域级 Resend 发信验证,再固定 From/签名快照;编辑器分别说明地址/域停用、验证状态、检查过期和失败。旧 `OUTBOUND_FROM_EMAIL` / `MAIL_FROM` 仅供系统自动回复和通知使用。 - 响应式阅读工作台:桌面三栏、可折叠侧栏、默认 440 px 且可在 280–480 px 拖拽/键盘调整的邮件列表、标准/紧凑显示密度、平板/手机 drill-in、近全屏专注阅读和 `/messages/[id]` 独立阅读地址;全局星标按 Owner 范围跨收件/归档/已发送/草稿服务端分页,域名概览、邮箱地址管理和设置可从侧栏分别直达,域名卡片可输入地址前缀快速创建并对收信规则未完成的状态给出提示;Owner 标签可创建、重命名、删除并应用到邮件,标签视图跨收件、归档、已发送、草稿分页;收件、已发送、归档、星标和标签视图支持仅对当前页已选邮件批量添加或移除标签,不扩展到整个会话;星标/标签视图对明确选中的非草稿邮件还支持跨文件夹已读、星标和删除操作,归档仅作用于全为收件的选择,含草稿时只保留标签操作;列表宽度会在详情区可用空间不足时临时收窄,按 Enter 可恢复 440 px 默认值;同一用户打开的窗口只同步邮件状态信号,不传播正文、地址或凭据。 - 写信界面:桌面浮动窗口支持拖动、键盘缩放、最小化与最大化,手机保持全屏;多发件身份选择、To 收件人最近联系人建议、Cc/Bcc chip、草稿自动保存及附件上传;建议只来自当前会话已加载的邮件,HTML 源码选项默认收起。当前 UI 审查和后续验收范围见 [docs/UI_UE_REVIEW.md](./docs/UI_UE_REVIEW.md)。 @@ -39,7 +39,7 @@ FlareMail 是一个部署在 Cloudflare Workers 上的个人自托管邮件工 | 环境 | 出站 provider | 数据与凭据 | 约束 | | --- | --- | --- | --- | | development/test | 显式 `demo`/fake | 本地 D1/R2;管理员需 bootstrap | 必须设置 `ALLOW_FAKE_SERVICES=true` | -| preview | 按私有配置 | 独立 preview 资源 | 不应复用生产凭据或 D1 | +| preview | 按私有配置 | 与生产共用 D1/R2 和 Owner 账号 | 代码独立部署;数据修改直接影响生产;原生 Preview 单独配置 secrets,版本预览可直接保留生产密钥,见 [Preview 文档](./docs/PREVIEW.md) | | production | 仅 `resend` | 真实 D1/R2 与 Wrangler secrets | 缺少必要 binding/secret 时 fail closed | 仓库不包含固定登录密码。使用 `scripts/bootstrap-admin.ts` 将 Owner 的本地用户名/凭据写入本地或远程 D1;登录名使用 `FLAREMAIL_ADMIN_USERNAME`,资料邮箱 `FLAREMAIL_PROFILE_EMAIL` 可选且不授予收发信权限。Access-only 初始化可通过 `bun run auth:bootstrap:access` 建立同一稳定 Owner,而无需设置本地密码。 diff --git a/docs/API.md b/docs/API.md index f066b0f..e35cb7d 100644 --- a/docs/API.md +++ b/docs/API.md @@ -81,11 +81,45 @@ the actual envelope destination independently from the message's To header. ## Managed domains and addresses `GET /api/workspace/mail-identities` returns only the authenticated Owner's -configured domains and addresses. Domain enrollment is an operator-controlled -configuration step (`bun run mail:domain:configure`) that records the exact -domain-to-zone and Worker mapping; the browser cannot choose an arbitrary zone, -Worker, API origin, or Cloudflare endpoint. The response also includes boolean -provider-configuration flags; it never returns a token or key. +configured domains and addresses. `domainOnboarding` reports whether browser +enrollment is available and whether route management credentials are configured. +The deployment fixes `MAIL_IDENTITY_WORKER_NAME` and `MAIL_IDENTITY_ACCOUNT_ID`; +the browser supplies a domain and Zone ID, which the server verifies against +Cloudflare before recording the mapping. The browser cannot choose a Worker, +account, API origin, or Cloudflare endpoint. The operator command +`bun run mail:domain:configure` remains available. Provider-configuration flags +never return a token or key; `cloudflareManagement` separately reports whether +the management credential is present. + +- `POST /api/workspace/mail-identities/sync` discovers accessible zones in the + deployment account and imports existing literal recipient rules targeting + the configured Worker. It requires the authenticated workspace Owner and + Zone Read / Email Routing Rules Read permissions. The UI invokes it on entry + and offers a retry button; GET remains a database read. Provider requests are + read-only, paginated and bounded. Other Worker/forward/drop rules, malformed + recipients and competing exact rules are skipped. Worker catch-all imports + a domain without inventing addresses; a new domain collects unknown recipients + only when its catch-all is verified to target this Worker. Existing settings, + tombstones and operations are preserved. Imported addresses are never granted + send permission or remote rule ownership. Returns `sync.domainsCreated`, + `addressesCreated`, `skippedRules` and per-domain `warnings` with safe error + categories. Provider failures retain local configuration. This writes shared + D1 identity metadata, without rewriting historical mail or remote routing. +- `POST /api/workspace/mail-identities/domains` accepts only `domainName` and + `zoneId`. It requires Zone Read permission, checks the zone ID, domain suffix + boundary and deployment account, and enrolls with unknown recipients rejected. + A repeated identical enrollment returns the existing domain; existing mappings + and ownership are never overwritten. Enrollment does not modify DNS or create + Email Routing rules, and does not claim receiving or sending readiness. +- `PATCH /api/workspace/mail-identities/domains/:domainId` accepts `enabled` + and/or `unknownRecipientPolicy` (`reject` or `collect`). It preserves the zone, + Worker mapping, addresses and historical mail. Switching to collect requires + a fresh successful observation of catch-all targeting the configured Worker. + Disabling a domain stops application receiving/sending without deleting + external rules. Concurrent settings or health updates cause a refresh/retry. +- `PATCH /api/workspace/mail-identities/:addressId` accepts `displayName` and + `signature`. It edits only the authenticated Owner's non-deleted address and + preserves the email, routing, and receiving/sending preferences. - `GET /api/workspace/mail-identities/:addressId/delete-preview` is an authenticated, read-only snapshot of the exact-address rule, catch-all target diff --git a/docs/PREVIEW.md b/docs/PREVIEW.md new file mode 100644 index 0000000..10588a4 --- /dev/null +++ b/docs/PREVIEW.md @@ -0,0 +1,143 @@ +# Preview 域名与邮件身份管理 + +使用 Cloudflare 原生 Worker Previews 部署,要求 Wrangler >= 4.135.0。 +已有较新全局 Wrangler 时可直接使用全局命令。仓库本地构建、迁移与测试继续遵循 +`package.json` 的 Bun 和 Wrangler 版本;不要使用本地旧版 Wrangler 执行新 Preview 命令。 + +本项目采用**共用生产数据、独立发布代码**的 Preview 模式。`previews.d1_databases` +的 `database_id` 与生产 `DB` 相同,`previews.r2_buckets` 的 `bucket_name` 与生产 +`BUCKET` 相同。邮件、域名、地址、Owner 账号及持久化设置共用;在 Preview 中 +保存、删除或配置规则会直接影响生产。新代码可单独发布到 Preview,无需同时 +发布生产代码。 + +1. 将 `wrangler.preview.deploy.toml.example` 复制为被忽略的 + `wrangler.preview.deploy.toml`,从当前生产绑定填写 D1/R2 标识及账号 ID, + 核对线上实际绑定;真实资源标识不得提交。域名接入的 + `MAIL_IDENTITY_WORKER_NAME` 指向生产收信 Worker。复制生产非敏感变量, + 保留 Preview 专用的 `APP_ENV`、`APP_BASE_URL`、`APP_VERSION`。 +2. 默认使用 Cloudflare 返回的 + `https://-..workers.dev`, + 并将 `APP_BASE_URL` 设置为该地址。不创建 Preview 自定义域名关联。 +3. 检查共享数据库的 schema 版本与待发布代码兼容。此次切换无需 migration。 + 后续 schema 变更同时影响两套代码,必须按远程迁移授权流程核验并保证当前 + 生产版本兼容;不要为发布 Preview 自动迁移或重置数据库。 +4. 使用现有生产 Owner 账号登录,不初始化或覆盖 Owner,不导入原临时 Preview + 账号。不同 hostname 的 Cookie 独立,需要分别登录。此前创建的独立 Preview + 数据库、临时账号、空 R2 桶及本机登录文件已按用户要求删除。旧部署历史仍可 + 保留代码记录,但其旧数据绑定已不可用;不再使用旧部署地址。 + **原生 Worker Preview** 不继承生产 secrets,也无法从 Cloudflare 读取其明文;需单独输入或 + 使用权限 `0600` 的私有 secrets 文件配置。缺少对应 Key 时,该服务不可用。 + 缺少 Telegram Token 时将 Preview 的 `TELEGRAM_ENABLED` 设为 `false`, + 避免配置校验阻止网页访问;生产 Telegram 功能及其他生产配置保持不变。 +5. 完成 `bun test`、`bun run check`、`bun run build` 和 Chromium 桌面/手机 QA, + 提交后执行: + + ```sh + wrangler preview --config wrangler.preview.deploy.toml --name mail-identities --ignore-base-config --message "git " + ``` + +6. 核对 Preview 部署 ID、D1/R2 与生产一致、应用版本、登录、身份管理页面及 + `/api/health`,再确认生产 deployment ID 没有变化。不要执行 `wrangler deploy` + 来发布原生 Preview,它会部署生产。 + +## 直接复用生产密钥的版本预览 + +如果需要与生产共用数据库和现有密钥,可使用 **Version URL**。这是与上述 +原生 Worker Preview 不同的发布方式:`wrangler versions upload` 上传新版本, +保留当前 Worker 的既有 secret 绑定,但不改变生产流量分配。密钥不会被读取、 +导出或重新输入;缺少的密钥也不会自动生成。 + +1. 从 `wrangler.version-preview.deploy.toml.example` 创建被忽略的私有 + `wrangler.version-preview.deploy.toml`。填入生产 D1/R2 绑定和线上非敏感变量, + 包括 Telegram 开关、Bot 用户名等;不要只依据可能过时的本机生产配置。 +2. 将 `APP_ENV`、`APP_BASE_URL`、`APP_VERSION` 设置为此预览的值, + `MAIL_IDENTITY_WORKER_NAME` 仍指向生产收信 Worker。保留当前生产的 + compatibility date/flags。不要配置新的 routes、DNS 或 Cron。 +3. 完成构建和校验,使用 `--dry-run` 检查版本打包,再执行: + + ```sh + wrangler versions upload --config wrangler.version-preview.deploy.toml --preview-alias function-check --secrets-file .env --message "git " + ``` + +4. 用返回的 `https://function-check-..workers.dev` + 入口验证,核对新版本的 D1/R2、secret **名称**、Telegram 开关和生产 deployment + ID。不执行 `wrangler versions deploy`、`wrangler deploy` 或 `wrangler triggers deploy`。 + +两个入口分别核验。原生 Preview 的资源元数据 `urls` 应包含默认的 `workers.dev` +入口,HTTPS、登录页与健康接口均应可访问。此前的 Preview 自定义域名已按用户 +要求移除,不在后续发布中自动恢复。移除旧关联时先核对域名 changeset 只删除目标 +Preview 域名,没有新增/冲突及生产域名修改;保留生产域名、其他域名和流量。 +此清理只涉及 Preview 网站入口,不调整邮件 MX 或邮件路由。 + +本机项目根目录的 `.env` 用于保存有明文来源的应用密钥,权限必须为 `0600`, +且已被 Git 忽略。当前保存 `CLOUDFLARE_EMAIL_ROUTING_TOKEN`;后续对话和版本 +预览部署从此文件读取,无需重新传递 Token。`--secrets-file .env` 将它作为 secret +上传,已有的 Resend/Telegram secret 绑定继续保留。不要把 `.env` 当作已保存所有 +远程密钥的备份:Cloudflare 上现有 secret 的明文无法读取回本机。 + +配置 Token 时先只读验证有效性、目标 Zone 和规则读取能力;验证不创建邮件 +路由、不改 catch-all 或 DNS。设置 secret 不等于验证真实收发信。 +存在未发布的新版本时,`wrangler secret put` 会拒绝直接更新生产, +`wrangler versions secret put` 则基于最新上传版本创建版本。使用上述版本上传 +命令更新 Preview,避免为配置 Token 将预览代码发布生产。 + +核对生产配置时,先读取生产 deployment 指向的 version,再检查该 version 的 +bindings;Worker settings 可能显示最新上传的预览配置,不代表生产流量配置。 + +Version URL 与原生 Worker Preview 都使用各自的 `workers.dev` 地址;原生 Preview +不会自动切换到 Version URL 的版本,也不会因此取得生产密钥。 +两种入口均使用生产 Owner,但需要分别登录。生产密钥轮换后需重新上传版本, +既有预览不会自动同步新值。Email Routing 和 Cron 仍执行生产部署的代码。 + +## 从网页接入邮件域名 + +管理员为目标环境配置 `MAIL_IDENTITY_WORKER_NAME` 和 +`MAIL_IDENTITY_ACCOUNT_ID`,并添加限于目标邮件 Zone 的 Cloudflare Token: + +- `CLOUDFLARE_EMAIL_ROUTING_READ_TOKEN`:Zone Read、Email Routing Rules Read。 +- `CLOUDFLARE_EMAIL_ROUTING_TOKEN`:创建/删除规则需要 Email Routing Rules Edit。 + 若不提供单独读取 Token,管理 Token 还需包含 Zone Read 和规则读取权限。 +- `RESEND_API_KEY`:发信与域名发信状态检查使用生产 Resend 账号所需的 Key。 + +向一个原生 Preview 添加 secret 使用: + +```sh +wrangler preview secret put CLOUDFLARE_EMAIL_ROUTING_READ_TOKEN --name mail-identities --config wrangler.preview.deploy.toml +``` + +通过交互式输入传递 Token,不写入配置、命令参数或版本控制。重新部署时使用 +所需 secrets 的受限文件和 `--secrets-file`,并核对部署后的 secret 名称;当前 +命令采用 `--ignore-base-config`,不从 Previews Base 自动补入 secrets。 + +进入“域名”或“邮箱地址”时,页面先读取本地配置,再通过已登录的 +`POST /api/workspace/mail-identities/sync` 自动发现 Token 可访问的本账号 Zone。 +同步识别指向配置收信 Worker 的精确邮箱规则及 catch-all,导入对应域名与地址; +无需手动填写已有配置的 Zone ID。也可以点击“同步 Cloudflare 配置”重新发现。 +属于其他 Worker、转发目标、重复或无效的规则不会导入,catch-all 不会虚构邮箱地址。 +Cloudflare 接口只执行读取,不创建/修改/删除路由或 DNS。导入的规则标记为 +`imported`,不取得规则删除权限,也不会自动启用发信。重复同步保留已有名称、 +签名、启停、删除及操作状态,不恢复已删除地址。同步失败时仍展示本地配置和重试提示。 +新接入且确认指向本应用的 catch-all 域名初始采用未知地址收集;既有域名的 +未知地址策略保持不变。此同步写入的是共用 D1 的身份记录,两种环境都能看到。 + +本地配置可见不等于本次 Cloudflare 同步成功。同步错误区分 Token 权限、连接失败、 +超时和限流;接口只返回安全的 `details.reason`,不暴露 Token 或原始供应商响应。 +发布时除登录页和健康接口外,还应在 Workers 运行时核验真实 Zone/规则读取, +避免仅在 Bun 中验证通过而漏过平台调用差异。 + +“手动接入其他域名”用于尚未发现的配置;其中“添加邮件域名”核验域名及所属 Zone,不自动修改 MX/SPF/DKIM 等 DNS。 +接入后检查域名状态,再创建邮箱地址。缺少 Token 或部署映射时,页面会显示 +配置提示;已有域名/地址的本地设置仍可以编辑。域名设置可启停域名及切换未知 +地址策略,地址可编辑名称和签名;已有的地址启停、删除、恢复及发信操作继续可用。 + +**原生 Preview 的 HTTP 测试不代表真实收信。** Email Routing 与 Cron 目标是 +Worker 的生产 handler,不能选择某个原生 Preview。本项目共用数据时继续由生产 +Worker 收信及执行定时任务,Preview 网页可查看其写入的邮件,但收信处理代码 +仍是生产版本。只有需要测试新的 `email()` / `scheduled()` 代码时,才另行安排 +接收/定时任务测试;无需为了网页 Preview 同时发布生产。配置收信规则时使用 +生产 Worker;不要把 Wrangler OAuth 登录凭据当成应用的长期管理 Token。 + +参考:[Worker Previews](https://developers.cloudflare.com/workers/previews/)、 +[自定义域名](https://developers.cloudflare.com/workers/previews/custom-domains/)、 +[资源隔离](https://developers.cloudflare.com/workers/previews/resources/)、 +[Version URLs](https://developers.cloudflare.com/workers/versions-and-deployments/version-urls/)。 diff --git a/docs/PRODUCTION_CHECKLIST.md b/docs/PRODUCTION_CHECKLIST.md index c91aa09..22a14e2 100644 --- a/docs/PRODUCTION_CHECKLIST.md +++ b/docs/PRODUCTION_CHECKLIST.md @@ -33,8 +33,9 @@ recipient addresses or full R2 keys into shared evidence. ## Target, configuration and invariants -- [ ] The target is explicitly recorded as production; no Preview command - resolves to production D1, R2, Worker, Resend credentials or webhook. +- [ ] The target is explicitly recorded as production and uses production + application variables. Preview deliberately shares D1/R2 and the Owner under + [PREVIEW.md](./PREVIEW.md), but its code release does not switch production traffic. - [ ] The private `wrangler.deploy.toml` was created from `wrangler.deploy.toml.example` and `git check-ignore wrangler.deploy.toml` confirms it is ignored. @@ -122,7 +123,7 @@ recipient addresses or full R2 keys into shared evidence. implied by local plan/apply/verify evidence. - [ ] The checkout's latest migration filename and schema version are recorded - (currently migrations `0001` through `0027` and schema version `27`); the + (currently migrations `0001` through `0028` and schema version `28`); the repository's `schema-version.ts` and preflight output were checked rather than relying on an old number. - [ ] Every unapplied migration is approved and applied in numeric order: @@ -205,9 +206,10 @@ recipient addresses or full R2 keys into shared evidence. Email Routing → Enable/Get started → verify the zone's current DNS ``` -- [ ] The exact actual domain-to-zone/Worker mapping is recorded with +- [ ] The exact actual domain-to-zone/Worker mapping is recorded by authenticated + Cloudflare configuration sync, verified browser enrollment, or `bun run mail:domain:configure -- --remote` after separate approval. The - application identity manager created or explicitly imported each exact + application identity manager created or imported each exact literal `to` Worker rule; it did not create a destination-address forwarding rule or overwrite a conflicting route. - [ ] The receiving address is active and receive-enabled. Its rule and any diff --git a/docs/adr/0014-owner-managed-mail-identities-and-access.md b/docs/adr/0014-owner-managed-mail-identities-and-access.md index 6eb32b3..5941acf 100644 --- a/docs/adr/0014-owner-managed-mail-identities-and-access.md +++ b/docs/adr/0014-owner-managed-mail-identities-and-access.md @@ -63,6 +63,15 @@ zone/account and Worker target, plus independent Cloudflare-routing and Resend-sending check state. A subdomain must be configured as its own explicit mapping. Zone visibility from an API token never enrolls a domain. +The Owner may explicitly enroll a domain through the workspace. The deployment +fixes the receiving Worker and account; the server verifies the submitted Zone +ID and domain boundary before inserting a mapping, with unknown recipients +rejected by default. The browser cannot choose the Worker or account, alter an +existing mapping, or supply credentials. Zone Read permission is required. +Domain enable/disable and unknown-recipient settings preserve addresses and mail +history; switching to collect requires fresh verified catch-all targeting this +Worker. Address names and signatures are editable without changing routing. + `mail_addresses` stores a stable address ID, Owner/domain, receive/send switches, lifecycle and routing state, exact remote rule ID, display name, signature, and optional default-sender flag. Creating addresses never creates @@ -81,7 +90,10 @@ saved ID and reconciles the result before reporting completion. Cloudflare's documented DELETE route is ID-based and exposes no conditional version precondition; this narrows but cannot eliminate a change made between the final read and DELETE. A matching existing Worker rule can be explicitly -imported; imported and conflicting rules are preserved by normal delete and +imported; the authenticated configuration sync also discovers existing zones +and imports exact rules targeting the deployment Worker without remote writes. +Repeated discovery preserves local settings, tombstones and operation leases. +Imported and conflicting rules are preserved by normal delete and retry operations. Create, check, enable, disable, delete, restore, and retry share the existing diff --git a/docs/images/mail-address-sync-mobile.png b/docs/images/mail-address-sync-mobile.png new file mode 100644 index 0000000..cce792c Binary files /dev/null and b/docs/images/mail-address-sync-mobile.png differ diff --git a/docs/images/mail-domain-sync-desktop.png b/docs/images/mail-domain-sync-desktop.png new file mode 100644 index 0000000..c26c3ee Binary files /dev/null and b/docs/images/mail-domain-sync-desktop.png differ diff --git a/package.json b/package.json index 58139b9..60e31b5 100644 --- a/package.json +++ b/package.json @@ -13,8 +13,8 @@ "preview": "bun run build && bun ./scripts/wrangler-local.ts dev worker/index.ts --local", "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json", "test": "bun test src scripts", - "test:unit": "bun test src/lib/client src/lib/components/mail/domain-capabilities.test.ts src/lib/components/ui src/lib/domain/mail src/lib/domain/utf8.test.ts src/lib/i18n src/lib/server/auth src/lib/server/config src/lib/server/body.test.ts src/lib/server/cloudflare-email-routing.test.ts src/lib/server/db/attachments.test.ts src/lib/server/db/capabilities.test.ts src/lib/server/db/deliveries.test.ts src/lib/server/db/mail-identities.test.ts src/lib/server/db/messages.test.ts src/lib/server/email.test.ts src/lib/server/inbound/parser.test.ts src/lib/server/mail-identities/check.test.ts src/lib/server/mail-identities/health-refresh.test.ts src/lib/server/mail-identities/routing.test.ts src/lib/server/mail-identities/sending.test.ts src/lib/server/mail-identities/validation.test.ts src/lib/server/mail/html-sanitize.test.ts src/lib/server/outbound/gateway.test.ts src/lib/server/outbound/rate-limit.test.ts src/lib/server/outbound/system.test.ts src/lib/server/resend-domains.test.ts src/lib/server/search/fts.test.ts src/lib/server/workspace/compose-body.test.ts src/lib/server/telegram/api.test.ts src/lib/server/telegram/config.test.ts src/lib/server/telegram/message.test.ts src/lib/server/scheduled.test.ts", - "test:integration": "bun test src/lib/server/email.integration.test.ts src/lib/server/workspace/attachment.integration.test.ts src/lib/server/workspace/outbound.integration.test.ts src/lib/server/workspace/delivery.integration.test.ts src/lib/server/workspace/draft.integration.test.ts src/lib/server/workspace/mailbox.integration.test.ts src/lib/server/workspace/mutation-query-counter.integration.test.ts src/lib/server/workspace/trash.integration.test.ts src/lib/server/db/migrations.test.ts src/lib/server/db/telegram.test.ts src/lib/server/telegram/dispatcher.test.ts src/routes/api/health/health.test.ts src/routes/api/readiness/readiness.test.ts src/routes/api/workspace/mailbox/mutate/server.test.ts src/routes/api/workspace/mailbox/categories/server.test.ts 'src/routes/api/workspace/mail-identities/[addressId]/server.test.ts'", + "test:unit": "bun test src/lib/client src/lib/components/mail/domain-capabilities.test.ts src/lib/components/ui src/lib/domain/mail src/lib/domain/utf8.test.ts src/lib/i18n src/lib/server/auth src/lib/server/config src/lib/server/body.test.ts src/lib/server/cloudflare-email-routing.test.ts src/lib/server/db/attachments.test.ts src/lib/server/db/capabilities.test.ts src/lib/server/db/deliveries.test.ts src/lib/server/db/mail-identities.test.ts src/lib/server/db/messages.test.ts src/lib/server/email.test.ts src/lib/server/inbound/parser.test.ts src/lib/server/mail-identities/check.test.ts src/lib/server/mail-identities/domains.test.ts src/lib/server/mail-identities/sync.test.ts src/lib/server/mail-identities/health-refresh.test.ts src/lib/server/mail-identities/routing.test.ts src/lib/server/mail-identities/sending.test.ts src/lib/server/mail-identities/validation.test.ts src/lib/server/mail/html-sanitize.test.ts src/lib/server/outbound/gateway.test.ts src/lib/server/outbound/rate-limit.test.ts src/lib/server/outbound/system.test.ts src/lib/server/resend-domains.test.ts src/lib/server/search/fts.test.ts src/lib/server/workspace/compose-body.test.ts src/lib/server/telegram/api.test.ts src/lib/server/telegram/config.test.ts src/lib/server/telegram/message.test.ts src/lib/server/scheduled.test.ts", + "test:integration": "bun test src/lib/server/email.integration.test.ts src/lib/server/workspace/attachment.integration.test.ts src/lib/server/workspace/outbound.integration.test.ts src/lib/server/workspace/delivery.integration.test.ts src/lib/server/workspace/draft.integration.test.ts src/lib/server/workspace/mailbox.integration.test.ts src/lib/server/workspace/mutation-query-counter.integration.test.ts src/lib/server/workspace/trash.integration.test.ts src/lib/server/db/migrations.test.ts src/lib/server/db/telegram.test.ts src/lib/server/telegram/dispatcher.test.ts src/routes/api/health/health.test.ts src/routes/api/readiness/readiness.test.ts src/routes/api/workspace/mail-identities/domains/server.test.ts src/routes/api/workspace/mail-identities/sync/server.test.ts src/routes/api/workspace/mailbox/mutate/server.test.ts src/routes/api/workspace/mailbox/categories/server.test.ts 'src/routes/api/workspace/mail-identities/[addressId]/server.test.ts'", "test:remaining": "bun test scripts src/hooks.server.test.ts src/lib/server/attachment-download.test.ts src/lib/server/attachment-integrity.test.ts src/lib/server/http/api.test.ts src/lib/server/resend-webhook.test.ts src/lib/server/workspace/mailbox-query.test.ts src/lib/server/workspace/reader.test.ts src/lib/server/workspace/r2-cleanup.test.ts src/lib/server/workspace/session.test.ts src/lib/server/workspace/shared.test.ts src/routes/api/send/server.test.ts src/routes/api/webhooks/resend/server.test.ts src/routes/api/webhooks/telegram/server.test.ts src/routes/api/workspace/notifications/telegram/settings/server.test.ts 'src/routes/api/workspace/messages/[id]/html/html.test.ts' 'src/routes/api/workspace/messages/[id]/server.test.ts' src/routes/api/workspace/session/server.test.ts src/routes/api/workspace/trash/trash.test.ts", "test:e2e": "bun scripts/playwright-projects.ts chromium", "test:e2e:webkit": "bun scripts/playwright-projects.ts webkit", diff --git a/src/lib/components/mail/MailDomainSetup.svelte b/src/lib/components/mail/MailDomainSetup.svelte new file mode 100644 index 0000000..a8bf5a0 --- /dev/null +++ b/src/lib/components/mail/MailDomainSetup.svelte @@ -0,0 +1,58 @@ + + +
+ {t('settings.addMailDomain')} +

{t('settings.domainSetupDescription')}

+ {#if !available} +

{t(workerName ? 'settings.domainReadPermissionMissing' : 'settings.domainWorkerMissing')}

+ + {/if} +
+ domainName = event.currentTarget.value} /> + zoneId = event.currentTarget.value} /> +
+

{t('settings.domainZoneHelp')}

+ {#if errorMessage}{/if} + +
+ + diff --git a/src/lib/components/mail/MailIdentityManager.svelte b/src/lib/components/mail/MailIdentityManager.svelte index 819b24a..ac29afd 100644 --- a/src/lib/components/mail/MailIdentityManager.svelte +++ b/src/lib/components/mail/MailIdentityManager.svelte @@ -6,6 +6,7 @@ import TextField from '$lib/components/ui/TextField.svelte'; import TextArea from '$lib/components/ui/TextArea.svelte'; import Dialog from '$lib/components/ui/Dialog.svelte'; + import MailDomainSetup from './MailDomainSetup.svelte'; import { requestJson } from '$lib/client/api'; import { mailHealthState } from '$lib/domain/mail/health'; import { mailSenderSendBlockReason } from '$lib/domain/mail/sender-readiness'; @@ -17,6 +18,8 @@ id: string; domain_name: string; enabled: number; + cloudflare_zone_id: string; + worker_name: string; unknown_recipient_policy: 'reject' | 'collect'; catch_all_target: 'unknown' | 'this_worker' | 'external' | 'drop' | 'none'; resend_status: 'unknown' | 'pending' | 'verified' | 'failed'; @@ -110,10 +113,21 @@ let quickCreateNotice = $state(''); let quickCreateNeedsAttention = $state(false); let loading = $state(true); + let syncing = $state(false); + let syncNotice = $state(''); + let syncError = $state(''); let pendingAction = $state(''); let errorMessage = $state(''); let notice = $state(''); let noticeNeedsAttention = $state(false); + let onboarding = $state<{ available: boolean; workerName: string | null; canManageRouting: boolean }>({ available: false, workerName: null, canManageRouting: false }); + let domainSettingsTarget = $state(null); + let domainEnabled = $state(true); + let unknownPolicy = $state<'reject' | 'collect'>('reject'); + let settingsError = $state(''); + let editAddressTarget = $state(null); + let editDisplayName = $state(''); + let editSignature = $state(''); let deleteTarget = $state(null); let deletePreview = $state(null); let deletePreviewLoading = $state(false); @@ -145,15 +159,34 @@ if (requestedLocalPart) untrack(() => { localPart = requestedLocalPart; }); }); - async function load() { + async function load(discover = false) { loading = true; errorMessage = ''; try { - const loaded = await requestJson<{ + type Identities = { domains: Omit[]; addresses: MailAddress[]; providerConfiguration: { cloudflare: boolean; resend: boolean }; - }>('/api/workspace/mail-identities'); + domainOnboarding?: typeof onboarding; + }; + let loaded = await requestJson('/api/workspace/mail-identities'); + if (discover && loaded.domainOnboarding?.available) { + syncing = true; + syncError = ''; + syncNotice = ''; + try { + const result = await requestJson<{ sync: { domainsCreated: number; addressesCreated: number; + warnings: Array<{ domainName: string; code: string }> } }>('/api/workspace/mail-identities/sync', { method: 'POST' }); + loaded = await requestJson('/api/workspace/mail-identities'); + syncNotice = t('settings.providerSyncComplete', { domains: result.sync.domainsCreated, addresses: result.sync.addressesCreated }); + if (result.sync.warnings.length) syncError = t('settings.providerSyncPartial', { + domains: result.sync.warnings.map((warning) => warning.domainName).join(', ') + }); + } catch (error) { + syncError = error instanceof Error ? error.message : t('settings.providerSyncFailed'); + } finally { syncing = false; } + } + onboarding = loaded.domainOnboarding ?? { available: false, workerName: null, canManageRouting: false }; domains = loaded.domains.map((domain) => ({ ...domain, cloudflare_configured: loaded.providerConfiguration.cloudflare, @@ -199,9 +232,64 @@ } onMount(() => { - void load(); + void load(true); }); + async function domainCreated(domainId: string) { + selectedDomainId = domainId; + notice = t('settings.mailDomainConnected'); + noticeNeedsAttention = false; + await load(); + } + + function openDomainSettings(domain: MailDomain) { + domainSettingsTarget = domain; + domainEnabled = Boolean(domain.enabled); + unknownPolicy = domain.unknown_recipient_policy; + settingsError = ''; + } + + async function saveDomainSettings(event: SubmitEvent) { + event.preventDefault(); + if (!domainSettingsTarget || pendingAction) return; + pendingAction = 'domain-settings'; + settingsError = ''; + try { + await requestJson(`/api/workspace/mail-identities/domains/${encodeURIComponent(domainSettingsTarget.id)}`, { + method: 'PATCH', body: JSON.stringify({ enabled: domainEnabled, unknownRecipientPolicy: unknownPolicy }) + }); + domainSettingsTarget = null; + notice = t('settings.domainSettingsSaved'); + noticeNeedsAttention = false; + await load(); + } catch (error) { settingsError = error instanceof Error ? error.message : t('settings.mailIdentityActionFailed'); } + finally { pendingAction = ''; } + } + + function openAddressSettings(address: MailAddress) { + editAddressTarget = address; + editDisplayName = address.display_name; + editSignature = address.signature; + settingsError = ''; + } + + async function saveAddressSettings(event: SubmitEvent) { + event.preventDefault(); + if (!editAddressTarget || pendingAction) return; + pendingAction = 'address-settings'; + settingsError = ''; + try { + await requestJson(`/api/workspace/mail-identities/${encodeURIComponent(editAddressTarget.id)}`, { + method: 'PATCH', body: JSON.stringify({ displayName: editDisplayName, signature: editSignature }) + }); + editAddressTarget = null; + notice = t('settings.addressSettingsSaved'); + noticeNeedsAttention = false; + await load(); + } catch (error) { settingsError = error instanceof Error ? error.message : t('settings.mailIdentityActionFailed'); } + finally { pendingAction = ''; } + } + function checkFor(domain: MailDomain, addressId: string): RouteStatus | undefined { return checks[domain.id]?.cloudflare.addresses.find((entry) => entry.addressId === addressId)?.status; } @@ -560,15 +648,32 @@ +
+

{t('settings.providerSyncDescription')}

+ +
+ {#if syncNotice}

{syncNotice}

{/if} + {#if syncError}{/if} {#if errorMessage}{/if} {#if notice}

{notice}

{/if} {#if loading}

{t('common.loading')}

- {:else if domains.length === 0} -

{t('settings.noMailDomains')}

-

{t('settings.mailDomainSetupHint')} bun run mail:domain:configure

{:else} + {#if domains.length === 0} + + {:else if view === 'domains'} +
+ {t('settings.addMailDomainManually')} + +
+ {/if} + {#if !onboarding.canManageRouting} +

{t('settings.routingManagementMissing')}

+ {/if} + {#if domains.length === 0} +

{t('settings.noMailDomains')}

+ {:else} {#if view === 'addresses'}
@@ -600,6 +705,7 @@
{#if view === 'domains'} +
{#if view === 'addresses'}
+ {#if address.lifecycle_status !== 'deleted'} + + {/if} {#if route === 'importable' && address.lifecycle_status !== 'deleted'} {/if} @@ -716,9 +825,39 @@ {/each}
+ {/if} {/if} +{#if domainSettingsTarget} + domainSettingsTarget = null}> + +

{t('settings.domainMappingLocked')}

+ +

{t('settings.domainDisableHelp')}

+ + +

{t('settings.collectRequiresWorkerCatchAll')}

+ {#if settingsError}{/if} + + +
+{/if} + +{#if editAddressTarget} + editAddressTarget = null}> +
+ editDisplayName = event.currentTarget.value} /> +