Skip to content

feat(email): OAuth 授权发信邮箱(Gmail / Microsoft 365)(HQ-Task T261111-06) - #24

Merged
AdoreJc merged 2 commits into
fork-mainfrom
hq/T261111-06-email-oauth
Nov 12, 2026
Merged

AdoreJc merged 2 commits into
fork-mainfrom
hq/T261111-06-email-oauth

Conversation

@AdoreJc

@AdoreJc AdoreJc commented Nov 12, 2026

Copy link
Copy Markdown
Owner

HQ-Task: T261111-06

本 PR 由 AI(Claude Code)生成,提交者不是本仓库历史核心开发者。

Agent

  • Tool: Claude Code(桌面版 Code 标签页,由 Project HQ 会话派发的子会话)
  • Tool version: Claude Agent SDK(桌面版内置)
  • Model (full id): claude-opus-5-5
  • Host (CLI / IDE / GitHub coding agent / other): Claude 桌面版,Windows 10 worktree
  • Date (UTC): 2026-11-12

Links

User request

  • Verbatim: (HQ 转述)“在「邮件与通知」里加 OAuth 授权方式添加发信邮箱”
  • Later constraints or corrections from the user (quote, or none): (HQ 转述)Gmail 和 Microsoft 365 都要;只需单个邮箱,作为第三种发信方式;只开 PR 不合并。

Out of scope — refuse

  • Matched: no
  • If yes, what was told to the user: 不适用

Open gate — do not open unless all are satisfied

  • Out of scope (including pass-through-only forwarding): no
  • Usage / configuration / integration (answered instead of opening): no
  • Required issue facts present without invention: yes
  • Verification is actual commands or steps and observed results, not only go build or tests passed: yes
  • Body is short and factual; no unfiltered AI-generated text: yes
  • Open: yes
  • If no, what was told to the user: 不适用

Kind

  • New feature

Issue facts

  • Actual behavior: EmailProvider 只有 smtp / resend;用 Gmail、Microsoft 365 发信只能走 SMTP 密码/应用专用密码,很多 M365 租户关闭了 SMTP AUTH。
  • Impact: 无法用 OAuth 授权的个人/企业邮箱发系统邮件。
  • Frequency: 不适用(功能缺失)
  • Evidence that the problem is in new-api rather than the client or upstream: common/email.go SendEmail 只分派 smtp/resend。
  • Applicable types and their fields: frontend(系统设置 → 邮件与通知);auth(管理员发起的 OAuth 授权流程);不涉及 relay、billing。

Change

发信(common/email_oauth.go,SendEmail 增加 oauth 分支)

  • Google:Gmail API users.messages.send(scope openid email gmail.send,发 RFC 5322 base64url 原文,主题 UTF-8 B 编码,HTML 正文 base64)。Microsoft:Graph POST /me/sendMail(scope offline_access Mail.Send User.Read,from 为授权邮箱,显示名 SystemName)。选 HTTP API 而不是 SMTP XOAUTH2:M365 常关 SMTP AUTH,gmail.send 比 SMTP 需要的 https://mail.google.com/ 窄。
  • access token 内存缓存(按 provider/client/tenant/refresh token 区分,到期前 1 分钟失效),刷新串行。服务商返回新 refresh token(Microsoft 每次轮换)时按“旧值仍等于刚用的值”条件更新 options 行,失败重试 4 次(0.1/0.3/1/2 s);仍失败则新 token 留在进程内,下一次发信先用它并再写库。条件不满足(期间被重新授权或解除)则丢弃轮换结果。
  • invalid_grant → “授权已过期或被撤销,请在邮件设置中重新授权”。任何失败都不回退 SMTP/Resend。日志只记 provider、HTTP 状态与错误码,不记 token、请求体或响应体。
  • 端点集中在 common.EmailOAuthEndpoints,测试用 httptest 替换。

授权(controller/email_oauth.go,路由在 /api/option 组内,与改 options 同一个 RootAuth)

  • POST /api/option/email_oauth/authorize:要求浏览器会话(PAT 在 access_token_routes 标为 session-only);生成 PKCE S256 与一次性 state,state 存 auth_flows(只存 HMAC,purpose=email_oauth,绑定 user id + session id,10 分钟过期),payload 存 verifier、redirect URI、client id、tenant 快照。
  • Redirect URI = ServerAddress + /system-settings/operations/email,即设置页本身。会话 cookie 是 SameSite=Strict,服务商跨站跳回时不带 cookie,后端 GET 回调无法把 state 绑到会话;所以由设置页读取 code/state 后用当前会话 POST /api/option/email_oauth/callback,并立即从地址栏去掉。
  • 回调先原子消费 state(匹配 user + session,过期/重放/他人会话都拒绝,且不会被他人会话消耗),服务商返回 error 时 state 也作废;再校验 app 设置未变、用 code 换 token、取邮箱(Google userinfo 要求 email_verified;Microsoft Graph /me 的 mail/UPN),refresh token 与邮箱在一个事务里写入。
  • DELETE /api/option/email_oauth/authorization:清空 token 与邮箱;OAuth 为当前发信方式时拒绝。授权/解除写管理审计(option.update,key=EmailOAuthAuthorization,不含 token)。

配置规则(model/email_oauth.go,validateOptionValue 调用)

  • 新 options:EmailOAuthProvider(google/microsoft)、EmailOAuthClientId、EmailOAuthClientSecret、EmailOAuthTenant(缺省 common)、EmailOAuthRefreshToken、EmailOAuthEmail。
  • GET /api/option/ 不返回 secret 与 refresh token(沿用 Secret/Token 后缀过滤),另给派生的 EmailOAuthSecretConfigured。
  • refresh token、邮箱、EmailOAuthSecretConfigured 不能经通用 options 接口写入。已授权时不能改 provider/client id/tenant(需先解除);secret 可轮换。选为发信方式要求 app 完整且已授权;OAuth 生效期间 secret 不能清空。

前端:发信方式加「OAuth 授权邮箱」;服务商、Client ID、Client secret(不回显)、Tenant(仅 Microsoft)、可复制的 Redirect URI、授权状态、授权/重新授权/解除(确认框)。未授权时保存只存 app 设置并提示授权后再保存。新文案 40 条补齐 7 个 locale。

Research

Duplicate / prior art

  • Search queries (issues, PRs): fork 内 gh pr list --state all 无相关;仓库内搜 EmailProvider、code_challenge、CreateAuthFlow。
  • What already existed and why this is not a duplicate: 只有 SMTP/Resend;Claude/Codex OAuth 是渠道凭据的粘贴式流程,不适用发信。

Docs and code

  • https://docs.newapi.ai/ : 未查到 OAuth 发信相关内容。
  • https://deepwiki.com/QuantumNous/new-api : 未查阅(离线实现,依据仓库代码)。
  • README / repo docs: AGENTS.md、web/AGENTS.md、i18n skill。
  • Code paths and what they imply for this change: model/auth_flow.go(一次性 state 的现成实现,HMAC 存储、原子消费);service/auth_session.go(SameSite=Strict,决定了回调形态);common/email_resend.go(收件人解析、错误不泄露内容的约定);service/claude_credential_refresh.go(轮换 token 写库失败丢失的教训)。

Alternatives considered

  • Option A: SMTP XOAUTH2 — 实现小,但 M365 常禁用 SMTP AUTH,Gmail 需更宽 scope。
  • Option B: 后端 GET 回调 + 不绑会话的 state — 违背“state 绑定管理员会话”。
  • Why this approach: HTTP API 兼容性与最小权限更好;页面回调 + RootAuth POST 能用现有会话与鉴权中间件。

Files

Path Why
common/email_oauth.go 授权 URL、换 token、取邮箱、token 缓存/轮换、两家发信
common/email.go oauth 分派,错误文案
model/email_oauth.go 配置校验、授权写入/清除、轮换条件写库
model/option.go 新 options 缺省值;邮件校验改调 validateEmailDeliveryOption
controller/email_oauth.go 发起/回调/解除接口
controller/option.go 派生 EmailOAuthSecretConfigured
router/api-router.go, middleware/access_token_routes.go 路由与 PAT 规则
controller/email_delivery_test.go, controller/email_oauth_test.go 后端测试
web/src/features/system-settings/... 设置界面、回调处理、类型与测试
web/src/i18n/locales/*.json 7 个 locale 新文案

Behavior

  • Before: 发信方式只有 SMTP / Resend。
  • After: 可选「OAuth 授权邮箱」,授权一个 Gmail/Google Workspace 或 Outlook/M365 邮箱后用其发系统邮件。
  • Explicit non-goals / leftover work: 只支持一个邮箱;本项目没有“发送测试邮件”功能,未新增;解除授权只删本地 token,不调用服务商撤销接口(界面提示到账户设置移除);state 存数据库,多节点可用,但 access token 缓存与未写库的轮换 token 是进程内的。

Verification

  • Commands and results:
    • GOWORK=off go test ./controller -run 'TestEmailOAuth|TestOAuthEmail|Resend|SMTP|EmailProvider|EmailOptions|EmailKey' -count=1 -v:新增与原有邮件测试全部断言通过(Error Trace 计数 0)。
    • GOWORK=off go test ./common/... ./model/... ./middleware/... ./router/... ./controller/... ./service/... ./setting/... -count=1:common/model/router/service/setting 全部 ok;controller、middleware 的 FAIL 全部是 Windows 上 TempDir RemoveAll cleanup ... being used by another process(audit.db / 日志文件句柄,已知预存问题),日志中断言失败 0 条。
    • 变异检查:去掉回调 state 匹配里的 session id 后,TestEmailOAuthCallbackRejectsUnusableState/other_session 失败(回调成功写入),恢复后通过。
    • 前端:bun x --package @typescript/native-preview tsgo -b 退出 0;bun run test 224 个文件 2606 个测试全部通过;bun run build 成功(rsbuild 产物生成);改动文件 oxlint 无 error、oxfmt --check 通过;bun run i18n:sync 报告 7 个 locale missing 0 / extras 0。
  • Manual steps and observed result: 无(没有可用的真实 Google/Microsoft 应用)。
  • UI: screenshot or recording (or why none): 无,未起本地服务;界面行为由组件测试覆盖。
  • Tests added or updated, or why none:
    • 后端:两条发信路径请求格式(UTF-8 主题、HTML 正文、收件人、From、Bearer、token 表单);access token 缓存(两封信一次刷新);Microsoft 轮换写库、写库失败重试、全部失败后下一封用新 token 并补写;旧授权的轮换不覆盖新授权;invalid_grant;未授权/token 端点失败/发送 500 都不连 SMTP、不调 Resend;授权成功写 token 与邮箱、PKCE verifier 与 challenge 对应、options 不回传 secret/token、重放拒绝;state 缺失/伪造/过期/他人会话拒绝且不发起换 token;服务商 error 作废 state;非管理员三个接口 401/403 且不建 state;配置规则(未授权不能启用、只读键、已授权不能换 app、生效时不能解除)。原有 EmailProvider 非法值测试的期望文案随新文案更新,并加了 OAuth 大小写用例。
    • 前端:email-oauth-settings.test.tsx 6 个用例(未授权时只保存 app、必填校验、发起授权跳转、已授权锁定 app 并启用、回调只提交一次并清地址栏、确认后解除);两个旧测试 fixture 补字段。
  • Databases / providers / platforms exercised: SQLite 3.50.4(Windows);TEST_SECURITY_DIALECT=mysql(MySQL 8.0.46)与 postgres(PostgreSQL 17.11)跑 TestEmailOAuth* 4 个测试全部 PASS(Mac mini 上临时容器,仅绑 127.0.0.1,SSH 转发,用完已删除)。无表结构变更(只新增 options 键与 auth_flows.purpose 新值)。
  • Not verified: 真实 Google / Microsoft 授权与发信未端到端验证;MySQL 5.7 / PostgreSQL 9.6 最低版本未跑(改动不依赖版本特性);rotation 相关测试只在 SQLite 上跑,MySQL/PG 上覆盖的是条件更新 ReplaceEmailOAuthRefreshToken 本身。

管理员配置说明

  1. 先在系统设置里填写「服务器地址」(ServerAddress),Redirect URI 为 <服务器地址>/system-settings/operations/email(设置页里可直接复制)。
  2. Google:Google Cloud Console → 启用 Gmail API → OAuth 同意屏幕(内部或外部;外部测试状态需把发信账号加为测试用户,且测试状态下 refresh token 7 天过期)→ 凭据 → 创建 OAuth 客户端(Web 应用),授权重定向 URI 填上面的地址;scope:openid、email、https://www.googleapis.com/auth/gmail.send。
  3. Microsoft:Entra ID → 应用注册 → 新注册(账户类型按需;单租户时 Tenant 填租户 ID 或域名,多租户/个人账户用 common)→ 身份验证 → 添加平台「Web」,重定向 URI 填上面的地址 → 证书和密码 → 新客户端密码 → API 权限:Microsoft Graph 委托权限 Mail.Send、User.Read、offline_access(按租户策略授予管理员同意)。
  4. 邮件与通知 → 选「OAuth 授权邮箱」→ 填服务商、Client ID、Client secret(Microsoft 填 Tenant)→ 保存 → 授权邮箱 → 用发信邮箱登录同意 → 回到设置页显示已授权邮箱 → 再保存一次启用。
  5. 更换应用或邮箱:先切到其他发信方式,解除授权,再修改。

Risks

  • Failure modes: 刷新失败或被撤销时系统邮件(验证码、找回密码、提醒)发送失败,不会回退;Microsoft 轮换 token 若重试和下次补写都失败且进程重启,需要重新授权。多节点部署时各节点各自刷新,Microsoft 轮换可能互相作废旧 token(单节点部署无此问题)。
  • Billing / quota / auth impact: 不涉及计费。授权接口为 root 管理员 + 浏览器会话;参考 OWASP ASVS 5.0 V10(OAuth 客户端:PKCE、state 绑定会话且一次性)与 OAuth2 Cheat Sheet;client secret / refresh token 不回传、不入日志、不进审计。
  • Follow-ups: 若需要多节点一致性,可把轮换写库改为分布式锁;可加“发送测试邮件”按钮。

Scope check

  • Single focused change: yes
  • Secrets included: no
  • Out of scope (Coding Plan / reverse-engineered channel / third-party wrapper / Codex / pass-through-only forwarding): no

🤖 Generated with Claude Code

Add a third email sending method, EmailProvider=oauth, that sends through
one administrator-authorized mailbox: Gmail API users.messages.send
(gmail.send) or Microsoft Graph /me/sendMail (Mail.Send). HTTP APIs are
used instead of SMTP XOAUTH2 because many Microsoft 365 tenants disable
SMTP AUTH and gmail.send is narrower than the SMTP scope.

Authorization uses the code flow with PKCE and a one-time state stored in
auth_flows, bound to the admin's browser session. Session cookies are
SameSite=Strict, so the provider returns to the email settings page, which
posts code and state to a RootAuth endpoint.

Access tokens are cached in memory. A rotated refresh token is saved with
a compare-and-swap on the options row, retried, and kept in memory for
the next send if every write fails, so it is not lost the way the Claude
credential refresh once lost one. invalid_grant asks for re-authorization
and failures never fall back to SMTP or Resend. The client secret and
refresh token are not returned by the options API and are not logged.

HQ-Task: T261111-06

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@AdoreJc

AdoreJc commented Nov 12, 2026

Copy link
Copy Markdown
Owner Author

HQ-Review R1: APPROVE

审查对象:7fa44bd15。没有阻塞项。授权接口和改 options 的接口一样挂在 /api/option 组的 RootAuth 下,PAT 规则也已登记;state 绑定了 user 和 session,10 分钟过期,原子消费;PKCE 用 S256;跳转地址由服务端用固定端点拼出;GET options 不回传 secret 和 refresh token,只读键不能经通用接口写入;oauth 失败时不回退到其他方式;用的是 common.Marshal/DecodeJson;没有改表结构。以下是非阻塞建议:

  1. common/email_oauth.go:574(buildEmailOAuthMIME 的 To: 头):收件人直接拼 mail.ParseAddress 解析出的裸 .Address。带引号 local-part 的地址,去掉引号后可能含有在头部里有分隔含义的字符,Gmail 会按 To: 头重新解析收件人,结果和本地校验的不一致。建议每个收件人用 (&mail.Address{Address: a}).String() 重新格式化,或者在 parseEmailRecipients 里拒绝带引号的 local-part。Graph 那条路径走 JSON,不受影响。
  2. model/email_oauth.go:66-86 与 :104-116:轮换写库和重新授权写库这两个操作,各自的“DB 写入 + updateOptionMap”之间没有串行。两者交错时,内存里的 OptionMap 可能出现旧授权轮换出来的 refresh token 配上新授权的邮箱地址,要等下一次 SyncOptions 才能纠正。建议在 model 层用一个 mutex 把 SaveEmailOAuthAuthorization 和 ReplaceEmailOAuthRefreshToken 的 DB 写入和 map 更新包起来。锁序是 emailOAuthState → 新 mutex → OptionMapRWMutex,ResetEmailOAuthTokenCache 继续放在锁外调用,这样不会形成环。
  3. common/email_oauth.go:442、controller/email_oauth.go:164:这两处用 %v 记录原始 DB 错误,没有经过 model/gorm_logger.go 的 sanitizeDBError。以现在的 UPDATE/UPSERT 来看,驱动报错基本不会带出取值,风险低,但建议只记错误类别或错误码,跟“日志不出现 token”的约定保持一致。
  4. common/email_oauth.go:69:SetEmailOAuthEndpointsForTest 是放在非测试文件里的导出函数,读端点的地方也不加锁。目前只有测试调用它。可以考虑挪进 export_test 风格的文件,或者加注释说明只用于测试。

复跑(Windows,GOWORK=off):go vet ./common ./model ./controller 通过;go test ./common ./model ./router 全部 ok;go test ./controller -run 'Email|OAuth|Option|Resend|AccessToken|Route' 中邮件和 OAuth 相关用例全部通过,唯一的 FAIL 是 Telegram 测试的 audit.db TempDir 清理(预存);./middleware 唯一的 FAIL 是 TestAccessAndPanicLogsFollowLogRotation 的日志文件 TempDir 清理(Windows 文件句柄,与本 PR 无关)。前端和 MySQL/PG 没有复跑,以 PR 描述里的结果为准。

Address HQ-Review R1 items 1 and 2 on PR #24.

- Gmail To header: re-format each validated recipient with
  mail.Address.String(). net/mail returns a quoted local-part unquoted,
  so "a,b"@example.com was written as a,b@example.com and Gmail would
  read two recipients. The header now parses back to exactly the
  validated addresses.
- A refresh token rotation and a re-authorization each wrote the
  database and then the option map. Interleaved, the map could hold the
  old grant's rotated token next to the new grant's mailbox until the
  next SyncOptions. Both writes now take one model-level mutex around the
  database write and map update; the token cache reset stays outside it,
  so the lock order is token state -> write mutex -> OptionMapRWMutex.

HQ-Task: T261111-06

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@AdoreJc

AdoreJc commented Nov 12, 2026

Copy link
Copy Markdown
Owner Author

HQ-Review R1 处理(commit 9ab7f2f)

  1. Gmail To: 头:已改。buildEmailOAuthMIME 对每个已校验的收件人用 (&mail.Address{Address: a}).String() 重新格式化。net/mail 解析带引号 local-part 后返回的是去掉引号的形式("first,second"@example.com → first,second@example.com),原来直接拼会让 Gmail 读成两个收件人。新测试 TestOAuthEmailGmailRecipientsMatchValidatedAddresses 用这个地址加一个普通地址发信,解析 To: 头后与本地校验结果逐一相等;把格式化改回去后该测试失败。普通地址现在写成 <one@example.com>,原有格式测试的期望随之更新。Graph 走 JSON,未改。
  2. 轮换与重新授权串行:已改。model/email_oauth.go 新增 emailOAuthWriteMutex,SaveEmailOAuthAuthorization(经 storeEmailOAuthAuthorization)和 ReplaceEmailOAuthRefreshToken 的“写库 + updateOptionMap”整体在锁内;ResetEmailOAuthTokenCache 移到锁外。锁序:common 的 token 状态锁 → 新 mutex → OptionMapRWMutex;新 mutex 不会在持 OptionMapRWMutex 时获取(ClearEmailOAuthAuthorization 先释放读锁再写)。新测试 model/email_oauth_test.go 用包内钩子在轮换“写库后、更新 map 前”插入一次重新授权:有锁时最终库和 map 都是新授权的 token + 邮箱;分别去掉任一处锁后测试失败(map 里是 grant-1-rotated 配新邮箱)。钩子是未导出的包变量,所以测试放在 model 包。
    3、4:按用户决定本轮不改。

复跑(Windows,GOWORK=off):

  • go vet ./common ./model ./controller ./router 通过。
  • go test ./common/... ./model/... ./router/... -count=1:全部 ok。
  • go test ./controller -run 'Email|OAuth|Option|Resend|SMTP|AccessToken|Route' -count=1 -v:Error Trace 0 条;6 个 TestOAuthEmail* 全部 PASS;FAIL 只有 TempDir 清理(77 行 TempDir RemoveAll cleanup,非清理类失败 0 条,预存问题)。
  • 未复跑:MySQL/PostgreSQL(本轮改动是进程内锁和头部格式,没有新增 SQL)、前端(未改)。

@AdoreJc

AdoreJc commented Nov 12, 2026

Copy link
Copy Markdown
Owner Author

HQ-Review R2: APPROVE

复审对象:9ab7f2fbb(相对 R1 的 7fa44bd 的增量)。R1 的非阻塞 1、2 都已修复,没有发现新问题;3、4 按决定不改,不算问题。

R1 条目核对:

  1. 已修复:common/email_oauth.go:574-580。buildEmailOAuthMIME 现在用 (&mail.Address{Address: a}).String() 逐个重新格式化收件人,带引号的 local-part 会重新加上引号。新增的 controller/email_delivery_test.go TestOAuthEmailGmailRecipientsMatchValidatedAddresses 用标准库重新解析 To: 头,断言结果和校验时的地址列表一致。我在本地把这一行还原成裸拼接后,这个用例确实失败,说明它能拦住回退。原有用例的期望也同步改成了 <a>, <b> 的形式,这只是等价的格式变化,Gmail 解析结果不变。Graph 那条路径不受影响。
  2. 已修复:model/email_oauth.go:20-30, 87-114, 135-148。新增的 emailOAuthWriteMutex 把重新授权和轮换写库两条路径各自的“写 DB + updateOptionMap”整体包起来;ResetEmailOAuthTokenCache 移到了锁外(SaveEmailOAuthAuthorization -> storeEmailOAuthAuthorization)。锁序核对如下:
    • 轮换:emailOAuthState -> emailOAuthWriteMutex -> OptionMapRWMutex。
    • 重新授权和解除授权:emailOAuthWriteMutex -> OptionMapRWMutex,释放之后才取 emailOAuthState。
    • updateOptionMap 持有 OptionMapRWMutex 期间不回调 email OAuth 代码。
    • 轮换重试的 sleep 不在新锁内,每次尝试都单独加锁。
      所以没有反向锁序,也没有重入。新增的 model/email_oauth_test.go 用 emailOAuthAfterDatabaseWrite 钩子在轮换的写库和写 map 之间插入一次重新授权,断言 DB 和 OptionMap 最终都是新授权的 token 和邮箱。我把锁去掉后,这个用例失败(OptionMap 里留下了旧授权轮换出的 token),加锁后连续 5 次都通过。测试钩子在生产环境恒为 nil;测试里对它的读写都由 mutex 或同一 goroutine 排出先后顺序。

新增改动的检查:没有发现正确性问题,没有违反 B 级规则(没有 .env、data/、资金或实盘路径),没有新的安全问题,测试覆盖了两项修复。

复跑(Windows,Go 1.26.10,GOWORK=off,从 9ab7f2f 用 git archive 导出到临时目录):

  • go test ./common ./model ./router:全部 ok。
  • go vet ./common ./model 通过;改动的文件 gofmt -l 没有输出。
  • go test -v ./controller -run 'Email|OAuth|Option':37 PASS / 23 FAIL。23 个 FAIL 全部只是 audit.db TempDir 清理报错(预存,Windows 文件句柄问题),断言错误为 0。TestOAuthEmail* 6 个用例全部 PASS,包括新增用例。
  • 变异验证:分别还原两处修复后,对应的新用例都会失败。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant