Repository navigation
feat(email): OAuth 授权发信邮箱(Gmail / Microsoft 365)(HQ-Task T261111-06) - #24
Conversation
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>
|
HQ-Review R1: APPROVE 审查对象:7fa44bd15。没有阻塞项。授权接口和改 options 的接口一样挂在
复跑(Windows, |
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>
|
HQ-Review R1 处理(commit 9ab7f2f)
复跑(Windows,
|
|
HQ-Review R2: APPROVE 复审对象:9ab7f2fbb(相对 R1 的 7fa44bd 的增量)。R1 的非阻塞 1、2 都已修复,没有发现新问题;3、4 按决定不改,不算问题。 R1 条目核对:
新增改动的检查:没有发现正确性问题,没有违反 B 级规则(没有 复跑(Windows,Go 1.26.10,
|
HQ-Task: T261111-06
本 PR 由 AI(Claude Code)生成,提交者不是本仓库历史核心开发者。
Agent
Links
model/option.go、controller/option.go、router/api-router.go、middleware/access_token_routes.go只改邮件相关的几行。User request
Out of scope — refuse
Open gate — do not open unless all are satisfied
go buildor tests passed: yesKind
Issue facts
EmailProvider只有smtp/resend;用 Gmail、Microsoft 365 发信只能走 SMTP 密码/应用专用密码,很多 M365 租户关闭了 SMTP AUTH。common/email.goSendEmail只分派 smtp/resend。Change
发信(
common/email_oauth.go,SendEmail增加oauth分支)users.messages.send(scopeopenid email gmail.send,发 RFC 5322 base64url 原文,主题 UTF-8 B 编码,HTML 正文 base64)。Microsoft:GraphPOST /me/sendMail(scopeoffline_access Mail.Send User.Read,from为授权邮箱,显示名SystemName)。选 HTTP API 而不是 SMTP XOAUTH2:M365 常关 SMTP AUTH,gmail.send比 SMTP 需要的https://mail.google.com/窄。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 快照。ServerAddress+/system-settings/operations/email,即设置页本身。会话 cookie 是 SameSite=Strict,服务商跨站跳回时不带 cookie,后端 GET 回调无法把 state 绑到会话;所以由设置页读取code/state后用当前会话POST /api/option/email_oauth/callback,并立即从地址栏去掉。/me的 mail/UPN),refresh token 与邮箱在一个事务里写入。DELETE /api/option/email_oauth/authorization:清空 token 与邮箱;OAuth 为当前发信方式时拒绝。授权/解除写管理审计(option.update,key=EmailOAuthAuthorization,不含 token)。配置规则(
model/email_oauth.go,validateOptionValue调用)EmailOAuthProvider(google/microsoft)、EmailOAuthClientId、EmailOAuthClientSecret、EmailOAuthTenant(缺省 common)、EmailOAuthRefreshToken、EmailOAuthEmail。GET /api/option/不返回 secret 与 refresh token(沿用Secret/Token后缀过滤),另给派生的EmailOAuthSecretConfigured。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
gh pr list --state all无相关;仓库内搜EmailProvider、code_challenge、CreateAuthFlow。Docs and code
AGENTS.md、web/AGENTS.md、i18n skill。model/auth_flow.go(一次性 state 的现成实现,HMAC 存储、原子消费);service/auth_session.go(SameSite=Strict,决定了回调形态);common/email_resend.go(收件人解析、错误不泄露内容的约定);service/claude_credential_refresh.go(轮换 token 写库失败丢失的教训)。Alternatives considered
Files
common/email_oauth.gocommon/email.gooauth分派,错误文案model/email_oauth.gomodel/option.govalidateEmailDeliveryOptioncontroller/email_oauth.gocontroller/option.goEmailOAuthSecretConfiguredrouter/api-router.go,middleware/access_token_routes.gocontroller/email_delivery_test.go,controller/email_oauth_test.goweb/src/features/system-settings/...web/src/i18n/locales/*.jsonBehavior
Verification
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 条。TestEmailOAuthCallbackRejectsUnusableState/other_session失败(回调成功写入),恢复后通过。bun x --package @typescript/native-preview tsgo -b退出 0;bun run test224 个文件 2606 个测试全部通过;bun run build成功(rsbuild 产物生成);改动文件oxlint无 error、oxfmt --check通过;bun run i18n:sync报告 7 个 locale missing 0 / extras 0。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.tsx6 个用例(未授权时只保存 app、必填校验、发起授权跳转、已授权锁定 app 并启用、回调只提交一次并清地址栏、确认后解除);两个旧测试 fixture 补字段。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新值)。ReplaceEmailOAuthRefreshToken本身。管理员配置说明
<服务器地址>/system-settings/operations/email(设置页里可直接复制)。openid、email、https://www.googleapis.com/auth/gmail.send。common)→ 身份验证 → 添加平台「Web」,重定向 URI 填上面的地址 → 证书和密码 → 新客户端密码 → API 权限:Microsoft Graph 委托权限Mail.Send、User.Read、offline_access(按租户策略授予管理员同意)。Risks
Scope check
🤖 Generated with Claude Code