Skip to content

Commit 5d759b1

Browse files
fix(rest): require a send capability on the REST email door and bound the sender address (#27469)
domain:devx#1 · sunhaolin · session_017xRBcVy4VXmkQjn2MGeaWk Clause-②: yes (narrowing) — the REST send door refuses callers and bodies it admitted (the breaking half), and the published `IEmailService` contract gains an optional `getDefaultFrom()` (a widening, the same move as `isConfigured()` on the same interface). No spec key, export or config field is removed or renamed. Metadata-protocol: none Skills-docs: none — no file under `skills/**` teaches `POST /api/v1/email/send`, `client.email.send` or `IEmailService` (a `git grep` of `skills/` for each names nothing), so no skill line changes. The runtime-services page, `content/docs/kernel/runtime-services/email-service.mdx` ("Over HTTP"), states the four bounds in this change. No tracking issue: this hardening was sent straight to a dev seat, so the body has no closing line. **Review tier:** this change narrows who may call a public REST door and what they may send through it. It needs one contract-review-tier review of the current head before it enters the queue. ## 维护者速读 - **改了什么:** REST 发信接口 `POST /api/v1/email/send` 在发送前做四道校验,不满足一律 403 `PERMISSION_DENIED`、不发信:① 调用方须持有 `manage_platform_settings`;② `sentBy` 一律记为当前登录用户;③ 发件人限定为部署配置的发件地址,自定义 `headers` 只接受"字符串到字符串"的普通对象(合法头名、单行值),且不得设 `From`/`Sender`/`Return-Path`;④ 邮件日志行的 `organizationId` 由服务端取调用方当前组织,不接受调用方另填别的组织,也不接受 `identityMail`(身份类邮件只由服务端自己发)。SMTP 通道把自定义头按"一个键一个头"的显式列表交给 nodemailer。 - **为什么改:** 这个接口原来只校验"已登录",请求体几乎原样转给邮件服务:谁都能用部署自己的邮件通道发信、自选发件人和署名、把日志记到任意组织名下。现在由服务端决定发件人、署名和归属组织(ADR-0124)。 - **风险与回滚:** 直接调此接口、但无该权限的集成会收到 403;带非配置发件人 `from`、他人 `sentBy`、别的组织 `organizationId`、`identityMail: true`,或自定义头不是普通字符串对象的调用都会被拒。flow、通知、认证邮件走服务内部调用,不受影响。回滚即 revert 本 PR。 - **先看:** ① `packages/rest/src/email-routes.ts`:`headersRefusal()` 与第 4 道(组织/身份邮件)分支,以及转发前的 `organizationId` 盖章;② `packages/plugins/plugin-email/src/transports/smtp.ts`:自定义头改为显式列表;③ `packages/rest/src/email-send-door-bounds.test.ts`。 - **两分钟验证:** `pnpm --filter @objectstack/rest exec vitest run src/email-send-door-bounds.test.ts`,预期 36/36 通过。 - **需要你做的:** 定夺发信门槛:沿用 `manage_platform_settings`(本 PR 现状),还是另立专用的发信能力(需在 spec 的 `PLATFORM_CAPABILITIES` 新增一项,另起一张卡)。本 PR 保持现状,等你一句话。 ## What changes `POST {base}/email/send` (`packages/rest/src/email-routes.ts`, both the unscoped and the environment-scoped mount) now applies four bounds between the auth floor and the send. Each one answers before the mail service is called, and each refusal is `403 PERMISSION_DENIED` in the nested ADR-0112 envelope (`{ error: { code, message } }`), the shape `enforceAuth` already uses: 1. **Capability.** The caller must hold `manage_platform_settings` (`EMAIL_SEND_CAPABILITY`), read from the resolved context's `systemPermissions`. It is the capability the `mail` settings namespace reads and writes on, the one `sys_identity_email` requires for the whole row, and the one `sys_email` requires for its two body columns (`body_text`, `body_html`; the rest of a `sys_email` row is not gated on it). The check runs before the provider lookup, so a refused caller gets the same answer whether or not mail is wired. 2. **Attribution.** `sentBy` is always the authenticated caller. A body that names a different user is refused; a body that names the caller, or no one, is stamped with the caller. 3. **Sender.** The envelope sender is the deployment's configured sender (`IEmailService.getDefaultFrom()`). A `from` naming another address is refused; one naming the configured address is accepted and the configured value is forwarded in its place. A service that cannot report its sender, or a deployment with none configured, refuses a caller `from`. Custom `headers` are accepted in one shape only, the contract's string-valued header map: a plain object whose every key is a header field name (printable ASCII, no space, control character or colon) and whose every value is a single-line string. Any other shape is refused, and so are custom `From`, `Sender` and `Return-Path` headers, so the reserved-name check reads each header exactly as a transport will. 4. **Organization.** The message's mail-log row belongs to the caller's active organization: the door stamps `organizationId` from the `tenantId` the identity resolver vetted onto the execution context (the source `meta-item-read-gate.ts` documents), and the service stamps it verbatim onto `sys_email.organization_id`. A body naming another organization is refused, and so is a body naming one when the caller has no active organization. `identityMail` is refused for any value but `false`: identity mail is sent by the server itself, and its log is not a destination an HTTP caller chooses. The forwarded message never carries the caller's `identityMail`. `replyTo` is deliberately not bounded: `SendEmailInput.replyTo` declares it a caller-supplied Reply-To address and makes no sender claim of it, so there is no configured value to bound it to. To support bound 3, `IEmailService` (`packages/spec/src/contracts/email-service.ts`) gains an optional `getDefaultFrom()`. plugin-email's `EmailService` implements it by reading the live `defaultFrom`, so a sender changed in the Mail settings is followed. The member is optional, so existing implementations stay valid, and the door treats a missing member as unknown. plugin-email's SMTP transport (`packages/plugins/plugin-email/src/transports/smtp.ts`) now hands nodemailer custom headers as an explicit list of name/value entries, one per key of the headers map, so every key is read as exactly one header name. A well-formed map puts the same headers on the wire as before (the existing wire test, `sys-email-payload.wire.test.ts`, still reads them there). Server-internal senders (flows, notifications, auth mail, the messaging email channel) call `IEmailService.send` directly and are unchanged. Docs: the `client.email.send` JSDoc; `content/docs/kernel/runtime-services/email-service.mdx` ("Over HTTP", now four bounds and the `replyTo` note); the `integration-system.email-template-render` checklist clause, revision 10, whose step (d) now also drives the headers-shape, organization and identity-mail refusals and the organization stamp. ## Tests - `packages/rest/src/email-send-door-bounds.test.ts` (36 cases), through the real `HonoHttpServer` transport over a contract-typed mail-service double. Every refusal case also asserts the service was never called; every admission case asserts what it was called with. - capability: entitled 200 with the caller stamped and no `from`; unentitled or no capability set 403 with neither service nor provider called; no provider 403 vs 501; anonymous 401; non-object body 400; - `sentBy`: foreign 403, the caller's own 200; - sender: foreign `from` 403 (string and object forms), restated configured address 200 with the configured value forwarded, no configured sender or no accessor 403 for a caller `from` while a send without one succeeds, `From` / `sender` / `Return-Path` 403, other headers pass through; - headers shape (new, 10 cases): a list of entries, an object value, a number value, a multi-line value, a name with a space, a name with a colon, a non-ASCII name, `null` and a string are each 403 with nothing sent; an empty map and a well-formed map are forwarded as sent; - organization (new, 5 cases): an organization-scoped caller is stamped with its organization, a restated organization is admitted, another organization 403, a caller with no active organization naming one 403, and a caller with none sends with no `organizationId` forwarded; - identity mail (new, 4 cases): `true`, `'true'` and `1` are 403 with nothing sent; `false` is admitted and the forwarded message carries no `identityMail`. - `packages/plugins/plugin-email/src/transports/smtp.test.ts`: the field mapping now expects the list form, and a new case pins one name/value entry per key, in order. - `packages/spec/src/contracts/email-service.test.ts`: a compile-time parity pin for `getDefaultFrom`, the way `isConfigured` is pinned (absent stays assignable; either address form or `undefined` accepted; a number, or an object without `address`, refused by `@ts-expect-error` in a file `check:test-typecheck` compiles). - `packages/plugins/plugin-email/src/email-service.test.ts` (unchanged in this round): `getDefaultFrom` returns the constructor sender, follows `setDefaultFrom`, and is `undefined` when none is set. ## Acceptance notes - **Capability choice (pending the maintainer).** `manage_platform_settings` is platform-scoped, so an organization administrator cannot send through this door. That matches who can configure the transport today. A dedicated send capability would be a `PLATFORM_CAPABILITIES` addition and is left to the maintainer's decision; this PR keeps the current choice. - **Display name.** A `from` that restates the configured address with its own display name is accepted, and the configured display name is sent. A per-send display name is no longer possible through this door. - **`replyTo`** stays caller-controlled (see What changes). Bounding it would need a contract that reserves it, which `SendEmailInput` does not. - **Service-level header validation** is not added: `normalizeMessage` still forwards any non-empty `headers` object from server-internal callers, which are typed against the contract. The HTTP door is the bound for outside input. ## Verification Tree `objectstack-ai/objectstack` at `1b5c8eef` (all readings below were taken at this head unless a line says otherwise). <details><summary>Package tests and typecheck (at 1b5c8ee)</summary> - `pnpm --filter @objectstack/rest test`: Test Files 335 passed (335), Tests 6614 passed, 326 skipped. Exit 0. (+19 over the previous head: the 19 new door cases.) - `pnpm --filter @objectstack/plugin-email test`: Test Files 44 passed (44), Tests 748 passed. Exit 0. - `pnpm --filter @objectstack/client test`: Test Files 52 passed (52), Tests 680 passed. Exit 0. - `pnpm --filter @objectstack/spec test`: Test Files 750 passed (750), Tests 22315 passed, 1 todo. Exit 0. - `typecheck` exit 0 on all four (`rest`, `plugin-email`, `client`, `spec`); each `check:test-typecheck` OK, `spec` holding its ledgered 52 files / 240 errors unchanged, the other three at 0. - Built first: the dependency closure of the four packages (`--filter 'PKG^...'`, 38 packages), lock verdict `command-exit 0`. </details> <details><summary>Ablations (committed first; each leg mutated through scripts/ablation-replace.mjs in wrap mode, restored to HEAD and proven by blob hash and an empty git diff HEAD)</summary> The door test resolves `./rest-server` and `./email-routes` from `src`, and `smtp.test.ts` resolves `./smtp.js` from `src`, so no rebuild leg was needed. Every leg's restore read `blob == HEAD` (`email-routes.ts` 0cd9f87, `smtp.ts` ad53055) with `git diff HEAD` empty, and `git status --porcelain` was empty after the last leg. - Shape check disabled: 2 of 36 red (`null`, a string). The list-of-entries case stays refused by the value check. - Field-name check disabled: 3 of 36 red (space, colon, non-ASCII name). - Value check disabled: 3 of 36 red (object value, number value, multi-line value). The list-of-entries case stays refused by the shape check. - Organization refusal disabled: 2 of 36 red (another organization; naming one with none active). - Organization stamp removed: 3 of 36 red (the two stamp cases and the `identityMail: false` case, which also reads the stamp). - Identity-mail refusal disabled: 3 of 36 red (`true`, `'true'`, `1`). - Identity-mail strip removed: 1 of 36 red (`identityMail: false` forwarded). - SMTP list form reverted to the plain map: 2 of 26 red in `smtp.test.ts` (the field mapping and the list-form case). </details> <details><summary>Full dogfood battery (the Clause-② line carries the narrowing arm)</summary> - At 1b5c8ee, after building the `@objectstack/dogfood` dependency closure (69 packages, exit 0): `pnpm --filter @objectstack/dogfood test`, no shard, no path. Test Files 348 passed, 3 skipped (351); Tests 2806 passed, 20 skipped (2826). Exit 0. </details> <details><summary>Derived gate families (node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack, at 1b5c8ee)</summary> - 110 derived. `--ran` reconciliation over the recorded exit codes: 110 derived, 109 run, 1 NOT-MEASURED, 0 UNRUN. - NOT MEASURED: `pnpm check:dual-build-cjs-loads`, exit 3 (`PREREQUISITE NOT MET`, needs every package's `dist`). CI's `Lint & Repo Gates` is green on this head. - `check:skill-examples` and `check:type-check-debt` first exited 3 on prerequisites (no `client-react` dist; the debt re-measure did not get a lock turn) and were re-run after the closure build: 272 prose examples type-check across 3 surfaces, exit 0; the type-check debt re-measure OK, 0 raw tsc errors, exit 0. - The changeset gates: `check-adr-0087-registration` accepts the one declared-breaking changeset (`BREAKING+bang+clause-②-narrowing`) with `not-required (no-migration-prescription)`; `check-changeset-no-major` driven offline with this body as the PR payload reads `Clause-②: yes (narrowing)`, `Metadata-protocol: none`, a non-protocol change at `patch`, exit 0. - The derivation warns its tree is behind `origin/main`, with 6 changed `scripts/pm/` inputs; none of this PR's files changed on `main` in that range, so `main` was not merged. </details> <details><summary>CI on 1b5c8ee</summary> 50 check runs: 41 success, 9 skipped (opt-in and matrix placeholders, `Lint UI` path-skipped), 0 failure, 0 pending. All ten required contexts are success except `Lint UI`, which is path-skipped. The red `TypeScript Type Check` on the previous head 5ba07d1 was its `Type Check · workspace` lane cancelled by the push of 1b5c8ee, not a type error. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_017xRBcVy4VXmkQjn2MGeaWk)_ <sub>Body refreshed by the PM seat 2026-10-29T13:18Z after contract review 6497633638 (must-fix 1: the body carried the stale Clause-② line) and os-dev report 6497744791.</sub> 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_017xRBcVy4VXmkQjn2MGeaWk --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 6cc5374 commit 5d759b1

15 files changed

Lines changed: 756 additions & 25 deletions

File tree

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
---
2+
'@objectstack/rest': patch
3+
'@objectstack/spec': patch
4+
'@objectstack/plugin-email': patch
5+
'@objectstack/client': patch
6+
---
7+
8+
fix(rest)!: the REST email send door requires a send capability and bounds the sender, the custom headers, the organization and identity mail
9+
10+
Clause-②: yes (narrowing) — the REST send door refuses callers and bodies it admitted (the breaking half), and the published `IEmailService` contract gains an optional `getDefaultFrom()` (a widening, the same move as `isConfigured()` on the same interface). No spec key, export or config field is removed or renamed.
11+
Metadata-protocol: none
12+
Skills-docs: none — no file under `skills/**` teaches `POST /api/v1/email/send`, `client.email.send` or `IEmailService` (a `git grep` of `skills/` for each names nothing), so no skill line changes. The runtime-services page, `content/docs/kernel/runtime-services/email-service.mdx` ("Over HTTP"), states the four bounds in this change.
13+
14+
<!-- adr-0087: not-required (no-migration-prescription) A runtime authorization narrowing at one REST door, not a metadata change. No spec key, export, option, config field, response field or stored shape is removed, renamed or re-shaped: SendEmailInput keeps every member, and a caller the bounds admit receives the same answer as before. There is no tombstone and nothing for `objectstack migrate meta` to rewrite. What narrows is which HTTP callers and bodies the door serves. The other categories are closed on facts: the four packages publish (not unpublished); no ADR-0087 id covers this door and this diff adds none (not registered or already-registered); and IEmailService, the one published interface that moves, gains an optional member and is referenced in code across the workspace (not runtime-interface-only or type-surface-only). -->
15+
16+
**BREAKING** (an accept-set narrowing of `POST /api/v1/email/send`), shipped as `patch` because no metadata protocol moves.
17+
18+
`POST /api/v1/email/send` (and its environment-scoped twin) now applies four bounds after the authentication floor and before anything is sent. Each refusal is `403 PERMISSION_DENIED` in the nested `{ error: { code, message } }` envelope, and the mail service is not called:
19+
20+
- **Capability.** The caller must hold `manage_platform_settings`, the capability that already governs the mail settings namespace, the `sys_identity_email` log and the two body columns of `sys_email`. An authenticated caller without it is refused. The check runs before the provider lookup, so a refused caller gets `403` whether or not mail is wired.
21+
- **Attribution.** `sentBy` is always the authenticated caller. A body that names another user is refused. A body that names the caller, or names no one, is stamped with the caller.
22+
- **Sender.** The envelope sender is the deployment's configured sender (the Mail settings' From address, or `defaultFrom`). A `from` naming any other address is refused. A `from` naming the configured address is accepted, and the configured value is sent in its place. `headers` is accepted only as the contract's `Record<string, string>`: a plain object whose every key is a header field name and whose every value is a single-line string. Any other shape is refused, and so are custom `From`, `Sender` and `Return-Path` headers.
23+
- **Organization.** The message is recorded under the caller's active organization: the door sets `organizationId` from the caller's execution context, and the service stamps it onto `sys_email.organization_id`. A body naming another organization is refused, and so is a body naming one when the caller has no active organization. `identityMail` is refused (any value but `false`): identity mail is sent by the server itself. `replyTo` is unchanged; it is the caller's Reply-To address and makes no claim about the sender.
24+
25+
Server-internal sends (flows, notifications, auth mail) call `IEmailService.send` directly and are unchanged.
26+
27+
`IEmailService` gains an optional `getDefaultFrom()` that returns the configured sender, and plugin-email's `EmailService` implements it. A service that does not implement it still sends through the door, but a caller `from` is refused because the sender cannot be checked.
28+
29+
plugin-email's SMTP transport now hands nodemailer custom headers as an explicit list of name/value entries, one per key of the headers map, so every key is read as exactly one header name. A well-formed headers map puts the same headers on the wire as before.
30+
31+
What changes for you: an integration that sends through the REST door needs a credential holding `manage_platform_settings`, and should leave `from`, `sentBy`, `organizationId` and `identityMail` out of the body, since the door supplies each of them. Custom headers are sent as a plain object of string values.

‎content/docs/kernel/runtime-services/email-service.mdx‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,19 @@ services.email.send(input: SendEmailInput): Promise<SendEmailResult>
1515
services.email.sendTemplate(input: SendTemplateInput): Promise<SendEmailResult>
1616
```
1717

18+
`services.email.getDefaultFrom?.()` returns the configured sender, the `from` that `send()` uses when the input names none. It is `undefined` when no sender is configured.
19+
20+
## Over HTTP
21+
22+
`POST /api/v1/email/send` (`client.email.send`) hands a message to `send()`. Plugins and flows call `send()` directly and are not affected by what follows. The HTTP door checks four things first, and refuses a failure with `403 PERMISSION_DENIED` before anything is sent:
23+
24+
- The caller must hold the `manage_platform_settings` capability.
25+
- `sentBy` is always the authenticated caller. A body that names another user is refused.
26+
- The sender is the deployment's configured sender. A `from` naming another address is refused. A `from` naming the configured address is replaced by the configured value. Omit `from` to send as the configured sender. `headers`, when sent, must be a plain object that maps each header name to a single-line string value. Any other shape is refused, and so are custom `From`, `Sender` and `Return-Path` headers.
27+
- The message is recorded under the caller's active organization, which the door sets as `organizationId`. A body that names another organization is refused, and so is one that names an organization when the caller has none. `identityMail` is refused: identity mail (verification, password reset, invitations) is sent by the server itself. Omit both.
28+
29+
`replyTo` is not bounded. It is the caller's choice of Reply-To address and makes no claim about the sender.
30+
1831
## Returns
1932

2033
`SendEmailResult`:

0 commit comments

Comments
 (0)