diff --git a/.changeset/body-mail-activity-doors.md b/.changeset/body-mail-activity-doors.md new file mode 100644 index 00000000000..f0ffd7e9a6e --- /dev/null +++ b/.changeset/body-mail-activity-doors.md @@ -0,0 +1,33 @@ +--- +'@objectstack/spec': minor +'@objectstack/core': patch +'@objectstack/objectql': patch +'@objectstack/runtime': patch +'@objectstack/cli': patch +'@objectstack/rest': patch +'@objectstack/plugin-email': patch +'@objectstack/plugin-audit': patch +'@objectstack/plugin-security': patch +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +feat(runtime): a script body sends mail and adds a timeline entry through platform doors that stamp who sent it + +Clause-②: yes (widening) +Metadata-protocol: added + +**BREAKING** (`@objectstack/plugin-email`): a `queued` row an app inserts into the mail log (`sys_email`, `sys_identity_email`) is sent from the configured sender, with no `From`, `Sender` or `Return-Path` header of its own, whatever sender the row names; a deployment with no configured sender refuses such a row. Migration: FROM inserting a mail-log row that names its own sender TO `ctx.email.send({ to, subject, text })` in a body that declares `email.send`, which sends from the configured sender with the calling user named in its display name. A row inserted with no sender of its own is delivered as before. + + + +- **`@objectstack/spec`:** two new body capabilities, `email.send` and `activity.append`, and their inputs `BodyMailSendInputSchema` and `BodyActivityAppendInputSchema` (`@objectstack/spec/data`). The sender, the sending user, the organization, the actor and the origin are stamped by the platform and are not inputs: a key outside either shape is refused. Every string either input takes has an upper bound, and the limits that read across fields (`BODY_MAIL_RECIPIENT_LIMIT`, `BODY_MAIL_ADDRESS_LIST_LIMIT`, `BODY_MAIL_ADDRESS_LIMIT`, `BODY_ACTIVITY_METADATA_LIMIT`) are stated in each schema's description. `SYS_ACTIVITY_PLATFORM_TYPES` names the timeline types only the platform records. `SendEmailInput.requireLogRow` (`@objectstack/spec/contracts`) asks the mail service to send a message only if its log records it. A hook whose body is granted `email.send` is refused at parse (`HookSchema`): a hook body sends no mail. +- **`@objectstack/runtime`:** an action or a job body that declares the capability calls `ctx.email.send({ to, subject, text })`, and a hook, action or job body `ctx.activity.append({ object, recordId, type, summary })`. A message is sent from the configured sender, as the calling user, under the caller's organization; a timeline entry is written with the calling user as its actor and the package and body as its origin. A record the call points at must be one the caller can read, in the caller's own scope: for a hook, the user of the write that fired it, never the system. A message names at most 50 recipients, each recipient list and `replyTo` fits the mail log as recorded, a message is sent only if the mail log records it, and an organization's mail is held to `OS_EMAIL_APP_SEND_HOURLY_LIMIT` messages an hour (default 200) before the door refuses another. A message cannot be taken back, so a hook body cannot send mail: a hook body granted `email.send` is not bound, and a call is refused (`403 PERMISSION_DENIED`); an action or a job body sends it, and is refused with `409 RESOURCE_CONFLICT` while it runs inside a transaction. A timeline entry commits or rolls back with the write that runs the body. A door call inside the body's own `ctx.api.transaction` is refused with `409 RESOURCE_CONFLICT`. An entry's origin names the package that holds the body. A body with no calling user (a job) sends and writes with no user recorded. +- **`@objectstack/cli`:** the build infers both capabilities from a handler's calls, under a renamed or destructured context too. `ExtractedBody.capabilities` on `@objectstack/cli/hook-body` may now hold `'email.send'` and `'activity.append'`. A hook handler that calls `ctx.email.send` fails the build, which refuses the inferred grant. +- **`@objectstack/objectql`:** `seedHookUserGrants` and `seedHookUnreadMembership`, the second step of a `runAs: 'user'` derivation and its fail-safe, are exported beside `deriveHookApi`. `openTransactionKind` answers whether a write runs inside a transaction that a write beside it joins (`'joined'`), one it cannot reach (`'separate'`), or none. +- **`@objectstack/core`:** the bounds a caller-sent message is held to (the sending user, the organization, the configured sender) are one function, `boundCallerMail`, shared by the REST mail door and the body door. +- **`@objectstack/rest`:** the REST mail door reads its bounds from `boundCallerMail`; its answers are unchanged. +- **`@objectstack/plugin-email`:** a mail-log row the mail service did not write is delivered from the configured sender, with no sender header of its own (see BREAKING above). `send()` honours `requireLogRow`: when the row cannot be written, it refuses with `503 SERVICE_UNAVAILABLE` and delivers nothing. +- **`@objectstack/plugin-audit`:** the activity feed owns the door's writer, `appendAppActivity` on the `audit` service. An app's entry may not use a platform-only type or a platform metadata key, and may not be about an object the feed does not show or an append-only object. `sys_activity` gains a read-only `origin` column, empty on an entry not written through the activity door. +- **`@objectstack/plugin-security`:** inserting into an append-only object from app automation that runs as system is deprecated, and says so once per kind and object, naming the two doors. +- **`@object-ui/app-shell`:** the script capability picker lists both capabilities with their calls; on a hook it does not offer `email.send`, and flags a stored grant. `@object-ui/i18n` carries the flag's text in the studio catalogue (en, zh). diff --git a/content/docs/automation/hook-bodies.mdx b/content/docs/automation/hook-bodies.mdx index 3751d9447c9..b9822f6d9e8 100644 --- a/content/docs/automation/hook-bodies.mdx +++ b/content/docs/automation/hook-bodies.mdx @@ -105,6 +105,8 @@ The script sees only what the surrounding `ctx` object exposes: | `ctx.title('')` | The related record's title, through a lookup / master_detail / user / tree column. Costs one `findOne` (plus the lookups that record's own title reads through). | `api.read` | | `ctx.crypto.randomUUID()` | UUID generation. | `crypto.uuid` | | `ctx.log.{info,warn,error}` | Structured logging. | `log` | +| `ctx.email.send({ to, subject, text })` | Sends mail through the mail service, from the configured sender, as the calling user and under the caller's organization. An action or a job body only: a hook body cannot send mail, because a message cannot be taken back if the write that runs the hook rolls back. A hook whose body is granted `email.send` is refused when it is saved, validated, built or bound, and the Console does not offer the grant on a hook. Send mail on a record change from an action, a job or a flow. See [Email service](/docs/kernel/runtime-services/email-service#from-a-script-body). | `email.send` | +| `ctx.activity.append({ object, recordId, type, summary })` | Adds an entry to a record's activity timeline. The platform stamps the calling user as the actor and the package and body as the entry's `origin`. `type` may not be one only the platform records (`SYS_ACTIVITY_PLATFORM_TYPES`), the record must be one the caller can read, and `metadata` takes at most 8,000 characters as JSON. The entry commits or rolls back with the write that runs the body. Refused inside the body's own `ctx.api.transaction`. | `activity.append` | | `ctx.connector(name).(...)` _(planned)_ | Outbound HTTP / SaaS calls. **Not yet wired into the sandbox** — ships with the separate Connector spec. | (separate Connector spec) | ### Write provenance — `ctx.provenance` diff --git a/content/docs/deployment/environment-variables.mdx b/content/docs/deployment/environment-variables.mdx index bc5201e1ba4..fe3bd9c35f0 100644 --- a/content/docs/deployment/environment-variables.mdx +++ b/content/docs/deployment/environment-variables.mdx @@ -175,6 +175,7 @@ Link previews read the same values. The console document served at `/_console/` | `OS_EMAIL_SMTP_SECURE` | boolean | `true` | Require TLS. On port `465` that means implicit TLS; on any other port a **required** STARTTLS upgrade (a server that will not upgrade fails the send instead of leaking credentials in the clear). `false` connects in the clear and upgrades only when STARTTLS is offered. | | `OS_EMAIL_SMTP_USER` | string | — | SMTP AUTH username. Omit for servers that accept unauthenticated relay. | | `OS_EMAIL_SMTP_PASSWORD` | string | — | SMTP AUTH password. | +| `OS_EMAIL_APP_SEND_HOURLY_LIMIT` | number | `200` | The most messages an organization's mail log may record in one hour before a script body's `ctx.email.send` is refused with `429 RATE_LIMIT_EXCEEDED`. A whole number, `0` or more; any other value fails the call. The count is read before each send, so it bounds volume rather than holding an exact number. See [Email service](/docs/kernel/runtime-services/email-service#from-a-script-body). | > SMTP delivery ships in `@objectstack/plugin-email` (ADR-0012) and is > implemented with `nodemailer`, imported lazily so deployments that never diff --git a/content/docs/kernel/runtime-services/email-service.mdx b/content/docs/kernel/runtime-services/email-service.mdx index 64a3c06c120..36a6d4744cc 100644 --- a/content/docs/kernel/runtime-services/email-service.mdx +++ b/content/docs/kernel/runtime-services/email-service.mdx @@ -30,6 +30,28 @@ services.email.sendTemplate(input: SendTemplateInput): Promise `replyTo` is not bounded. It is the caller's choice of Reply-To address and makes no claim about the sender. +## From a script body + +An action or a job body sends mail with `ctx.email.send(input)` when it declares the `email.send` capability (`os build` infers it from the call). The input is `BodyMailSendInputSchema` (`@objectstack/spec/data`): `to`, `cc`, `bcc`, `replyTo`, `subject`, `text` and/or `html`, and `related`, the record the message is about. + +- The message is sent from the configured sender. Its display name names the calling user beside the organization, for example `Ann Lee via Acme`. Replies go to `replyTo`. +- It is recorded as sent by the calling user and under the caller's organization, with the same bounds as the HTTP door. `from`, `sentBy`, `organizationId`, `headers` and `identityMail` are not inputs, and a call that names one is refused with `400 VALIDATION_ERROR`. +- `related` must be a record the caller can read, in the caller's own scope. Otherwise the call is refused with `404 RECORD_NOT_FOUND` and nothing is sent. +- A message names at most 50 recipients across `to`, `cc` and `bcc`. Each of the three takes at most 4,000 characters as the mail log records it (every recipient as `"Name"
`, joined by `, `), and a `replyTo` at most 320. The subject takes at most 998 characters, and `text` and `html` at most 1,000,000 each. A message over any of these is refused with `400 VALIDATION_ERROR`. +- While the organization's mail log records `OS_EMAIL_APP_SEND_HOURLY_LIMIT` messages (default 200) in the last hour, the call is refused with `429 RATE_LIMIT_EXCEEDED`. A caller with no organization is counted against the whole log. The count is read before the send, so two calls racing for the last message of the hour can both be sent. +- The message is sent only if the mail log records it. When the row cannot be written, the call is refused with `503 SERVICE_UNAVAILABLE` and nothing is sent. +- A message cannot be taken back, so a hook body cannot send mail: the write that runs the hook may still roll back. A hook whose body is granted `email.send` is refused when it is saved, validated, built or bound, and a call from a hook body is refused with `403 PERMISSION_DENIED`. Send mail on a record change from an action, a job or a flow. +- A call made while an action or a job runs inside a transaction, or inside the body's own `ctx.api.transaction`, is refused with `409 RESOURCE_CONFLICT`. +- A job body has no calling user, so its message is recorded with no `sentBy`. + +The call answers `{ id, status }`. A deployment with no mail service answers `501 NOT_IMPLEMENTED`. + +A row written into the mail log (`sys_email`, `sys_identity_email`) at `queued` by anything other than the mail service is sent from the configured sender, with no `From`, `Sender` or `Return-Path` header of its own, whatever the row said. Where no sender is configured, the mail log refuses such a row. + + +**Breaking for direct inserts.** Before this release, a `queued` row an app inserted into the mail log was sent from the `from_address` the row named. It is now sent from the configured sender. Send through `ctx.email.send`, which names the calling user in the sender's display name, instead of inserting the row. + + ## Returns `SendEmailResult`: diff --git a/content/docs/permissions/system-context.mdx b/content/docs/permissions/system-context.mdx index f31faa21519..cddc110ee4c 100644 --- a/content/docs/permissions/system-context.mdx +++ b/content/docs/permissions/system-context.mdx @@ -223,8 +223,8 @@ One of the largest consumers of the flag; ### 6. Reads that only carry the flag onward -Not behaviours: these four sites read the flag solely to copy it into another -context or envelope. They are listed because the census counts them, and because +Not behaviours: these five sites read the flag solely to copy it into another +context or envelope, or to take it off one. They are listed because the census counts them, and because a reader tracing where elevation travels needs them. | # | Symbol | Package | What it does | @@ -232,6 +232,7 @@ a reader tracing where elevation travels needs them. | 63 | `buildSession` | objectql | Propagates `isSystem` into the hook session so hooks can tell engine self-writes from user writes | | 64 | `isSystem` | objectql | `ScopedContext.isSystem` getter — re-exposes the underlying execution context's flag | | 65 | `executionContextFromHook` | runtime | Rebuilds an `ExecutionContext` from a hook session, carrying the flag across | +| 65b | `callerScopeOf` | runtime | Takes a script body's own elevation off its caller's envelope (the app-automation mark and the flag it came with), so `ctx.email.send` and `ctx.activity.append` read the record a body points at in the caller's scope. It removes the flag and grants nothing | | 66 | `toolCallPrincipalOf` | mcp | Projects the host's resolved `ExecutionContext` into the frozen principal an installed MCP tool-call interceptor reads, carrying `isSystem: true` only for a system caller. It decides nothing: the tool still runs under its own context | --- @@ -681,6 +682,7 @@ and CI refuses one that differs from what the tree produces. | `packages/runtime/src/domains/permission-set-clone.ts#handlePermissionSetCloneWrite` | 2 | 50 | | `packages/runtime/src/domains/security.ts#handleSecurityRequest` | 1 | 52 | | `packages/runtime/src/flow-start-admission.ts#flowStartRefusal` | 1 | 57 | +| `packages/runtime/src/sandbox/body-doors.ts#callerScopeOf` | 1 | 65b | | `packages/runtime/src/sandbox/body-runner.ts#executionContextFromHook` | 1 | 65 | | `packages/services/service-automation/src/runtime-identity.ts#stampSystemInsertOwner` | 1 | 60 | | `packages/services/service-knowledge/src/knowledge-service.ts#applyPermissionFilter` | 1 | 46 | diff --git a/content/docs/permissions/tenant-audit-census.mdx b/content/docs/permissions/tenant-audit-census.mdx index dfcb16d853c..608a6cd360e 100644 --- a/content/docs/permissions/tenant-audit-census.mdx +++ b/content/docs/permissions/tenant-audit-census.mdx @@ -132,7 +132,7 @@ are reported as `undecidable` rather than assumed either way. The same holds twice over for the context. An options argument spelled as a literal can be read; one spelled `options`, `{ ...opts }`, or handed through a -forwarding shim cannot, and **58 of the 308 sites are spelled that way**. A +forwarding shim cannot, and **59 of the 309 sites are spelled that way**. A context resolved from an inline literal or a local `const` can be tested for `isSystem`; one arriving from a helper call cannot. @@ -160,8 +160,8 @@ now **0**: nothing on this surface threads a context that provably lacks the fla **"No tenant context" counted sites it had not read.** An options argument the walker could not parse was folded into the same bucket as one it had read and -found empty. That published **70 sites "carrying no tenant context at all"** -when 12 said so and 58 were simply unread — an over-claim in the *alarming* +found empty. That published **71 sites "carrying no tenant context at all"** +when 12 said so and 59 were simply unread — an over-claim in the *alarming* direction, on the very figure this page tells other cards to cite. `carries` is now three-valued, and an unreadable argument can never contribute to the provable count. @@ -197,10 +197,10 @@ reproduce them. Where it disagrees, it disagrees on the page: | carried figure | where it survives | this census | | :--- | :--- | ---: | -| 175 write call sites | quoted in the merged changeset | **308** | -| 24 carrying no tenant context | quoted in the merged changeset | **3** provable and tenancy-enabled; **31** more whose options argument is unreadable | -| 127 of 175 statically decidable, 48 runtime-parameter-name sites | restated on the `isSystem`-scoping card | **214 of 308** decidable, **94** undecidable | -| 135 (77%) silenced by the `isSystem` guard before the posture gate | the lost issue body — **no surviving corroboration** | **not reproduced**: 173 decidably elevated, 0 decidably not, 123 undecidable | +| 175 write call sites | quoted in the merged changeset | **309** | +| 24 carrying no tenant context | quoted in the merged changeset | **3** provable and tenancy-enabled; **32** more whose options argument is unreadable | +| 127 of 175 statically decidable, 48 runtime-parameter-name sites | restated on the `isSystem`-scoping card | **215 of 309** decidable, **94** undecidable | +| 135 (77%) silenced by the `isSystem` guard before the posture gate | the lost issue body — **no surviving corroboration** | **not reproduced**: 173 decidably elevated, 0 decidably not, 124 undecidable | | 141 and 132, two independent re-derivations | the card that filed this work | — | **The differences are not reconciled, and deliberately so.** The old census's @@ -217,14 +217,14 @@ would report a smaller number and would not say so. The fourth row is the one worth flagging to anyone citing it. **The 135 / 77% figure has no surviving corroboration anywhere in the tree.** This census reads -173 of 308 (56%) as decidably elevated, with 123 more whose elevation is a +173 of 309 (56%) as decidably elevated, with 124 more whose elevation is a run-time fact — so the claim is neither confirmed nor refuted, and the honest answer is that a static reading cannot settle it. -⇒ **Cite `3 / 308`, and say what it is**: the sites whose options argument was +⇒ **Cite `3 / 309`, and say what it is**: the sites whose options argument was READ and holds no tenant context, against a decidably tenancy-enabled object. That is the control's provable yield surface. ⛔ Do not cite it as "the sites -without tenant context" — **31 further sites** have an options argument this +without tenant context" — **32 further sites** have an options argument this cannot read, and they are neither in nor out. {/* BEGIN GENERATED: tenant-audit-census (scripts/tenant-audit-census.mjs) — DO NOT EDIT */} @@ -233,28 +233,28 @@ cannot read, and they are neither in nor out. | what | count | | :--- | ---: | -| write call sites on the application surface | **308** | -| …whose object name is statically decidable | 214 | +| write call sites on the application surface | **309** | +| …whose object name is statically decidable | 215 | | …whose object name is chosen at run time | 94 | -| …against an object with tenancy ENABLED | 207 | +| …against an object with tenancy ENABLED | 208 | | …against an object that declares tenancy off | 7 | | threading a tenant context | 238 | | PROVABLY carrying none (options read, no context key) | **12** | | …of those, against a decidably tenancy-enabled object | **3** | -| options argument UNREADABLE — may or may not carry one | 58 | -| …of those, against a decidably tenancy-enabled object | 31 | +| options argument UNREADABLE — may or may not carry one | 59 | +| …of those, against a decidably tenancy-enabled object | 32 | | threading a decidably ELEVATED (`isSystem`) context | 173 | | threading a context that is decidably NOT elevated | 0 | -| threading a context whose elevation is a run-time fact | 123 | +| threading a context whose elevation is a run-time fact | 124 | | how the instrument reached the site | count | | :--- | ---: | -| receiver carried a readable engine type | 246 | +| receiver carried a readable engine type | 247 | | receiver erased, placed by the object NAME | 52 | | receiver erased, placed by an `object: string` PARAMETER | 5 | | receiver erased, placed by an `UNTYPED_RECEIVERS` row | 5 | -| object name spelled inline | 129 | +| object name spelled inline | 130 | | object name spelled through a `const` | 85 | | object name is an `object: string` parameter | 10 | | object name is some other run-time expression | 84 | @@ -307,13 +307,13 @@ holds still. They are required to be HERE and to say WHEN they were true; their values are not compared. The reasoning, and the measurement behind it, are in `scripts/check-tenant-audit-census.mjs`. -Measured on 2026-11-12 at `0e97e095f`. +Measured on 2026-11-13 at `1bb3c359e`. | corpus scale (not enforced) | count | | :--- | ---: | -| tracked non-test sources scanned | 1139 | +| tracked non-test sources scanned | 1144 | | engine-shaped types recognised | 134 | | declared objects in the registry | 137 | -| same-named calls subtracted as non-engine | 291 | +| same-named calls subtracted as non-engine | 292 | {/* END GENERATED: tenant-audit-census */} diff --git a/content/docs/references/data/hook-body-doors.mdx b/content/docs/references/data/hook-body-doors.mdx new file mode 100644 index 00000000000..db5d60c737d --- /dev/null +++ b/content/docs/references/data/hook-body-doors.mdx @@ -0,0 +1,110 @@ +--- +title: Hook Body Doors — Data Protocol reference +navTitle: Hook Body Doors +description: "The two platform doors a sandboxed script body (a hook, action or job body) reaches for records it may not write itself: mail goes through the mail service." +--- + +{/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} + +The two platform doors a sandboxed script body (a hook, action or job body) +reaches for records it may not write itself: mail goes through the mail +service, and a timeline entry goes through the activity door. A body asks for +each with its own capability token (`email.send`, `activity.append`, +`HookBodyCapability`), and calls it as `ctx.email.send(input)` / +`ctx.activity.append(input)`. + +Each input below is what the BODY may say. What the platform says about the +message or the entry is stamped by the door and is not an input: the sender, +the user the mail is sent by, the organization it belongs to, the actor of a +timeline entry and the origin naming the body that wrote it. A key outside +the shape is refused, never dropped, so a body that names one of those is +told at the call. + +A message cannot be taken back, so mail is sent from an action or a job +body, never from a hook body; mail on a record change goes through an +action, a job or a flow. A timeline entry is written with the write that +runs the body, and commits or rolls back with it. + + +**Source:** `packages/spec/src/data/hook-body-doors.zod.ts` + + +## TypeScript Usage + +```typescript +import { BodyActivityAppendInputSchema, BodyDoorRecordRefSchema, BodyMailSendInputSchema } from '@objectstack/spec/data'; +import type { BodyActivityAppendInput, BodyDoorRecordRef, BodyMailSendInput } from '@objectstack/spec/data'; + +// Validate data +const result = BodyActivityAppendInputSchema.parse(data); +``` + +--- + +## BodyActivityAppendInput + +ctx.activity.append input: one entry a script body adds to a record timeline; it commits or rolls back with the write that runs the body. metadata is at most 8000 characters as JSON. + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **object** | `string` | ✅ | Object name of the record the entry is about | +| **recordId** | `string` | ✅ | Id of the record the entry is about | +| **type** | `string` | ✅ | Activity kind, from the open vocabulary less the platform-only values | +| **summary** | `string` | ✅ | One-line summary | +| **recordLabel** | `string` | optional | Display label of the record, as of the entry | +| **source** | `{ object: string; id: string }` | optional | The record the entry points at for its detail | +| **metadata** | `Record` | optional | Display hints stored beside the entry, at most 8000 characters as JSON | + +### Nested Shape: `BodyActivityAppendInput.source` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **object** | `string` | ✅ | Object name of the record | +| **id** | `string` | ✅ | Record id | + + +--- + +## BodyDoorRecordRef + +A record the door reads in the caller's scope before it acts + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **object** | `string` | ✅ | Object name of the record | +| **id** | `string` | ✅ | Record id | + + +--- + +## BodyMailSendInput + +ctx.email.send input: a message an action or a job body hands to the mail service; a hook body cannot send mail. At most 50 recipients across to, cc and bcc together; each of to, cc and bcc at most 4000 characters as recorded ("Name" `
`, joined by ", "); a replyTo at most 320 characters as recorded. + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **to** | `string \| { name?: string; address: string } \| (string \| { name?: string; address: string })[]` | ✅ | Recipient address, or a list of them | +| **cc** | `string \| { name?: string; address: string } \| (string \| { name?: string; address: string })[]` | optional | Carbon-copy recipients | +| **bcc** | `string \| { name?: string; address: string } \| (string \| { name?: string; address: string })[]` | optional | Blind carbon-copy recipients | +| **replyTo** | `string \| { name?: string; address: string }` | optional | Reply-To address; the sender itself is the configured one | +| **subject** | `string` | ✅ | Subject line | +| **text** | `string` | optional | Plain-text body | +| **html** | `string` | optional | HTML body | +| **related** | `{ object: string; id: string }` | optional | The record the message is about | + +### Nested Shape: `BodyMailSendInput.related` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **object** | `string` | ✅ | Object name of the record | +| **id** | `string` | ✅ | Record id | + + +--- + diff --git a/content/docs/references/data/hook-body.mdx b/content/docs/references/data/hook-body.mdx index ae570d492d5..9cb9af35d14 100644 --- a/content/docs/references/data/hook-body.mdx +++ b/content/docs/references/data/hook-body.mdx @@ -67,7 +67,7 @@ L2 sandboxed JS body — runs inside an isolated VM with declared capabilities | :--- | :--- | :--- | :--- | | **language** | `'js'` | ✅ | | | **source** | `string` | ✅ | Function body source | -| **capabilities** | `Enum<'api.read' \| 'api.write' \| 'api.transaction' \| 'crypto.uuid' \| 'log'>[]` | optional (default: `[]`) | Granted capability tokens | +| **capabilities** | `Enum<'api.read' \| 'api.write' \| 'api.transaction' \| 'crypto.uuid' \| 'log' \| 'email.send' \| 'activity.append'>[]` | optional (default: `[]`) | Granted capability tokens | | **timeoutMs** | `integer` | optional | Per-invocation timeout (ms) | | **memoryMb** | `integer` | optional | Per-invocation memory cap (MB) | @@ -85,6 +85,8 @@ L2 sandboxed JS body — runs inside an isolated VM with declared capabilities * `api.transaction` * `crypto.uuid` * `log` +* `email.send` +* `activity.append` --- @@ -99,7 +101,7 @@ L2 sandboxed JS body — runs inside an isolated VM with declared capabilities | :--- | :--- | :--- | :--- | | **language** | `'js'` | ✅ | | | **source** | `string` | ✅ | Function body source | -| **capabilities** | `Enum<'api.read' \| 'api.write' \| 'api.transaction' \| 'crypto.uuid' \| 'log'>[]` | optional (default: `[]`) | Granted capability tokens | +| **capabilities** | `Enum<'api.read' \| 'api.write' \| 'api.transaction' \| 'crypto.uuid' \| 'log' \| 'email.send' \| 'activity.append'>[]` | optional (default: `[]`) | Granted capability tokens | | **timeoutMs** | `integer` | optional | Per-invocation timeout (ms) | | **memoryMb** | `integer` | optional | Per-invocation memory cap (MB) | diff --git a/content/docs/references/data/hook.mdx b/content/docs/references/data/hook.mdx index cca3ff3ca04..67c3f368279 100644 --- a/content/docs/references/data/hook.mdx +++ b/content/docs/references/data/hook.mdx @@ -33,7 +33,7 @@ const result = HookSchema.parse(data); | **object** | `string \| string[]` | ✅ | Target object(s) | | **events** | `Enum<'beforeFind' \| 'afterFind' \| 'beforeInsert' \| 'afterInsert' \| 'beforeUpdate' \| 'afterUpdate' \| 'beforeDelete' \| 'afterDelete'>[]` | ✅ | Lifecycle events | | **handler** | `string` | optional | Handler function name (string, post-build) or inline function (pre-build) — DEPRECATED, prefer `body` | -| **body** | `{ language: 'expression'; source: string } \| { language: 'js'; source: string; capabilities?: Enum<'api.read' \| 'api.write' \| 'api.transaction' \| 'crypto.uuid' \| 'log'>[]; timeoutMs?: integer; … }` | optional | Hook body — expression (L1) or sandboxed JS (L2) | +| **body** | `{ language: 'expression'; source: string } \| { language: 'js'; source: string; capabilities?: Enum<'api.read' \| 'api.write' \| 'api.transaction' \| 'crypto.uuid' \| 'log' \| …>[]; timeoutMs?: integer; … }` | optional | Hook body — expression (L1) or sandboxed JS (L2) | | **priority** | `number` | optional (default: `100`) | Execution priority | | **async** | `boolean` | optional (default: `false`) | Run specifically as fire-and-forget | | **condition** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL); hook runs only when TRUE. e.g. P`record.status == "closed" && record.amount != null && record.amount > 1000` | @@ -69,7 +69,7 @@ L2 sandboxed JS body — runs inside an isolated VM with declared capabilities | :--- | :--- | :--- | :--- | | **language** | `'js'` | ✅ | | | **source** | `string` | ✅ | Function body source | -| **capabilities** | `Enum<'api.read' \| 'api.write' \| 'api.transaction' \| 'crypto.uuid' \| 'log'>[]` | optional (default: `[]`) | Granted capability tokens | +| **capabilities** | `Enum<'api.read' \| 'api.write' \| 'api.transaction' \| 'crypto.uuid' \| 'log' \| …>[]` | optional (default: `[]`) | Granted capability tokens | | **timeoutMs** | `integer` | optional | Per-invocation timeout (ms) | | **memoryMb** | `integer` | optional | Per-invocation memory cap (MB) | diff --git a/content/docs/references/data/index.mdx b/content/docs/references/data/index.mdx index 489d400f8c7..af1dff5c5b1 100644 --- a/content/docs/references/data/index.mdx +++ b/content/docs/references/data/index.mdx @@ -1,7 +1,7 @@ --- title: Data Protocol — complete schema reference navTitle: Data Protocol -description: "The ObjectStack Data Protocol in 34 reference pages: every schema in @objectstack/spec with its properties, types, defaults and a TypeScript example." +description: "The ObjectStack Data Protocol in 35 reference pages: every schema in @objectstack/spec with its properties, types, defaults and a TypeScript example." --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -34,6 +34,7 @@ This section contains all protocol schemas for the data layer of ObjectStack. + diff --git a/content/docs/references/data/meta.json b/content/docs/references/data/meta.json index 938aedc92b8..69d2069514d 100644 --- a/content/docs/references/data/meta.json +++ b/content/docs/references/data/meta.json @@ -37,6 +37,7 @@ "driver-sqlite", "driver-turso", "field-value", + "hook-body-doors", "picklist", "recycle-bin", "seed-file" diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index b6824dd2bae..5d211321bab 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -496,7 +496,7 @@ const result = ApiMethod.parse(data); | **type** | `Enum<'script' \| 'url' \| 'modal' \| 'flow' \| 'api' \| 'form'>` | optional (default: `"script"`) | Action functionality type — the dispatch route. The declarative single-record field write is not a type: it is `operation: 'update'` + `patch` on the default `script` route. | | **target** | `string` | optional | URL, Script Name, Flow ID, or API Endpoint. Supports $`{param.X}` and $`{ctx.X}` interpolation. For type:'url': an http:// or https:// URL, a mailto: address, or an in-app path starting with / or ./ (a console route; a record is /apps/APP/OBJECT/record/ID, APP being the app's route segment — see onSuccess.navigate) — every other scheme and a protocol-relative //host are refused. | | **openIn** | `Enum<'self' \| 'new-tab'>` | optional | For type:'url' — where to open `target`. 'new-tab' opens a new browser tab; 'self' navigates in place. When omitted, external/absolute URLs open in a new tab and relative URLs navigate in place. Static execution option — keep it OUT of `params` (which is user-input-collection only). | -| **body** | `{ language: 'expression'; source: string } \| { language: 'js'; source: string; capabilities?: Enum<'api.read' \| 'api.write' \| 'api.transaction' \| 'crypto.uuid' \| 'log'>[]; timeoutMs?: integer; … }` | optional | Action body — expression (L1) or sandboxed JS (L2). Only used when type is `script`. An action body runs as system, and its update, transfer, delete, purge or restore of an object declared managedBy: 'append-only' is refused with PERMISSION_DENIED; an insert is not judged by this rule. | +| **body** | `{ language: 'expression'; source: string } \| { language: 'js'; source: string; capabilities?: Enum<'api.read' \| 'api.write' \| 'api.transaction' \| 'crypto.uuid' \| 'log' \| …>[]; timeoutMs?: integer; … }` | optional | Action body — expression (L1) or sandboxed JS (L2). Only used when type is `script`. An action body runs as system, and its update, transfer, delete, purge or restore of an object declared managedBy: 'append-only' is refused with PERMISSION_DENIED; an insert is not judged by this rule. | | **operation** | `Enum<'update'>` | optional | The declarative single-record field write, mirroring a list view's `bulkActionDefs`: `'update'` applies `patch` (merged under the collected `params`) to the current record on the data plane AS THE CALLER — never system-elevated — so the caller's permissions, the object's hooks and its validations fire as for a user edit. `type` stays at its default `'script'` (the platform action route the write is performed on); `target`/`body`/`method`/`bodyExtra` are refused beside it. `'delete'` and `'custom'` have no row-level form. | | **patch** | `Record` | optional | For `operation: 'update'` — static field values written to the current record, merged UNDER the user-supplied `params` so a fixed value can be declared without exposing it in the dialog. Written on the data plane as the caller: object permissions, hooks and validations fire as for a user edit. Refused on an action without `operation: 'update'` (it would be silently dropped). | | **execution** | `Enum<'perRecord' \| 'aggregate'>` | optional | The bulk dispatch contract this action's BODY is written for, in `bulkActionDefs`' own vocabulary: 'perRecord' = one dispatch per selected row carrying that row's `recordId` (the view's `bulkActions: ['']` bare-string form); 'aggregate' = ONE dispatch for the whole selection carrying every id in `params._selectedIds` (a `bulkActionDefs` entry with `execution: 'aggregate'`). Optional with NO default — omit it only when the body genuinely serves both. A list view wiring a declared action under the other contract is refused by `@objectstack/lint` (`action-dispatch-contract-mismatch`). | diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index f1bb48ce851..7161e90a222 100644 --- a/content/docs/references/index.mdx +++ b/content/docs/references/index.mdx @@ -1,7 +1,7 @@ --- title: Protocol reference — every schema by module navTitle: Protocol Reference -description: Every schema published by @objectstack/spec — 1658 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1661 schemas across 14 protocol modules --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -23,7 +23,7 @@ counts are sums of the rows they head. Regenerate with | [AI Protocol](/docs/references/ai) | 14 | 81 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | | [API Protocol](/docs/references/api) | 36 | 492 | REST contracts, endpoints, routing, realtime, batch, discovery. | | [Automation Protocol](/docs/references/automation) | 16 | 81 | Flows and their nodes, approvals, ETL pipelines, webhooks, state machines, execution records. | -| [Data Protocol](/docs/references/data) | 34 | 183 | Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. | +| [Data Protocol](/docs/references/data) | 35 | 186 | Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. | | [Identity Protocol](/docs/references/identity) | 5 | 27 | Users and accounts, organizations, positions, SCIM provisioning. | | [Integration Protocol](/docs/references/integration) | 1 | 23 | The single connector protocol (ADR-0097) — catalog descriptors and provider-bound instances. | | [Kernel Protocol](/docs/references/kernel) | 30 | 153 | Plugin lifecycle and manifests, capabilities and security, metadata loading, service registry. | @@ -34,7 +34,7 @@ counts are sums of the rows they head. Regenerate with | [Studio Protocol](/docs/references/studio) | 3 | 35 | Studio designer metadata — the authoring surfaces for the protocols above. | | [System Protocol](/docs/references/system) | 40 | 297 | The runtime environment — logging, jobs, cache, metrics, notifications, i18n and compliance. | | [UI Protocol](/docs/references/ui) | 16 | 176 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | -| **Total** | **217** | **1658** | 14 protocol modules | +| **Total** | **218** | **1661** | 14 protocol modules | --- @@ -139,7 +139,7 @@ Flows and their nodes, approvals, ETL pipelines, webhooks, state machines, execu ## Data Protocol -**Source:** `packages/spec/src/data/` · **Import:** `@objectstack/spec/data` · **34 pages, 183 schemas** +**Source:** `packages/spec/src/data/` · **Import:** `@objectstack/spec/data` · **35 pages, 186 schemas** Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. @@ -170,6 +170,7 @@ Objects, fields, queries, filters, datasources and drivers — the ObjectQL laye | [`filter.zod.ts`](/docs/references/data/filter) | `ComparisonOperator`, `EqualityOperator`, `FieldOperators`, `FieldReference`, `FilterArray`, `FilterCondition`, `NormalizedFilter`, `NowAnchor`, `QueryFilter`, `RangeOperator`, `SetOperator`, `SpecialOperator`, `StringOperator` | | [`hook.zod.ts`](/docs/references/data/hook) | `Hook`, `HookContext`, `HookEvent`, `HookRefusal` | | [`hook-body.zod.ts`](/docs/references/data/hook-body) | `ExpressionBody`, `HookBody`, `HookBodyCapability`, `ScriptBody` | +| [`hook-body-doors.zod.ts`](/docs/references/data/hook-body-doors) | `BodyActivityAppendInput`, `BodyDoorRecordRef`, `BodyMailSendInput` | | [`mapping.zod.ts`](/docs/references/data/mapping) | `ImportFieldMapping`, `Mapping`, `TransformType` | | [`object.zod.ts`](/docs/references/data/object) | `ApiMethod`, `ApiOperation`, `Index`, `Lifecycle`, `LifecycleClass`, `Object`, `ObjectAccessConfig`, `ObjectCapabilities`, `ObjectExtension`, `ObjectExternalBinding`, `ObjectFieldGroup`, `ObjectOwnershipEnum`, `ObjectRequiredPermissions`, `PerOperationRequiredPermissions`, `RowCrudActionOverride`, `TenancyConfig` | | [`picklist.zod.ts`](/docs/references/data/picklist) | `Picklist`, `PicklistExtension`, `PicklistServedField` | diff --git a/content/docs/references/kernel/metadata-plugin.mdx b/content/docs/references/kernel/metadata-plugin.mdx index b5564875dee..142a458c8f7 100644 --- a/content/docs/references/kernel/metadata-plugin.mdx +++ b/content/docs/references/kernel/metadata-plugin.mdx @@ -330,7 +330,7 @@ const result = MetadataBulkResultSchema.parse(data); | **type** | `Enum<'script' \| 'url' \| 'modal' \| 'flow' \| 'api' \| 'form'>` | optional (default: `"script"`) | Action functionality type — the dispatch route. The declarative single-record field write is not a type: it is `operation: 'update'` + `patch` on the default `script` route. | | **target** | `string` | optional | URL, Script Name, Flow ID, or API Endpoint. Supports $`{param.X}` and $`{ctx.X}` interpolation. For type:'url': an http:// or https:// URL, a mailto: address, or an in-app path starting with / or ./ (a console route; a record is /apps/APP/OBJECT/record/ID, APP being the app's route segment — see onSuccess.navigate) — every other scheme and a protocol-relative //host are refused. | | **openIn** | `Enum<'self' \| 'new-tab'>` | optional | For type:'url' — where to open `target`. 'new-tab' opens a new browser tab; 'self' navigates in place. When omitted, external/absolute URLs open in a new tab and relative URLs navigate in place. Static execution option — keep it OUT of `params` (which is user-input-collection only). | -| **body** | `{ language: 'expression'; source: string } \| { language: 'js'; source: string; capabilities?: Enum<'api.read' \| 'api.write' \| 'api.transaction' \| 'crypto.uuid' \| 'log'>[]; timeoutMs?: integer; … }` | optional | Action body — expression (L1) or sandboxed JS (L2). Only used when type is `script`. An action body runs as system, and its update, transfer, delete, purge or restore of an object declared managedBy: 'append-only' is refused with PERMISSION_DENIED; an insert is not judged by this rule. | +| **body** | `{ language: 'expression'; source: string } \| { language: 'js'; source: string; capabilities?: Enum<'api.read' \| 'api.write' \| 'api.transaction' \| 'crypto.uuid' \| 'log' \| …>[]; timeoutMs?: integer; … }` | optional | Action body — expression (L1) or sandboxed JS (L2). Only used when type is `script`. An action body runs as system, and its update, transfer, delete, purge or restore of an object declared managedBy: 'append-only' is refused with PERMISSION_DENIED; an insert is not judged by this rule. | | **operation** | `Enum<'update'>` | optional | The declarative single-record field write, mirroring a list view's `bulkActionDefs`: `'update'` applies `patch` (merged under the collected `params`) to the current record on the data plane AS THE CALLER — never system-elevated — so the caller's permissions, the object's hooks and its validations fire as for a user edit. `type` stays at its default `'script'` (the platform action route the write is performed on); `target`/`body`/`method`/`bodyExtra` are refused beside it. `'delete'` and `'custom'` have no row-level form. | | **patch** | `Record` | optional | For `operation: 'update'` — static field values written to the current record, merged UNDER the user-supplied `params` so a fixed value can be declared without exposing it in the dialog. Written on the data plane as the caller: object permissions, hooks and validations fire as for a user edit. Refused on an action without `operation: 'update'` (it would be silently dropped). | | **execution** | `Enum<'perRecord' \| 'aggregate'>` | optional | The bulk dispatch contract this action's BODY is written for, in `bulkActionDefs`' own vocabulary: 'perRecord' = one dispatch per selected row carrying that row's `recordId` (the view's `bulkActions: ['']` bare-string form); 'aggregate' = ONE dispatch for the whole selection carrying every id in `params._selectedIds` (a `bulkActionDefs` entry with `execution: 'aggregate'`). Optional with NO default — omit it only when the body genuinely serves both. A list view wiring a declared action under the other contract is refused by `@objectstack/lint` (`action-dispatch-contract-mismatch`). | diff --git a/content/docs/references/system/job.mdx b/content/docs/references/system/job.mdx index c7c3b19bf3d..49faaf20d4b 100644 --- a/content/docs/references/system/job.mdx +++ b/content/docs/references/system/job.mdx @@ -58,7 +58,7 @@ const result = CronScheduleSchema.parse(data); | **description** | `string` | optional | Job description / purpose | | **schedule** | `{ type: 'cron'; expression: string \| object; timezone?: string } \| { type: 'interval'; intervalMs: integer } \| { type: 'once'; at: string }` | ✅ | Job schedule configuration | | **handler** | `string` | optional | Handler function name (must match a key in `defineStack({ functions })`) — DEPRECATED, prefer `body`. When both are present `body` wins; refused beside `pull`. A job must declare one of `body`, `handler` or `pull`. Time-zone date maths moves to `body` too: `Intl.DateTimeFormat` with a `timeZone` option is available in the sandbox (nothing else of `Intl` is). | -| **body** | `{ language: 'js'; source: string; capabilities?: Enum<'api.read' \| 'api.write' \| 'api.transaction' \| 'crypto.uuid' \| 'log'>[]; timeoutMs?: integer; … }` | optional | Job body — a sandboxed JS (L2) body, the same shape hooks and actions use; an expression (L1) body is refused, because a job runs for its effects and an expression has none. Preferred over `handler`: when both are present `body` wins. It runs in the QuickJS sandbox with no module scope (no imports, no helpers or constants from the surrounding file): it reaches data only through `ctx.api` under its declared `capabilities` (`api.read` / `api.write` / `api.transaction`) and logs through `ctx.log` (`log`); the in-process handler context (`ql`, `logger`, `bundle`) does not exist there. Its time limit is the job's `timeoutMs` (see there): long-running work declares a `timeoutMs` that covers it, or splits into bounded runs that each finish within it. Every door that brings an artifact in schedules a job's `body` — the boot, and `os package install` on install and on every restart — while a `handler` is code that travels only in the artifact's runtime module and runs only on a boot that loads it (a config, or `os start --artifact`); `os package install` therefore refuses an enabled job with no `body`. A `pull` is data too, so an enabled `pull` job is judged by its `pull` instead: it installs when the `pull` binds (it names a mapping the package declares, with a `connectorSource`) and is refused when it does not, as is a job whose `body` the declaration refuses. Refused beside `pull`. | +| **body** | `{ language: 'js'; source: string; capabilities?: Enum<'api.read' \| 'api.write' \| 'api.transaction' \| 'crypto.uuid' \| 'log' \| …>[]; timeoutMs?: integer; … }` | optional | Job body — a sandboxed JS (L2) body, the same shape hooks and actions use; an expression (L1) body is refused, because a job runs for its effects and an expression has none. Preferred over `handler`: when both are present `body` wins. It runs in the QuickJS sandbox with no module scope (no imports, no helpers or constants from the surrounding file): it reaches data only through `ctx.api` under its declared `capabilities` (`api.read` / `api.write` / `api.transaction`) and logs through `ctx.log` (`log`); the in-process handler context (`ql`, `logger`, `bundle`) does not exist there. Its time limit is the job's `timeoutMs` (see there): long-running work declares a `timeoutMs` that covers it, or splits into bounded runs that each finish within it. Every door that brings an artifact in schedules a job's `body` — the boot, and `os package install` on install and on every restart — while a `handler` is code that travels only in the artifact's runtime module and runs only on a boot that loads it (a config, or `os start --artifact`); `os package install` therefore refuses an enabled job with no `body`. A `pull` is data too, so an enabled `pull` job is judged by its `pull` instead: it installs when the `pull` binds (it names a mapping the package declares, with a `connectorSource`) and is refused when it does not, as is a job whose `body` the declaration refuses. Refused beside `pull`. | | **pull** | `{ mapping: string }` | optional | Pull run form: on each run the platform pulls the named mapping's `connectorSource` (one action call, one response) and writes the rows through the import runner — no code. A refused pull records the run `failed` (retried per `retryPolicy`); a pull whose rows the import runner refused records it `degraded`. Data like `body`, so every door schedules it. Refused beside `body` or `handler`. | | **organization** | `string` | optional | Organization id (sys_organization.id) this job runs as — its `body`'s `ctx.api`, the execution context its `handler` is handed, and its `pull`'s reads and writes alike, as a system run carrying that organization. A scheduled run has no session to inherit one from. Judged at bind by the posture rule scheduled flows use: required under the isolated tenancy posture (a job that declares none is not scheduled); optional under group (undeclared, the run carries no organization and a tenant-scoped write it makes is refused); not required under single (the install's one organization is resolved beneath each write). Where declared, it is the organization the run acts as on every posture. | | **retryPolicy** | `{ maxRetries?: integer; backoffMs?: integer; backoffMultiplier?: number; maxRetryDelayMs?: integer; … }` | optional | Retry policy: failed runs (including timeouts) are retried with exponential backoff (delay = min(backoffMs * backoffMultiplier^(retry-1), maxRetryDelayMs), optionally jittered) up to maxRetries retries after the initial attempt. Omit the block for a single attempt; a block must state `maxRetries` >= 1 — one that omits it or writes 0 is refused, since it would buy no retry. | @@ -101,7 +101,7 @@ const result = CronScheduleSchema.parse(data); | :--- | :--- | :--- | :--- | | **language** | `'js'` | ✅ | | | **source** | `string` | ✅ | Function body source | -| **capabilities** | `Enum<'api.read' \| 'api.write' \| 'api.transaction' \| 'crypto.uuid' \| 'log'>[]` | optional (default: `[]`) | Granted capability tokens | +| **capabilities** | `Enum<'api.read' \| 'api.write' \| 'api.transaction' \| 'crypto.uuid' \| 'log' \| …>[]` | optional (default: `[]`) | Granted capability tokens | | **timeoutMs** | `integer` | optional | Per-invocation timeout (ms) | | **memoryMb** | `integer` | optional | Per-invocation memory cap (MB) | diff --git a/content/docs/references/ui/action.mdx b/content/docs/references/ui/action.mdx index dc75707a2d2..3a68e9bd83b 100644 --- a/content/docs/references/ui/action.mdx +++ b/content/docs/references/ui/action.mdx @@ -38,7 +38,7 @@ const result = ActionSchema.parse(data); | **type** | `Enum<'script' \| 'url' \| 'modal' \| 'flow' \| 'api' \| 'form'>` | optional (default: `"script"`) | Action functionality type — the dispatch route. The declarative single-record field write is not a type: it is `operation: 'update'` + `patch` on the default `script` route. | | **target** | `string` | optional | URL, Script Name, Flow ID, or API Endpoint. Supports $`{param.X}` and $`{ctx.X}` interpolation. For type:'url': an http:// or https:// URL, a mailto: address, or an in-app path starting with / or ./ (a console route; a record is /apps/APP/OBJECT/record/ID, APP being the app's route segment — see onSuccess.navigate) — every other scheme and a protocol-relative //host are refused. | | **openIn** | `Enum<'self' \| 'new-tab'>` | optional | For type:'url' — where to open `target`. 'new-tab' opens a new browser tab; 'self' navigates in place. When omitted, external/absolute URLs open in a new tab and relative URLs navigate in place. Static execution option — keep it OUT of `params` (which is user-input-collection only). | -| **body** | `{ language: 'expression'; source: string } \| { language: 'js'; source: string; capabilities?: Enum<'api.read' \| 'api.write' \| 'api.transaction' \| 'crypto.uuid' \| 'log'>[]; timeoutMs?: integer; … }` | optional | Action body — expression (L1) or sandboxed JS (L2). Only used when type is `script`. An action body runs as system, and its update, transfer, delete, purge or restore of an object declared managedBy: 'append-only' is refused with PERMISSION_DENIED; an insert is not judged by this rule. | +| **body** | `{ language: 'expression'; source: string } \| { language: 'js'; source: string; capabilities?: Enum<'api.read' \| 'api.write' \| 'api.transaction' \| 'crypto.uuid' \| 'log' \| …>[]; timeoutMs?: integer; … }` | optional | Action body — expression (L1) or sandboxed JS (L2). Only used when type is `script`. An action body runs as system, and its update, transfer, delete, purge or restore of an object declared managedBy: 'append-only' is refused with PERMISSION_DENIED; an insert is not judged by this rule. | | **operation** | `Enum<'update'>` | optional | The declarative single-record field write, mirroring a list view's `bulkActionDefs`: `'update'` applies `patch` (merged under the collected `params`) to the current record on the data plane AS THE CALLER — never system-elevated — so the caller's permissions, the object's hooks and its validations fire as for a user edit. `type` stays at its default `'script'` (the platform action route the write is performed on); `target`/`body`/`method`/`bodyExtra` are refused beside it. `'delete'` and `'custom'` have no row-level form. | | **patch** | `Record` | optional | For `operation: 'update'` — static field values written to the current record, merged UNDER the user-supplied `params` so a fixed value can be declared without exposing it in the dialog. Written on the data plane as the caller: object permissions, hooks and validations fire as for a user edit. Refused on an action without `operation: 'update'` (it would be silently dropped). | | **execution** | `Enum<'perRecord' \| 'aggregate'>` | optional | The bulk dispatch contract this action's BODY is written for, in `bulkActionDefs`' own vocabulary: 'perRecord' = one dispatch per selected row carrying that row's `recordId` (the view's `bulkActions: ['']` bare-string form); 'aggregate' = ONE dispatch for the whole selection carrying every id in `params._selectedIds` (a `bulkActionDefs` entry with `execution: 'aggregate'`). Optional with NO default — omit it only when the body genuinely serves both. A list view wiring a declared action under the other contract is refused by `@objectstack/lint` (`action-dispatch-contract-mismatch`). | @@ -131,7 +131,7 @@ L2 sandboxed JS body — runs inside an isolated VM with declared capabilities | :--- | :--- | :--- | :--- | | **language** | `'js'` | ✅ | | | **source** | `string` | ✅ | Function body source | -| **capabilities** | `Enum<'api.read' \| 'api.write' \| 'api.transaction' \| 'crypto.uuid' \| 'log'>[]` | optional (default: `[]`) | Granted capability tokens | +| **capabilities** | `Enum<'api.read' \| 'api.write' \| 'api.transaction' \| 'crypto.uuid' \| 'log' \| …>[]` | optional (default: `[]`) | Granted capability tokens | | **timeoutMs** | `integer` | optional | Per-invocation timeout (ms) | | **memoryMb** | `integer` | optional | Per-invocation memory cap (MB) | diff --git a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/data.md b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/data.md index 7cb2b15367b..f99230906ff 100644 --- a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/data.md +++ b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/data.md @@ -21,7 +21,7 @@ The `strict` column is the one the campaign schedules against; it counts both th | Dir | Sites | strict | passthrough | catchall | strip | |---|---|---|---|---|---| -| `data/` | 169 | 100 | 2 | 0 | 67 | +| `data/` | 173 | 104 | 2 | 0 | 67 | ## `data/` — sites @@ -49,6 +49,7 @@ classify and is not listed (it becomes reportable the day it grows its first sit | `field-value.zod.ts` | 5 | | `field.zod.ts` | 15 | | `filter.zod.ts` | 13 | +| `hook-body-doors.zod.ts` | 4 | | `hook-body.zod.ts` | 2 | | `hook.zod.ts` | 8 | | `mapping.zod.ts` | 8 | @@ -60,7 +61,7 @@ classify and is not listed (it becomes reportable the day it grows its first sit | `seed-loader.zod.ts` | 12 | | `seed.zod.ts` | 2 | | `validation.zod.ts` | 6 | -| **total** | **169** | +| **total** | **173** | ## `data/` — open @@ -68,7 +69,7 @@ Per file, how many of its sites still silently discard unknown keys. The `Class` column that decides the bucket split is hand-written in the ledger; the arithmetic over it is here. -**67 strip of 169**, in 11 file(s). +**67 strip of 173**, in 11 file(s). | File | Strip | Sites | |---|---|---| @@ -83,7 +84,7 @@ over it is here. | `query.zod.ts` | 3 | 5 | | `recycle-bin.zod.ts` | 4 | 4 | | `seed-loader.zod.ts` | 12 | 12 | -| **total** | **67** | **169** | +| **total** | **67** | **173** | | Bucket | Sites | |---|---| diff --git a/docs/audits/2026-07-unknown-key-strictness-ledger.md b/docs/audits/2026-07-unknown-key-strictness-ledger.md index 58e115ef786..7486a0b5f29 100644 --- a/docs/audits/2026-07-unknown-key-strictness-ledger.md +++ b/docs/audits/2026-07-unknown-key-strictness-ledger.md @@ -729,6 +729,7 @@ column does not move and the `strip` column falls by the count of what left. | `driver/oracle.zod.ts` | authorable | The Oracle `config` contract, added by **#31328** with the `oracle` driver row (a federation-only dialect, ADR-0015 §4.6). Strict from its first commit, same error factory as the rest of the campaign: the keys are what the factory hands node-oracledb Thin (`connectString`, or `host`/`port`/`serviceName`, and `username`), and the plausible wrong spellings are refused by name with the working one — `password` (the credential is the bound secret), `url` (an Oracle connect string is not a URL), and `ssl`/`ca`/`cert`/`key`/`rejectUnauthorized` (Thin chooses TLS by a `tcps://` connect string and has no slot for them, so each would parse and do nothing) | | `analytics.zod.ts` | authorable | **strict as of #4001 batch D — all 8 sites; the `mixed (p)` resolved to authorable on both halves.** **Two of the eight sites later left with their keys (ADR-0049 enforce-or-remove): the metric `filters[]` item (#10414) and the cube's `refreshKey` block (#20637, retired whole — nothing read `every` or `sql`, and no analytics result is cached). The batch-D verdicts for those two are superseded, not reopened; their pins in `analytics-strictness-batchd.test.ts` now assert the retirement prescriptions.** The cube family (Metric + its `filters[]` item, Dimension, CubeJoin, Cube + `refreshKey`) has two live authoring doors, measured: `defineCube()` `.parse()`s an author literal (the showcase example authors through it) and `defineStack({ analyticsCubes })` carries every cube through `StackSchema.parse` — the whole family resolves REACHABLE in the batch-D BFS (positive/negative controls green in the same run). Pre-close probes: a cube's `publik`, a metric's `title`, a join's `relationshipp` (falling back to the `many_to_one` default — a different join shape under a successful parse), a `refreshKey.sqll` all parsed clean and vanished. The query half was subtler and is the batch's live behaviour change: `AnalyticsQuerySchema`'s TOP level was already gated at its one production door (`api/analytics.zod.ts`'s `AnalyticsQueryRequestSchema` is `.extend(…).strict()` since #3878), but **top-level strictness does not recurse** — measured on `main`, `timeDimensions: [{ dimension, granuarity: 'day' }]` rode through the strict wrapper with the typo silently stripped, bucketing the whole range as one group under an ordinary 200. Closing the base makes the posture hold at every door instead of only at the wrapper that re-applied it. ADR-0010 envelope deliberately NOT declared: no protected item re-parses here (`CubeRegistry.register` takes typed objects without a parse; `analytics_cube` resolves no `getMetadataTypeSchema` entry so `saveMetaItem` never parses it; artifact ingest parses the compiled definition BEFORE `applyProtection` stamps). Producer sweep over objectui/cloud: zero cube/analytics-vocabulary producers (objectui's `data-objectstack` sends only declared keys — `cube`/`measures`/`dimensions`/`where`) | | `hook.zod.ts` / `hook-body.zod.ts` | mixed | **strict as of #4001 data step** for the AUTHORING shapes: `HookSchema` (+ `retryPolicy`) and both body branches (`ExpressionBodySchema` / `ScriptBodySchema`). `HookContextSchema` and its `session` / `provenance` / `user` blocks are the RUNTIME shape the engine hands a handler — they stay tolerant, and must: strictness there would make an engine-internal enrichment (as `provenance` was in #3712) a breaking change for anyone parsing a context they were given. The file's old blanket `authorable (p)` was too wide — verification split it | +| `hook-body-doors.zod.ts` | authorable | **strict from birth.** Four sites: `BodyDoorRecordRefSchema`, the recipient object of `BodyMailSendInputSchema`, `BodyMailSendInputSchema` and `BodyActivityAppendInputSchema`. The input is what a script body's author writes as the argument of `ctx.email.send(…)` / `ctx.activity.append(…)`, and the door parses it on every call. A key outside the shape is refused rather than dropped, because the values the platform stamps (the sender, the sending user, the organization, the actor, the origin) are not inputs and a body that names one is told at the call | | `mapping.zod.ts` | authorable (p) | | | `picklist.zod.ts` | mixed | `PicklistSchema` and `PicklistExtensionSchema` are authoring shapes, strict from birth (`strictObject`). `PicklistServedFieldSchema` is a SERVED shape — the slice a resolved picklist reference adds to a served field — and is a `looseObject` by design: every other key of that field is `FieldSchema`'s | | `external-catalog.zod.ts` | wire (p) | | diff --git a/docs/audits/2026-08-tenant-audit-write-call-sites.counts.md b/docs/audits/2026-08-tenant-audit-write-call-sites.counts.md index e7f7e64d2cb..73bddc10c4f 100644 --- a/docs/audits/2026-08-tenant-audit-write-call-sites.counts.md +++ b/docs/audits/2026-08-tenant-audit-write-call-sites.counts.md @@ -33,19 +33,19 @@ silent, and `node scripts/tenant-audit-census.mjs --write` is the resolution. | Measure | Value | |---|---:| -| Write call sites | 308 | -| Object name statically decidable | 214 | +| Write call sites | 309 | +| Object name statically decidable | 215 | | Object name chosen at run time | 94 | -| Against a tenancy-enabled object | 207 | +| Against a tenancy-enabled object | 208 | | Against an object declaring tenancy off | 7 | | Threading a tenant context | 238 | | Provably carrying none | 12 | | …and decidably tenancy-enabled | 3 | -| Options argument unreadable | 58 | -| …and decidably tenancy-enabled | 31 | +| Options argument unreadable | 59 | +| …and decidably tenancy-enabled | 32 | | Threading a decidably elevated context | 173 | | Threading a decidably non-elevated context | 0 | -| Threading a context of undecidable elevation | 123 | +| Threading a context of undecidable elevation | 124 | ## Subtractions the census could NOT defend — enforced @@ -90,14 +90,14 @@ holds still. They are required to be HERE and to say WHEN they were true; their values are not compared. The reasoning, and the measurement behind it, are in `scripts/check-tenant-audit-census.mjs`. -Measured on 2026-11-12 at `0e97e095f`. +Measured on 2026-11-13 at `1bb3c359e`. | corpus scale (not enforced) | count | | :--- | ---: | -| tracked non-test sources scanned | 1139 | +| tracked non-test sources scanned | 1144 | | engine-shaped types recognised | 134 | | declared objects in the registry | 137 | -| same-named calls subtracted as non-engine | 291 | +| same-named calls subtracted as non-engine | 292 | ## Every site @@ -119,6 +119,7 @@ Measured on 2026-11-12 at `0e97e095f`. | `packages/plugins/plugin-approvals/src/stored-process-package-backfill.ts` | `update` | `sys_approval_request` | enabled | elevated | 1 | | `packages/plugins/plugin-audit/src/action-invocation-audit.ts` | `insert` | `sys_audit_log` | enabled | elevated | 1 | | `packages/plugins/plugin-audit/src/activity-changed-fields-backfill.ts` | `update` | `sys_activity` | enabled | elevated | 1 | +| `packages/plugins/plugin-audit/src/app-activity-door.ts` | `insert` | `sys_activity` | enabled | options unreadable | 1 | | `packages/plugins/plugin-audit/src/audit-seal/amendment-writer.ts` | `insert` | `AUDIT_AMENDMENT_OBJECT` | undecidable | elevated | 1 | | `packages/plugins/plugin-audit/src/audit-seal/sealer.ts` | `insert` | `AUDIT_CHECKPOINT_OBJECT` | undecidable | elevated | 1 | | `packages/plugins/plugin-audit/src/audit-seal/signer.ts` | `insert` | `AUDIT_SIGNING_KEY_OBJECT` | undecidable | elevated | 1 | diff --git a/packages/cli/src/utils/extract-hook-body.ts b/packages/cli/src/utils/extract-hook-body.ts index 41fab5f3041..3a6ad012947 100644 --- a/packages/cli/src/utils/extract-hook-body.ts +++ b/packages/cli/src/utils/extract-hook-body.ts @@ -505,7 +505,7 @@ const FORBIDDEN_PATTERNS: Array<{ rx: RegExp; reason: string; face?: LoweringFac }, ]; -const CAPABILITY_PATTERNS: Array<{ rx: RegExp; cap: 'api.read' | 'api.write' | 'crypto.uuid' | 'log' }> = [ +const CAPABILITY_PATTERNS: Array<{ rx: RegExp; cap: 'api.read' | 'api.write' | 'crypto.uuid' | 'log' | 'email.send' | 'activity.append' }> = [ // Match `ctx.api.object(...)` directly OR a local alias like // `const api = ctx.api;` then `api.object(...)`. We accept any // identifier (or chain) ending in `.object(...)` followed by a known @@ -535,6 +535,9 @@ const CAPABILITY_PATTERNS: Array<{ rx: RegExp; cap: 'api.read' | 'api.write' | ' // arrives as a sandbox refusal at run time, far from its cause. Over-inferring // grants a token the body may not use, which the sandbox simply never checks. { rx: /\.\s*title\s*\(\s*[^)\s]/, cap: 'api.read' }, + // The two platform doors: a call to the door is what its token grants. + { rx: /ctx\.email\.send\b/, cap: 'email.send' }, + { rx: /ctx\.activity\.append\b/, cap: 'activity.append' }, ]; export interface ExtractedBody { @@ -546,7 +549,7 @@ export interface ExtractedBody { * is retired (see this file's header). An author whose needs differ from what * inference derives writes `body.capabilities` on the hook instead. */ - capabilities: Array<'api.read' | 'api.write' | 'crypto.uuid' | 'log'>; + capabilities: Array<'api.read' | 'api.write' | 'crypto.uuid' | 'log' | 'email.send' | 'activity.append'>; /** True when source is a single expression (arrow with implicit return). */ isExpression: boolean; } @@ -740,10 +743,10 @@ interface ParameterRebind { /** Names bound to the WHOLE context: an identifier parameter, an object-rest element. */ contextRoots: readonly string[]; /** Names bound to ONE capability-bearing member: `({ log: l })` binds `l` to `ctx.log`. */ - memberLocals: Readonly>; + memberLocals: Readonly>; } -const NO_REBIND: ParameterRebind = { prologue: '', contextRoots: [], memberLocals: { log: [], crypto: [], title: [] } }; +const NO_REBIND: ParameterRebind = { prologue: '', contextRoots: [], memberLocals: { log: [], crypto: [], title: [], email: [], activity: [] } }; /** * The context members {@link CAPABILITY_PATTERNS} infers a token from. A @@ -752,7 +755,7 @@ const NO_REBIND: ParameterRebind = { prologue: '', contextRoots: [], memberLocal * computed key under one of them could not be followed, and a body the build * under-grants is refused by the sandbox at run time. */ -const CAPABILITY_BEARING_MEMBERS: ReadonlySet = new Set(['api', 'log', 'crypto', 'title']); +const CAPABILITY_BEARING_MEMBERS: ReadonlySet = new Set(['api', 'log', 'crypto', 'title', 'email', 'activity']); /** * A hook-face refusal that names the PARAMETER, in the family's wording: what @@ -863,7 +866,7 @@ function planHookParameterRebind( } const contextRoots: string[] = []; - const memberLocals: Record<'log' | 'crypto' | 'title', string[]> = { log: [], crypto: [], title: [] }; + const memberLocals: Record<'log' | 'crypto' | 'title' | 'email' | 'activity', string[]> = { log: [], crypto: [], title: [], email: [], activity: [] }; if (ts.isIdentifier(name)) { contextRoots.push(name.text); } else if (ts.isObjectBindingPattern(name)) { @@ -890,7 +893,7 @@ function planHookParameterRebind( `(\`{ ${key ?? 'log'} }\`), or read it as \`ctx.${key ?? 'log'}\``, ); } - if (key !== 'api') memberLocals[key as 'log' | 'crypto' | 'title'].push(el.name.text); + if (key !== 'api') memberLocals[key as 'log' | 'crypto' | 'title' | 'email' | 'activity'].push(el.name.text); } } @@ -963,6 +966,8 @@ function reboundCapabilities(source: string, rebind: ParameterRebind): Array { expect(extractHookBody(fn, 'hook uuid').capabilities).toContain('crypto.uuid'); }); + it('infers email.send and activity.append from the platform door calls', () => { + const fn = async (ctx: any) => { + await ctx.email.send({ to: 'pat@example.test', subject: 'Hi', text: 'x' }); + await ctx.activity.append({ object: 'crm_contact', recordId: 'c1', type: 'completed', summary: 'x' }); + }; + const caps = extractHookBody(fn, 'hook doors').capabilities; + expect(caps).toContain('email.send'); + expect(caps).toContain('activity.append'); + expect(caps).not.toContain('api.write'); + }); + // #1876 — a handler that references a module-scope helper is not self- // contained; extraction must throw so lowerCallables falls back to bundling // (which carries the closure) instead of shipping a body that ReferenceErrors. diff --git a/packages/cli/test/hook-body-mail-grant.test.ts b/packages/cli/test/hook-body-mail-grant.test.ts new file mode 100644 index 00000000000..102e3eb8471 --- /dev/null +++ b/packages/cli/test/hook-body-mail-grant.test.ts @@ -0,0 +1,61 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#32004] A hook body sends no mail, so the build refuses a hook whose handler + * calls `ctx.email.send`: lowering infers the `email.send` grant from the call + * (`extractLoweredBody`), and the hook parse every build runs after lowering + * (`HookSchema`) refuses that grant, naming it. An action's handler that makes + * the same call lowers to a body the body schema takes. + */ + +import { describe, it, expect } from 'vitest'; +import { HookBodySchema, HookSchema } from '@objectstack/spec/data'; +import { lowerCallables } from '../src/utils/lower-callables.js'; + +describe('the build refuses a hook whose handler sends mail', () => { + it('lowers the handler to a body granted email.send, which the hook parse refuses', () => { + const out = lowerCallables({ + hooks: [ + { + name: 'welcome_contact', + object: 'crm_contact', + events: ['afterInsert'], + handler: async (ctx: any) => { + await ctx.email.send({ to: 'pat@example.test', subject: 'Welcome', text: 'Hello' }); + }, + }, + ], + }); + const lowered = (out.lowered.hooks as any[])[0]; + expect(lowered.body.capabilities).toContain('email.send'); + + const r = HookSchema.safeParse(lowered); + expect(r.success).toBe(false); + const issues = r.success ? [] : r.error.issues; + expect(issues.map((i) => i.path.join('.'))).toEqual([`body.capabilities.${lowered.body.capabilities.indexOf('email.send')}`]); + expect(issues[0].message).toContain('A hook body cannot be granted `email.send`'); + }); + + it('lowers a hook handler that only adds a timeline entry to a body the hook parse takes', () => { + const out = lowerCallables({ + hooks: [ + { + name: 'note_contact', + object: 'crm_contact', + events: ['afterInsert'], + handler: async (ctx: any) => { + await ctx.activity.append({ object: 'crm_contact', recordId: 'c1', type: 'completed', summary: 'Welcomed' }); + }, + }, + ], + }); + const lowered = (out.lowered.hooks as any[])[0]; + expect(lowered.body.capabilities).toEqual(['activity.append']); + const r = HookSchema.safeParse(lowered); + expect(r.success, JSON.stringify(r.error?.issues ?? [])).toBe(true); + }); + + it('leaves the grant to the body an action takes', () => { + expect(HookBodySchema.safeParse({ language: 'js', source: 'x', capabilities: ['email.send'] }).success).toBe(true); + }); +}); diff --git a/packages/cli/test/hook-body-parameter-rebind.test.ts b/packages/cli/test/hook-body-parameter-rebind.test.ts index 97264094ff4..314af0e7f86 100644 --- a/packages/cli/test/hook-body-parameter-rebind.test.ts +++ b/packages/cli/test/hook-body-parameter-rebind.test.ts @@ -275,6 +275,16 @@ describe('capability inference follows the rebound names', () => { async ({ api }: any) => { await api.object('t').insert({ n: await api.object('t').count({}) }); }, async (ctx: any) => { await ctx.api.object('t').insert({ n: await ctx.api.object('t').count({}) }); }, ], + [ + 'email.send / activity.append through a renamed context', + async (h: any) => { await h.email.send({ to: 'a@b.test', subject: 's', text: 't' }); await h.activity.append({ object: 'o', recordId: 'r', type: 't', summary: 's' }); }, + async (ctx: any) => { await ctx.email.send({ to: 'a@b.test', subject: 's', text: 't' }); await ctx.activity.append({ object: 'o', recordId: 'r', type: 't', summary: 's' }); }, + ], + [ + 'email.send / activity.append through destructured members', + async ({ email, activity }: any) => { await email.send({ to: 'a@b.test', subject: 's', text: 't' }); await activity.append({ object: 'o', recordId: 'r', type: 't', summary: 's' }); }, + async (ctx: any) => { await ctx.email.send({ to: 'a@b.test', subject: 's', text: 't' }); await ctx.activity.append({ object: 'o', recordId: 'r', type: 't', summary: 's' }); }, + ], [ 'log through an object rest element', ({ input, ...rest }: any) => { rest.log.info(String(input.name)); }, diff --git a/packages/cli/test/published-subpath-hook-body.pin.test.ts b/packages/cli/test/published-subpath-hook-body.pin.test.ts index f7420589194..b5cda52acd3 100644 --- a/packages/cli/test/published-subpath-hook-body.pin.test.ts +++ b/packages/cli/test/published-subpath-hook-body.pin.test.ts @@ -283,7 +283,7 @@ type ExtractedBodyHasExactlyTheseThreeFields = Expect; isExpression: boolean } + { source: string; capabilities: Array<'api.read' | 'api.write' | 'crypto.uuid' | 'log' | 'email.send' | 'activity.append'>; isExpression: boolean } > >; diff --git a/packages/core/src/security/caller-mail-bounds.test.ts b/packages/core/src/security/caller-mail-bounds.test.ts new file mode 100644 index 00000000000..2aab4e692e7 --- /dev/null +++ b/packages/core/src/security/caller-mail-bounds.test.ts @@ -0,0 +1,42 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, it, expect } from 'vitest'; +import { boundCallerMail } from './caller-mail-bounds.js'; + +const SENDER = { getDefaultFrom: () => ({ name: 'Acme', address: 'noreply@acme.test' }) }; +const CALLER = { userId: 'usr_ann', organizationId: 'org_acme' }; +const message = { to: 'pat@example.test', subject: 'Quote', text: 'Attached.' }; + +describe('a caller-sent message is sent by the caller, from the configured sender, under the caller\'s organization', () => { + it('stamps the sending user and the organization', () => { + const out = boundCallerMail({ ...message }, CALLER, SENDER); + expect(out).toEqual({ ok: true, input: { ...message, sentBy: 'usr_ann', organizationId: 'org_acme' } }); + }); + + it('refuses a message naming another user, another organization, another sender, or identity mail', () => { + expect(boundCallerMail({ ...message, sentBy: 'usr_other' }, CALLER, SENDER).ok).toBe(false); + expect(boundCallerMail({ ...message, organizationId: 'org_other' }, CALLER, SENDER).ok).toBe(false); + expect(boundCallerMail({ ...message, from: 'ceo@acme.test' }, CALLER, SENDER).ok).toBe(false); + expect(boundCallerMail({ ...message, headers: { Sender: 'ceo@acme.test' } }, CALLER, SENDER).ok).toBe(false); + expect(boundCallerMail({ ...message, identityMail: true }, CALLER, SENDER).ok).toBe(false); + }); + + it('replaces a `from` restating the configured address with the configured value', () => { + const out = boundCallerMail({ ...message, from: 'Someone ' }, CALLER, SENDER); + expect(out).toEqual({ + ok: true, + input: { ...message, sentBy: 'usr_ann', organizationId: 'org_acme', from: SENDER.getDefaultFrom() }, + }); + }); + + it('records no sending user for a call that has none, and refuses a message naming one', () => { + const none = { userId: undefined, organizationId: 'org_acme' }; + expect(boundCallerMail({ ...message }, none, SENDER)).toEqual({ + ok: true, + input: { ...message, organizationId: 'org_acme' }, + }); + const named = boundCallerMail({ ...message, sentBy: 'usr_ann' }, none, SENDER); + expect(named.ok).toBe(false); + expect((named as { reason: string }).reason).toMatch(/no calling user/); + }); +}); diff --git a/packages/core/src/security/caller-mail-bounds.ts b/packages/core/src/security/caller-mail-bounds.ts new file mode 100644 index 00000000000..0cf11c52834 --- /dev/null +++ b/packages/core/src/security/caller-mail-bounds.ts @@ -0,0 +1,182 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The bounds a caller's message passes before the mail service sends it, for + * every door a caller reaches mail through: the HTTP send door + * (`POST /api/v1/email/send`, `@objectstack/rest`) and the script-body door + * (`ctx.email.send`, `@objectstack/runtime`). One implementation, so the two + * doors cannot admit different messages. + * + * What a door decides itself, before it calls this: WHO may use it (the HTTP + * door's capability; the body door's declared `email.send` token) and what + * shape a body may have. What this module decides, for both: + * + * 1. ATTRIBUTION — `sentBy` is the calling user. A message naming another + * user is refused; one naming the caller (or none) is stamped with the + * caller. A call with no calling user (a scheduled job's body) records no + * sender, and a message naming one is refused. + * 2. SENDER — the envelope sender is the deployment's configured sender + * (`IEmailService.getDefaultFrom`). A `from` naming any other address is + * refused; one naming the configured address is replaced by the configured + * value. A deployment that reports no configured sender refuses a caller + * `from`. Custom `headers` may not name the sender + * ({@link SENDER_HEADER_NAMES}), and are accepted in one shape only: a + * plain object mapping each header field name to a single-line string. + * 3. TENANT — the message belongs to the caller's organization, which this + * stamps as `organizationId`. A message naming another organization, or + * naming one when the caller has none, is refused. `identityMail` is + * refused: identity mail is sent by the server itself. A message restating + * `identityMail: false` is admitted, and the forwarded message never + * carries the caller's value. + * + * `replyTo` is not bounded: it is the caller's choice of Reply-To address and + * makes no claim about the sender. + */ + +import type { EmailAddress } from '@objectstack/spec/contracts'; + +/** + * Custom header names (compared case-insensitively) a caller may not set: each + * one states who the message is from, which bound 2 reserves to the configured + * sender. + */ +export const SENDER_HEADER_NAMES: ReadonlySet = new Set(['from', 'sender', 'return-path']); + +/** + * A header field name: one or more printable US-ASCII characters other than + * the colon (RFC 5322 §2.2). + */ +const HEADER_FIELD_NAME = /^[\x21-\x39\x3b-\x7e]+$/; + +/** A plain object — an object literal or a JSON-parsed object, never an array or a class instance. */ +export function isPlainMailObject(value: unknown): value is Record { + if (value === null || typeof value !== 'object' || Array.isArray(value)) return false; + const proto = Object.getPrototypeOf(value); + return proto === Object.prototype || proto === null; +} + +/** + * Why a caller's `headers` cannot be forwarded, or `undefined` when it can. + * Absent is fine. Otherwise it must be the contract's `Record` + * exactly, with no key one of {@link SENDER_HEADER_NAMES}. + */ +function headersRefusal(headers: unknown): string | undefined { + if (headers === undefined) return undefined; + if (!isPlainMailObject(headers)) { + return 'Custom `headers` must be an object mapping each header name to a string value.'; + } + for (const [name, value] of Object.entries(headers)) { + if (!HEADER_FIELD_NAME.test(name)) { + return 'Custom `headers` must be keyed by header field names: printable ASCII with no space, control character or colon.'; + } + if (typeof value !== 'string' || /[\r\n]/.test(value)) { + return `Custom \`headers\` value for \`${name}\` must be a single-line string.`; + } + if (SENDER_HEADER_NAMES.has(name.toLowerCase())) { + return `Custom header \`${name}\` cannot be set: the sender is the deployment's configured sender.`; + } + } + return undefined; +} + +/** + * The bare address an {@link EmailAddress} names, lower-cased for comparison, + * or `undefined` when it names none. For the string form a trailing + * `
` wins over the display name before it. + */ +export function mailAddressOf(value: unknown): string | undefined { + let raw: unknown = value; + if (value && typeof value === 'object') raw = (value as { address?: unknown }).address; + if (typeof raw !== 'string') return undefined; + const angled = /<([^<>]*)>\s*$/.exec(raw); + const address = (angled ? angled[1] : raw).trim().toLowerCase(); + return address.length > 0 ? address : undefined; +} + +/** Who is sending, as the door resolved it — never as the message says. */ +export interface CallerMailIdentity { + /** The calling user, or `undefined` for a call with none (a scheduled job). */ + userId: string | undefined; + /** The caller's active organization, or `undefined` when it has none. */ + organizationId: string | undefined; +} + +/** The part of the mail service the bounds read: its configured sender. */ +export interface CallerMailSenderSource { + getDefaultFrom?: () => EmailAddress | undefined; +} + +/** The bounded message, or the reason the caller's message is refused. */ +export type CallerMailBoundsResult = + | { ok: true; input: Record } + | { ok: false; reason: string }; + +/** + * Apply the three bounds of the module header to a caller's `message`, and + * answer the message the mail service is handed, or the refusal. Pure: it + * reads only its arguments and the service's configured sender. + */ +export function boundCallerMail( + message: Record, + caller: CallerMailIdentity, + sender: CallerMailSenderSource, +): CallerMailBoundsResult { + // Bound 1: attribution. + if (message.sentBy !== undefined && message.sentBy !== caller.userId) { + return { + ok: false, + reason: caller.userId + ? '`sentBy` is the authenticated caller; a send cannot be attributed to another user.' + : '`sentBy` cannot be set: this call has no calling user. Omit it.', + }; + } + + // Bound 2: the sender is the configured one. + const headersRefused = headersRefusal(message.headers); + if (headersRefused !== undefined) return { ok: false, reason: headersRefused }; + let from: EmailAddress | undefined; + if (message.from !== undefined) { + const configured = typeof sender.getDefaultFrom === 'function' ? sender.getDefaultFrom() : undefined; + const configuredAddress = mailAddressOf(configured); + if (!configuredAddress || mailAddressOf(message.from) !== configuredAddress) { + return { + ok: false, + reason: configuredAddress + ? `\`from\` must be the deployment's configured sender (${configuredAddress}); omit it to send as that sender.` + : '`from` cannot be chosen by the caller: this deployment reports no configured sender. Configure one in Settings → Mail → From address and omit `from`.', + }; + } + from = configured; + } + + // Bound 3: the caller's organization, and identity mail is the server's. + const organizationId = caller.organizationId; + if (message.organizationId !== undefined && message.organizationId !== organizationId) { + return { + ok: false, + reason: organizationId + ? '`organizationId` is the caller\'s active organization; a send cannot be recorded under another organization.' + : '`organizationId` cannot be set: the caller has no active organization. Omit it.', + }; + } + if (message.identityMail !== undefined && message.identityMail !== false) { + return { + ok: false, + reason: '`identityMail` cannot be set through this door: identity mail is sent by the server itself. Omit it.', + }; + } + + const rest = { ...message }; + delete rest.organizationId; + delete rest.identityMail; + delete rest.sentBy; + return { + ok: true, + input: { + ...rest, + ...(caller.userId !== undefined ? { sentBy: caller.userId } : {}), + ...(organizationId !== undefined ? { organizationId } : {}), + ...(from !== undefined ? { from } : {}), + }, + }; +} diff --git a/packages/core/src/security/index.ts b/packages/core/src/security/index.ts index 120de1e23f0..b22f1eeb4af 100644 --- a/packages/core/src/security/index.ts +++ b/packages/core/src/security/index.ts @@ -704,3 +704,15 @@ export { type AuthzGrantsCacheTtlReading, type AuthzPostureSink, } from './authz-cache-posture.js'; + +// The bounds a caller's message passes before the mail service sends it, shared +// by the HTTP send door (rest) and the script-body door (runtime). +export { + boundCallerMail, + mailAddressOf, + isPlainMailObject, + SENDER_HEADER_NAMES, + type CallerMailIdentity, + type CallerMailSenderSource, + type CallerMailBoundsResult, +} from './caller-mail-bounds.js'; diff --git a/packages/core/src/utils/import-runner-sandbox-fault-row.test.ts b/packages/core/src/utils/import-runner-sandbox-fault-row.test.ts index e342198e7b6..5085210bae4 100644 --- a/packages/core/src/utils/import-runner-sandbox-fault-row.test.ts +++ b/packages/core/src/utils/import-runner-sandbox-fault-row.test.ts @@ -103,6 +103,9 @@ const SAMPLES: Readonly> = { method: 'find', required: 'api.read', fieldName: 'owner', + token: 'email.send', + member: 'email', + fnName: 'send', }; /** The helper every capability gate throws through, read below from the producer. */ diff --git a/packages/objectql/src/hook-run-as.ts b/packages/objectql/src/hook-run-as.ts index f2cefd73f20..c3cb16e8b0d 100644 --- a/packages/objectql/src/hook-run-as.ts +++ b/packages/objectql/src/hook-run-as.ts @@ -212,8 +212,11 @@ export function deriveHookApi(api: unknown, runAs: HookRunAs, ref: HookRunAsRef) * list and email (#24639) onto the api `withRunAs('user')` derived. * * A symbol, and ⛔ deliberately NOT re-exported from the package entry, so the - * method is no NAMEABLE member of `ScopedContext`'s published face: only the - * hook wrapper reaches it, through {@link seedHookUserGrants}. A public named + * method is no NAMEABLE member of `ScopedContext`'s published face: it is + * reached only through {@link seedHookUserGrants}, which the entry does export, + * by the hook wrapper and by the runtime's script-body doors (`body-runner.ts` + * `hookDoorCaller`, which reads one record's existence in the hook's calling + * user's scope). A public named * method would widen the published surface, and it would also be a derivation * the runtime's stored-metadata seams (`deriveThroughSeam`) do not know, so a * seam-served host api calling it would get back an unserved context. diff --git a/packages/objectql/src/index.ts b/packages/objectql/src/index.ts index 84f8d095ab9..d1c9ac4b50a 100644 --- a/packages/objectql/src/index.ts +++ b/packages/objectql/src/index.ts @@ -373,7 +373,16 @@ export { UnscopedHookApi, hookRunAs, deriveHookApi, + // The second step of a `runAs: 'user'` derivation, and its fail-safe: the + // runtime's body doors read a record in the hook's calling user's scope + // through the same two steps the hook wrapper takes. + seedHookUserGrants, + seedHookUnreadMembership, } from './hook-run-as.js'; +// Whether a write runs inside a transaction a write beside it joins, or one it +// cannot reach: read by the runtime's script-body doors. +export { openTransactionKind } from './open-transaction.js'; +export type { OpenTransactionKind } from './open-transaction.js'; export type { HookRunAs, HookRunAsRef, RunAsDerivableApi } from './hook-run-as.js'; // Boot guard: thrown by `ObjectQL.init()` when a registered driver's connect() // fails (framework#3741). Hosts that boot the engine themselves can catch it to diff --git a/packages/objectql/src/open-transaction.test.ts b/packages/objectql/src/open-transaction.test.ts new file mode 100644 index 00000000000..63863c2c14a --- /dev/null +++ b/packages/objectql/src/open-transaction.test.ts @@ -0,0 +1,36 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, it, expect } from 'vitest'; +import { openTransactionKind } from './open-transaction.js'; + +function engineWith(ambient: unknown, closed: unknown[] = []) { + return { + txStore: { getStore: () => (ambient === undefined ? undefined : { transaction: ambient }) }, + isClosedUnitHandle: (h: unknown) => closed.includes(h), + }; +} + +describe('where a write stands with respect to a transaction', () => { + const a = { tx: 'ambient' }; + const t = { tx: 'threaded' }; + + it('answers none with no open transaction', () => { + expect(openTransactionKind(engineWith(undefined))).toBe('none'); + expect(openTransactionKind(engineWith(a, [a]), a)).toBe('none'); + }); + + it('answers joined for the ambient transaction, carried or not', () => { + expect(openTransactionKind(engineWith(a))).toBe('joined'); + expect(openTransactionKind(engineWith(a), a)).toBe('joined'); + }); + + it('answers separate for a carried handle the ambient store does not hold', () => { + expect(openTransactionKind(engineWith(undefined), t)).toBe('separate'); + expect(openTransactionKind(engineWith(a), t)).toBe('separate'); + }); + + it('reads an engine double from the carried handle alone', () => { + expect(openTransactionKind({}, undefined)).toBe('none'); + expect(openTransactionKind({}, t)).toBe('separate'); + }); +}); diff --git a/packages/objectql/src/open-transaction.ts b/packages/objectql/src/open-transaction.ts new file mode 100644 index 00000000000..ca6f46b6d53 --- /dev/null +++ b/packages/objectql/src/open-transaction.ts @@ -0,0 +1,55 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Where a write stands with respect to a transaction, for code that acts + * BESIDE that write through the engine (the runtime's script-body doors) and + * must know whether what it writes will commit or roll back with it. + * + * - `'none'`: no transaction is open; a write through the engine stands alone. + * - `'joined'`: the engine's ambient transaction is open (ADR-0034), and a + * write through the engine joins it: it commits or rolls back with the + * write that is running. + * - `'separate'`: the running write carries a transaction handle the ambient + * store does not hold (a sandboxed body's `ctx.api.transaction`, threaded + * explicitly, ADR-0067). A write through the engine would take another + * connection, outside it. + * + * A handle of a unit the engine opened that has since closed counts as no + * transaction. Read through the engine's own ambient store and unit ledger, so + * the answer is the one the engine's write path acts on; those members are + * private, and a real engine pins what is read off them + * (`body-doors-transaction.integration.test.ts`, `@objectstack/runtime`). + */ +export type OpenTransactionKind = 'none' | 'joined' | 'separate'; + +interface TransactionReadableEngine { + txStore?: { getStore(): { transaction?: unknown } | undefined }; + isClosedUnitHandle?: (handle: unknown) => boolean; +} + +/** + * Answer {@link OpenTransactionKind} for a write running on `engine` whose + * execution context carries `threaded` as its transaction handle (or none). + * An engine that exposes neither the ambient store nor the unit ledger (a + * double) is read from `threaded` alone. + */ +export function openTransactionKind(engine: unknown, threaded?: unknown): OpenTransactionKind { + const e = engine as TransactionReadableEngine | undefined; + const closed = (handle: unknown): boolean => { + try { + return typeof e?.isClosedUnitHandle === 'function' && e.isClosedUnitHandle(handle) === true; + } catch { + return false; + } + }; + let ambient: unknown; + try { + ambient = e?.txStore?.getStore()?.transaction; + } catch { + ambient = undefined; + } + const ambientOpen = ambient != null && !closed(ambient); + const threadedOpen = threaded != null && !closed(threaded); + if (threadedOpen && (!ambientOpen || threaded !== ambient)) return 'separate'; + return ambientOpen || threadedOpen ? 'joined' : 'none'; +} diff --git a/packages/plugins/plugin-audit/src/app-activity-door.test.ts b/packages/plugins/plugin-audit/src/app-activity-door.test.ts new file mode 100644 index 00000000000..91e80e63625 --- /dev/null +++ b/packages/plugins/plugin-audit/src/app-activity-door.test.ts @@ -0,0 +1,134 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, it, expect } from 'vitest'; +import { SYS_ACTIVITY_PLATFORM_TYPES } from '@objectstack/spec/data'; +import { + PLATFORM_ACTIVITY_METADATA_KEYS, + appActivityEntryRefusal, + createAppActivityWriter, + type AppActivityEntry, +} from './app-activity-door.js'; +import { ACTIVITY_FEED_EXCLUDED_OBJECTS } from './objects/sys-activity.object.js'; + +const entry: AppActivityEntry = { object: 'crm_contact', recordId: 'c1', type: 'completed', summary: 'Email: Quote' }; +const noSchema = () => undefined; + +describe('an app adds only its own kind of timeline entry', () => { + it('takes an entry of an app type about an ordinary record', () => { + expect(appActivityEntryRefusal(entry, noSchema)).toBeUndefined(); + }); + + for (const type of SYS_ACTIVITY_PLATFORM_TYPES) { + it(`refuses the platform-only type '${type}'`, () => { + expect(appActivityEntryRefusal({ ...entry, type }, noSchema)).toMatchObject({ code: 'PERMISSION_DENIED', statusCode: 403 }); + }); + } + + for (const key of PLATFORM_ACTIVITY_METADATA_KEYS) { + it(`refuses the platform metadata key '${key}'`, () => { + expect(appActivityEntryRefusal({ ...entry, metadata: { [key]: 'x' } }, noSchema)).toMatchObject({ + code: 'PERMISSION_DENIED', + }); + }); + } + + it('refuses an entry about an object the feed does not show, or about an append-only ledger', () => { + expect(appActivityEntryRefusal({ ...entry, object: ACTIVITY_FEED_EXCLUDED_OBJECTS[0] }, noSchema)).toMatchObject({ + code: 'PERMISSION_DENIED', + }); + expect( + appActivityEntryRefusal({ ...entry, object: 'crm_ledger' }, (o) => (o === 'crm_ledger' ? { managedBy: 'append-only' } : undefined)), + ).toMatchObject({ code: 'PERMISSION_DENIED' }); + }); +}); + +function fakeEngine(fields: string[]) { + const inserts: Array<{ object: string; row: Record; options: any }> = []; + const engine = { + getSchema: (object: string) => (object === 'sys_activity' ? { fields: Object.fromEntries(fields.map((f) => [f, {}])) } : { fields: {} }), + createContext: (context: unknown) => ({ context }), + insert: async (object: string, row: Record, options: unknown) => { + inserts.push({ object, row, options }); + return { id: 'act_1' }; + }, + }; + return { engine, inserts }; +} + +describe('the activity door writes the actor, organization and origin the platform stamps', () => { + const columns = ['type', 'summary', 'actor_id', 'origin', 'organization_id', 'metadata']; + const snapshot = async () => ({ name: 'Ann Lee', avatarUrl: 'https://img.test/ann.png' }); + + it('writes the stamped actor (with the platform snapshot), organization and origin', async () => { + const { engine, inserts } = fakeEngine(columns); + const writer = createAppActivityWriter({ getEngine: () => engine as any, getActorSnapshot: () => snapshot }); + const out = await writer.appendAppActivity( + { ...entry, metadata: { kind: 'email' }, source: { object: 'sys_email', id: 'e1' } }, + { actorId: 'usr_ann', organizationId: 'org_acme', origin: 'com.acme.crm/action:send_quote' }, + ); + expect(out).toEqual({ id: 'act_1' }); + expect(inserts).toHaveLength(1); + const { object, row, options } = inserts[0]; + expect(object).toBe('sys_activity'); + expect(row).toMatchObject({ + type: 'completed', + summary: 'Email: Quote', + actor_id: 'usr_ann', + actor_name: 'Ann Lee', + actor_avatar_url: 'https://img.test/ann.png', + object_name: 'crm_contact', + record_id: 'c1', + source_object: 'sys_email', + source_id: 'e1', + metadata: JSON.stringify({ kind: 'email' }), + origin: 'com.acme.crm/action:send_quote', + organization_id: 'org_acme', + }); + expect(options.context).toEqual({ isSystem: true, tenantId: 'org_acme' }); + }); + + it('writes the entry, and reads its actor, under the transaction handle it is given', async () => { + const { engine, inserts } = fakeEngine(columns); + const read: unknown[] = []; + const writer = createAppActivityWriter({ + getEngine: () => engine as any, + getActorSnapshot: () => async (scope: any) => { + read.push(scope.context); + return { name: 'Ann Lee', avatarUrl: null }; + }, + }); + await writer.appendAppActivity( + entry, + { actorId: 'usr_ann', organizationId: 'org_acme', origin: 'p/hook:h' }, + { transaction: 'trx_1' }, + ); + expect(inserts[0].options.context).toEqual({ isSystem: true, tenantId: 'org_acme', transaction: 'trx_1' }); + expect(read).toEqual([{ isSystem: true, tenantId: 'org_acme', transaction: 'trx_1' }]); + }); + + it('writes an entry with no user with an empty actor', async () => { + const { engine, inserts } = fakeEngine(columns); + const writer = createAppActivityWriter({ getEngine: () => engine as any, getActorSnapshot: () => snapshot }); + await writer.appendAppActivity(entry, { actorId: undefined, organizationId: 'org_acme', origin: 'p/job:nightly' }); + expect(inserts[0].row.actor_id).toBeNull(); + expect(inserts[0].row).not.toHaveProperty('actor_name'); + }); + + it('refuses an entry with no organization where the feed is organization-scoped, and writes nothing', async () => { + const { engine, inserts } = fakeEngine(columns); + const writer = createAppActivityWriter({ getEngine: () => engine as any, getActorSnapshot: () => snapshot }); + await expect( + writer.appendAppActivity(entry, { actorId: 'usr_ann', organizationId: undefined, origin: 'p/hook:h' }), + ).rejects.toMatchObject({ code: 'VALIDATION_ERROR', statusCode: 400 }); + expect(inserts).toHaveLength(0); + }); + + it('writes nothing for a refused entry', async () => { + const { engine, inserts } = fakeEngine(columns); + const writer = createAppActivityWriter({ getEngine: () => engine as any, getActorSnapshot: () => snapshot }); + await expect( + writer.appendAppActivity({ ...entry, type: 'updated' }, { actorId: 'usr_ann', organizationId: 'org_acme', origin: 'p/hook:h' }), + ).rejects.toMatchObject({ code: 'PERMISSION_DENIED' }); + expect(inserts).toHaveLength(0); + }); +}); diff --git a/packages/plugins/plugin-audit/src/app-activity-door.ts b/packages/plugins/plugin-audit/src/app-activity-door.ts new file mode 100644 index 00000000000..636c31dd743 --- /dev/null +++ b/packages/plugins/plugin-audit/src/app-activity-door.ts @@ -0,0 +1,216 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The activity door's writer: one timeline entry an app adds to a record's + * activity feed, written by this plugin, which owns `sys_activity`. + * + * An app adds an entry through `ctx.activity.append(input)` in a script body + * (`@objectstack/runtime`). The runtime door parses the body's input against + * `BodyActivityAppendInputSchema`, reads the record (and `source`) in the + * caller's scope, and hands the entry here with what the platform stamps: the + * acting user, the organization and the origin. This writer then holds the + * ledger's own rules and writes the row as the platform: + * + * - `type` may not be one only the platform records + * (`SYS_ACTIVITY_PLATFORM_TYPES`, `@objectstack/spec/data`). + * - `metadata` may not use a key the platform's own entries carry + * ({@link PLATFORM_ACTIVITY_METADATA_KEYS}): those keys render a recorded + * change, an impersonation or a localized summary. + * - the record must be of an object whose activity the timeline shows: not one + * of `ACTIVITY_FEED_EXCLUDED_OBJECTS`, and not an append-only ledger. + * - the actor's name and avatar are the platform's snapshot of the acting user + * (the one resolution every activity row is written with), and the time is + * the write's. + * - `origin` names the package and the body that wrote the entry, so a reader + * tells an app's entry from one the platform recorded, whose `origin` is + * empty. + * + * A refusal is `PERMISSION_DENIED` (403) for a value only the platform may + * write, and `VALIDATION_ERROR` (400) for an entry with no organization to + * belong to where the feed is organization-scoped. + */ + +import { SYS_ACTIVITY_PLATFORM_TYPES } from '@objectstack/spec/data'; +import type { IDataEngine } from '@objectstack/spec/contracts'; +import { createFieldPresenceProbe } from '@objectstack/metadata-core'; +import { ACTIVITY_FEED_EXCLUDED_OBJECTS } from './objects/sys-activity.object.js'; +import { ACTIVITY_TEXT_SOURCES_KEY } from './activity-changed-fields.js'; +import { ACTIVITY_SUMMARY_MESSAGE_KEY } from './activity-summary-message.js'; +import { IMPERSONATED_BY_KEY, IMPERSONATED_BY_NAME_KEY } from './impersonation-attribution.js'; +import type { AuditActorSnapshot } from './audit-writers.js'; + +/** + * The `metadata` keys the platform's own activity entries carry, which an app's + * entry may not use: the recorded change (`old` / `new`), the impersonation + * attribution, the declaration of where the text columns came from, and the + * localized summary. + */ +export const PLATFORM_ACTIVITY_METADATA_KEYS: readonly string[] = Object.freeze([ + 'old', + 'new', + IMPERSONATED_BY_KEY, + IMPERSONATED_BY_NAME_KEY, + ACTIVITY_TEXT_SOURCES_KEY, + ACTIVITY_SUMMARY_MESSAGE_KEY, +]); + +const PLATFORM_TYPES: ReadonlySet = new Set(SYS_ACTIVITY_PLATFORM_TYPES); + +/** One entry as the body asked for it, already parsed by the runtime door. */ +export interface AppActivityEntry { + object: string; + recordId: string; + type: string; + summary: string; + recordLabel?: string; + source?: { object: string; id: string }; + metadata?: Record; +} + +/** What the door stamps — never what the body said. */ +export interface AppActivityStamp { + /** The acting user, or `undefined` for a body with none (a scheduled job). */ + actorId: string | undefined; + /** The caller's organization, or `undefined` when it has none. */ + organizationId: string | undefined; + /** `/:` of the body that wrote the entry. */ + origin: string; +} + +/** How one entry is written. */ +export interface AppActivityWriteOptions { + /** + * The transaction handle the entry is written under, so it commits or rolls + * back with the write that runs the body: given when that write carries a + * handle the engine's ambient transaction does not hold. Without it, the + * entry joins the engine's ambient transaction, or stands alone. + */ + transaction?: unknown; +} + +/** The writer's dependencies, resolved at each call. */ +export interface AppActivityWriterDeps { + getEngine: () => IDataEngine | undefined; + /** + * The platform's display snapshot of a user (`installAuditWriters`' + * `resolveActorSnapshot`), or `undefined` before the writers are installed; + * the entry is then written with the actor id alone. + */ + getActorSnapshot: () => ((api: unknown, userId: string) => Promise) | undefined; +} + +function refusal(code: 'PERMISSION_DENIED' | 'VALIDATION_ERROR', message: string): Error { + const status = code === 'PERMISSION_DENIED' ? 403 : 400; + return Object.assign(new Error(message), { code, status, statusCode: status }); +} + +/** + * The refusal for an entry this writer does not write, or `undefined`. Reads + * the target object's registered schema for its bucket. + */ +export function appActivityEntryRefusal( + entry: AppActivityEntry, + schemaOf: (object: string) => { managedBy?: unknown } | null | undefined, +): Error | undefined { + if (PLATFORM_TYPES.has(entry.type)) { + return refusal( + 'PERMISSION_DENIED', + `An app cannot add a '${entry.type}' activity entry: '${entry.type}' is recorded by the platform itself. ` + + `Use a type of your own (for example 'completed', 'scheduled' or one your app declares).`, + ); + } + for (const key of Object.keys(entry.metadata ?? {})) { + if (PLATFORM_ACTIVITY_METADATA_KEYS.includes(key)) { + return refusal( + 'PERMISSION_DENIED', + `An app's activity entry cannot carry metadata key '${key}': the platform's own entries use it. Rename the key.`, + ); + } + } + if (ACTIVITY_FEED_EXCLUDED_OBJECTS.includes(entry.object)) { + return refusal( + 'PERMISSION_DENIED', + `An app cannot add an activity entry about a '${entry.object}' record: the activity feed does not show that object's activity.`, + ); + } + if (schemaOf(entry.object)?.managedBy === 'append-only') { + return refusal( + 'PERMISSION_DENIED', + `An app cannot add an activity entry about a '${entry.object}' record: '${entry.object}' is an append-only ledger.`, + ); + } + return undefined; +} + +/** + * Create the activity door's writer. Registered on the `audit` service as + * `appendAppActivity`. + */ +export function createAppActivityWriter(deps: AppActivityWriterDeps) { + let probe: ((object: string, field: string) => boolean) | undefined; + let probedEngine: IDataEngine | undefined; + return { + async appendAppActivity( + entry: AppActivityEntry, + stamp: AppActivityStamp, + options?: AppActivityWriteOptions, + ): Promise<{ id: string }> { + const engine = deps.getEngine(); + if (!engine) throw new Error('The activity feed is not available: no data engine is registered.'); + if (probe === undefined || probedEngine !== engine) { + probe = createFieldPresenceProbe(engine); + probedEngine = engine; + } + const schemaOf = (object: string): { managedBy?: unknown } | null | undefined => { + try { + return typeof (engine as any).getSchema === 'function' ? (engine as any).getSchema(object) : null; + } catch { + return null; + } + }; + const refused = appActivityEntryRefusal(entry, schemaOf); + if (refused) throw refused; + + const organizationScoped = probe('sys_activity', 'organization_id'); + if (organizationScoped && !stamp.organizationId) { + throw refusal( + 'VALIDATION_ERROR', + 'This activity entry has no organization to belong to: the call has no active organization.', + ); + } + + const context = { + isSystem: true, + ...(stamp.organizationId ? { tenantId: stamp.organizationId } : {}), + ...(options?.transaction != null ? { transaction: options.transaction } : {}), + }; + const snapshotOf = deps.getActorSnapshot(); + const actor: AuditActorSnapshot = + stamp.actorId && snapshotOf + ? await snapshotOf((engine as any).createContext?.(context) ?? engine, stamp.actorId) + : { name: null, avatarUrl: null }; + + const row: Record = { + type: entry.type, + timestamp: new Date().toISOString(), + summary: entry.summary, + actor_id: stamp.actorId ?? null, + ...(actor.name ? { actor_name: actor.name } : {}), + ...(actor.avatarUrl ? { actor_avatar_url: actor.avatarUrl } : {}), + object_name: entry.object, + record_id: entry.recordId, + record_label: entry.recordLabel ?? null, + ...(entry.source ? { source_object: entry.source.object, source_id: entry.source.id } : {}), + ...(entry.metadata ? { metadata: JSON.stringify(entry.metadata) } : {}), + ...(probe('sys_activity', 'origin') ? { origin: stamp.origin } : {}), + ...(organizationScoped ? { organization_id: stamp.organizationId } : {}), + }; + const created: any = await engine.insert('sys_activity', row, { context } as any); + const id = created?.id ?? created?.data?.id; + return { id: id != null ? String(id) : '' }; + }, + }; +} + +/** The writer {@link createAppActivityWriter} answers. */ +export type AppActivityWriter = ReturnType; diff --git a/packages/plugins/plugin-audit/src/audit-plugin.ts b/packages/plugins/plugin-audit/src/audit-plugin.ts index 650b9fce7c4..de6f37939e7 100644 --- a/packages/plugins/plugin-audit/src/audit-plugin.ts +++ b/packages/plugins/plugin-audit/src/audit-plugin.ts @@ -41,7 +41,8 @@ import { SysAuditLogDetailPage } from './sys-audit-log.page.js'; // core path depend on this plugin being installed. `sys_attachment` moved to // @objectstack/service-storage for the same ownership reason (ADR-0052 §3: a // file↔record link belongs with storage, not the compliance ledger). -import { installAuditWriters, type AuditI18nSurface, type MessagingEmitSurface } from './audit-writers.js'; +import { installAuditWriters, type AuditActorSnapshot, type AuditI18nSurface, type MessagingEmitSurface } from './audit-writers.js'; +import { createAppActivityWriter } from './app-activity-door.js'; import { installReadAuditWriter, type ReadAuditWriterHandle } from './read-audit.js'; import { createAuthEventAuditSink } from './auth-event-audit.js'; import { createActionInvocationAuditWriter } from './action-invocation-audit.js'; @@ -319,6 +320,11 @@ export class AuditPlugin implements Plugin { * and the hook write through one writer. */ private credentialUseWriter: CredentialUseAuditWriter | null = null; + /** + * The platform's display snapshot of a user, once the writers are installed + * at `kernel:ready`; the activity door's writer reads it at each call. + */ + private actorSnapshotOf: ((api: unknown, userId: string) => Promise) | undefined; constructor(private readonly options: AuditPluginOptions = {}) {} @@ -428,6 +434,9 @@ export class AuditPlugin implements Plugin { ...createPackageLifecycleAuditWriter({ getEngine: getLedgerEngine, logger: ctx.logger }), ...this.credentialUseWriter, ...createScimRefusalAuditWriter({ getEngine: getLedgerEngine, logger: ctx.logger }), + // The activity door's writer: one timeline entry an app adds through + // `ctx.activity.append` (`app-activity-door.ts`). + ...createAppActivityWriter({ getEngine: getLedgerEngine, getActorSnapshot: () => this.actorSnapshotOf }), }); // ADR-0029 D8 — contribute this plugin's object translations to the i18n @@ -544,6 +553,7 @@ export class AuditPlugin implements Plugin { admitMentionRecipients: (input) => admitMentionRecipients({ engine: engine as any, getTenancyPosture, logger: ctx.logger as any }, input), }); + this.actorSnapshotOf = auditWriters?.resolveActorSnapshot; ctx.logger.info('AuditPlugin: audit + activity writers installed'); // [#31796] The `credential_use` row: recognised on each credential's own diff --git a/packages/plugins/plugin-audit/src/objects/sys-activity.object.ts b/packages/plugins/plugin-audit/src/objects/sys-activity.object.ts index b204eba7f44..d534b038594 100644 --- a/packages/plugins/plugin-audit/src/objects/sys-activity.object.ts +++ b/packages/plugins/plugin-audit/src/objects/sys-activity.object.ts @@ -374,6 +374,21 @@ export const SysActivity = ObjectSchema.create({ group: 'Context', }), + // The activity door (`app-activity-door.ts`) stamps the app code that wrote + // an entry here. Every other writer leaves it empty: the platform's own, + // and, while it is still taken, an app's insert into this object. + origin: Field.text({ + label: 'Origin', + required: false, + readonly: true, + searchable: true, + maxLength: 500, + description: + 'The app code that added this entry through the activity door, as "/:" ' + + '(for example "com.acme.crm/action:send_email"). Empty on an entry not written through the activity door.', + group: 'Context', + }), + // ── Writer-stamped read-rule columns (ADR-0139 D4, E6) ─────────── // Stamped at write time by ONE derivation (`activity-changed-fields.ts`): // the CRUD mirror, a before-insert hook for every other writer, and the diff --git a/packages/plugins/plugin-audit/src/translations/ar.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/ar.objects.generated.ts index d600fad03ca..47ac16a6ffb 100644 --- a/packages/plugins/plugin-audit/src/translations/ar.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/ar.objects.generated.ts @@ -191,6 +191,10 @@ export const arObjects: NonNullable = { label: "البيانات الوصفية", help: "سياق إضافي مُسلسَل بصيغة JSON" }, + origin: { + label: "Origin", + help: "The app code that added this entry through the activity door, as \"/:\" (for example \"com.acme.crm/action:send_email\"). Empty on an entry not written through the activity door." + }, changed_fields: { label: "الحقول المتغيّرة", help: "مجموعة مفاتيح التغيير المسجَّل: في التحديث، كل حقل تذكره القيم القديمة/الجديدة المسجَّلة؛ وفارغة لكل صف آخر. تختمها المنصّة وقت الكتابة؛ وتُقدَّم مقصورة على الحقول المتاحة للقارئ. تعني NULL أن الصف لم يُختم بعد (شغّل `os migrate activity-changed-fields`)." diff --git a/packages/plugins/plugin-audit/src/translations/ar.source-hashes.generated.ts b/packages/plugins/plugin-audit/src/translations/ar.source-hashes.generated.ts index 035a5b88a6e..d522f37ec99 100644 --- a/packages/plugins/plugin-audit/src/translations/ar.source-hashes.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/ar.source-hashes.generated.ts @@ -18,6 +18,8 @@ */ export const arGeneratedSourceHashes: Readonly> = { + "objects.sys_activity.fields.origin.help": "036947e355512b7f", + "objects.sys_activity.fields.origin.label": "f8071c8dc31952ae", "objects.sys_activity.fields.url.label": "2203b0b9f72534f7", "objects.sys_audit_amendment.description": "593f7118f80bd85d", "objects.sys_audit_amendment.fields.amended_at.label": "eb49c9af1cb3db60", diff --git a/packages/plugins/plugin-audit/src/translations/de.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/de.objects.generated.ts index e1f552c8d71..0725a5e71dc 100644 --- a/packages/plugins/plugin-audit/src/translations/de.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/de.objects.generated.ts @@ -191,6 +191,10 @@ export const deObjects: NonNullable = { label: "Metadaten", help: "Zusätzlicher Kontext, als JSON serialisiert" }, + origin: { + label: "Origin", + help: "The app code that added this entry through the activity door, as \"/:\" (for example \"com.acme.crm/action:send_email\"). Empty on an entry not written through the activity door." + }, changed_fields: { label: "Geänderte Felder", help: "Die Schlüsselmenge der erfassten Änderung: bei einer Aktualisierung jedes Feld, das die erfassten alten/neuen Werte nennen; bei jeder anderen Zeile leer. Von der Plattform beim Schreiben gesetzt; ausgeliefert nur mit den Feldern, die der Leser sehen darf. NULL bedeutet, dass die Zeile noch nicht gekennzeichnet ist (führen Sie `os migrate activity-changed-fields` aus)." diff --git a/packages/plugins/plugin-audit/src/translations/de.source-hashes.generated.ts b/packages/plugins/plugin-audit/src/translations/de.source-hashes.generated.ts index 20275c37042..1814d471e76 100644 --- a/packages/plugins/plugin-audit/src/translations/de.source-hashes.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/de.source-hashes.generated.ts @@ -18,6 +18,8 @@ */ export const deGeneratedSourceHashes: Readonly> = { + "objects.sys_activity.fields.origin.help": "036947e355512b7f", + "objects.sys_activity.fields.origin.label": "f8071c8dc31952ae", "objects.sys_activity.fields.url.label": "2203b0b9f72534f7", "objects.sys_audit_amendment.description": "593f7118f80bd85d", "objects.sys_audit_amendment.fields.amended_at.label": "eb49c9af1cb3db60", diff --git a/packages/plugins/plugin-audit/src/translations/en.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/en.objects.generated.ts index 0b5209f8058..c1a082de590 100644 --- a/packages/plugins/plugin-audit/src/translations/en.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/en.objects.generated.ts @@ -191,6 +191,10 @@ export const enObjects: NonNullable = { label: "Metadata", help: "JSON-serialized additional context" }, + origin: { + label: "Origin", + help: "The app code that added this entry through the activity door, as \"/:\" (for example \"com.acme.crm/action:send_email\"). Empty on an entry not written through the activity door." + }, changed_fields: { label: "Changed Fields", help: "The key set of the recorded change: for an update, every field its recorded old/new values name; empty for every other row. Stamped by the platform at write time; served narrowed to the fields the reader is served. NULL means the row is not stamped yet (run `os migrate activity-changed-fields`)." diff --git a/packages/plugins/plugin-audit/src/translations/es-ES.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/es-ES.objects.generated.ts index 302346ed9ed..9d5c070662d 100644 --- a/packages/plugins/plugin-audit/src/translations/es-ES.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/es-ES.objects.generated.ts @@ -191,6 +191,10 @@ export const esESObjects: NonNullable = { label: "Metadatos", help: "Contexto adicional serializado en JSON." }, + origin: { + label: "Origin", + help: "The app code that added this entry through the activity door, as \"/:\" (for example \"com.acme.crm/action:send_email\"). Empty on an entry not written through the activity door." + }, changed_fields: { label: "Campos modificados", help: "El conjunto de claves del cambio registrado: para una actualización, cada campo que nombran sus valores antiguos/nuevos registrados; vacío para cualquier otra fila. La plataforma lo marca al escribir; se sirve reducido a los campos que se sirven al lector. NULL significa que la fila aún no está marcada (ejecute `os migrate activity-changed-fields`)." diff --git a/packages/plugins/plugin-audit/src/translations/es-ES.source-hashes.generated.ts b/packages/plugins/plugin-audit/src/translations/es-ES.source-hashes.generated.ts index e4a60c4ec2c..71aa5710371 100644 --- a/packages/plugins/plugin-audit/src/translations/es-ES.source-hashes.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/es-ES.source-hashes.generated.ts @@ -19,6 +19,8 @@ export const esESGeneratedSourceHashes: Readonly> = { "objects.sys_activity.fields.actor_id.label": "b155813f8a7f06e3", + "objects.sys_activity.fields.origin.help": "036947e355512b7f", + "objects.sys_activity.fields.origin.label": "f8071c8dc31952ae", "objects.sys_activity.fields.type.help": "5d8df777db464241", "objects.sys_activity.fields.url.label": "2203b0b9f72534f7", "objects.sys_audit_amendment.description": "593f7118f80bd85d", diff --git a/packages/plugins/plugin-audit/src/translations/fr.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/fr.objects.generated.ts index 6b025b93d81..27e32b6c708 100644 --- a/packages/plugins/plugin-audit/src/translations/fr.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/fr.objects.generated.ts @@ -191,6 +191,10 @@ export const frObjects: NonNullable = { label: "Métadonnées", help: "Contexte supplémentaire sérialisé en JSON" }, + origin: { + label: "Origin", + help: "The app code that added this entry through the activity door, as \"/:\" (for example \"com.acme.crm/action:send_email\"). Empty on an entry not written through the activity door." + }, changed_fields: { label: "Champs modifiés", help: "L’ensemble des clés du changement enregistré : pour une mise à jour, chaque champ nommé par ses anciennes/nouvelles valeurs ; vide pour toute autre ligne. Apposé par la plateforme à l’écriture ; servi restreint aux champs servis au lecteur. NULL signifie que la ligne n’est pas encore marquée (exécutez `os migrate activity-changed-fields`)." diff --git a/packages/plugins/plugin-audit/src/translations/fr.source-hashes.generated.ts b/packages/plugins/plugin-audit/src/translations/fr.source-hashes.generated.ts index 89071c8e80b..2de189384cb 100644 --- a/packages/plugins/plugin-audit/src/translations/fr.source-hashes.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/fr.source-hashes.generated.ts @@ -18,6 +18,8 @@ */ export const frGeneratedSourceHashes: Readonly> = { + "objects.sys_activity.fields.origin.help": "036947e355512b7f", + "objects.sys_activity.fields.origin.label": "f8071c8dc31952ae", "objects.sys_activity.fields.type.label": "901bb552898b2cab", "objects.sys_activity.fields.url.label": "2203b0b9f72534f7", "objects.sys_audit_amendment.description": "593f7118f80bd85d", diff --git a/packages/plugins/plugin-audit/src/translations/ja-JP.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/ja-JP.objects.generated.ts index 85e41aff8db..72b0316c262 100644 --- a/packages/plugins/plugin-audit/src/translations/ja-JP.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/ja-JP.objects.generated.ts @@ -191,6 +191,10 @@ export const jaJPObjects: NonNullable = { label: "メタデータ", help: "JSON シリアライズされた追加コンテキスト" }, + origin: { + label: "Origin", + help: "The app code that added this entry through the activity door, as \"/:\" (for example \"com.acme.crm/action:send_email\"). Empty on an entry not written through the activity door." + }, changed_fields: { label: "変更フィールド", help: "記録された変更のキー集合:更新の場合は、記録された旧値/新値が含むすべてのフィールド。その他の行では空。書き込み時にプラットフォームが付与し、閲覧者に提供されるフィールドに絞り込んで返されます。NULL はその行がまだ付与されていないことを示します(`os migrate activity-changed-fields` を実行してください)。" diff --git a/packages/plugins/plugin-audit/src/translations/ja-JP.source-hashes.generated.ts b/packages/plugins/plugin-audit/src/translations/ja-JP.source-hashes.generated.ts index 0df26609cfa..1f01fb8981b 100644 --- a/packages/plugins/plugin-audit/src/translations/ja-JP.source-hashes.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/ja-JP.source-hashes.generated.ts @@ -18,6 +18,8 @@ */ export const jaJPGeneratedSourceHashes: Readonly> = { + "objects.sys_activity.fields.origin.help": "036947e355512b7f", + "objects.sys_activity.fields.origin.label": "f8071c8dc31952ae", "objects.sys_activity.fields.type.help": "5d8df777db464241", "objects.sys_activity.fields.url.label": "2203b0b9f72534f7", "objects.sys_audit_amendment.description": "593f7118f80bd85d", diff --git a/packages/plugins/plugin-audit/src/translations/ko.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/ko.objects.generated.ts index fc0e661c851..7f833047ed1 100644 --- a/packages/plugins/plugin-audit/src/translations/ko.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/ko.objects.generated.ts @@ -191,6 +191,10 @@ export const koObjects: NonNullable = { label: "메타데이터", help: "JSON으로 직렬화된 추가 컨텍스트" }, + origin: { + label: "Origin", + help: "The app code that added this entry through the activity door, as \"/:\" (for example \"com.acme.crm/action:send_email\"). Empty on an entry not written through the activity door." + }, changed_fields: { label: "변경된 필드", help: "기록된 변경의 키 집합입니다. 수정이면 기록된 이전/새 값이 가리키는 모든 필드이고, 그 밖의 행은 비어 있습니다. 쓰기 시점에 플랫폼이 기록하며, 읽는 사람에게 제공되는 필드로 좁혀서 제공됩니다. NULL은 아직 기록되지 않은 행입니다(`os migrate activity-changed-fields` 실행)." diff --git a/packages/plugins/plugin-audit/src/translations/ko.source-hashes.generated.ts b/packages/plugins/plugin-audit/src/translations/ko.source-hashes.generated.ts index 7b7ac041037..b3eb442b766 100644 --- a/packages/plugins/plugin-audit/src/translations/ko.source-hashes.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/ko.source-hashes.generated.ts @@ -18,6 +18,8 @@ */ export const koGeneratedSourceHashes: Readonly> = { + "objects.sys_activity.fields.origin.help": "036947e355512b7f", + "objects.sys_activity.fields.origin.label": "f8071c8dc31952ae", "objects.sys_activity.fields.url.label": "2203b0b9f72534f7", "objects.sys_audit_amendment.description": "593f7118f80bd85d", "objects.sys_audit_amendment.fields.amended_at.label": "eb49c9af1cb3db60", diff --git a/packages/plugins/plugin-audit/src/translations/pt-BR.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/pt-BR.objects.generated.ts index cc0a31b42da..5513611c149 100644 --- a/packages/plugins/plugin-audit/src/translations/pt-BR.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/pt-BR.objects.generated.ts @@ -191,6 +191,10 @@ export const ptBRObjects: NonNullable = { label: "Metadados", help: "Contexto adicional serializado em JSON" }, + origin: { + label: "Origin", + help: "The app code that added this entry through the activity door, as \"/:\" (for example \"com.acme.crm/action:send_email\"). Empty on an entry not written through the activity door." + }, changed_fields: { label: "Campos alterados", help: "O conjunto de chaves da alteração registrada: em uma atualização, todos os campos citados pelos valores antigos/novos registrados; vazio para as demais linhas. Gravado pela plataforma no momento da escrita; servido restrito aos campos que o leitor pode ver. NULL significa que a linha ainda não foi marcada (execute `os migrate activity-changed-fields`)." diff --git a/packages/plugins/plugin-audit/src/translations/pt-BR.source-hashes.generated.ts b/packages/plugins/plugin-audit/src/translations/pt-BR.source-hashes.generated.ts index c6678ac1b89..03b424f62a3 100644 --- a/packages/plugins/plugin-audit/src/translations/pt-BR.source-hashes.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/pt-BR.source-hashes.generated.ts @@ -18,6 +18,8 @@ */ export const ptBRGeneratedSourceHashes: Readonly> = { + "objects.sys_activity.fields.origin.help": "036947e355512b7f", + "objects.sys_activity.fields.origin.label": "f8071c8dc31952ae", "objects.sys_activity.fields.url.label": "2203b0b9f72534f7", "objects.sys_audit_amendment.description": "593f7118f80bd85d", "objects.sys_audit_amendment.fields.amended_at.label": "eb49c9af1cb3db60", diff --git a/packages/plugins/plugin-audit/src/translations/ru.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/ru.objects.generated.ts index 9928b61b255..ab5582b88b8 100644 --- a/packages/plugins/plugin-audit/src/translations/ru.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/ru.objects.generated.ts @@ -191,6 +191,10 @@ export const ruObjects: NonNullable = { label: "Метаданные", help: "Дополнительный контекст, сериализованный в JSON" }, + origin: { + label: "Origin", + help: "The app code that added this entry through the activity door, as \"/:\" (for example \"com.acme.crm/action:send_email\"). Empty on an entry not written through the activity door." + }, changed_fields: { label: "Изменённые поля", help: "Набор ключей записанного изменения: для обновления — каждое поле, названное в записанных старых/новых значениях; для остальных строк — пусто. Проставляется платформой при записи; отдаётся только с теми полями, которые доступны читателю. NULL означает, что строка ещё не помечена (выполните `os migrate activity-changed-fields`)." diff --git a/packages/plugins/plugin-audit/src/translations/ru.source-hashes.generated.ts b/packages/plugins/plugin-audit/src/translations/ru.source-hashes.generated.ts index 2b20dd730b6..d28c39ad2c6 100644 --- a/packages/plugins/plugin-audit/src/translations/ru.source-hashes.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/ru.source-hashes.generated.ts @@ -18,6 +18,8 @@ */ export const ruGeneratedSourceHashes: Readonly> = { + "objects.sys_activity.fields.origin.help": "036947e355512b7f", + "objects.sys_activity.fields.origin.label": "f8071c8dc31952ae", "objects.sys_activity.fields.url.label": "2203b0b9f72534f7", "objects.sys_audit_amendment.description": "593f7118f80bd85d", "objects.sys_audit_amendment.fields.amended_at.label": "eb49c9af1cb3db60", diff --git a/packages/plugins/plugin-audit/src/translations/zh-CN.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/zh-CN.objects.generated.ts index 854ad073ffa..b649ae4ae23 100644 --- a/packages/plugins/plugin-audit/src/translations/zh-CN.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/zh-CN.objects.generated.ts @@ -191,6 +191,10 @@ export const zhCNObjects: NonNullable = { label: "元数据", help: "附加上下文的 JSON 序列化内容" }, + origin: { + label: "Origin", + help: "The app code that added this entry through the activity door, as \"/:\" (for example \"com.acme.crm/action:send_email\"). Empty on an entry not written through the activity door." + }, changed_fields: { label: "变更字段", help: "所记录变更的字段键集合:对于更新,为其记录的旧值/新值涉及的每个字段;其他行为空。由平台在写入时标记;仅返回读者有权查看的字段。NULL 表示该行尚未标记(请运行 `os migrate activity-changed-fields`)。" diff --git a/packages/plugins/plugin-audit/src/translations/zh-CN.source-hashes.generated.ts b/packages/plugins/plugin-audit/src/translations/zh-CN.source-hashes.generated.ts index b3f7d47ed04..e5e21a0d8a6 100644 --- a/packages/plugins/plugin-audit/src/translations/zh-CN.source-hashes.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/zh-CN.source-hashes.generated.ts @@ -18,6 +18,8 @@ */ export const zhCNGeneratedSourceHashes: Readonly> = { + "objects.sys_activity.fields.origin.help": "036947e355512b7f", + "objects.sys_activity.fields.origin.label": "f8071c8dc31952ae", "objects.sys_activity.fields.type.help": "5d8df777db464241", "objects.sys_activity.fields.url.label": "2203b0b9f72534f7", "objects.sys_audit_amendment.description": "593f7118f80bd85d", diff --git a/packages/plugins/plugin-audit/src/translations/zh-Hant.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/zh-Hant.objects.generated.ts index a5e4b120c71..3d3dfead628 100644 --- a/packages/plugins/plugin-audit/src/translations/zh-Hant.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/zh-Hant.objects.generated.ts @@ -191,6 +191,10 @@ export const zhHantObjects: NonNullable = { label: "中繼資料", help: "附加內容的 JSON 序列化結果" }, + origin: { + label: "Origin", + help: "The app code that added this entry through the activity door, as \"/:\" (for example \"com.acme.crm/action:send_email\"). Empty on an entry not written through the activity door." + }, changed_fields: { label: "變更欄位", help: "所記錄變更的鍵集合:對於更新,為其記錄的舊值/新值所提及的每個欄位;其他列為空。由平台在寫入時標記;回傳時僅保留讀者可見的欄位。NULL 表示該列尚未標記(請執行 `os migrate activity-changed-fields`)。" diff --git a/packages/plugins/plugin-audit/src/translations/zh-Hant.source-hashes.generated.ts b/packages/plugins/plugin-audit/src/translations/zh-Hant.source-hashes.generated.ts index 1bffe57eccf..a09d064c7e8 100644 --- a/packages/plugins/plugin-audit/src/translations/zh-Hant.source-hashes.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/zh-Hant.source-hashes.generated.ts @@ -18,6 +18,8 @@ */ export const zhHantGeneratedSourceHashes: Readonly> = { + "objects.sys_activity.fields.origin.help": "036947e355512b7f", + "objects.sys_activity.fields.origin.label": "f8071c8dc31952ae", "objects.sys_activity.fields.url.label": "2203b0b9f72534f7", "objects.sys_audit_amendment.description": "593f7118f80bd85d", "objects.sys_audit_amendment.fields.amended_at.label": "eb49c9af1cb3db60", diff --git a/packages/plugins/plugin-email/src/email-plugin.outbox-sweep.test.ts b/packages/plugins/plugin-email/src/email-plugin.outbox-sweep.test.ts index 75996e98920..1c7273ddd16 100644 --- a/packages/plugins/plugin-email/src/email-plugin.outbox-sweep.test.ts +++ b/packages/plugins/plugin-email/src/email-plugin.outbox-sweep.test.ts @@ -433,7 +433,8 @@ describe('normal delivery is unchanged', () => { }); it('an app-inserted row is still drained by the afterInsert hook, exactly once', async () => { - const h = await boot(); + // The drain sends a row the service did not write from the configured sender. + const h = await boot({ plugin: { defaultFrom: { address: 'no-reply@example.test' } } }); await h.ready(); await h.engine.insert('sys_email', { @@ -449,6 +450,26 @@ describe('normal delivery is unchanged', () => { }); }); +describe('an app-inserted row is sent from the configured sender', () => { + it('whatever sender its columns and headers name', async () => { + const h = await boot({ plugin: { defaultFrom: { name: 'Acme', address: 'no-reply@example.test' } } }); + await h.ready(); + + await h.engine.insert('sys_email', { + id: 'row-named', from_address: 'ceo@example.test', to_addresses: 'c@d.test', + subject: 'App', body_text: 'x', status: 'queued', attempt_count: 0, + headers_json: JSON.stringify({ Sender: 'ceo@example.test', 'X-Campaign': 'q4' }), + created_at: new Date(NOW).toISOString(), + }); + await flush(); + + expect(h.transport.send).toHaveBeenCalledTimes(1); + const sent = (h.transport.send as any).mock.calls[0][0]; + expect(sent.from).toBe('Acme '); + expect(sent.headers ?? {}).toEqual({ 'X-Campaign': 'q4' }); + }); +}); + // ── the insert id contract, at the seam that motivated it (#5523) ─────────── describe('a datasource that re-keys a sys_email insert', () => { @@ -475,7 +496,7 @@ describe('a datasource that re-keys a sys_email insert', () => { return { messageId: '' }; }), }; - const h = await boot({ engine: { reKeyInsert: 'db-pk-7' }, transport }); + const h = await boot({ engine: { reKeyInsert: 'db-pk-7' }, transport, plugin: { defaultFrom: { address: 'no-reply@example.test' } } }); await h.ready(); await expect( @@ -701,7 +722,7 @@ describe('[ADR-0131 D7, Q2 A] identity mail is written to sys_identity_email', ( }); it('the outbox drain hook delivers a queued row inserted into the sibling', async () => { - const h = await boot(); + const h = await boot({ plugin: { defaultFrom: { address: 'no-reply@example.test' } } }); await h.ready(); await h.engine.insert(IDENTITY, { ...eighteenZeroIdentityRow('id-drained', ago(0)) }); diff --git a/packages/plugins/plugin-email/src/email-plugin.ts b/packages/plugins/plugin-email/src/email-plugin.ts index e56b41560b3..1634121c8d7 100644 --- a/packages/plugins/plugin-email/src/email-plugin.ts +++ b/packages/plugins/plugin-email/src/email-plugin.ts @@ -47,6 +47,7 @@ import { emailLogObjectOfJob, isEmailLogObject, } from './email-log-objects.js'; +import { installOutboxSenderBound } from './outbox-sender-bound.js'; import { EMAIL_ATTACHMENT_RECLAIM_QUEUE, EMAIL_ATTACHMENT_RECLAIM_GRACE_MS, @@ -1113,7 +1114,10 @@ export class EmailServicePlugin implements Plugin { const fresh = Array.isArray(rows) ? rows[0] : (rows as any)?.data?.[0]; const target = fresh ?? row; if (target.status !== 'queued' || target.message_id) return; - await svc.deliverPersistedRow(target, undefined, object); + // Sent from the configured sender, as the insert-time bound + // recorded it (`outbox-sender-bound.ts`), whatever the row + // says by the time it is read here. + await svc.deliverPersistedRow(target, { asConfiguredSender: true }, object); } catch (err: any) { // `error`, not `warn` (#5161): the insert returned, the row // is there, everything looks normal — and the mail was NOT @@ -1142,6 +1146,9 @@ export class EmailServicePlugin implements Plugin { }, { packageId: DRAIN_PKG }, ); + // An outbox row the service did not write is sent as the configured + // sender, whatever its `from_address` says (`outbox-sender-bound.ts`). + installOutboxSenderBound(engine as any, svc, DRAIN_PKG); ctx.logger.info('EmailServicePlugin: sys_email / sys_identity_email outbox drain hook installed'); } diff --git a/packages/plugins/plugin-email/src/email-service.test.ts b/packages/plugins/plugin-email/src/email-service.test.ts index 44c21dbef22..3dbcfbc9280 100644 --- a/packages/plugins/plugin-email/src/email-service.test.ts +++ b/packages/plugins/plugin-email/src/email-service.test.ts @@ -324,6 +324,62 @@ describe('EmailService', () => { expect(warn).toHaveBeenCalledWith(expect.stringContaining('persist failed'), expect.any(Object)); }); + it('sends nothing when the caller requires the log row and it cannot be written', async () => { + const transport = { send: vi.fn(async () => ({ messageId: '' })) }; + const failing: EmailPersistence = { + insert: vi.fn(async () => { throw new Error('db down'); }), + update: vi.fn(async () => {}), + }; + const svc = new EmailService({ transport, defaultFrom: 'no@reply.com', persistence: failing, logger: { info: vi.fn(), warn: vi.fn() } }); + await expect(svc.send({ to: 'a@b.com', subject: 'Hi', text: 'x', requireLogRow: true })).rejects.toMatchObject({ + code: 'SERVICE_UNAVAILABLE', + statusCode: 503, + }); + const none = new EmailService({ transport, defaultFrom: 'no@reply.com' }); + await expect(none.send({ to: 'a@b.com', subject: 'Hi', text: 'x', requireLogRow: true })).rejects.toMatchObject({ + code: 'SERVICE_UNAVAILABLE', + }); + expect(transport.send).not.toHaveBeenCalled(); + + const { p, rows } = makePersistence(); + const logged = new EmailService({ transport, defaultFrom: 'no@reply.com', persistence: p }); + const res = await logged.send({ to: 'a@b.com', subject: 'Hi', text: 'x', requireLogRow: true }); + expect(res.status).toBe('sent'); + expect(rows.get(res.id)).toMatchObject({ status: 'sent' }); + }); + + it('delivers a row the service did not write from the configured sender, with no sender header of its own', async () => { + const sent: any[] = []; + const transport = { send: vi.fn(async (m: any) => { sent.push(m); return { messageId: '' }; }) }; + const { p, rows } = makePersistence(); + rows.set('r1', { id: 'r1', status: 'queued' }); + const svc = new EmailService({ transport, defaultFrom: { name: 'Acme', address: 'noreply@acme.test' }, persistence: p }); + const res = await svc.deliverPersistedRow( + { + id: 'r1', + status: 'queued', + from_address: 'ceo@acme.test', + to_addresses: 'pat@example.test', + subject: 'Hi', + body_text: 'x', + headers_json: JSON.stringify({ Sender: 'ceo@acme.test', 'X-Campaign': 'q4' }), + }, + { asConfiguredSender: true }, + ); + expect(res.status).toBe('sent'); + expect(sent[0].from).toBe('Acme '); + expect(sent[0].headers).toEqual({ 'X-Campaign': 'q4' }); + + const unconfigured = new EmailService({ transport, persistence: p }); + rows.set('r2', { id: 'r2', status: 'queued' }); + const failed = await unconfigured.deliverPersistedRow( + { id: 'r2', status: 'queued', from_address: 'ceo@acme.test', to_addresses: 'pat@example.test', subject: 'Hi', body_text: 'x' }, + { asConfiguredSender: true }, + ); + expect(failed.status).toBe('failed'); + expect(transport.send).toHaveBeenCalledTimes(1); + }); + // ── Outbox-drain support (sys_email afterInsert) ─────────────────── it('marks its own row managed during send() so the drain hook skips it', async () => { // The persistence.insert callback fires at exactly the moment the diff --git a/packages/plugins/plugin-email/src/email-service.ts b/packages/plugins/plugin-email/src/email-service.ts index 5ce3cf81caa..43914f4da38 100644 --- a/packages/plugins/plugin-email/src/email-service.ts +++ b/packages/plugins/plugin-email/src/email-service.ts @@ -28,6 +28,7 @@ import { type EncodedAttachments, } from './sys-email-payload.js'; import { withRecoveredHeaders } from './internal-header-readback.js'; +import { SENDER_HEADER_NAMES } from '@objectstack/core'; import { EMAIL_ATTACHMENT_RECLAIM_QUEUE, EMAIL_ATTACHMENT_RECLAIM_GRACE_MS, @@ -113,6 +114,33 @@ export interface DeliverAttemptOptions { * accumulates across queue redeliveries instead of resetting to 1. */ priorAttempts?: number; + /** + * Send the row from the configured sender ({@link EmailService.getDefaultFrom}) + * with no sender header of its own (`SENDER_HEADER_NAMES`, `@objectstack/core`), + * whatever the row says. The outbox drain passes it for a row the service did + * not write. With no configured sender the row lands at `failed`. + */ + asConfiguredSender?: boolean; +} + +/** + * {@link DeliverAttemptOptions.asConfiguredSender}: the message sent from the + * configured sender, with every sender header taken off. Throws when no sender + * is configured, which lands the row at `failed`. + */ +function asConfiguredSender(message: NormalizedEmailMessage, configured: EmailAddress | undefined): NormalizedEmailMessage { + if (configured == null) { + throw new Error('no configured sender: a mail-log row the mail service did not write is sent only from the configured sender'); + } + const out: NormalizedEmailMessage = { ...message, from: formatAddress(configured) }; + if (message.headers) { + const kept = Object.fromEntries( + Object.entries(message.headers).filter(([name]) => !SENDER_HEADER_NAMES.has(name.trim().toLowerCase())), + ); + if (Object.keys(kept).length > 0) out.headers = kept; + else delete out.headers; + } + return out; } /** @@ -1084,6 +1112,16 @@ export class EmailService implements IEmailService { // is built to make impossible. await this.discardOrphanedAttachmentContent(storageKeys, 'the sys_email row could not be persisted'); } + if (!rowPersisted && input.requireLogRow === true) { + // The caller sends only what the mail log records (`SendEmailInput.requireLogRow`): + // refused before any delivery, so nothing goes out unrecorded. + throw Object.assign( + new Error( + `SERVICE_UNAVAILABLE: the message was not sent, because the mail log (${object}) could not record it. Try again later.`, + ), + { code: 'SERVICE_UNAVAILABLE', status: 503, statusCode: 503 }, + ); + } if (queue) { // Queue mode delivers the ROW, so a row that never landed leaves the // job with nothing to reference. Deliver inline instead of publishing @@ -1567,6 +1605,7 @@ export class EmailService implements IEmailService { // the reason, which is the whole point: an unfetchable attachment must // never become a message delivered without it. normalized = await rowToNormalizedAsync(source, { fetchContent: this.attachmentFetcher() }); + if (opts?.asConfiguredSender) normalized = asConfiguredSender(normalized, this.getDefaultFrom()); } catch (err: any) { const errMessage = String(err?.message ?? err ?? 'invalid row').slice(0, 1000); await this.updateRow(rowId, { diff --git a/packages/plugins/plugin-email/src/outbox-sender-bound.test.ts b/packages/plugins/plugin-email/src/outbox-sender-bound.test.ts new file mode 100644 index 00000000000..25abbe06a2f --- /dev/null +++ b/packages/plugins/plugin-email/src/outbox-sender-bound.test.ts @@ -0,0 +1,80 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, it, expect } from 'vitest'; +import { boundOutboxRowSender, installOutboxSenderBound } from './outbox-sender-bound.js'; + +const configured = { name: 'Acme', address: 'noreply@acme.test' }; +function source(opts: { from?: unknown; managed?: string[] } = {}) { + const managed = new Set(opts.managed ?? []); + return { + getDefaultFrom: () => ('from' in opts ? (opts.from as any) : configured), + isServiceManaged: (id: string) => managed.has(id), + }; +} + +describe('an outbox row the mail service did not write is sent as the configured sender', () => { + it('writes the configured sender over the row\'s from_address', () => { + const row = { status: 'queued', from_address: 'ceo@acme.test', to_addresses: 'pat@example.test' }; + expect(boundOutboxRowSender('sys_email', row, source())).toBe(true); + expect(row.from_address).toBe('Acme '); + }); + + it('applies to both mail logs', () => { + const row = { status: 'queued', from_address: 'ceo@acme.test' }; + expect(boundOutboxRowSender('sys_identity_email', row, source())).toBe(true); + expect(row.from_address).toBe('Acme '); + }); + + it('empties the column when no sender is configured, so the mail log refuses the row', () => { + const row = { status: 'queued', from_address: 'ceo@acme.test' }; + boundOutboxRowSender('sys_email', row, source({ from: undefined })); + expect(row.from_address).toBe(''); + }); + + it('takes every sender header out of the row\'s headers, and keeps the others', () => { + const row: Record = { + status: 'queued', + from_address: 'ceo@acme.test', + headers_json: JSON.stringify({ From: 'ceo@acme.test', ' sender ': 'x@acme.test', 'Return-Path': 'y@acme.test', 'X-Campaign': 'q4' }), + }; + boundOutboxRowSender('sys_email', row, source()); + expect(JSON.parse(String(row.headers_json))).toEqual({ 'X-Campaign': 'q4' }); + + const only: Record = { status: 'queued', headers_json: JSON.stringify({ Sender: 'x@acme.test' }) }; + boundOutboxRowSender('sys_email', only, source()); + expect(only.headers_json).toBeNull(); + }); + + it('CONTROL: a row the service wrote keeps the sender its send decided', () => { + const row = { id: 'em_1', status: 'queued', from_address: 'Templates ' }; + expect(boundOutboxRowSender('sys_email', row, source({ managed: ['em_1'] }))).toBe(false); + expect(row.from_address).toBe('Templates '); + }); + + it('CONTROL: a record of mail (not queued, or already sent) keeps its from_address', () => { + for (const row of [ + { status: 'sent', from_address: 'x@acme.test' }, + { status: 'queued', message_id: 'm1', from_address: 'x@acme.test' }, + ]) { + expect(boundOutboxRowSender('sys_email', row, source())).toBe(false); + expect(row.from_address).toBe('x@acme.test'); + } + expect(boundOutboxRowSender('crm_note', { status: 'queued', from_address: 'x' }, source())).toBe(false); + }); + + it('is registered before insert on both mail logs and bounds every row of a batch', () => { + const hooks: Array<{ event: string; object: unknown; handler: (ctx: any) => unknown }> = []; + installOutboxSenderBound( + { registerHook: (event, handler, options) => hooks.push({ event, object: options?.object, handler }) }, + source(), + 'pkg', + ); + expect(hooks.map((h) => `${h.event}:${h.object}`)).toEqual(['beforeInsert:sys_email', 'beforeInsert:sys_identity_email']); + const rows = [ + { status: 'queued', from_address: 'a@x.test' }, + { status: 'queued', from_address: 'b@x.test' }, + ]; + hooks[0].handler({ object: 'sys_email', input: { data: rows } }); + expect(rows.map((r) => r.from_address)).toEqual(['Acme ', 'Acme ']); + }); +}); diff --git a/packages/plugins/plugin-email/src/outbox-sender-bound.ts b/packages/plugins/plugin-email/src/outbox-sender-bound.ts new file mode 100644 index 00000000000..8c893459735 --- /dev/null +++ b/packages/plugins/plugin-email/src/outbox-sender-bound.ts @@ -0,0 +1,106 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * An outbox row is sent as the deployment's configured sender. + * + * A mail-log row (`sys_email`, `sys_identity_email`) inserted at `queued` with + * no `message_id` by anyone other than the mail service's own `send()` is an + * outbox entry: the drain (`email-plugin.ts`) and the boot sweep + * (`outbox-sweep.ts`) deliver it, and a row's `from_address` is the From the + * transport sends. Such a row's sender is therefore the configured sender, + * whatever the row says: this `beforeInsert` bound writes the configured value + * over the row's `from_address`, and takes every sender header + * (`SENDER_HEADER_NAMES`, `@objectstack/core`) out of its `headers_json`, + * before the row lands, so the row records the sender that is actually sent. + * The drain sends such a row from the configured sender again at delivery + * (`DeliverAttemptOptions.asConfiguredSender`), whatever the row says by then. + * A deployment that reports no configured sender empties the column, and the + * mail log refuses the insert itself (`from_address` is required): no row + * lands, and nothing is sent as an address nobody configured. + * + * Out of scope, deliberately: + * - A row the service's own `send()` writes (it reserves the row id first, + * `EmailService.isServiceManaged`): its sender was already decided by + * `send()` — the configured default, a caller's `from` bounded by its door + * (`boundCallerMail`, `@objectstack/core`), or a platform template's + * declared sender. + * - A row that is not an outbox entry (any other status, or one carrying a + * `message_id`): it is a record of mail, not a request to send one. + */ + +import type { EmailAddress } from '@objectstack/spec/contracts'; +import { SENDER_HEADER_NAMES } from '@objectstack/core'; +import { isEmailLogObject } from './email-log-objects.js'; + +/** The part of the mail service this bound reads. */ +export interface OutboxSenderSource { + getDefaultFrom(): EmailAddress | undefined; + isServiceManaged(id: string): boolean; +} + +/** The address text a mail-log row stores for one sender. */ +function senderText(from: EmailAddress | undefined): string { + if (from == null) return ''; + if (typeof from === 'string') return from.trim(); + const address = String(from.address ?? '').trim(); + if (!address) return ''; + const name = typeof from.name === 'string' ? from.name.trim() : ''; + return name ? `${name} <${address}>` : address; +} + +/** + * A row's `headers_json` with every sender header taken out; `null` when none + * is left. One that does not decode to an object of headers is left as it is: + * delivery refuses it. + */ +function withoutSenderHeaders(value: unknown): unknown { + if (typeof value !== 'string' || value.trim() === '') return value; + let parsed: unknown; + try { + parsed = JSON.parse(value); + } catch { + return value; + } + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return value; + const kept = Object.entries(parsed as Record).filter( + ([name]) => !SENDER_HEADER_NAMES.has(name.trim().toLowerCase()), + ); + return kept.length > 0 ? JSON.stringify(Object.fromEntries(kept)) : null; +} + +/** + * Bound one row about to be inserted into `object`: when it is an outbox entry + * the service did not write, its `from_address` becomes the configured + * sender's (empty when none is configured) and its `headers_json` loses every + * sender header. Answers whether it rewrote the row. + */ +export function boundOutboxRowSender(object: unknown, row: unknown, source: OutboxSenderSource): boolean { + if (!isEmailLogObject(object)) return false; + if (!row || typeof row !== 'object' || Array.isArray(row)) return false; + const record = row as Record; + if (record.status !== 'queued' || record.message_id) return false; + if (record.id != null && source.isServiceManaged(String(record.id))) return false; + record.from_address = senderText(source.getDefaultFrom()); + if ('headers_json' in record) record.headers_json = withoutSenderHeaders(record.headers_json); + return true; +} + +/** The engine surface {@link installOutboxSenderBound} registers on. */ +interface HookEngine { + registerHook(event: string, handler: (ctx: any) => unknown, options?: Record): void; +} + +/** + * Register the bound as a `beforeInsert` hook on both mail logs, under + * `packageId` (the drain's, so the two come and go together). + */ +export function installOutboxSenderBound(engine: HookEngine, source: OutboxSenderSource, packageId: string): void { + const handler = (hookCtx: any): void => { + // The engine hands an insert's row (or rows, for a batch) as `input.data`. + const data = hookCtx?.input?.data; + for (const row of Array.isArray(data) ? data : [data]) boundOutboxRowSender(hookCtx?.object, row, source); + }; + for (const object of ['sys_email', 'sys_identity_email']) { + engine.registerHook('beforeInsert', handler, { object, packageId }); + } +} diff --git a/packages/plugins/plugin-security/src/flow-system-identity-write-refusal.test.ts b/packages/plugins/plugin-security/src/flow-system-identity-write-refusal.test.ts index 00aea94890d..cb0c1c01569 100644 --- a/packages/plugins/plugin-security/src/flow-system-identity-write-refusal.test.ts +++ b/packages/plugins/plugin-security/src/flow-system-identity-write-refusal.test.ts @@ -49,6 +49,8 @@ import { FLOW_SYSTEM_IDENTITY_WRITE_OBJECTS, assertAppAutomationAppendOnlyWriteAllowed, assertFlowSystemIdentityWriteAllowed, + resetAppAutomationAppendOnlyInsertWarnings, + warnAppAutomationAppendOnlyInsert, } from './flow-system-identity-write-refusal.js'; import { SysUserPermissionSet, SysUserPosition } from './objects/index.js'; import { SysPermissionSet, SysPosition, SysPositionPermissionSet } from './__tests__/legacy-catalog-objects.testkit.js'; @@ -608,3 +610,31 @@ describe("[seat decision on the contract review] an elevated automation's delete expect(await stored(engine, 'sys_activity', 'act_1')).toMatchObject({ id: 'act_1', actor_id: null }); }); }); + +describe('an elevated automation\'s insert into an append-only object is told, once, to use the platform doors', () => { + const schemaOf = (object: string) => (object === 'sys_activity' ? { managedBy: 'append-only' } : { managedBy: 'user' }); + const hook = markAppAutomationElevation({ isSystem: true }, 'hook'); + afterEach(() => resetAppAutomationAppendOnlyInsertWarnings()); + + it('names ctx.email.send and ctx.activity.append, once per elevation and object', () => { + const warn = vi.fn(); + const op = { object: 'sys_activity', operation: 'insert', context: hook }; + const line = warnAppAutomationAppendOnlyInsert(op, schemaOf, warn); + expect(line).toMatch(/Deprecated/); + expect(line).toMatch(/ctx\.email\.send/); + expect(line).toMatch(/ctx\.activity\.append/); + expect(warnAppAutomationAppendOnlyInsert(op, schemaOf, warn)).toBeUndefined(); + expect(warn).toHaveBeenCalledTimes(1); + const action = markAppAutomationElevation({ isSystem: true }, 'action'); + expect(warnAppAutomationAppendOnlyInsert({ ...op, context: action }, schemaOf, warn)).toBeDefined(); + expect(warn).toHaveBeenCalledTimes(2); + }); + + it('CONTROL: says nothing for an unelevated insert, another verb, or another object', () => { + const warn = vi.fn(); + expect(warnAppAutomationAppendOnlyInsert({ object: 'sys_activity', operation: 'insert', context: { isSystem: true } }, schemaOf, warn)).toBeUndefined(); + expect(warnAppAutomationAppendOnlyInsert({ object: 'sys_activity', operation: 'find', context: hook }, schemaOf, warn)).toBeUndefined(); + expect(warnAppAutomationAppendOnlyInsert({ object: 'crm_note', operation: 'insert', context: hook }, schemaOf, warn)).toBeUndefined(); + expect(warn).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/plugins/plugin-security/src/flow-system-identity-write-refusal.ts b/packages/plugins/plugin-security/src/flow-system-identity-write-refusal.ts index 51815997dc2..162fe0734f1 100644 --- a/packages/plugins/plugin-security/src/flow-system-identity-write-refusal.ts +++ b/packages/plugins/plugin-security/src/flow-system-identity-write-refusal.ts @@ -275,6 +275,47 @@ export function assertAppAutomationAppendOnlyWriteAllowed( ); } +/** The elevations and objects already told about, so each is said once per process. */ +const appendOnlyInsertWarned = new Set(); + +/** + * The deprecation notice for an insert into an append-only object from + * app-authored automation's system elevation (the elevation + * {@link elevationSource} names). Said once per elevation kind and object per + * process, at `warn`, naming the doors that replace the insert. Answers the + * line it logged, or `undefined`. + */ +export function warnAppAutomationAppendOnlyInsert( + opCtx: { + object?: unknown; + operation?: unknown; + context?: { isSystem?: unknown; flowRunId?: unknown } | null; + }, + schemaOf: (object: string) => { managedBy?: unknown } | null | undefined, + warn: (message: string) => void, +): string | undefined { + const source = elevationSource(opCtx?.context); + if (!source) return undefined; + if (opCtx.operation !== 'insert') return undefined; + const object = typeof opCtx.object === 'string' ? opCtx.object : ''; + if (!object || schemaOf(object)?.managedBy !== APPEND_ONLY_BUCKET) return undefined; + const key = `${source}:${object}`; + if (appendOnlyInsertWarned.has(key)) return undefined; + appendOnlyInsertWarned.add(key); + const line = + `[Security] Deprecated: inserting into '${object}' from ${SUBJECT[source]}. A coming release refuses it — ` + + `'${object}' is append-only, written by the platform service that owns it. ` + + 'Send mail with ctx.email.send (capability email.send) and add timeline entries with ctx.activity.append ' + + '(capability activity.append) instead.'; + warn(line); + return line; +} + +/** Forget which elevations were told (tests). */ +export function resetAppAutomationAppendOnlyInsertWarnings(): void { + appendOnlyInsertWarned.clear(); +} + /** The rule's reach, stated in every answer it gives. */ const APPEND_ONLY_SCOPE = 'This check covers the update, transfer, delete, purge and restore of an append-only object; an insert is not judged by it.'; diff --git a/packages/plugins/plugin-security/src/security-plugin-authz-middleware.ts b/packages/plugins/plugin-security/src/security-plugin-authz-middleware.ts index 5cb3431a648..3438ed8ec36 100644 --- a/packages/plugins/plugin-security/src/security-plugin-authz-middleware.ts +++ b/packages/plugins/plugin-security/src/security-plugin-authz-middleware.ts @@ -106,6 +106,7 @@ import { isGuestEnvelope, readUnlessRefused, requiredCapsForOperation } from './ import { assertAppAutomationAppendOnlyWriteAllowed, assertFlowSystemIdentityWriteAllowed, + warnAppAutomationAppendOnlyInsert, } from './flow-system-identity-write-refusal.js'; import { delegatedUnitReadScope, isUnreadableAddressedRowRefusal } from './delegated-admin-gate.js'; import { isRowWriteProbe, logGateRefusal, type AuthzMiddlewareFn } from './record-row-write-probe.js'; @@ -542,6 +543,13 @@ export function registerAuthzMiddleware( assertAppAutomationAppendOnlyWriteAllowed(opCtx, (object) => typeof ql?.getSchema === 'function' ? ql.getSchema(object) : undefined, ); + // The same elevation's insert into an append-only object is told, once, + // that it is deprecated, naming the two doors that replace it. + warnAppAutomationAppendOnlyInsert( + opCtx, + (object) => (typeof ql?.getSchema === 'function' ? ql.getSchema(object) : undefined), + (line) => ctx.logger.warn(line), + ); // System operations bypass security if (opCtx.context?.isSystem) { diff --git a/packages/rest/src/email-routes.ts b/packages/rest/src/email-routes.ts index 626f40efea2..ca46949fcb6 100644 --- a/packages/rest/src/email-routes.ts +++ b/packages/rest/src/email-routes.ts @@ -76,7 +76,7 @@ * ({@link SENDER_HEADER_NAMES}), and the door accepts them in one shape * only: the contract's `Record`, a plain object whose * every key is a header field name and whose every value is a single-line - * string ({@link headersRefusal}). Any other shape is refused, so the + * string (`boundCallerMail`, `@objectstack/core`). Any other shape is refused, so the * reserved-name check reads each header exactly as a transport will. * 4. TENANT — the message's mail-log row belongs to the caller's active * organization: the `tenantId` the identity resolver vetted onto the @@ -101,7 +101,7 @@ * claim of it, so no configured value exists to bound it to. */ -import type { EmailAddress } from '@objectstack/spec/contracts'; +import { boundCallerMail, isPlainMailObject as isPlainObject } from '@objectstack/core'; import { logError } from './log.js'; import { seamOrUndefined, type RestServer } from './rest-server.js'; @@ -112,67 +112,10 @@ import { seamOrUndefined, type RestServer } from './rest-server.js'; export const EMAIL_SEND_CAPABILITY = 'manage_platform_settings'; /** - * Custom header names (compared case-insensitively) a caller of the send door - * may not set: each one states who the message is from, which bound 3 of the - * module header reserves to the configured sender. + * Custom header names a caller of the send door may not set. Re-exported from + * the shared mail bounds (`@objectstack/core`), which both mail doors apply. */ -export const SENDER_HEADER_NAMES: ReadonlySet = new Set(['from', 'sender', 'return-path']); - -/** - * A header field name: one or more printable US-ASCII characters other than - * the colon (RFC 5322 §2.2). Whitespace, control characters and non-ASCII - * characters are not part of any field name. - */ -const HEADER_FIELD_NAME = /^[\x21-\x39\x3b-\x7e]+$/; - -/** A plain object — an object literal or a JSON-parsed object, never an array or a class instance. */ -function isPlainObject(value: unknown): value is Record { - if (value === null || typeof value !== 'object' || Array.isArray(value)) return false; - const proto = Object.getPrototypeOf(value); - return proto === Object.prototype || proto === null; -} - -/** - * Why a caller's `headers` cannot be forwarded, or `undefined` when it can - * (module header, bound 3). Absent is fine. Otherwise it must be the - * contract's `Record` exactly: a plain object, each key a - * header field name, each value a string with no line break, and no key one - * of {@link SENDER_HEADER_NAMES}. - */ -function headersRefusal(headers: unknown): string | undefined { - if (headers === undefined) return undefined; - if (!isPlainObject(headers)) { - return 'Custom `headers` must be an object mapping each header name to a string value.'; - } - for (const [name, value] of Object.entries(headers)) { - if (!HEADER_FIELD_NAME.test(name)) { - return 'Custom `headers` must be keyed by header field names: printable ASCII with no space, control character or colon.'; - } - if (typeof value !== 'string' || /[\r\n]/.test(value)) { - return `Custom \`headers\` value for \`${name}\` must be a single-line string.`; - } - if (SENDER_HEADER_NAMES.has(name.toLowerCase())) { - return `Custom header \`${name}\` cannot be set: the sender is the deployment's configured sender.`; - } - } - return undefined; -} - -/** - * The bare address an {@link EmailAddress} names, lower-cased for comparison — - * or `undefined` when it names none. For the string form a trailing - * `
` wins over the display name before it. This only DECIDES whether - * a caller's `from` restates the configured sender: the value forwarded to - * the transport is always the configured one, never the caller's text. - */ -function addressOf(value: unknown): string | undefined { - let raw: unknown = value; - if (value && typeof value === 'object') raw = (value as { address?: unknown }).address; - if (typeof raw !== 'string') return undefined; - const angled = /<([^<>]*)>\s*$/.exec(raw); - const address = (angled ? angled[1] : raw).trim().toLowerCase(); - return address.length > 0 ? address : undefined; -} +export { SENDER_HEADER_NAMES } from '@objectstack/core'; /** The nested ADR-0112 refusal every bound of this door answers with. */ function refuse(res: any, message: string): void { @@ -274,65 +217,24 @@ export function registerEmailEndpoints(this: EmailRouteHost, basePath: string): res.status(400).json({ code: 'INVALID_REQUEST', error: 'JSON body required' }); return; } - // Bound 2 (module header): `sentBy` is the authenticated caller. - // `enforceAuth` above has already proved `userId` present. - const userId = String((context as any).userId); - if (body.sentBy !== undefined && body.sentBy !== userId) { - refuse(res, '`sentBy` is the authenticated caller; a send cannot be attributed to another user.'); - return; - } - - // Bound 3 (module header): the sender is the configured one. - const headersRefused = headersRefusal(body.headers); - if (headersRefused !== undefined) { - refuse(res, headersRefused); - return; - } - let from: EmailAddress | undefined; - if (body.from !== undefined) { - const configured = typeof emailService.getDefaultFrom === 'function' - ? emailService.getDefaultFrom() - : undefined; - const configuredAddress = addressOf(configured); - if (!configuredAddress || addressOf(body.from) !== configuredAddress) { - refuse( - res, - configuredAddress - ? `\`from\` must be the deployment's configured sender (${configuredAddress}); omit it to send as that sender.` - : '`from` cannot be chosen by the caller: this deployment reports no configured sender. Configure one in Settings → Mail → From address and omit `from`.', - ); - return; - } - from = configured; - } - - // Bound 4 (module header): the row belongs to the caller's - // active organization, and identity mail is the server's. + // Bounds 2-4 (module header): one implementation, shared with + // the script-body mail door (`@objectstack/core` + // `boundCallerMail`). `enforceAuth` above has already proved + // `userId` present. const tenantId: unknown = (context as any).tenantId; - const organizationId = typeof tenantId === 'string' && tenantId.length > 0 ? tenantId : undefined; - if (body.organizationId !== undefined && body.organizationId !== organizationId) { - refuse( - res, - organizationId - ? '`organizationId` is the caller\'s active organization; a send cannot be recorded under another organization.' - : '`organizationId` cannot be set: the caller has no active organization. Omit it.', - ); + const bounded = boundCallerMail( + body, + { + userId: String((context as any).userId), + organizationId: typeof tenantId === 'string' && tenantId.length > 0 ? tenantId : undefined, + }, + emailService, + ); + if (!bounded.ok) { + refuse(res, bounded.reason); return; } - if (body.identityMail !== undefined && body.identityMail !== false) { - refuse(res, '`identityMail` cannot be set through this door: identity mail is sent by the server itself. Omit it.'); - return; - } - - const message = { ...body }; - delete message.organizationId; - delete message.identityMail; - const input = { - ...message, - sentBy: userId, - ...(organizationId !== undefined ? { organizationId } : {}), - ...(from !== undefined ? { from } : {}), - }; + const input = bounded.input as any; try { const result = await emailService.send(input); diff --git a/packages/runtime/src/app-artifact-handlers.test.ts b/packages/runtime/src/app-artifact-handlers.test.ts index 24f064de27a..d3b63b96e9b 100644 --- a/packages/runtime/src/app-artifact-handlers.test.ts +++ b/packages/runtime/src/app-artifact-handlers.test.ts @@ -288,6 +288,36 @@ describe('[ADR-0150 D4] bindAppArtifactHandlers on a multi-package artifact', () await expect(ql.executeAction('global', 'qa_note', { params: {} })).resolves.toEqual({ from: 'two' }); }); + it('a body\'s door origin names the package body that declares it, not the artifact', async () => { + const body = (ns: string) => ({ + id: `com.qa.origin.${ns}`, namespace: ns, name: `qa_origin_${ns}`, version: '1.0.0', type: 'module', + actions: [{ + name: `qa_${ns}_note`, label: 'Note', type: 'script', + body: { + language: 'js', + source: "return await ctx.activity.append({ object: 'qa_doc', recordId: 'd1', type: 'completed', summary: 'x' });", + capabilities: ['activity.append'], + }, + }], + }); + const artifact = { + manifest: { id: 'com.qa.origin', name: 'qa_origin', version: '1.0.0', type: 'app' }, + packages: [{ manifest: body('alpha') }, { manifest: body('beta') }], + }; + const stamps: any[] = []; + const getService = (name: string): unknown => + name === 'audit' + ? { appendAppActivity: async (_entry: unknown, stamp: unknown) => { stamps.push(stamp); return { id: 'act_1' }; } } + : undefined; + const ql = new ObjectQL({ logger: quiet } as any); + // The record the entry is about reads as present to the caller. + (ql as any).findOne = async (_object: string, query: any) => ({ id: query?.where?.id }); + bindAppArtifactHandlers(ql as any, artifact, { appId: 'com.qa.origin', logger: quiet, getService } as any); + + await ql.executeAction('global', 'qa_beta_note', { params: {} }); + expect(stamps.map((s) => s.origin)).toEqual(['com.qa.origin.beta/action:qa_beta_note']); + }); + it('a re-bind that drops a package body stops that body\'s actions', async () => { const body = (ns: string, action: string) => ({ id: `com.qa.rebind.${ns}`, namespace: ns, name: `qa_rebind_${ns}`, version: '1.0.0', type: 'module', diff --git a/packages/runtime/src/app-artifact-handlers.ts b/packages/runtime/src/app-artifact-handlers.ts index 5484ce848df..17673664642 100644 --- a/packages/runtime/src/app-artifact-handlers.ts +++ b/packages/runtime/src/app-artifact-handlers.ts @@ -252,6 +252,11 @@ export interface AppArtifactHandlerBindingOptions { * with its declared message. */ i18n?: HookRefusalI18nSource; + /** + * Kernel service lookup for the platform doors a hook or action body + * reaches (`ctx.email.send`, `ctx.activity.append`), read at call time. + */ + getService?: (name: string) => unknown; } /** What one {@link bindAppArtifactHandlers} call bound. */ @@ -396,11 +401,21 @@ export function bindAppArtifactHandlers( const bindable = hookGroups.filter((group) => group.hooks.length > 0 || Object.keys(group.functions).length > 0); if (bindable.length > 0) { if (typeof ql.bindHooks === 'function') { - const bodyRunner = hookBodyRunnerFactory(new QuickJSScriptRunner(), { ql, logger, appId, i18n: options.i18n }); + const scriptRunner = new QuickJSScriptRunner(); // One `bindHooks` per owner: the binder replaces an owner's hook // set on each call, so an owner is never bound twice. for (const group of bindable) { try { + // Per owner, so a body's door `origin` names the package + // that holds it, not the bundle. + const bodyRunner = hookBodyRunnerFactory(scriptRunner, { + ql, + logger, + appId, + i18n: options.i18n, + getService: options.getService, + originPackageId: handlerOwnerPackage(group.owner), + }); ql.bindHooks(group.hooks, { packageId: group.owner, functions: group.functions, @@ -443,28 +458,38 @@ export function bindAppArtifactHandlers( try { const total = actionGroups.reduce((sum, group) => sum + group.actions.length, 0); if (total > 0 && typeof ql.registerAction === 'function') { - const actionBodyRunner = actionBodyRunnerFactory(new QuickJSScriptRunner(), { ql, logger, appId }); - for (const { owner: actionOwner, actions } of actionGroups) for (const action of actions) { - const handler = actionBodyRunner(action); - if (!handler) continue; - // Object-less actions register under the canonical `'global'` - // key (#3913) — the literal every reader probes - // (`actionHandlerObjectKeys`), since `executeAction` is an - // exact-string Map lookup with no wildcard semantics. - const objectKey = - typeof action.object === 'string' && action.object.length > 0 - ? action.object - : GLOBAL_ACTION_OBJECT_KEY; - try { - ql.registerAction(objectKey, action.name, handler, actionOwner); - out.actions++; - } catch (err: any) { - logger.warn(`${tag} Failed to register action body`, { - appId, - action: action.name, - object: objectKey, - error: err?.message ?? String(err), - }); + const scriptRunner = new QuickJSScriptRunner(); + for (const { owner: actionOwner, actions } of actionGroups) { + // Per owner, so a body's door `origin` names the package that holds it. + const actionBodyRunner = actionBodyRunnerFactory(scriptRunner, { + ql, + logger, + appId, + getService: options.getService, + originPackageId: handlerOwnerPackage(actionOwner), + }); + for (const action of actions) { + const handler = actionBodyRunner(action); + if (!handler) continue; + // Object-less actions register under the canonical `'global'` + // key (#3913) — the literal every reader probes + // (`actionHandlerObjectKeys`), since `executeAction` is an + // exact-string Map lookup with no wildcard semantics. + const objectKey = + typeof action.object === 'string' && action.object.length > 0 + ? action.object + : GLOBAL_ACTION_OBJECT_KEY; + try { + ql.registerAction(objectKey, action.name, handler, actionOwner); + out.actions++; + } catch (err: any) { + logger.warn(`${tag} Failed to register action body`, { + appId, + action: action.name, + object: objectKey, + error: err?.message ?? String(err), + }); + } } } } @@ -1760,7 +1785,17 @@ export async function scheduleAppArtifactJobs( // D4, #15005). Identical reference on every bundle that carries no // `packages[]`. const collections = resolveArtifactCollections(bundle); - const bodyRunner = jobBodyRunnerFactory(new QuickJSScriptRunner(), { ql, logger, appId }); + const scriptRunner = new QuickJSScriptRunner(); + // Per job, so a body's door `origin` names the package that declares it + // (`declaringPackageOf`, below); the bundle's id where no one package does. + const bodyRunner = (job: Parameters>[0], packageId: string | undefined) => + jobBodyRunnerFactory(scriptRunner, { + ql, + logger, + appId, + getService: (name) => ctx.getService(name), + ...(packageId ? { originPackageId: packageId } : {}), + })(job); const metrics = resolveMetrics(ctx); // [#20281 stage ③] Jobs armed with NO organization on a posture whose // writes need one (`group`): legal, and refused at their first @@ -1887,7 +1922,8 @@ export async function scheduleAppArtifactJobs( } else if (job.body) { // The body wins over a `handler` beside it, as for hooks. When it // cannot be bound the factory has said why, and nothing runs. - const bound = bodyRunner({ ...job, organization }); + const declarer = declaringPackageOf(job); + const bound = bodyRunner({ ...job, organization }, typeof declarer === 'string' ? declarer : undefined); if (!bound) { out.notScheduled.push(jobName); continue; diff --git a/packages/runtime/src/app-plugin.ts b/packages/runtime/src/app-plugin.ts index 4c045551ee2..192673ea316 100644 --- a/packages/runtime/src/app-plugin.ts +++ b/packages/runtime/src/app-plugin.ts @@ -916,6 +916,7 @@ export class AppPlugin implements Plugin { logger: ctx.logger, appId: 'runtime-authored', i18n: hookRefusalI18nReader(ctx), + getService: (name) => ctx.getService(name), })); if (installed !== false) { ctx.logger.info('[AppPlugin] Installed default hook body runner (runtime-authored hooks can execute)'); @@ -956,6 +957,7 @@ export class AppPlugin implements Plugin { ql, logger: ctx.logger, appId: 'runtime-authored', + getService: (name) => ctx.getService(name), })); if (installed !== false) { ctx.logger.info('[AppPlugin] Installed default action body runner (runtime-authored actions can execute)'); @@ -1867,6 +1869,8 @@ export class AppPlugin implements Plugin { // [#26170] A hook's declared refusal is answered in the caller's // language, through the i18n service read at refusal time. i18n: hookRefusalI18nReader(ctx), + // The platform doors a body reaches, read at call time. + getService: (name) => ctx.getService(name), }); // [ADR-0110 D5] The action-governance inventory used to hang off a diff --git a/packages/runtime/src/sandbox/body-doors-caller-scope.integration.test.ts b/packages/runtime/src/sandbox/body-doors-caller-scope.integration.test.ts new file mode 100644 index 00000000000..0f126ed9949 --- /dev/null +++ b/packages/runtime/src/sandbox/body-doors-caller-scope.integration.test.ts @@ -0,0 +1,117 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A hook body's door reads the record it points at in the scope of the user + * whose write fired the hook: that write's own grants, never the system's. + * + * Measured in composition: a real `ObjectQL`, a real SQLite driver, the real + * hook wrapper and `QuickJSScriptRunner`. The pointed-at object is guarded by + * an engine middleware that stands in for the authorization door: it lets a + * read through only for a context that carries the `account_reader` grant and + * is not the system, and records every context it judged. + */ + +import { describe, it, expect, afterEach } from 'vitest'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { ObjectQL, bindHooksToEngine } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { hookBodyRunnerFactory } from './body-runner.js'; +import { QuickJSScriptRunner } from './quickjs-runner.js'; + +const TASK = { name: 'door_task', fields: { title: { type: 'text', name: 'title' } } }; +const ACCOUNT = { name: 'door_account', fields: { name: { type: 'text', name: 'name' } } }; + +describe('a hook body\'s door reads in the scope of the user whose write fired it', () => { + let engine: ObjectQL | null = null; + let dir: string | null = null; + + afterEach(async () => { + try { await engine?.destroy(); } catch { /* noop */ } + engine = null; + if (dir) { rmSync(dir, { recursive: true, force: true }); dir = null; } + }); + + async function boot() { + dir = mkdtempSync(join(tmpdir(), 'os-body-door-scope-')); + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: join(dir, 'data.sqlite') }, useNullAsDefault: true }); + await driver.initObjects([TASK, ACCOUNT]); + engine = new ObjectQL(); + engine.registerDriver(driver as any, true); + await engine.init(); + for (const o of [TASK, ACCOUNT]) engine.registry.registerObject(o as any); + const account = (await engine.insert('door_account', { name: 'Acme' }, { context: { isSystem: true } } as any)) as { id: string }; + + const judged: Array> = []; + engine.registerMiddleware( + async (op, next) => { + if (op.operation === 'findOne' || op.operation === 'find') { + const context = (op.context ?? {}) as Record; + judged.push(context); + const grants = Array.isArray(context.permissions) ? (context.permissions as string[]) : []; + if (context.isSystem === true || !grants.includes('account_reader')) { + throw Object.assign(new Error('not readable'), { code: 'PERMISSION_DENIED', statusCode: 403 }); + } + } + await next(); + }, + { object: 'door_account' }, + ); + + const appended: Array<{ entry: any; stamp: any }> = []; + const getService = (name: string): unknown => + name === 'audit' + ? { + appendAppActivity: async (entry: unknown, stamp: unknown) => { + appended.push({ entry, stamp }); + return { id: 'act_1' }; + }, + } + : undefined; + const bodyRunner = hookBodyRunnerFactory(new QuickJSScriptRunner(), { ql: engine, appId: 'door', getService }); + bindHooksToEngine( + engine, + [ + { + name: 'note_on_account', + object: 'door_task', + events: ['afterInsert'], + body: { + language: 'js', + source: `await ctx.activity.append({ object: 'door_account', recordId: '${account.id}', type: 'completed', summary: 'Task added' });`, + capabilities: ['activity.append'], + }, + } as any, + ], + { packageId: 'door', bodyRunner }, + ); + return { e: engine, accountId: account.id, judged, appended }; + } + + const ann = { userId: 'usr_ann', tenantId: 'org_acme', positions: ['member'] }; + + it('reads with the grants the write carried, so a record readable through an assigned permission set is found', async () => { + const { e, judged, appended } = await boot(); + await e.insert('door_task', { title: 'Call back' }, { context: { ...ann, permissions: ['account_reader'] } } as any); + expect(appended).toHaveLength(1); + expect(appended[0].stamp).toMatchObject({ actorId: 'usr_ann', organizationId: 'org_acme' }); + expect(judged.at(-1)).toMatchObject({ userId: 'usr_ann', permissions: ['account_reader'] }); + }, 30_000); + + it('reads as the user, not as the system, when the write that fired the hook ran elevated', async () => { + const { e, judged, appended } = await boot(); + await e.insert('door_task', { title: 'Call back' }, { context: { ...ann, permissions: ['account_reader'], isSystem: true } } as any); + expect(appended).toHaveLength(1); + expect(judged.at(-1)?.isSystem).not.toBe(true); + }, 30_000); + + it('refuses a record the user cannot read, and writes nothing', async () => { + const { e, appended } = await boot(); + const err = await e + .insert('door_task', { title: 'Call back' }, { context: { ...ann, permissions: ['other_set'], isSystem: true } } as any) + .then(() => null, (x) => x); + expect(String(err?.message ?? err)).toContain("no 'door_account' record"); + expect(appended).toHaveLength(0); + }, 30_000); +}); diff --git a/packages/runtime/src/sandbox/body-doors-capability.test.ts b/packages/runtime/src/sandbox/body-doors-capability.test.ts new file mode 100644 index 00000000000..6a55f9cf601 --- /dev/null +++ b/packages/runtime/src/sandbox/body-doors-capability.test.ts @@ -0,0 +1,250 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A body reaches `ctx.email.send` and `ctx.activity.append` only with the + * capability that names each, and the call reaches the door with the caller + * the platform resolved for the body's invocation. + */ + +import { describe, it, expect } from 'vitest'; +import { QuickJSScriptRunner, SandboxError } from './quickjs-runner.js'; +import { hookBodyRunnerFactory } from './body-runner.js'; +import type { ScriptRunOptions } from './script-runner.js'; + +const runner = new QuickJSScriptRunner({ hookTimeoutMs: 10_000, actionTimeoutMs: 10_000 }); +const actionOpts: ScriptRunOptions = { origin: { kind: 'action', name: 'send_quote' } }; + +async function refusalOf(run: () => Promise): Promise { + const e = await run().then(() => null, (err) => err as SandboxError); + expect(e, 'expected the sandbox to refuse, but the script resolved').toBeInstanceOf(SandboxError); + return e!; +} + +describe('the door capabilities gate ctx.email.send and ctx.activity.append', () => { + for (const [token, call] of [ + ['email.send', "ctx.email.send({ to: 'pat@example.test', subject: 'Hi', text: 'x' })"], + ['activity.append', "ctx.activity.append({ object: 'crm_contact', recordId: 'c1', type: 'completed', summary: 'x' })"], + ] as const) { + it(`refuses ${call.split('(')[0]} without '${token}', and never reaches the door`, async () => { + let reached = false; + const seam = async () => { + reached = true; + return {}; + }; + const err = await refusalOf(() => + runner.runScript( + { language: 'js', source: `return await ${call};`, capabilities: [] }, + { input: {}, email: { send: seam }, activity: { append: seam } }, + actionOpts, + ), + ); + expect(err.innerMessage).toContain(`capability '${token}' not granted to action 'send_quote'`); + expect(err.code).toBe('INSUFFICIENT_PRIVILEGES'); + expect(err.status).toBe(403); + expect(reached).toBe(false); + }); + } + + it('hands the body\'s input to the door and the door\'s answer back to the body', async () => { + const got: unknown[] = []; + const out = await runner.runScript( + { + language: 'js', + source: "var r = await ctx.email.send({ to: 'pat@example.test', subject: 'Hi', text: 'x' }); return r.id + ':' + r.status;", + capabilities: ['email.send'], + }, + { + input: {}, + email: { + send: async (input: unknown) => { + got.push(input); + return { id: 'em_1', status: 'queued' }; + }, + }, + }, + actionOpts, + ); + expect((out as { value: unknown }).value).toBe('em_1:queued'); + expect(got).toEqual([{ to: 'pat@example.test', subject: 'Hi', text: 'x' }]); + }); + + it('refuses a door call inside ctx.api.transaction, and serves one after it settles', async () => { + const reached: unknown[] = []; + const seam = async (input: unknown) => { + reached.push(input); + return { id: 'em_1', status: 'queued' }; + }; + const api = { object: () => ({}) }; + const err = await refusalOf(() => + runner.runScript( + { + language: 'js', + source: + "await ctx.api.transaction(async () => { await ctx.email.send({ to: 'pat@example.test', subject: 'Hi', text: 'x' }); });", + capabilities: ['api.transaction', 'email.send'], + }, + { input: {}, api, email: { send: seam } } as any, + actionOpts, + ), + ); + expect(err.innerMessage).toContain('ctx.email.send cannot be called inside ctx.api.transaction'); + expect(reached).toHaveLength(0); + + const out = await runner.runScript( + { + language: 'js', + source: + "await ctx.api.transaction(async () => {}); var r = await ctx.email.send({ to: 'pat@example.test', subject: 'Hi', text: 'x' }); return r.status;", + capabilities: ['api.transaction', 'email.send'], + }, + { input: {}, api, email: { send: seam } } as any, + actionOpts, + ); + expect((out as { value: unknown }).value).toBe('queued'); + expect(reached).toHaveLength(1); + }); + + it('tells a body on a host with no door that the door is not available', async () => { + const err = await refusalOf(() => + runner.runScript( + { + language: 'js', + source: "return await ctx.activity.append({ object: 'crm_contact', recordId: 'c1', type: 'completed', summary: 'x' });", + capabilities: ['activity.append'], + }, + { input: {} }, + actionOpts, + ), + ); + expect(err.innerMessage).toContain('ctx.activity.append is not available here'); + }); +}); + +describe('a hook body\'s timeline entry carries the user whose write fired it, and a hook body sends no mail', () => { + const mailService = (sent: unknown[]) => ({ + getDefaultFrom: () => ({ name: 'Acme CRM', address: 'noreply@acme.test' }), + send: async (input: unknown) => { + sent.push(input); + return { id: 'em_1', status: 'queued' }; + }, + }); + + it('stamps the session\'s user and organization, and the hook as the origin', async () => { + const appended: any[] = []; + const ql = { findOne: async (object: string, query: any) => (object === 'crm_contact' ? { id: query.where.id } : null) }; + const getService = (name: string): unknown => + name === 'audit' + ? { + appendAppActivity: async (entry: unknown, stamp: unknown) => { + appended.push({ entry, stamp }); + return { id: 'act_1' }; + }, + } + : undefined; + const factory = hookBodyRunnerFactory(runner, { ql, appId: 'com.acme.crm', getService } as any); + const fn = factory({ + name: 'note_new_contact', + object: 'crm_contact', + events: ['afterInsert'], + body: { + language: 'js', + source: "await ctx.activity.append({ object: 'crm_contact', recordId: 'c1', type: 'completed', summary: 'Welcomed' });", + capabilities: ['activity.append'], + }, + } as any); + await fn!({ + object: 'crm_contact', + event: 'afterInsert', + input: {}, + result: { id: 'c1' }, + session: { userId: 'usr_ann', organizationId: 'org_acme' }, + } as any); + + expect(appended).toEqual([ + { + entry: { object: 'crm_contact', recordId: 'c1', type: 'completed', summary: 'Welcomed' }, + stamp: { actorId: 'usr_ann', organizationId: 'org_acme', origin: 'com.acme.crm/hook:note_new_contact' }, + }, + ]); + }); + + it('refuses to bind a hook body granted email.send', () => { + const sent: unknown[] = []; + const getService = (name: string): unknown => (name === 'email' ? mailService(sent) : undefined); + const factory = hookBodyRunnerFactory(runner, { ql: {}, appId: 'com.acme.crm', getService } as any); + let thrown: any; + try { + factory({ + name: 'mail_new_contact', + object: 'crm_contact', + events: ['afterInsert'], + body: { + language: 'js', + source: "await ctx.email.send({ to: 'pat@example.test', subject: 'Welcome', text: 'Hello' });", + capabilities: ['email.send'], + }, + } as any); + } catch (err) { + thrown = err; + } + expect(thrown?.message).toContain("Hook 'mail_new_contact' was not bound: its body is granted `email.send`"); + expect(thrown).toMatchObject({ code: 'PERMISSION_DENIED', statusCode: 403 }); + expect(sent).toHaveLength(0); + }); + + it('refuses a hook body\'s mail call it was not granted, and sends nothing', async () => { + const sent: unknown[] = []; + const getService = (name: string): unknown => (name === 'email' ? mailService(sent) : undefined); + const factory = hookBodyRunnerFactory(runner, { ql: {}, appId: 'com.acme.crm', getService } as any); + const fn = factory({ + name: 'mail_new_contact', + object: 'crm_contact', + events: ['afterInsert'], + body: { language: 'js', source: "await ctx.email.send({ to: 'pat@example.test', subject: 'Welcome', text: 'Hello' });" }, + } as any); + const err: any = await fn!({ + object: 'crm_contact', + event: 'afterInsert', + input: {}, + result: { id: 'c1' }, + session: { userId: 'usr_ann', organizationId: 'org_acme' }, + } as any).then( + () => null, + (x: unknown) => x, + ); + expect(String(err?.innerMessage ?? err?.message ?? err)).toContain("capability 'email.send' not granted to hook 'mail_new_contact'"); + expect(sent).toHaveLength(0); + }); + + it('names the package that holds the body in the origin, not the bundle', async () => { + const appended: any[] = []; + const getService = (name: string): unknown => + name === 'audit' + ? { + appendAppActivity: async (entry: unknown, stamp: unknown) => { + appended.push({ entry, stamp }); + return { id: 'act_1' }; + }, + } + : undefined; + const ql = { findOne: async (_object: string, query: any) => ({ id: query.where.id }) }; + const factory = hookBodyRunnerFactory(runner, { + ql, + appId: 'com.acme.bundle', + originPackageId: 'com.acme.crm', + getService, + } as any); + const fn = factory({ + name: 'note_contact', + object: 'crm_contact', + events: ['afterInsert'], + body: { + language: 'js', + source: "await ctx.activity.append({ object: 'crm_contact', recordId: 'c1', type: 'completed', summary: 'x' });", + capabilities: ['activity.append'], + }, + } as any); + await fn!({ object: 'crm_contact', event: 'afterInsert', input: {}, result: { id: 'c1' }, session: { userId: 'usr_ann', organizationId: 'org_acme' } } as any); + expect(appended[0].stamp.origin).toBe('com.acme.crm/hook:note_contact'); + }); +}); diff --git a/packages/runtime/src/sandbox/body-doors-transaction.integration.test.ts b/packages/runtime/src/sandbox/body-doors-transaction.integration.test.ts new file mode 100644 index 00000000000..549e058a2e7 --- /dev/null +++ b/packages/runtime/src/sandbox/body-doors-transaction.integration.test.ts @@ -0,0 +1,191 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A hook body sends no mail, and a body's timeline entry commits or rolls back + * with the write that runs the body. + * + * Measured in composition: a real `ObjectQL`, a real SQLite driver (one + * connection), the real hook wrapper and `QuickJSScriptRunner`. The timeline + * writer is a stand-in that writes its entry through the engine as the + * platform, under the transaction handle it is passed, as the activity feed's + * own writer does (`app-activity-door.ts`, `@objectstack/plugin-audit`). + */ + +import { describe, it, expect, afterEach } from 'vitest'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { ObjectQL, bindHooksToEngine, openTransactionKind } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { hookBodyRunnerFactory } from './body-runner.js'; +import { QuickJSScriptRunner } from './quickjs-runner.js'; + +const TASK = { name: 'txd_task', fields: { title: { type: 'text', name: 'title' } } }; +const ACCOUNT = { name: 'txd_account', fields: { name: { type: 'text', name: 'name' } } }; +const ENTRY = { name: 'txd_entry', fields: { summary: { type: 'text', name: 'summary' } } }; + +describe('a body\'s door and the transaction of the write that runs it', () => { + let engine: ObjectQL | null = null; + let dir: string | null = null; + + afterEach(async () => { + try { await engine?.destroy(); } catch { /* noop */ } + engine = null; + if (dir) { rmSync(dir, { recursive: true, force: true }); dir = null; } + }); + + async function boot(source: string, capabilities: string[]) { + dir = mkdtempSync(join(tmpdir(), 'os-body-door-tx-')); + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: join(dir, 'data.sqlite') }, useNullAsDefault: true }); + await driver.initObjects([TASK, ACCOUNT, ENTRY]); + const e = new ObjectQL(); + engine = e; + e.registerDriver(driver as any, true); + await e.init(); + for (const o of [TASK, ACCOUNT, ENTRY]) e.registry.registerObject(o as any); + const account = (await e.insert('txd_account', { name: 'Acme' }, { context: { isSystem: true } } as any)) as { id: string }; + + const sent: unknown[] = []; + const getService = (name: string): unknown => { + if (name === 'email') { + return { + getDefaultFrom: () => ({ address: 'noreply@acme.test' }), + send: async (input: unknown) => { + sent.push(input); + return { id: 'em_1', status: 'sent' }; + }, + }; + } + if (name === 'audit') { + return { + appendAppActivity: async (entry: { summary: string }, _stamp: unknown, options?: { transaction?: unknown }) => + (await e.insert('txd_entry', { summary: entry.summary }, { + context: { isSystem: true, ...(options?.transaction != null ? { transaction: options.transaction } : {}) }, + } as any)) as { id: string }, + }; + } + return undefined; + }; + const bodyRunner = hookBodyRunnerFactory(new QuickJSScriptRunner(), { ql: e, appId: 'txd', getService }); + const bound = bindHooksToEngine( + e, + [ + { + name: 'on_task', + object: 'txd_task', + events: ['afterInsert'], + body: { language: 'js', source: source.replace('ACCOUNT_ID', account.id), capabilities }, + } as any, + ], + { packageId: 'txd', bodyRunner }, + ); + return { e, sent, bound }; + } + + const ann = { userId: 'usr_ann', tenantId: 'org_acme', permissions: ['reader'] }; + const mail = "await ctx.email.send({ to: 'pat@example.test', subject: 'Task added', text: 'x' });"; + const entry = "await ctx.activity.append({ object: 'txd_account', recordId: 'ACCOUNT_ID', type: 'completed', summary: 'Task added' });"; + + it('refuses to bind a hook body granted email.send, so its write sends no mail', async () => { + const { e, sent, bound } = await boot(mail, ['email.send']); + expect(bound.registered).toBe(0); + expect(bound.errors.map((x) => x.reason)).toEqual([ + expect.stringContaining("Hook 'on_task' was not bound: its body is granted `email.send`"), + ]); + await e.insert('txd_task', { title: 'Call back' }, { context: ann } as any); + expect(sent).toHaveLength(0); + }, 30_000); + + it('sends no mail from a hook body whose write runs inside a transaction', async () => { + const { e, sent } = await boot(mail, []); + const err = await e + .transaction(async (trx: any) => { + await e.insert('txd_task', { title: 'Call back' }, { context: trx } as any); + }, ann) + .then(() => null, (x: unknown) => x); + expect(String((err as Error | null)?.message ?? err)).toContain("capability 'email.send' not granted to hook 'on_task'"); + expect(sent).toHaveLength(0); + expect(await e.find('txd_task', {})).toHaveLength(0); + }, 30_000); + + it('keeps a timeline entry when the write that runs the body commits, and drops it when it rolls back', async () => { + const { e } = await boot(entry, ['activity.append']); + await e.transaction(async (trx: any) => { + await e.insert('txd_task', { title: 'Kept' }, { context: trx } as any); + }, ann); + expect(await e.find('txd_entry', {})).toHaveLength(1); + + await e + .transaction(async (trx: any) => { + await e.insert('txd_task', { title: 'Dropped' }, { context: trx } as any); + throw new Error('the caller gives up'); + }, ann) + .catch(() => undefined); + expect(await e.find('txd_entry', {})).toHaveLength(1); + expect(await e.find('txd_task', {})).toHaveLength(1); + }, 30_000); + + it('keeps a timeline entry when a write under a transaction handle commits, and drops it when it rolls back', async () => { + const { e } = await boot(entry, ['activity.append']); + const kept = await e.createContext(ann as any).beginTransaction(); + expect(kept, 'precondition: the driver opens transactions').not.toBeNull(); + await kept!.ctx.object('txd_task').insert({ title: 'Kept' }); + await e.createContext(ann as any).commitTransaction(kept!.handle); + expect(await e.find('txd_entry', {})).toHaveLength(1); + + const dropped = await e.createContext(ann as any).beginTransaction(); + await dropped!.ctx.object('txd_task').insert({ title: 'Dropped' }); + await e.createContext(ann as any).rollbackTransaction(dropped!.handle); + expect(await e.find('txd_entry', {})).toHaveLength(1); + expect(await e.find('txd_task', {})).toHaveLength(1); + }, 30_000); +}); + +describe('where a write stands with respect to a transaction, read off a real engine', () => { + let engine: ObjectQL | null = null; + let dir: string | null = null; + + afterEach(async () => { + try { await engine?.destroy(); } catch { /* noop */ } + engine = null; + if (dir) { rmSync(dir, { recursive: true, force: true }); dir = null; } + }); + + async function boot() { + dir = mkdtempSync(join(tmpdir(), 'os-open-tx-')); + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: join(dir, 'data.sqlite') }, useNullAsDefault: true }); + await driver.initObjects([TASK]); + const e = new ObjectQL(); + engine = e; + e.registerDriver(driver as any, true); + await e.init(); + e.registry.registerObject(TASK as any); + return e; + } + + const ann = { userId: 'usr_ann', tenantId: 'org_acme' }; + + it('answers none outside a transaction, and joined inside the engine\'s own, carried or not', async () => { + const e = await boot(); + expect(openTransactionKind(e)).toBe('none'); + const inside: string[] = []; + let handle: unknown; + await e.transaction(async (trx: any) => { + handle = trx.transaction; + inside.push(openTransactionKind(e), openTransactionKind(e, trx.transaction)); + await e.insert('txd_task', { title: 'Inside' }, { context: trx } as any); + inside.push(openTransactionKind(e)); + }, ann); + expect(inside).toEqual(['joined', 'joined', 'joined']); + expect(openTransactionKind(e)).toBe('none'); + expect(openTransactionKind(e, handle)).toBe('none'); + }, 30_000); + + it('answers separate for an open handle the engine\'s own transaction does not hold', async () => { + const e = await boot(); + const opened = await e.createContext(ann as any).beginTransaction(); + expect(opened, 'precondition: the driver opens transactions').not.toBeNull(); + expect(openTransactionKind(e, opened!.handle)).toBe('separate'); + await e.createContext(ann as any).rollbackTransaction(opened!.handle); + }, 30_000); +}); diff --git a/packages/runtime/src/sandbox/body-doors.test.ts b/packages/runtime/src/sandbox/body-doors.test.ts new file mode 100644 index 00000000000..857a7420d4a --- /dev/null +++ b/packages/runtime/src/sandbox/body-doors.test.ts @@ -0,0 +1,295 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * `ctx.email.send` and `ctx.activity.append`: a body's mail and timeline + * entries carry the caller the platform resolved, never one the body names. + * + * Each door is driven through {@link buildBodyDoors} with a recording mail + * service, a recording activity writer and a data layer that answers only the + * records the caller can read. + */ + +import { describe, it, expect, afterEach, vi } from 'vitest'; +import { + BODY_ACTIVITY_METADATA_LIMIT, + BODY_MAIL_ADDRESS_LIMIT, + BODY_MAIL_ADDRESS_LIST_LIMIT, + BODY_MAIL_RECIPIENT_LIMIT, +} from '@objectstack/spec/data'; +import { buildBodyDoors, appMailHourlyLimit, callerScopeOf, DEFAULT_APP_MAIL_HOURLY_LIMIT, type BodyDoorCaller, type BodyDoorTransaction } from './body-doors.js'; +import { APP_AUTOMATION_ELEVATION } from '@objectstack/core'; + +const ANN: BodyDoorCaller = { userId: 'usr_ann', organizationId: 'org_acme', readContext: { userId: 'usr_ann', tenantId: 'org_acme' } }; + +function world(opts: { readable?: string[]; sentLastHour?: number; from?: unknown; noEmail?: boolean; noAudit?: boolean } = {}) { + const readable = new Set(opts.readable ?? ['crm_contact/c1', 'sys_email/e1']); + const reads: Array<{ object: string; context: unknown }> = []; + const counts: Array<{ where: unknown }> = []; + const sent: any[] = []; + const appended: Array<{ entry: any; stamp: any; options?: any }> = []; + const ql = { + async findOne(object: string, query: any, options: any) { + const id = query?.where?.id; + if (object === 'sys_user' && id === 'usr_ann') return { id, name: 'Ann "The" Lee' }; + if (object === 'sys_organization' && id === 'org_acme') return { id, name: 'Acme ' }; + reads.push({ object, context: options?.context }); + return readable.has(`${object}/${id}`) ? { id } : null; + }, + async count(_object: string, query: any) { + counts.push({ where: query?.where }); + return opts.sentLastHour ?? 0; + }, + }; + const email = { + getDefaultFrom: () => ('from' in opts ? opts.from : { name: 'Acme CRM', address: 'noreply@acme.test' }), + async send(input: any) { + sent.push(input); + return { id: 'em_1', status: 'queued' }; + }, + }; + const audit = { + async appendAppActivity(entry: any, stamp: any, options?: any) { + appended.push({ entry, stamp, ...(options !== undefined ? { options } : {}) }); + return { id: 'act_1' }; + }, + }; + const getService = (name: string) => { + if (name === 'email') return opts.noEmail ? undefined : email; + if (name === 'audit') return opts.noAudit ? undefined : audit; + throw new Error(`no service '${name}'`); + }; + return { ql, getService, reads, counts, sent, appended }; +} + +function doors( + w: ReturnType, + caller: BodyDoorCaller = ANN, + openTransaction?: () => BodyDoorTransaction, + kind: 'hook' | 'action' | 'job' = 'action', +) { + return buildBodyDoors({ + ql: w.ql, + getService: w.getService, + packageId: 'com.acme.crm', + origin: { kind, name: 'send_quote' }, + caller, + ...(openTransaction ? { openTransaction } : {}), + }); +} + +const message = { to: 'pat@example.test', subject: 'Quote', text: 'Attached.' }; +const entry = { object: 'crm_contact', recordId: 'c1', type: 'completed', summary: 'Email: Quote' }; + +describe('ctx.email.send sends as the calling user, under the caller\'s organization, from the configured sender', () => { + it('stamps the sending user and organization, and names the user beside the organization in the sender', async () => { + const w = world(); + const out = await doors(w).email.send({ ...message, related: { object: 'crm_contact', id: 'c1' } }); + expect(out).toEqual({ id: 'em_1', status: 'queued' }); + expect(w.sent).toHaveLength(1); + expect(w.sent[0]).toMatchObject({ + ...message, + sentBy: 'usr_ann', + organizationId: 'org_acme', + relatedObject: 'crm_contact', + relatedId: 'c1', + from: { name: 'Ann The Lee via Acme Corp', address: 'noreply@acme.test' }, + }); + }); + + it('reads the related record in the caller\'s own scope, and refuses one the caller cannot read without sending', async () => { + const w = world({ readable: [] }); + await expect(doors(w).email.send({ ...message, related: { object: 'crm_contact', id: 'c1' } })).rejects.toMatchObject({ + code: 'RECORD_NOT_FOUND', + statusCode: 404, + }); + expect(w.reads).toEqual([{ object: 'crm_contact', context: ANN.readContext }]); + expect(w.sent).toHaveLength(0); + }); + + for (const key of ['from', 'sentBy', 'organizationId', 'headers', 'identityMail']) { + it(`refuses a message naming \`${key}\` and sends nothing`, async () => { + const w = world(); + await expect(doors(w).email.send({ ...message, [key]: 'x' })).rejects.toMatchObject({ code: 'VALIDATION_ERROR', statusCode: 400 }); + expect(w.sent).toHaveLength(0); + }); + } + + it(`refuses more than ${BODY_MAIL_RECIPIENT_LIMIT} recipients across to, cc and bcc`, async () => { + const w = world(); + const list = (n: number, tag: string) => Array.from({ length: n }, (_, i) => `${tag}${i}@example.test`); + await expect( + doors(w).email.send({ ...message, to: list(30, 't'), cc: list(15, 'c'), bcc: list(6, 'b') }), + ).rejects.toMatchObject({ code: 'VALIDATION_ERROR' }); + expect(w.sent).toHaveLength(0); + }); + + it(`refuses a slot that takes more than ${BODY_MAIL_ADDRESS_LIST_LIMIT} characters as the mail log records it`, async () => { + const w = world(); + const long = (i: number) => ({ name: 'N'.repeat(150), address: `r${i}@example.test` }); + await expect( + doors(w).email.send({ ...message, cc: Array.from({ length: 30 }, (_, i) => long(i)) }), + ).rejects.toMatchObject({ code: 'VALIDATION_ERROR' }); + expect(w.sent).toHaveLength(0); + }); + + it(`refuses a replyTo that takes more than ${BODY_MAIL_ADDRESS_LIMIT} characters as recorded`, async () => { + const w = world(); + await expect( + doors(w).email.send({ ...message, replyTo: { name: '"'.repeat(150), address: 'desk@example.test' } }), + ).rejects.toMatchObject({ code: 'VALIDATION_ERROR' }); + expect(w.sent).toHaveLength(0); + }); + + it('asks the mail service to send only what its log records', async () => { + const w = world(); + await doors(w).email.send(message); + expect(w.sent[0]).toMatchObject({ requireLogRow: true }); + }); + + it('cuts the sender\'s display name so the sender fits the mail log', async () => { + const address = `${'a'.repeat(200)}@acme.test`; + const w = world({ from: { name: 'Acme CRM', address } }); + await doors(w).email.send(message); + const from = w.sent[0].from as { name?: string; address: string }; + expect(from.address).toBe(address); + expect((from.name ?? '').length + 5 + address.length).toBeLessThanOrEqual(BODY_MAIL_ADDRESS_LIMIT); + }); + + it('refuses a send once the organization\'s mail log records the hourly limit, counted for that organization', async () => { + const w = world({ sentLastHour: DEFAULT_APP_MAIL_HOURLY_LIMIT }); + await expect(doors(w).email.send(message)).rejects.toMatchObject({ code: 'RATE_LIMIT_EXCEEDED', statusCode: 429 }); + expect(w.sent).toHaveLength(0); + expect(w.counts[0].where).toMatchObject({ organization_id: 'org_acme' }); + }); + + it('says the whole log was counted for a caller with no organization', async () => { + const w = world({ sentLastHour: DEFAULT_APP_MAIL_HOURLY_LIMIT }); + const job: BodyDoorCaller = { userId: undefined, organizationId: undefined, readContext: {} }; + await expect(doors(w, job).email.send(message)).rejects.toThrow(/with no organization to count by, the whole mail log records/); + expect(w.counts[0].where).not.toHaveProperty('organization_id'); + }); + + it('sends with no user recorded for a body with no calling user', async () => { + const w = world(); + const job: BodyDoorCaller = { userId: undefined, organizationId: 'org_acme', readContext: { isSystem: true, tenantId: 'org_acme' } }; + await doors(w, job).email.send(message); + expect(w.sent[0]).not.toHaveProperty('sentBy'); + expect(w.sent[0]).toMatchObject({ organizationId: 'org_acme', from: { name: 'Acme CRM', address: 'noreply@acme.test' } }); + }); + + it('answers NOT_IMPLEMENTED where the deployment has no mail service', async () => { + await expect(doors(world({ noEmail: true })).email.send(message)).rejects.toMatchObject({ code: 'NOT_IMPLEMENTED', statusCode: 501 }); + }); +}); + +describe('ctx.activity.append adds an entry stamped with the caller and the body that wrote it', () => { + it('hands the writer the stamped actor, organization and origin', async () => { + const w = world(); + const out = await doors(w).activity.append({ ...entry, source: { object: 'sys_email', id: 'e1' } }); + expect(out).toEqual({ id: 'act_1' }); + expect(w.appended).toEqual([ + { + entry: { ...entry, source: { object: 'sys_email', id: 'e1' } }, + stamp: { actorId: 'usr_ann', organizationId: 'org_acme', origin: 'com.acme.crm/action:send_quote' }, + }, + ]); + }); + + for (const key of ['actor_id', 'organization_id', 'origin']) { + it(`refuses an entry naming \`${key}\` and writes nothing`, async () => { + const w = world(); + await expect(doors(w).activity.append({ ...entry, [key]: 'x' })).rejects.toMatchObject({ code: 'VALIDATION_ERROR' }); + expect(w.appended).toHaveLength(0); + }); + } + + it('refuses an entry about a record, or pointing at a source, the caller cannot read, and writes nothing', async () => { + const w1 = world({ readable: [] }); + await expect(doors(w1).activity.append(entry)).rejects.toMatchObject({ code: 'RECORD_NOT_FOUND' }); + const w2 = world({ readable: ['crm_contact/c1'] }); + await expect(doors(w2).activity.append({ ...entry, source: { object: 'sys_email', id: 'e9' } })).rejects.toMatchObject({ + code: 'RECORD_NOT_FOUND', + }); + expect([...w1.appended, ...w2.appended]).toHaveLength(0); + }); + + it(`refuses metadata that takes more than ${BODY_ACTIVITY_METADATA_LIMIT} characters as JSON, and writes nothing`, async () => { + const w = world(); + await expect( + doors(w).activity.append({ ...entry, metadata: { note: 'x'.repeat(BODY_ACTIVITY_METADATA_LIMIT) } }), + ).rejects.toMatchObject({ code: 'VALIDATION_ERROR' }); + expect(w.appended).toHaveLength(0); + }); + + it('answers NOT_IMPLEMENTED where the deployment has no activity feed', async () => { + await expect(doors(world({ noAudit: true })).activity.append(entry)).rejects.toMatchObject({ code: 'NOT_IMPLEMENTED' }); + }); +}); + +describe('a hook body sends no mail', () => { + it('refuses mail from a hook body, with or without a transaction, and sends nothing', async () => { + for (const kind of ['none', 'joined', 'separate'] as const) { + const w = world(); + await expect(doors(w, ANN, () => ({ kind }), 'hook').email.send(message)).rejects.toMatchObject({ + code: 'PERMISSION_DENIED', + statusCode: 403, + message: expect.stringContaining('ctx.email.send cannot be called from a hook body'), + }); + expect(w.sent).toHaveLength(0); + expect(w.counts).toHaveLength(0); + } + }); + + it('adds a hook body\'s timeline entry', async () => { + const w = world(); + await expect(doors(w, ANN, undefined, 'hook').activity.append(entry)).resolves.toEqual({ id: 'act_1' }); + }); +}); + +describe('a door and the transaction of the write that runs the body', () => { + for (const kind of ['joined', 'separate'] as const) { + it(`refuses mail from an action inside a transaction (${kind}), and sends nothing`, async () => { + const w = world(); + await expect(doors(w, ANN, () => ({ kind, handle: 'trx_1' })).email.send(message)).rejects.toMatchObject({ + code: 'RESOURCE_CONFLICT', + statusCode: 409, + }); + expect(w.sent).toHaveLength(0); + expect(w.counts).toHaveLength(0); + }); + } + + it('writes a timeline entry in the transaction the write joins, handing the writer no handle', async () => { + const w = world(); + await expect(doors(w, ANN, () => ({ kind: 'joined' })).activity.append(entry)).resolves.toEqual({ id: 'act_1' }); + expect(w.appended[0]).not.toHaveProperty('options'); + }); + + it('writes a timeline entry under the handle the write carries, so it commits or rolls back with it', async () => { + const w = world(); + await expect(doors(w, ANN, () => ({ kind: 'separate', handle: 'trx_1' })).activity.append(entry)).resolves.toEqual({ + id: 'act_1', + }); + expect(w.appended[0].options).toEqual({ transaction: 'trx_1' }); + }); +}); + +describe('the caller\'s scope and the hourly limit', () => { + afterEach(() => vi.unstubAllEnvs()); + + it('takes the body\'s elevation off the caller\'s envelope', () => { + const elevated = { userId: 'usr_ann', tenantId: 'org_acme', isSystem: true, [APP_AUTOMATION_ELEVATION]: 'action' }; + expect(callerScopeOf(elevated)).toEqual({ userId: 'usr_ann', tenantId: 'org_acme' }); + expect(callerScopeOf({ isSystem: true })).toEqual({ isSystem: true }); + }); + + it('answers a scope with no principal for no context', () => { + expect(callerScopeOf(undefined)).toEqual({}); + }); + + it('reads OS_EMAIL_APP_SEND_HOURLY_LIMIT, and refuses a value that is not a whole number', () => { + expect(appMailHourlyLimit({})).toBe(DEFAULT_APP_MAIL_HOURLY_LIMIT); + expect(appMailHourlyLimit({ OS_EMAIL_APP_SEND_HOURLY_LIMIT: '25' })).toBe(25); + expect(() => appMailHourlyLimit({ OS_EMAIL_APP_SEND_HOURLY_LIMIT: 'lots' })).toThrow(/whole number/); + }); +}); diff --git a/packages/runtime/src/sandbox/body-doors.ts b/packages/runtime/src/sandbox/body-doors.ts new file mode 100644 index 00000000000..6a975090f94 --- /dev/null +++ b/packages/runtime/src/sandbox/body-doors.ts @@ -0,0 +1,431 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The two platform doors a sandboxed script body reaches: `ctx.email.send` + * (capability `email.send`) hands a message to the mail service, and + * `ctx.activity.append` (capability `activity.append`) adds one entry to a + * record's activity timeline. A body asks for each by its token; the sandbox + * (`quickjs-runner.ts`) refuses a call whose token the body did not declare, + * and calls the host seam built here for one that it did. + * + * What a body says is parsed against the door's spec schema + * (`BodyMailSendInputSchema`, `BodyActivityAppendInputSchema`, + * `@objectstack/spec/data`); a key outside it is refused, never dropped. What + * the platform says is stamped here from the HOST's view of the call, never + * from the body's copy of `ctx.user` (a JSON copy the body can change): + * + * - the calling user and organization ({@link BodyDoorCaller}), resolved by + * the body runner from the engine's context for the hook, the action door's + * caller envelope, or a job's declared organization; + * - the origin, `/:` of the body. + * + * Every record a body points at (the mail's `related` record, the timeline + * entry's record and its `source`) is read in the CALLER's scope before the + * door acts, and one the caller cannot read is answered as one that does not + * exist. + * + * Mail: the bounds both mail doors share (`boundCallerMail`, + * `@objectstack/core`) stamp the sending user and the organization; the + * sender is the configured address, with a display name naming the calling + * user beside the organization; at most `BODY_MAIL_RECIPIENT_LIMIT` recipients + * per message across `to`, `cc` and `bcc` (each slot by the schema, the sum + * here), each slot and a `replyTo` within what the mail log's columns hold as + * recorded; no send while the organization's mail log already records + * {@link appMailHourlyLimit} messages in the last hour; no send at all + * unless the mail log records it (`requireLogRow`). A message cannot be taken + * back, so none is sent from a hook body, whose write may still roll back, nor + * from an action or a job running inside a transaction. The hourly count is read + * before the send and is not held across it, so callers racing the last free + * slot can each pass it: the limit bounds a body's volume, not an exact count. + * + * Timeline: the entry is written by the activity feed's owner + * (`appendAppActivity` on the `audit` service, `@objectstack/plugin-audit`), + * which holds the ledger's own rules (no platform-only type or metadata key, + * no excluded or append-only object) and writes the row as the platform. The + * entry is written in the transaction of the write that runs the body, and + * commits or rolls back with it. + */ + +import { + BODY_ACTIVITY_METADATA_LIMIT, + BODY_MAIL_ADDRESS_LIMIT, + BODY_MAIL_ADDRESS_LIST_LIMIT, + BODY_MAIL_RECIPIENT_LIMIT, + BodyActivityAppendInputSchema, + BodyMailSendInputSchema, + type BodyActivityAppendInput, + type BodyMailSendInput, +} from '@objectstack/spec/data'; +import type { EmailAddress, IEmailService, SendEmailInput } from '@objectstack/spec/contracts'; +import { APP_AUTOMATION_ELEVATION, boundCallerMail, mailAddressOf } from '@objectstack/core'; + +/** Who is calling, as the host resolved it for one body invocation. */ +export interface BodyDoorCaller { + /** The calling user, or `undefined` for a body with none (a scheduled job). */ + userId: string | undefined; + /** The caller's active organization, or `undefined` when it has none. */ + organizationId: string | undefined; + /** The execution context a record the body points at is read in: the caller's own. */ + readContext?: Record; + /** + * Read one record in the caller's own scope, answering the row or nothing. + * Where the host holds the caller's scope as an api rather than a context + * (a hook: `body-runner.ts`), it reads through this, and `readContext` is + * not read. + */ + readRecord?: (object: string, id: string) => Promise; +} + +/** What the body runner hands {@link buildBodyDoors} for one invocation. */ +export interface BodyDoorOptions { + ql: any; + /** Kernel service lookup, read at call time; `undefined` when the runner was built without one. */ + getService?: (name: string) => unknown; + /** The package the body belongs to — the first part of the origin. */ + packageId: string; + origin: { kind: 'hook' | 'action' | 'job'; name: string }; + caller: BodyDoorCaller; + /** + * The transaction the write that runs this body stands in, read at call + * time: `kind` as `openTransactionKind` (`@objectstack/objectql`) answers it, + * and, for `'separate'`, the `handle` a write beside it carries to join it. + * Absent, `{ kind: 'none' }`. + */ + openTransaction?: () => BodyDoorTransaction; +} + +/** Where the write that runs a body stands with respect to a transaction. */ +export interface BodyDoorTransaction { + kind: 'none' | 'joined' | 'separate'; + /** The handle a write beside it carries to join it; given for `'separate'`. */ + handle?: unknown; +} + +/** The host seams installed on the body's `ctx`. */ +export interface BodyDoors { + email: { send(input: unknown): Promise<{ id: string; status: string }> }; + activity: { append(input: unknown): Promise<{ id: string }> }; +} + +/** Default for {@link appMailHourlyLimit}. */ +export const DEFAULT_APP_MAIL_HOURLY_LIMIT = 200; + +/** + * The most messages an organization's mail log may record in one hour before + * `ctx.email.send` refuses another: `OS_EMAIL_APP_SEND_HOURLY_LIMIT`, else + * {@link DEFAULT_APP_MAIL_HOURLY_LIMIT}. Counted on the mail log, so every + * node of a cluster sees the same count. + */ +export function appMailHourlyLimit(env: Record = process.env): number { + const raw = env.OS_EMAIL_APP_SEND_HOURLY_LIMIT; + if (raw === undefined || raw.trim() === '') return DEFAULT_APP_MAIL_HOURLY_LIMIT; + const n = Number(raw); + if (!Number.isInteger(n) || n < 0) { + throw new Error( + `OS_EMAIL_APP_SEND_HOURLY_LIMIT must be a whole number of messages, 0 or more; it is '${raw}'.`, + ); + } + return n; +} + +type DoorCode = + | 'VALIDATION_ERROR' + | 'RECORD_NOT_FOUND' + | 'RATE_LIMIT_EXCEEDED' + | 'NOT_IMPLEMENTED' + | 'PERMISSION_DENIED' + | 'RESOURCE_CONFLICT'; +const STATUS: Record = { + VALIDATION_ERROR: 400, + PERMISSION_DENIED: 403, + RECORD_NOT_FOUND: 404, + RESOURCE_CONFLICT: 409, + RATE_LIMIT_EXCEEDED: 429, + NOT_IMPLEMENTED: 501, +}; + +function doorError(code: DoorCode, message: string): Error { + return Object.assign(new Error(message), { code, status: STATUS[code], statusCode: STATUS[code] }); +} + +/** Parse a body's input, or throw the door's `VALIDATION_ERROR` naming each problem. */ +function parseInput( + schema: { safeParse(v: unknown): { success: true; data: T } | { success: false; error: { issues: Array<{ path: PropertyKey[]; message: string }> } } }, + input: unknown, + door: string, +): T { + const parsed = schema.safeParse(input); + if (parsed.success) return parsed.data; + const lines = parsed.error.issues + .slice(0, 5) + .map((i) => `${i.path.length > 0 ? i.path.map(String).join('.') + ': ' : ''}${i.message}`); + throw doorError('VALIDATION_ERROR', `${door} was called with input it does not take: ${lines.join('; ')}`); +} + +/** The number of addresses one recipient slot names. */ +function recipientCount(value: unknown): number { + if (value === undefined) return 0; + return Array.isArray(value) ? value.length : 1; +} + +/** + * The characters one address takes as the mail log records it: the bare + * address, or `"Name"
` with each `"` in the name escaped. Read the + * way {@link BodyMailSendInputSchema}'s description states the limits, with + * every display name counted as quoted. + */ +function recordedAddressLength(value: unknown): number { + if (typeof value === 'string') return value.trim().length; + const { name, address } = value as { name?: string; address: string }; + const shown = name?.trim() ?? ''; + const bare = address.trim().length; + return shown.length === 0 ? bare : shown.length + (shown.match(/"/g)?.length ?? 0) + 5 + bare; +} + +/** The characters one recipient slot takes as recorded: its addresses joined by `", "`. */ +function recordedSlotLength(value: unknown): number { + if (value === undefined) return 0; + const list = Array.isArray(value) ? value : [value]; + return list.reduce((sum: number, a) => sum + recordedAddressLength(a), 0) + 2 * Math.max(0, list.length - 1); +} + +/** Refuse a message whose slots, as recorded, exceed what the mail log's columns hold. */ +function refuseOverRecordedLimits(message: BodyMailSendInput): void { + const recipients = recipientCount(message.to) + recipientCount(message.cc) + recipientCount(message.bcc); + if (recipients > BODY_MAIL_RECIPIENT_LIMIT) { + throw doorError( + 'VALIDATION_ERROR', + `ctx.email.send: a message may name at most ${BODY_MAIL_RECIPIENT_LIMIT} recipients across \`to\`, \`cc\` and \`bcc\`; this one names ${recipients}. Send it in smaller messages.`, + ); + } + for (const slot of ['to', 'cc', 'bcc'] as const) { + const length = recordedSlotLength(message[slot]); + if (length > BODY_MAIL_ADDRESS_LIST_LIMIT) { + throw doorError( + 'VALIDATION_ERROR', + `ctx.email.send: \`${slot}\` takes ${length} characters as the mail log records it ("Name"
, joined by ", "), ` + + `over the ${BODY_MAIL_ADDRESS_LIST_LIMIT} it holds. Send it in smaller messages.`, + ); + } + } + if (message.replyTo !== undefined) { + const length = recordedAddressLength(message.replyTo); + if (length > BODY_MAIL_ADDRESS_LIMIT) { + throw doorError( + 'VALIDATION_ERROR', + `ctx.email.send: \`replyTo\` takes ${length} characters as the mail log records it ("Name"
), over the ${BODY_MAIL_ADDRESS_LIMIT} it holds.`, + ); + } + } +} + +/** + * The caller's read scope: the context with the body's elevation taken off. + * An action body's engine context is the caller's envelope elevated + * (`buildActionExecutionContext`); this hands back the envelope. No context is + * a scope with no principal. + */ +export function callerScopeOf(context: Record | undefined): Record { + if (!context || typeof context !== 'object') return {}; + const out: Record = { ...context }; + if (out[APP_AUTOMATION_ELEVATION] !== undefined) { + delete out[APP_AUTOMATION_ELEVATION]; + delete out.isSystem; + } + return out; +} + +/** Answer whether `object`/`id` is a record the caller can read. Never throws. */ +async function readableByCaller(ql: any, object: string, id: string, caller: BodyDoorCaller): Promise { + try { + let row: any; + if (caller.readRecord) row = await caller.readRecord(object, id); + else if (caller.readContext && ql && typeof ql.findOne === 'function') { + row = await ql.findOne(object, { where: { id }, fields: ['id'] }, { context: caller.readContext }); + } else return false; + return row != null && String(row.id) === id; + } catch { + return false; + } +} + +async function requireReadable(ql: any, ref: { object: string; id: string }, caller: BodyDoorCaller, door: string): Promise { + if (await readableByCaller(ql, ref.object, ref.id, caller)) return; + throw doorError( + 'RECORD_NOT_FOUND', + `${door}: no '${ref.object}' record '${ref.id}' that this caller can read. The door acts only on a record the caller can read.`, + ); +} + +function service(getService: BodyDoorOptions['getService'], name: string): T | undefined { + if (!getService) return undefined; + try { + return (getService(name) as T) ?? undefined; + } catch { + return undefined; + } +} + +/** A display-name fragment safe for a header: one line, no quotes or angle brackets. */ +function displayText(value: unknown): string | undefined { + if (typeof value !== 'string') return undefined; + const text = value.replace(/[\r\n"<>]/g, ' ').replace(/\s+/g, ' ').trim(); + return text.length > 0 ? text.slice(0, 120) : undefined; +} + +async function nameOf(ql: any, object: string, id: string | undefined): Promise { + if (!id || !ql || typeof ql.findOne !== 'function') return undefined; + try { + const row = await ql.findOne(object, { where: { id }, fields: ['id', 'name'] }, { context: { isSystem: true } }); + return displayText(row?.name); + } catch { + return undefined; + } +} + +/** + * The sender of a body's message: the configured address, with a display name + * naming the calling user beside the organization (「Ann Lee via Acme」). + * `undefined` when the deployment reports no configured sender, which the + * mail service then answers as it answers any send without one. + */ +async function senderFor(ql: any, email: IEmailService, caller: BodyDoorCaller): Promise { + const configured = typeof email.getDefaultFrom === 'function' ? email.getDefaultFrom() : undefined; + const address = mailAddressOf(configured); + if (!address) return undefined; + const configuredName = typeof configured === 'object' && configured ? displayText(configured.name) : undefined; + const [userName, orgName] = await Promise.all([ + nameOf(ql, 'sys_user', caller.userId), + nameOf(ql, 'sys_organization', caller.organizationId), + ]); + const base = orgName ?? configuredName; + const name = fitSenderName(userName ? (base ? `${userName} via ${base}` : userName) : configuredName, address); + return name ? { name, address } : { address }; +} + +/** + * A sender display name cut so `"Name"
` fits the mail log's sender + * column ({@link BODY_MAIL_ADDRESS_LIMIT}); none when the address leaves no room. + */ +function fitSenderName(name: string | undefined, address: string): string | undefined { + if (!name) return undefined; + const room = BODY_MAIL_ADDRESS_LIMIT - address.length - 5; + if (room < 1) return undefined; + const cut = name.slice(0, room).trim(); + return cut.length > 0 ? cut : undefined; +} + +/** + * Refuse a send while the mail log already records the hourly limit: the + * caller's organization's messages, or, for a caller with no organization, + * the whole log's. Read before the send, not held across it (see the module + * docblock). + */ +async function refuseOverHourlyLimit(ql: any, caller: BodyDoorCaller): Promise { + const limit = appMailHourlyLimit(); + const since = new Date(Date.now() - 60 * 60 * 1000).toISOString(); + const where: Record = { + created_at: { $gte: since }, + ...(caller.organizationId ? { organization_id: caller.organizationId } : {}), + }; + if (!ql || typeof ql.count !== 'function') { + throw doorError('NOT_IMPLEMENTED', 'ctx.email.send: the mail log cannot be counted here, so the hourly limit cannot be held.'); + } + const sent = await ql.count('sys_email', { where }, { context: { isSystem: true } }); + if (typeof sent === 'number' && sent >= limit) { + const counted = caller.organizationId + ? "this organization's mail log records" + : 'with no organization to count by, the whole mail log records'; + throw doorError( + 'RATE_LIMIT_EXCEEDED', + `ctx.email.send: ${counted} ${sent} messages in the last hour, at the limit of ${limit}. ` + + 'Try again later; an operator raises the limit with OS_EMAIL_APP_SEND_HOURLY_LIMIT.', + ); + } +} + +/** Build the two door seams for one body invocation. */ +export function buildBodyDoors(opts: BodyDoorOptions): BodyDoors { + const { ql, getService, caller } = opts; + const origin = `${opts.packageId}/${opts.origin.kind}:${opts.origin.name}`; + const transaction = (): BodyDoorTransaction => opts.openTransaction?.() ?? { kind: 'none' }; + + return { + email: { + async send(input: unknown) { + // A message cannot be taken back, so it is never sent from a hook + // body, whose write may still roll back, and never from an action or + // a job running inside a transaction. + if (opts.origin.kind === 'hook') { + throw doorError( + 'PERMISSION_DENIED', + 'ctx.email.send cannot be called from a hook body: a message cannot be taken back if the write ' + + 'that runs the hook rolls back. Send mail on a record change from an action, a job or a flow.', + ); + } + if (transaction().kind !== 'none') { + throw doorError( + 'RESOURCE_CONFLICT', + `ctx.email.send cannot be called while this ${opts.origin.kind} runs inside a transaction: ` + + 'a message cannot be taken back if that transaction rolls back.', + ); + } + const message = parseInput(BodyMailSendInputSchema as any, input, 'ctx.email.send'); + refuseOverRecordedLimits(message); + const email = service(getService, 'email'); + if (!email || typeof email.send !== 'function') { + throw doorError('NOT_IMPLEMENTED', 'ctx.email.send: this deployment has no mail service.'); + } + if (message.related) await requireReadable(ql, message.related, caller, 'ctx.email.send'); + await refuseOverHourlyLimit(ql, caller); + + const { related, ...rest } = message; + const bounded = boundCallerMail(rest as Record, caller, email); + if (!bounded.ok) throw doorError('PERMISSION_DENIED', `ctx.email.send: ${bounded.reason}`); + const from = await senderFor(ql, email, caller); + const sendInput = { + ...bounded.input, + ...(related ? { relatedObject: related.object, relatedId: related.id } : {}), + ...(from ? { from } : {}), + requireLogRow: true, + } as SendEmailInput; + const result = await email.send(sendInput); + return { id: String(result?.id ?? ''), status: String(result?.status ?? '') }; + }, + }, + activity: { + async append(input: unknown) { + const entry = parseInput( + BodyActivityAppendInputSchema as any, + input, + 'ctx.activity.append', + ); + if (entry.metadata !== undefined) { + const size = JSON.stringify(entry.metadata)?.length ?? 0; + if (size > BODY_ACTIVITY_METADATA_LIMIT) { + throw doorError( + 'VALIDATION_ERROR', + `ctx.activity.append: \`metadata\` takes ${size} characters as JSON, over the ${BODY_ACTIVITY_METADATA_LIMIT} an entry holds.`, + ); + } + } + const audit = service<{ + appendAppActivity?: (e: unknown, s: unknown, o?: { transaction?: unknown }) => Promise<{ id: string }>; + }>(getService, 'audit'); + if (!audit || typeof audit.appendAppActivity !== 'function') { + throw doorError('NOT_IMPLEMENTED', 'ctx.activity.append: this deployment has no activity feed.'); + } + await requireReadable(ql, { object: entry.object, id: entry.recordId }, caller, 'ctx.activity.append'); + if (entry.source) await requireReadable(ql, entry.source, caller, 'ctx.activity.append'); + // The entry is written in the transaction of the write that runs the + // body, and commits or rolls back with it: the engine's ambient one + // joins by itself, and a handle the write carries is passed through. + const tx = transaction(); + const stamp = { actorId: caller.userId, organizationId: caller.organizationId, origin }; + return tx.kind === 'separate' && tx.handle != null + ? audit.appendAppActivity(entry, stamp, { transaction: tx.handle }) + : audit.appendAppActivity(entry, stamp); + }, + }, + }; +} diff --git a/packages/runtime/src/sandbox/body-runner.ts b/packages/runtime/src/sandbox/body-runner.ts index ed6e5218e5e..cb46a4ea8f1 100644 --- a/packages/runtime/src/sandbox/body-runner.ts +++ b/packages/runtime/src/sandbox/body-runner.ts @@ -77,6 +77,8 @@ import { import { mapDataError } from '@objectstack/types'; import { resolveHookRefusal, type HookRefusalI18nSource } from './hook-refusal-catalogue.js'; import { isRelayedSandboxRefusal } from './quickjs-runner.js'; +import { buildBodyDoors, callerScopeOf, type BodyDoorCaller } from './body-doors.js'; +import { deriveHookApi, openTransactionKind, seedHookUnreadMembership, seedHookUserGrants } from '@objectstack/objectql'; interface FactoryOptions { ql: any; @@ -88,6 +90,18 @@ interface FactoryOptions { * declared refusal is answered with its declared message. */ i18n?: HookRefusalI18nSource; + /** + * Kernel service lookup for the two platform doors a body reaches + * (`ctx.email.send`, `ctx.activity.append`; `body-doors.ts`), read at call + * time. Absent, a body that calls either door is told it is unavailable. + */ + getService?: (name: string) => unknown; + /** + * The package that holds the bodies this runner binds, the first part of a + * door's `origin`. Absent, {@link appId}: a bundle with no `packages[]` is + * its own one package. + */ + originPackageId?: string; } /** @@ -455,6 +469,21 @@ export function hookBodyRunnerFactory( } const body = parsed.data; + // [#32004] A hook body sends no mail: a message cannot be taken back if the + // write that runs the hook rolls back. The parse refuses the grant + // (`HookSchema`); a hook that reaches this bind without that parse is + // refused here, thrown like the binding refusal above. + if (body.language === 'js' && (body.capabilities ?? []).includes('email.send')) { + throw Object.assign( + new Error( + `Hook '${hook.name}' was not bound: its body is granted \`email.send\`, and a hook body cannot send mail, ` + + 'because a message cannot be taken back if the write that runs the hook rolls back. Send mail on a ' + + 'record change from an action, a job or a flow.', + ), + { code: 'PERMISSION_DENIED', status: 403, statusCode: 403 }, + ); + } + // [#21520] A wildcard target names no family table, so it binds — but it // admits every object, the family's among them, and the boundary is that a // body never touches those tables. So the body is not run for a family @@ -479,6 +508,13 @@ export function hookBodyRunnerFactory( buildBodyLogSurface(opts, { kind: 'hook', name: hook.name }), buildTitleSurface(engineCtx, opts.ql, { kind: 'hook', name: hook.name }), ); + installBodyDoors( + sandboxCtx, + opts, + { kind: 'hook', name: hook.name }, + hookDoorCaller(engineCtx, hook.name, opts.logger), + engineCtx?.transaction, + ); try { opts.logger?.debug?.('[BodyRunner] hook fired', { appId: opts.appId, hook: hook.name }); const result = await runner.run(body, sandboxCtx, { @@ -590,6 +626,13 @@ export function actionBodyRunnerFactory( opts.ql, buildBodyLogSurface(opts, { kind: 'action', name: action.name }), ); + installBodyDoors( + sandboxCtx, + opts, + { kind: 'action', name: action.name }, + actionDoorCaller(actionCtx), + actionCtx?.executionContext?.transaction, + ); try { opts.logger?.debug?.('[BodyRunner] action fired', { appId: opts.appId, @@ -756,6 +799,7 @@ export function jobBodyRunnerFactory( buildBodyLogSurface(opts, { kind: 'job', name: job.name }), job.organization, ); + installBodyDoors(sandboxCtx, opts, { kind: 'job', name: job.name }, jobDoorCaller(job.organization)); try { opts.logger?.debug?.('[BodyRunner] job fired', { appId: opts.appId, job: job.name }); const result = await runner.run(body, sandboxCtx, { @@ -1168,6 +1212,129 @@ function buildEngineRepoFacade(ql: any, objectName: string, context?: any) { * ({@link refuseBodyPermanentDeletes}): app-authored code cannot purge, so its * deletes enter the recycle bin, whatever envelope the body runs under. */ +/** + * Install the two platform doors (`body-doors.ts`) on a body's sandbox + * context, built with the caller the HOST resolved for this invocation. + */ +function installBodyDoors( + sandboxCtx: ScriptContext, + opts: FactoryOptions, + origin: { kind: 'hook' | 'action' | 'job'; name: string }, + caller: BodyDoorCaller, + threadedTransaction?: unknown, +): void { + const doors = buildBodyDoors({ + ql: opts.ql, + getService: opts.getService, + packageId: opts.originPackageId ?? opts.appId, + origin, + caller, + // Read at call time: the transaction the write that runs this body stands + // in, the engine's ambient one or the handle the write's context carries. + openTransaction: () => { + const kind = openTransactionKind(opts.ql, threadedTransaction); + return kind === 'separate' ? { kind, handle: threadedTransaction } : { kind }; + }, + }); + sandboxCtx.email = doors.email; + sandboxCtx.activity = doors.activity; +} + +function nonEmptyString(value: unknown): string | undefined { + return typeof value === 'string' && value.length > 0 ? value : undefined; +} + +/** + * A hook body's caller: the user of the write that fired it, read in that + * user's own scope. + * + * The scope is built from the write's whole execution context, which only the + * engine's hook api holds (`ctx.session` is a projection of it), by the two + * steps a `runAs: 'user'` hook takes (`hook-run-as.ts`, `@objectstack/objectql`): + * the context as the user, never as the system, whatever elevation the write + * or the hook's own `runAs` carried; then the user's grants, seeded where the + * context carries none. Built once per invocation, at the first record a door + * reads, so a body that never calls a door costs nothing. + * + * A write with no calling user stamps no user, and a door reads only what the + * body's own api reads. A host whose hook api cannot derive a scope (a hook + * context assembled by hand) reads with the session's user and organization + * and no elevation. + */ +function hookDoorCaller(engineCtx: any, hookName: string, logger?: FactoryOptions['logger']): BodyDoorCaller { + const session = engineCtx?.session; + const userId = nonEmptyString(session?.userId); + const organizationId = nonEmptyString(session?.organizationId); + const api = engineCtx?.api; + const derivable = !!api && typeof api.object === 'function' && (!userId || typeof api.withRunAs === 'function'); + if (!derivable) { + return { + userId, + organizationId, + readContext: userId ? { userId, ...(organizationId ? { tenantId: organizationId } : {}) } : {}, + }; + } + let scoped: Promise | undefined; + const callerApi = (): Promise => + (scoped ??= (async () => { + if (!userId) return api; + const asUser = deriveHookApi(api, 'user', { + hook: hookName, + object: typeof engineCtx?.object === 'string' ? engineCtx.object : undefined, + event: engineCtx?.event, + }); + try { + return await seedHookUserGrants(asUser); + } catch (err) { + // The hook wrapper's fail-safe for the same step (`installRunAsApi`, + // `@objectstack/objectql`): the user's grants could not be read, so the + // read runs on the context's own grants and an empty membership set. + // It sees less, never more, so a record may answer as not found. + logger?.warn?.( + `[BodyRunner] hook '${hookName}': the calling user's grants could not be resolved for a door's record read, ` + + 'so it reads with the triggering context\'s own grants and no membership; a record the user reads through ' + + 'a permission set may answer as not found', + { hook: hookName, error: (err as { message?: unknown } | undefined)?.message }, + ); + return seedHookUnreadMembership(asUser); + } + })()); + return { + userId, + organizationId, + readRecord: async (object, id) => (await callerApi()).object(object).findOne({ where: { id }, fields: ['id'] }), + }; +} + +/** + * An action body's caller: the action door's caller envelope, which the body's + * own engine context carries elevated (`buildActionExecutionContext`), with the + * elevation taken off ({@link callerScopeOf}). An action called from host code + * with no caller reads as the system. + */ +function actionDoorCaller(actionCtx: any): BodyDoorCaller { + const ec = actionCtx?.executionContext; + const userId = nonEmptyString(ec?.userId) ?? nonEmptyString(actionCtx?.user?.id); + const organizationId = nonEmptyString(ec?.tenantId) ?? nonEmptyString(actionCtx?.session?.organizationId); + const readContext = + ec && typeof ec === 'object' + ? callerScopeOf(ec) + : userId + ? { userId, ...(organizationId ? { tenantId: organizationId } : {}) } + : { isSystem: true }; + return { userId, organizationId, readContext }; +} + +/** A job body has no calling user: it acts in its declared organization. */ +function jobDoorCaller(organization: string | undefined): BodyDoorCaller { + const organizationId = nonEmptyString(organization); + return { + userId: undefined, + organizationId, + readContext: { isSystem: true, ...(organizationId ? { tenantId: organizationId } : {}) }, + }; +} + function buildSandboxApi(engineCtx: any, ql: any, errLabel: string) { return refuseBodyPermanentDeletes( refuseStoredMetadataBodyWrites( diff --git a/packages/runtime/src/sandbox/quickjs-runner.ts b/packages/runtime/src/sandbox/quickjs-runner.ts index 5e56e6d1499..5354a1aa892 100644 --- a/packages/runtime/src/sandbox/quickjs-runner.ts +++ b/packages/runtime/src/sandbox/quickjs-runner.ts @@ -872,6 +872,79 @@ export class QuickJSScriptRunner implements ScriptRunner { vm.setProp(ctxObj, 'crypto', cryptoObj); cryptoObj.dispose(); + // ── The two platform doors: `ctx.email.send` and `ctx.activity.append` ── + // + // Each behind its own token, checked before anything else. The host seam + // (`body-doors.ts`) is built with the caller the HOST resolved, so a body + // cannot name another user or organization by editing its copy of + // `ctx.user`. Installed on every body, like `log` and `crypto`: a body that + // declared the token on a host built without kernel services is told the + // door is unavailable, never handed `undefined is not a function`. Settled + // through the same deferred-promise pump every other host call uses. + // + // A door call inside `ctx.api.transaction` is refused (`409 + // RESOURCE_CONFLICT`): a door reads and writes outside the body's + // transaction, so what it wrote would outlive a rollback and what the body + // wrote inside it is not yet readable to it. Called after the transaction + // settles, it acts on what was committed. + const installDoor = ( + member: 'email' | 'activity', + fnName: 'send' | 'append', + token: 'email.send' | 'activity.append', + ): void => { + const doorObj = vm.newObject(); + const doorFn = vm.newFunction(fnName, (inputH) => { + if (!caps.has(token)) { + throwCapabilityDenial( + vm, + origin, + token, + `capability '${token}' not granted to ${origin.kind} '${origin.name}' (called ctx.${member}.${fnName})`, + ); + } + const input = inputH === undefined ? undefined : vm.dump(inputH); + const deferred = vm.newPromise(); + deferreds.add(deferred); + void (async () => { + try { + if (txState.open) { + throw Object.assign( + new Error( + `ctx.${member}.${fnName} cannot be called inside ctx.api.transaction: the door acts outside the transaction, ` + + 'so a rollback would not undo it. Call it after the transaction commits.', + ), + { code: 'RESOURCE_CONFLICT', status: 409, statusCode: 409 }, + ); + } + const seam = (ctx[member] as Record Promise) | undefined> | undefined)?.[fnName]; + if (typeof seam !== 'function') { + throw Object.assign( + new Error(`ctx.${member}.${fnName} is not available here: the host provides no ${member} door.`), + { code: 'NOT_IMPLEMENTED', status: 501, statusCode: 501 }, + ); + } + const value = await seam(input); + if (!vm.alive) return; + const h = jsonToHandle(vm, value ?? null); + deferred.resolve(h); + h.dispose(); + } catch (err) { + if (!vm.alive) return; + const errH = hostErrorToVm(vm, err); + deferred.reject(errH); + errH.dispose(); + } + })(); + return deferred.handle; + }); + vm.setProp(doorObj, fnName, doorFn); + doorFn.dispose(); + vm.setProp(ctxObj, member, doorObj); + doorObj.dispose(); + }; + installDoor('email', 'send', 'email.send'); + installDoor('activity', 'append', 'activity.append'); + // ── [#11293] `ctx.title(field?)` — "what is this record called?" ──────── // // Installed only when the host built the seam (hook bodies; the action face diff --git a/packages/runtime/src/sandbox/script-runner.ts b/packages/runtime/src/sandbox/script-runner.ts index f64f89a9edb..f9f53171e27 100644 --- a/packages/runtime/src/sandbox/script-runner.ts +++ b/packages/runtime/src/sandbox/script-runner.ts @@ -462,6 +462,19 @@ export interface ScriptContext { crypto?: { randomUUID?: () => string; }; + /** + * The mail door (`body-doors.ts`): `ctx.email.send(input)`, behind the + * `email.send` capability. Built by the host with the caller it resolved, so + * the sending user and organization are the host's, never the body's copy of + * `ctx.user`. Absent when the runner was built without kernel services; the + * VM's `ctx.email.send` then refuses a call as unavailable. + */ + email?: { send: (input: unknown) => Promise }; + /** + * The activity door (`body-doors.ts`): `ctx.activity.append(input)`, behind + * the `activity.append` capability. Same provenance as {@link email}. + */ + activity?: { append: (input: unknown) => Promise }; } /** diff --git a/packages/spec/api-surface/data.json b/packages/spec/api-surface/data.json index 0460cd72940..d296b55f986 100644 --- a/packages/spec/api-surface/data.json +++ b/packages/spec/api-surface/data.json @@ -51,6 +51,10 @@ "AutonumberFormatSource (interface)", "AutonumberToken (type)", "BASE_FIELD_DISPLAY_WHITELIST (const)", + "BODY_ACTIVITY_METADATA_LIMIT (const)", + "BODY_MAIL_ADDRESS_LIMIT (const)", + "BODY_MAIL_ADDRESS_LIST_LIMIT (const)", + "BODY_MAIL_RECIPIENT_LIMIT (const)", "BOOLEAN_COMPARAND_DOOR_CASES (const)", "BOOLEAN_COMPARAND_DOOR_FIXTURE (const)", "BOOLEAN_COMPARAND_DOOR_FIXTURE_FIELDS (const)", @@ -70,6 +74,12 @@ "BaseFieldDisplayProperty (type)", "BaseFieldOptionDisplayProperty (type)", "BaseValidationRuleShape (interface)", + "BodyActivityAppendInput (type)", + "BodyActivityAppendInputSchema (const)", + "BodyDoorRecordRef (type)", + "BodyDoorRecordRefSchema (const)", + "BodyMailSendInput (type)", + "BodyMailSendInputSchema (const)", "BooleanComparandDoorCase (type)", "BooleanComparandDoorDeferredCase (interface)", "BooleanComparandDoorFieldMeta (interface)", @@ -734,6 +744,7 @@ "STRING_VALUE_TYPES (const)", "STRUCTURED_JSON_TYPES (const)", "SYS_ACTIVITY_BUILTIN_TYPES (const)", + "SYS_ACTIVITY_PLATFORM_TYPES (const)", "Scalar (type)", "SchemaMode (type)", "SchemaModeSchema (const)", diff --git a/packages/spec/authorable-surface/data.json b/packages/spec/authorable-surface/data.json index 641826654dd..48362e1d32f 100644 --- a/packages/spec/authorable-surface/data.json +++ b/packages/spec/authorable-surface/data.json @@ -41,6 +41,23 @@ "data/AutoPersistenceConfig:path", "data/AutoPersistenceConfig:type", "data/BaseEngineOptions:context", + "data/BodyActivityAppendInput:metadata", + "data/BodyActivityAppendInput:object", + "data/BodyActivityAppendInput:recordId", + "data/BodyActivityAppendInput:recordLabel", + "data/BodyActivityAppendInput:source", + "data/BodyActivityAppendInput:summary", + "data/BodyActivityAppendInput:type", + "data/BodyDoorRecordRef:id", + "data/BodyDoorRecordRef:object", + "data/BodyMailSendInput:bcc", + "data/BodyMailSendInput:cc", + "data/BodyMailSendInput:html", + "data/BodyMailSendInput:related", + "data/BodyMailSendInput:replyTo", + "data/BodyMailSendInput:subject", + "data/BodyMailSendInput:text", + "data/BodyMailSendInput:to", "data/ComparisonOperator:$gt", "data/ComparisonOperator:$gte", "data/ComparisonOperator:$lt", diff --git a/packages/spec/declaration-map/data.json b/packages/spec/declaration-map/data.json index 1ad5f2a908e..ce5810ff0e2 100644 --- a/packages/spec/declaration-map/data.json +++ b/packages/spec/declaration-map/data.json @@ -28,6 +28,12 @@ "BaseEngineOptions": "data/BaseEngineOptions", "BaseEngineOptionsSchema": "data/BaseEngineOptions", "BaseQuerySchema": "data/Query", + "BodyActivityAppendInput": "data/BodyActivityAppendInput", + "BodyActivityAppendInputSchema": "data/BodyActivityAppendInput", + "BodyDoorRecordRef": "data/BodyDoorRecordRef", + "BodyDoorRecordRefSchema": "data/BodyDoorRecordRef", + "BodyMailSendInput": "data/BodyMailSendInput", + "BodyMailSendInputSchema": "data/BodyMailSendInput", "CalendarDateValue": "data/CalendarDateValue", "CalendarDateValueSchema": "data/CalendarDateValue", "ClockTimeValue": "data/ClockTimeValue", diff --git a/packages/spec/export-origins/data.json b/packages/spec/export-origins/data.json index c7686d73c24..930b4c53d50 100644 --- a/packages/spec/export-origins/data.json +++ b/packages/spec/export-origins/data.json @@ -48,6 +48,10 @@ "AutonumberFormatSource": "src/data/autonumber-format.ts#AutonumberFormatSource (interface)", "AutonumberToken": "src/data/autonumber-format.ts#AutonumberToken (type)", "BASE_FIELD_DISPLAY_WHITELIST": "src/data/field-customization.ts#BASE_FIELD_DISPLAY_WHITELIST (const)", + "BODY_ACTIVITY_METADATA_LIMIT": "src/data/hook-body-doors.zod.ts#BODY_ACTIVITY_METADATA_LIMIT (const)", + "BODY_MAIL_ADDRESS_LIMIT": "src/data/hook-body-doors.zod.ts#BODY_MAIL_ADDRESS_LIMIT (const)", + "BODY_MAIL_ADDRESS_LIST_LIMIT": "src/data/hook-body-doors.zod.ts#BODY_MAIL_ADDRESS_LIST_LIMIT (const)", + "BODY_MAIL_RECIPIENT_LIMIT": "src/data/hook-body-doors.zod.ts#BODY_MAIL_RECIPIENT_LIMIT (const)", "BOOLEAN_COMPARAND_DOOR_CASES": "src/data/filter-boolean-comparand-declared-type.ts#BOOLEAN_COMPARAND_DOOR_CASES (const)", "BOOLEAN_COMPARAND_DOOR_FIXTURE": "src/data/filter-boolean-comparand-declared-type.ts#BOOLEAN_COMPARAND_DOOR_FIXTURE (const)", "BOOLEAN_COMPARAND_DOOR_FIXTURE_FIELDS": "src/data/filter-boolean-comparand-declared-type.ts#BOOLEAN_COMPARAND_DOOR_FIXTURE_FIELDS (const)", @@ -67,6 +71,12 @@ "BaseFieldDisplayProperty": "src/data/field-customization.ts#BaseFieldDisplayProperty (type)", "BaseFieldOptionDisplayProperty": "src/data/field-customization.ts#BaseFieldOptionDisplayProperty (type)", "BaseValidationRuleShape": "src/data/validation.zod.ts#BaseValidationRuleShape (interface)", + "BodyActivityAppendInput": "src/data/hook-body-doors.zod.ts#BodyActivityAppendInput (type)", + "BodyActivityAppendInputSchema": "src/data/hook-body-doors.zod.ts#BodyActivityAppendInputSchema (const)", + "BodyDoorRecordRef": "src/data/hook-body-doors.zod.ts#BodyDoorRecordRef (type)", + "BodyDoorRecordRefSchema": "src/data/hook-body-doors.zod.ts#BodyDoorRecordRefSchema (const)", + "BodyMailSendInput": "src/data/hook-body-doors.zod.ts#BodyMailSendInput (type)", + "BodyMailSendInputSchema": "src/data/hook-body-doors.zod.ts#BodyMailSendInputSchema (const)", "BooleanComparandDoorCase": "src/data/filter-boolean-comparand-declared-type.ts#BooleanComparandDoorCase (type)", "BooleanComparandDoorDeferredCase": "src/data/filter-boolean-comparand-declared-type.ts#BooleanComparandDoorDeferredCase (interface)", "BooleanComparandDoorFieldMeta": "src/data/filter-boolean-comparand-declared-type.ts#BooleanComparandDoorFieldMeta (interface)", @@ -722,6 +732,7 @@ "STRING_VALUE_TYPES": "src/data/field-value.zod.ts#STRING_VALUE_TYPES (const)", "STRUCTURED_JSON_TYPES": "src/data/field-value.zod.ts#STRUCTURED_JSON_TYPES (const)", "SYS_ACTIVITY_BUILTIN_TYPES": "src/data/feed.zod.ts#SYS_ACTIVITY_BUILTIN_TYPES (const)", + "SYS_ACTIVITY_PLATFORM_TYPES": "src/data/feed.zod.ts#SYS_ACTIVITY_PLATFORM_TYPES (const)", "Scalar": "src/data/filter.zod.ts#Scalar (type)", "SchemaMode": "src/data/datasource.zod.ts#SchemaMode (type)", "SchemaModeSchema": "src/data/datasource.zod.ts#SchemaModeSchema (const)", diff --git a/packages/spec/json-schema.manifest/data.json b/packages/spec/json-schema.manifest/data.json index 2189c47fe28..32d125d021d 100644 --- a/packages/spec/json-schema.manifest/data.json +++ b/packages/spec/json-schema.manifest/data.json @@ -16,6 +16,9 @@ "data/ApiOperation", "data/AutoPersistenceConfig", "data/BaseEngineOptions", + "data/BodyActivityAppendInput", + "data/BodyDoorRecordRef", + "data/BodyMailSendInput", "data/CalendarDateValue", "data/ClockTimeValue", "data/ColumnApplyOn", diff --git a/packages/spec/llms.txt b/packages/spec/llms.txt index 5dcf299b2b1..99bcf5c5f68 100644 --- a/packages/spec/llms.txt +++ b/packages/spec/llms.txt @@ -77,7 +77,7 @@ const query = { --- -## 3. Schema Inventory by Domain (225 schemas) +## 3. Schema Inventory by Domain (226 schemas) Counted as `*.zod.ts` modules under `packages/spec/src//` — the sources that ship in this tarball (`files` includes `src/**/*.zod.ts`), so every number @@ -87,7 +87,7 @@ here is verifiable from the installed package. |--------|-------|-------------| | system | 40 | Auth, Cache, Demo Staff, Dev Login, Email / SMS / Push Config, Push Device, Encryption, Fate Supplement (organization ownership), HTTP Server, License, Logging, Metrics, Restriction Profile | | kernel | 31 | Plugin, Manifest, Events (6 sub-modules), Feature, Context, Package Registry, Override Declaration | -| data | 35 | Object, Field, Picklist, Query, Filter, Driver (SQL/NoSQL/Memory/Mongo/Postgres/Oracle/SQL Server), Cube, Seed, Recycle Bin | +| data | 36 | Object, Field, Picklist, Query, Filter, Driver (SQL/NoSQL/Memory/Mongo/Postgres/Oracle/SQL Server), Cube, Seed, Recycle Bin | | api | 35 | Endpoint, REST Server, Discovery, OData, Batch, WebSocket, Response Envelope, Package Lifecycle, Package API (assembled stage), Record Page, App Metadata Bundle, Push Delivery, Push Relay | | ui | 18 | View, App, Action, Dashboard, Page, Chart, Component, Animation | | automation | 16 | Flow, Approval, Assignment Rule, BPMN Interop, Control Flow, Webhook, Schedule Organization | diff --git a/packages/spec/src/contracts/email-service.ts b/packages/spec/src/contracts/email-service.ts index f4a906f70b7..378fdb20d74 100644 --- a/packages/spec/src/contracts/email-service.ts +++ b/packages/spec/src/contracts/email-service.ts @@ -102,6 +102,15 @@ export interface SendEmailInput { * two silently dropped. */ identityMail?: boolean; + /** + * The message is sent only if the mail log records it. `true`: when the + * log row cannot be written (no persistence, or the insert fails), the send + * is refused with `SERVICE_UNAVAILABLE` and nothing is delivered. Absent or + * `false` keeps the default, where a message whose row could not be written + * is still delivered, with a warning. A script body's `ctx.email.send` sets + * it. + */ + requireLogRow?: boolean; } /** diff --git a/packages/spec/src/data/feed.zod.ts b/packages/spec/src/data/feed.zod.ts index e2483e8252e..68f2054e5ed 100644 --- a/packages/spec/src/data/feed.zod.ts +++ b/packages/spec/src/data/feed.zod.ts @@ -70,8 +70,11 @@ export type FeedFilterMode = z.input; * and offers in pickers/filters, never the ceiling of legal values. An app may * contribute its own values — the sanctioned authoring channel is * `activityMilestones[].type` (ADR-0052 §5b.2, `z.string()`, forwarded - * verbatim), and an app's server-side action can insert one directly — and an - * undeclared value is stored verbatim, not rejected. + * verbatim), and a script body adds one through `ctx.activity.append` + * (capability `activity.append`, input `BodyActivityAppendInputSchema`) + * — and an undeclared value is stored verbatim, not rejected. The door refuses + * only the values in {@link SYS_ACTIVITY_PLATFORM_TYPES}, which name what the + * platform itself recorded. * * What that binds for a consumer of this constant: * @@ -113,3 +116,25 @@ export const SYS_ACTIVITY_BUILTIN_TYPES = [ * the known-built-in narrowing only. */ export type SysActivityBuiltinType = (typeof SYS_ACTIVITY_BUILTIN_TYPES)[number]; + +/** + * The `sys_activity.type` values only the platform records: what happened to a + * record (`created` / `updated` / `deleted`), the collaboration events the + * platform writes (`commented` / `mentioned` / `shared` / `assigned`), sign-in + * events and `system`. An app adds timeline entries through the activity door + * (`ctx.activity.append`), which refuses these values, so an entry an app wrote + * cannot read as one the platform recorded. Every other value, built-in + * (`completed`, `scheduled`) or author-contributed, stays open to apps. + */ +export const SYS_ACTIVITY_PLATFORM_TYPES = [ + 'created', + 'updated', + 'deleted', + 'commented', + 'mentioned', + 'shared', + 'assigned', + 'login', + 'logout', + 'system', +] as const satisfies readonly SysActivityBuiltinType[]; diff --git a/packages/spec/src/data/hook-body-doors.test.ts b/packages/spec/src/data/hook-body-doors.test.ts new file mode 100644 index 00000000000..3bc3c387f90 --- /dev/null +++ b/packages/spec/src/data/hook-body-doors.test.ts @@ -0,0 +1,111 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, it, expect } from 'vitest'; +import { + BODY_ACTIVITY_METADATA_LIMIT, + BODY_MAIL_ADDRESS_LIST_LIMIT, + BODY_MAIL_RECIPIENT_LIMIT, + BodyActivityAppendInputSchema, + BodyMailSendInputSchema, +} from './hook-body-doors.zod'; +import { SYS_ACTIVITY_BUILTIN_TYPES, SYS_ACTIVITY_PLATFORM_TYPES } from './feed.zod'; + +describe('ctx.email.send input: what the platform says about a message is not an input', () => { + const message = { to: 'pat@example.test', subject: 'Quote', text: 'Attached.' }; + + it('takes a message with recipients, a subject and a body', () => { + expect(BodyMailSendInputSchema.safeParse(message).success).toBe(true); + expect( + BodyMailSendInputSchema.safeParse({ + ...message, + cc: [{ name: 'Lee', address: 'lee@example.test' }], + replyTo: 'rep@example.test', + related: { object: 'crm_contact', id: 'c1' }, + }).success, + ).toBe(true); + }); + + for (const key of ['from', 'sentBy', 'organizationId', 'identityMail', 'headers', 'attachments']) { + it(`refuses \`${key}\`: the door stamps it, or does not take it`, () => { + expect(BodyMailSendInputSchema.safeParse({ ...message, [key]: 'x' }).success).toBe(false); + }); + } + + it('refuses a message with no body', () => { + expect(BodyMailSendInputSchema.safeParse({ to: 'pat@example.test', subject: 'Quote' }).success).toBe(false); + }); + + it(`names at most ${BODY_MAIL_RECIPIENT_LIMIT} recipients in one slot`, () => { + const addresses = (n: number) => Array.from({ length: n }, (_, i) => `t${i}@example.test`); + expect(BodyMailSendInputSchema.safeParse({ ...message, to: addresses(BODY_MAIL_RECIPIENT_LIMIT) }).success).toBe(true); + expect(BodyMailSendInputSchema.safeParse({ ...message, bcc: addresses(BODY_MAIL_RECIPIENT_LIMIT + 1) }).success).toBe(false); + }); +}); + +describe('every string a door input takes has an upper bound', () => { + const message = { to: 'pat@example.test', subject: 'Quote', text: 'Attached.' }; + const entry = { object: 'crm_contact', recordId: 'c1', type: 'completed', summary: 'Email: Quote' }; + + it('bounds a message\'s subject, addresses, display names, bodies and related record', () => { + for (const over of [ + { subject: 'x'.repeat(999) }, + { to: `${'a'.repeat(320)}@x.test` }, + { to: { name: 'n'.repeat(201), address: 'pat@example.test' } }, + { replyTo: `${'a'.repeat(320)}@x.test` }, + { text: 'x'.repeat(1_000_001) }, + { html: 'x'.repeat(1_000_001) }, + { related: { object: 'o'.repeat(101), id: 'c1' } }, + { related: { object: 'crm_contact', id: 'i'.repeat(101) } }, + ]) { + expect(BodyMailSendInputSchema.safeParse({ ...message, ...over }).success, JSON.stringify(Object.keys(over))).toBe(false); + } + }); + + it('bounds an entry\'s object, record, type and label', () => { + for (const over of [ + { object: 'o'.repeat(256) }, + { recordId: 'i'.repeat(256) }, + { type: 't'.repeat(101) }, + { recordLabel: 'l'.repeat(256) }, + ]) { + expect(BodyActivityAppendInputSchema.safeParse({ ...entry, ...over }).success, JSON.stringify(Object.keys(over))).toBe(false); + } + }); + + it('states the limits it cannot spell as a rule in the published description', () => { + const mail = BodyMailSendInputSchema.description ?? ''; + expect(mail).toContain(`At most ${BODY_MAIL_RECIPIENT_LIMIT} recipients across to, cc and bcc together`); + expect(mail).toContain(`at most ${BODY_MAIL_ADDRESS_LIST_LIMIT} characters`); + expect(BodyActivityAppendInputSchema.description ?? '').toContain(`at most ${BODY_ACTIVITY_METADATA_LIMIT} characters as JSON`); + }); +}); + +describe('ctx.activity.append input: the actor, organization and origin are not inputs', () => { + const entry = { object: 'crm_contact', recordId: 'c1', type: 'completed', summary: 'Email: Quote' }; + + it('takes an entry with a record, a type and a summary', () => { + expect(BodyActivityAppendInputSchema.safeParse(entry).success).toBe(true); + expect( + BodyActivityAppendInputSchema.safeParse({ + ...entry, + recordLabel: 'Pat Doe', + source: { object: 'sys_email', id: 'e1' }, + metadata: { kind: 'email' }, + }).success, + ).toBe(true); + }); + + for (const key of ['actor_id', 'actorId', 'actor_name', 'organization_id', 'origin', 'timestamp']) { + it(`refuses \`${key}\`: the door stamps it`, () => { + expect(BodyActivityAppendInputSchema.safeParse({ ...entry, [key]: 'x' }).success).toBe(false); + }); + } +}); + +describe('the platform-only activity types', () => { + it('are built-in types, and leave completed and scheduled open to apps', () => { + for (const type of SYS_ACTIVITY_PLATFORM_TYPES) expect(SYS_ACTIVITY_BUILTIN_TYPES).toContain(type); + expect(SYS_ACTIVITY_PLATFORM_TYPES).not.toContain('completed'); + expect(SYS_ACTIVITY_PLATFORM_TYPES).not.toContain('scheduled'); + }); +}); diff --git a/packages/spec/src/data/hook-body-doors.zod.ts b/packages/spec/src/data/hook-body-doors.zod.ts new file mode 100644 index 00000000000..84d2e54b7a5 --- /dev/null +++ b/packages/spec/src/data/hook-body-doors.zod.ts @@ -0,0 +1,149 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { z } from 'zod'; +import { requiredOneOf } from '../shared/refinement-projection'; + +/** + * The two platform doors a sandboxed script body (a hook, action or job body) + * reaches for records it may not write itself: mail goes through the mail + * service, and a timeline entry goes through the activity door. A body asks for + * each with its own capability token (`email.send`, `activity.append`, + * {@link HookBodyCapability}), and calls it as `ctx.email.send(input)` / + * `ctx.activity.append(input)`. + * + * Each input below is what the BODY may say. What the platform says about the + * message or the entry is stamped by the door and is not an input: the sender, + * the user the mail is sent by, the organization it belongs to, the actor of a + * timeline entry and the origin naming the body that wrote it. A key outside + * the shape is refused, never dropped, so a body that names one of those is + * told at the call. + * + * A message cannot be taken back, so mail is sent from an action or a job + * body, never from a hook body; mail on a record change goes through an + * action, a job or a flow. A timeline entry is written with the write that + * runs the body, and commits or rolls back with it. + */ + +/** The most recipients one `ctx.email.send` call may name, across `to`, `cc` and `bcc`. */ +export const BODY_MAIL_RECIPIENT_LIMIT = 50; + +/** + * The most characters each of `to`, `cc` and `bcc` may take as the mail log + * records it: every recipient as `"Name"
` (or the bare address), + * joined by `", "`. The log's address columns hold this many. + */ +export const BODY_MAIL_ADDRESS_LIST_LIMIT = 4000; + +/** The most characters an address may have, and a `replyTo` as recorded (`"Name"
`). */ +export const BODY_MAIL_ADDRESS_LIMIT = 320; + +/** The most characters `ctx.activity.append`'s `metadata` may take, written as JSON. */ +export const BODY_ACTIVITY_METADATA_LIMIT = 8000; + +/** + * One recipient: a bare address, or a display name with an address. The same + * two forms `SendEmailInput` takes (`@objectstack/spec/contracts`). + */ +const BodyMailAddressSchema = z.union([ + z.string().min(1).max(BODY_MAIL_ADDRESS_LIMIT), + z + .object({ + name: z.string().max(200).optional(), + address: z.string().min(1).max(BODY_MAIL_ADDRESS_LIMIT), + }) + .strict(), +]); + +const BodyMailAddressesSchema = z.union([ + BodyMailAddressSchema, + z.array(BodyMailAddressSchema).min(1).max(BODY_MAIL_RECIPIENT_LIMIT), +]); + +/** + * A record the body points at, by object name and record id. The door reads it + * in the caller's scope before it acts, and refuses one the caller cannot read + * with the answer it gives one that does not exist. + */ +export const BodyDoorRecordRefSchema = z + .object({ + object: z.string().min(1).max(100).describe('Object name of the record'), + id: z.string().min(1).max(100).describe('Record id'), + }) + .strict() + .describe('A record the door reads in the caller\'s scope before it acts'); +export type BodyDoorRecordRef = z.input; + +/** + * `ctx.email.send(input)` — a message an action or a job body hands to the + * mail service. A hook body cannot send mail. + * + * The sender is the deployment's configured sender, and the door names the + * calling user beside the organization in its display name; a reply goes to + * `replyTo`. The message is recorded as sent by the calling user and under the + * caller's organization. At least one of `text` or `html`. + * + * Two limits read across fields, which a JSON Schema cannot state exactly, so + * the schema's description states them and the door holds them: at most + * {@link BODY_MAIL_RECIPIENT_LIMIT} recipients across `to`, `cc` and `bcc` + * together (each slot alone is held to that number here), and each of the + * three at most {@link BODY_MAIL_ADDRESS_LIST_LIMIT} characters as the mail log + * records it; a `replyTo` as recorded is at most + * {@link BODY_MAIL_ADDRESS_LIMIT}. + */ +export const BodyMailSendInputSchema = z + .object({ + to: BodyMailAddressesSchema.describe('Recipient address, or a list of them'), + cc: BodyMailAddressesSchema.optional().describe('Carbon-copy recipients'), + bcc: BodyMailAddressesSchema.optional().describe('Blind carbon-copy recipients'), + replyTo: BodyMailAddressSchema.optional().describe('Reply-To address; the sender itself is the configured one'), + subject: z.string().min(1).max(998).describe('Subject line'), + text: z.string().max(1_000_000).optional().describe('Plain-text body'), + html: z.string().max(1_000_000).optional().describe('HTML body'), + related: BodyDoorRecordRefSchema.optional().describe('The record the message is about'), + }) + .strict() + .refine(requiredOneOf(['text', 'html']), { + message: 'A message needs a body: give `text`, `html`, or both.', + path: ['text'], + }) + .describe( + 'ctx.email.send input: a message an action or a job body hands to the mail service; a hook body cannot send mail. ' + + `At most ${BODY_MAIL_RECIPIENT_LIMIT} recipients across to, cc and bcc together; ` + + `each of to, cc and bcc at most ${BODY_MAIL_ADDRESS_LIST_LIMIT} characters as recorded ` + + '("Name"
, joined by ", "); ' + + `a replyTo at most ${BODY_MAIL_ADDRESS_LIMIT} characters as recorded.`, + ); +export type BodyMailSendInput = z.input; + +/** + * `ctx.activity.append(input)` — one entry a body adds to a record's activity + * timeline. The entry commits or rolls back with the write that runs the body. + * + * The door stamps the actor (the calling user), the organization, the time and + * the origin (the package and the body that wrote it). `type` is the open + * timeline vocabulary less the values only the platform records + * (`SYS_ACTIVITY_PLATFORM_TYPES`); the record, and `source` when given, must be + * readable by the caller. `metadata` is a plain object the timeline stores + * beside the entry, at most {@link BODY_ACTIVITY_METADATA_LIMIT} characters as + * JSON (a limit the door holds, stated in the description), and may not use the + * keys the platform's own entries carry. + */ +export const BodyActivityAppendInputSchema = z + .object({ + object: z.string().min(1).max(255).describe('Object name of the record the entry is about'), + recordId: z.string().min(1).max(255).describe('Id of the record the entry is about'), + type: z.string().min(1).max(100).describe('Activity kind, from the open vocabulary less the platform-only values'), + summary: z.string().min(1).max(500).describe('One-line summary'), + recordLabel: z.string().max(255).optional().describe('Display label of the record, as of the entry'), + source: BodyDoorRecordRefSchema.optional().describe('The record the entry points at for its detail'), + metadata: z + .record(z.string(), z.unknown()) + .optional() + .describe(`Display hints stored beside the entry, at most ${BODY_ACTIVITY_METADATA_LIMIT} characters as JSON`), + }) + .strict() + .describe( + 'ctx.activity.append input: one entry a script body adds to a record timeline; it commits or rolls back with the write that runs the body. ' + + `metadata is at most ${BODY_ACTIVITY_METADATA_LIMIT} characters as JSON.`, + ); +export type BodyActivityAppendInput = z.input; diff --git a/packages/spec/src/data/hook-body-mail-grant.test.ts b/packages/spec/src/data/hook-body-mail-grant.test.ts new file mode 100644 index 00000000000..04c8677919d --- /dev/null +++ b/packages/spec/src/data/hook-body-mail-grant.test.ts @@ -0,0 +1,52 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#32004] `HookSchema` refuses a hook body granted `email.send`: a hook body + * sends no mail, so the grant is refused at every door that parses a hook, + * before the hook is deployed. The runtime half (`hookBodyRunnerFactory`) + * refuses to bind the same hook. + * + * Not wider: an action's body, which is the same body schema, takes the grant; + * a hook body with every other grant parses unchanged. + */ + +import { describe, expect, it } from 'vitest'; +import { defineStack } from '../stack.zod'; +import { HookSchema } from './hook.zod'; +import { HookBodySchema } from './hook-body.zod'; + +const hook = (capabilities: string[]) => ({ + name: 'welcome_contact', + object: 'crm_contact', + events: ['afterInsert'], + body: { language: 'js', source: "await ctx.email.send({ to: 'pat@example.test', subject: 'Hi', text: 'x' });", capabilities }, +}); + +describe('a hook body is not granted email.send', () => { + it('refuses the grant at parse, at the grant, saying why and where mail goes instead', () => { + const r = HookSchema.safeParse(hook(['api.read', 'email.send'])); + expect(r.success).toBe(false); + const issues = r.success ? [] : r.error.issues; + expect(issues.map((i) => ({ code: i.code, path: i.path.join('.') }))).toEqual([ + { code: 'custom', path: 'body.capabilities.1' }, + ]); + expect(issues[0].message).toContain('A hook body cannot be granted `email.send`'); + expect(issues[0].message).toContain('from an action, a job or a flow'); + }); + + it('refuses it where a stack is defined too', () => { + expect(() => + defineStack({ manifest: { id: 'com.acme.crm', name: 'crm', version: '1.0.0', type: 'app' }, hooks: [hook(['email.send'])] } as any), + ).toThrow(/A hook body cannot be granted `email.send`/); + }); + + it('parses a hook body with every other grant unchanged', () => { + const others = HookSchema.safeParse(hook(['api.read', 'api.write', 'log', 'activity.append'])); + expect(others.success, JSON.stringify(others.error?.issues ?? [])).toBe(true); + }); + + it('leaves the grant to the body schema an action takes', () => { + const body = HookBodySchema.safeParse({ language: 'js', source: 'x', capabilities: ['email.send'] }); + expect(body.success).toBe(true); + }); +}); diff --git a/packages/spec/src/data/hook-body.test.ts b/packages/spec/src/data/hook-body.test.ts index 89309fe281a..4bfd4abb362 100644 --- a/packages/spec/src/data/hook-body.test.ts +++ b/packages/spec/src/data/hook-body.test.ts @@ -69,6 +69,8 @@ describe('HookBody', () => { 'api.transaction', 'crypto.uuid', 'log', + 'email.send', + 'activity.append', ]); expect(HookBodyCapability.options).not.toContain('crypto.hash'); }); diff --git a/packages/spec/src/data/hook-body.zod.ts b/packages/spec/src/data/hook-body.zod.ts index 378228cc9c0..9902600d234 100644 --- a/packages/spec/src/data/hook-body.zod.ts +++ b/packages/spec/src/data/hook-body.zod.ts @@ -34,6 +34,15 @@ const CRYPTO_HASH_RETIRED = * alongside it to be useful (the transaction body still needs write access). * - `crypto.uuid` — `ctx.crypto.randomUUID()` * - `log` — `ctx.log.info / warn / error` + * - `email.send` — `ctx.email.send(input)`: hand a message to the mail + * service. The sender, the sending user and the organization are stamped by + * the platform (`BodyMailSendInputSchema`). An action or a job body sends + * mail; a hook body cannot, because a message cannot be taken back if the + * write that runs the hook rolls back, and `HookSchema` refuses the grant. + * - `activity.append` — `ctx.activity.append(input)`: add one entry to a + * record's activity timeline. The actor, the organization and the origin are + * stamped by the platform (`BodyActivityAppendInputSchema`). The entry + * commits or rolls back with the write that runs the body. * * `http.fetch` is intentionally absent — outbound calls go through Connector * recipes (separate spec) so they remain auditable and replayable. @@ -51,6 +60,8 @@ export const HookBodyCapability = z.enum([ 'api.transaction', 'crypto.uuid', 'log', + 'email.send', + 'activity.append', ], { // Only the value that USED to be legal gets the retirement prescription — // telling the author of `crypto.hsah` that their value "was removed" would diff --git a/packages/spec/src/data/hook.zod.ts b/packages/spec/src/data/hook.zod.ts index 5ede90cb5c6..1edadf9c5ed 100644 --- a/packages/spec/src/data/hook.zod.ts +++ b/packages/spec/src/data/hook.zod.ts @@ -199,6 +199,40 @@ function refuseElevatedIdentityAssignmentBodyWrite( } } +/* + * ── A hook body is not granted `email.send` ────────────────────────────────── + * + * [#32004, ruling 6843314411] A message cannot be taken back, and the write + * that runs a hook may still roll back, so a hook body sends no mail: mail on a + * record change goes through an action, a job or a flow. The runtime refuses + * to bind a hook body granted `email.send` (`hookBodyRunnerFactory`) and + * refuses `ctx.email.send` in a hook body at every call; the parse refuses the + * grant at every door that parses a hook — the metadata save door, + * `defineStack` / `os validate`, compile (where the build infers the grant from + * a handler's `ctx.email.send` call), an artifact's parse — so the author meets + * it before the hook is deployed. One issue, at the grant. An action or a job + * body is granted it as before. + */ + +/** The object-level check that refuses a hook body granted `email.send`. See the block above. */ +function refuseHookBodyMailGrant( + hook: { body?: { language?: string; capabilities?: unknown } }, + ctx: z.RefinementCtx, +): void { + const granted = hook.body?.language === 'js' ? hook.body.capabilities : undefined; + if (!Array.isArray(granted)) return; + const index = granted.indexOf('email.send'); + if (index < 0) return; + ctx.addIssue({ + code: 'custom', + path: ['body', 'capabilities', index], + message: + 'A hook body cannot be granted `email.send`: a message cannot be taken back if the write that runs the hook ' + + 'rolls back. Remove the grant and the `ctx.email.send` call, and send mail on a record change from an action, ' + + 'a job or a flow.', + }); +} + /* * ── A hook that declares `refusals` refuses by code only ──────────────────── * @@ -701,12 +735,13 @@ export const HookSchema = lazySchema(() => strictObject( ...MetadataProtectionFields, // [#21565] The object-level checks: the first pairs `object` with `body`, // [#25653] the second `runAs` with `body`, [#26170] the third `refusals` - // with `body`, pairs no field-level refine can see together. A schema - // DERIVED from this one by overriding a key must use `.safeExtend()` (zod + // with `body`, pairs no field-level refine can see together; [#32004] the + // fourth refuses a body's `email.send` grant, which only the hook can judge, + // since an action's body takes it. A schema DERIVED from this one by overriding a key must use `.safeExtend()` (zod // refuses `.extend()` over a refined object), which is what keeps every // check on the derived schema too. }).superRefine(refuseBodyOnStoredMetadataTarget).superRefine(refuseElevatedIdentityAssignmentBodyWrite) - .superRefine(refuseUndeclaredLiteralRefusalCode)); + .superRefine(refuseUndeclaredLiteralRefusalCode).superRefine(refuseHookBodyMailGrant)); /** * Hook Runtime Context diff --git a/packages/spec/src/data/index.ts b/packages/spec/src/data/index.ts index cf423b5f07c..58c1f915fd4 100644 --- a/packages/spec/src/data/index.ts +++ b/packages/spec/src/data/index.ts @@ -228,6 +228,7 @@ export * from './autonumber-format'; export * from './validation.zod'; export * from './hook.zod'; export * from './hook-body.zod'; +export * from './hook-body-doors.zod'; // [#26170] A hook's refusal catalogue: the code spelling, the save-time reading // of a body's literal throws, and the sentences the schema and the body runner // both speak. diff --git a/packages/spec/src/type-alias-convention.pin.test.ts b/packages/spec/src/type-alias-convention.pin.test.ts index 1199b3fa051..806418c668a 100644 --- a/packages/spec/src/type-alias-convention.pin.test.ts +++ b/packages/spec/src/type-alias-convention.pin.test.ts @@ -137,6 +137,7 @@ import type * as M65 from './data/feed.zod.js'; import type * as M66 from './data/field.zod.js'; import type * as M67 from './data/filter.zod.js'; import type * as M68 from './data/hook-body.zod.js'; +import type * as M206 from './data/hook-body-doors.zod.js'; import type * as M69 from './data/hook.zod.js'; import type * as M70 from './data/object.zod.js'; import type * as M71 from './data/query.zod.js'; @@ -303,7 +304,7 @@ import type * as M204 from './ai/dataset-tools.zod.js'; import type * as M205 from './ai/object-query-source.zod.js'; // --------------------------------------------------------------------------- -// 853 isomorphic aliases: `z.input` === `z.infer`, so no `XParsed` is declared. +// 854 isomorphic aliases: `z.input` === `z.infer`, so no `XParsed` is declared. // // That number is machine-checked, not hand-kept. The runtime companion at the // bottom of this file recomputes the pin count from the source and asserts that @@ -949,6 +950,9 @@ export type Iso_data_filter__QueryFilterSchema = Assert, z.infer< typeof M68.ExpressionBodySchema > >>; export type Iso_data_hookBody__HookBodyCapability = Assert, z.infer< typeof M68.HookBodyCapability > >>; +// data/hook-body-doors.zod.ts +export type Iso_data_hookBodyDoors__BodyDoorRecordRefSchema = Assert, z.infer< typeof M206.BodyDoorRecordRefSchema > >>; + // data/hook.zod.ts export type Iso_data_hook__HookContextSchema = Assert, z.infer< typeof M69.HookContextSchema > >>; export type Iso_data_hook__HookEvent = Assert, z.infer< typeof M69.HookEvent > >>; @@ -1825,7 +1829,7 @@ describe('ADR-0122 type-alias convention', () => { // this title and the section header above the pin list — are now asserted // against the recomputed count below, so neither can go stale without a red // test naming it. - it('still declares all 853 isomorphic pins', () => { + it('still declares all 854 isomorphic pins', () => { // The truth of each pin is proved by tsc, not here — an `Assert>` // that stops holding is a compile error with the alias named. What tsc // cannot notice is a pin that was DELETED: removing the assertion removes @@ -2884,7 +2888,11 @@ describe('ADR-0122 type-alias convention', () => { // `FilterConditionSchema` tree (itself typed with one shape for both // states), no default and no transform // (Iso_ai_objectQuerySource__ObjectQuerySourceSchema). +1 added. - expect(pins).toHaveLength(853); + // 853 -> 854 is the record a script body's door reads before it acts + // (`data/hook-body-doors.zod.ts` `BodyDoorRecordRefSchema`): two bounded + // strings, strict, no default and no transform + // (Iso_data_hookBodyDoors__BodyDoorRecordRefSchema). +1 added. + expect(pins).toHaveLength(854); // The count is stated in PROSE twice as well — this case's title and the // section header above the pin list — and until commit c6b05c76a nothing read either diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/HookDefaultInspector.capabilities-26726.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/inspectors/HookDefaultInspector.capabilities-26726.test.tsx index 4c6cc10fc14..def0423a4e2 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/HookDefaultInspector.capabilities-26726.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/HookDefaultInspector.capabilities-26726.test.tsx @@ -16,6 +16,9 @@ import { describe, it, expect, vi, afterEach } from 'vitest'; import { render, screen, fireEvent, cleanup, within } from '@testing-library/react'; import { HookSchema, HookBodyCapability } from '@objectstack/spec/data'; +// The inspector's condition field loads these on first use; paid here, at collection, not inside a case. +import '@objectstack/formula'; +import '@objectstack/lint'; // The object picker fetches on mount; every fixture uses `object: '*'`, so // stub the shared client and keep that fetch off the network. @@ -79,13 +82,15 @@ function savedHook(draft: Record, body: Record const box = (name: string) => screen.getByRole('checkbox', { name }) as HTMLInputElement; describe('HookDefaultInspector — body capabilities (objectstack#26726)', () => { - it('offers one checkbox per spec token on a js body, read from the enum', () => { + it('offers one checkbox per spec token on a js body, read from the enum, less the one a hook body cannot be granted', () => { renderInspector(hookDraft(JS_BODY)); const control = screen.getByTestId('hook-body-capabilities'); const names = within(control) .getAllByRole('checkbox') .map((el) => el.closest('label')!.textContent); - expect(names).toEqual([...HookBodyCapability.options]); + // objectstack#32004 — a hook body sends no mail; the hook parse refuses the grant. + expect(names).toEqual(HookBodyCapability.options.filter((c) => c !== 'email.send')); + expect(screen.queryByRole('checkbox', { name: 'email.send' })).toBeNull(); // Each token names the ctx call it unlocks. expect(within(control).getByText('ctx.api.object(…).find / findOne / count / aggregate')).toBeInTheDocument(); expect(within(control).getByText('ctx.log.debug / info / warn / error')).toBeInTheDocument(); @@ -189,6 +194,25 @@ describe('HookDefaultInspector — body capabilities (objectstack#26726)', () => expect(writtenBody(onPatch).capabilities).toEqual(['api.read']); }); + it('a stored email.send grant stays visible, flagged as one a hook body cannot be granted, and unticking removes it', () => { + // Not parsed: the hook parse refuses this grant (objectstack#32004), which is why it must not vanish unseen. + const draft = { + name: 'reads_accounts', + object: '*', + events: ['beforeInsert'], + body: { ...JS_BODY, capabilities: ['api.read', 'email.send'] }, + }; + const onPatch = renderInspector(draft); + + const flagged = box(`email.send ${t('engine.inspector.hook.capabilityNotForHook', 'en-US')}`); + expect(flagged.checked).toBe(true); + + fireEvent.click(flagged); + const body = writtenBody(onPatch); + expect(body.capabilities).toEqual(['api.read']); + expect(savedHook(draft, body).body).toMatchObject({ capabilities: ['api.read'] }); + }); + it('"More fields" does not draw the key a second time', () => { const serverSchema = { type: 'object', diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/HookDefaultInspector.tsx b/ui/packages/app-shell/src/views/metadata-admin/inspectors/HookDefaultInspector.tsx index 5c8f6ebeccf..54117a943d0 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/HookDefaultInspector.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/HookDefaultInspector.tsx @@ -441,6 +441,9 @@ export function HookDefaultInspector({ locale={locale} disabled={readOnly} testId="hook-body-capabilities" + // objectstack#32004 — a hook body sends no mail: the hook parse + // refuses the grant, so it is not offered here. + withheld={{ tokens: ['email.send'], flagKey: 'engine.inspector.hook.capabilityNotForHook' }} /> )} diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/ScriptCapabilitiesField.tsx b/ui/packages/app-shell/src/views/metadata-admin/inspectors/ScriptCapabilitiesField.tsx index c1a272db649..c988369d445 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/ScriptCapabilitiesField.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/ScriptCapabilitiesField.tsx @@ -21,6 +21,11 @@ * * The host draws this for a `js` body only: an expression body is strict and * refuses `capabilities` by name. Module-private: no barrel re-exports it. + * + * A token the host's body cannot be granted (`withheld`: a hook body's + * `email.send`, objectstack#32004, which the hook parse refuses) is not + * offered. A stored one stays on screen, flagged, like an unknown token, so it + * is never dropped unseen and unticking it removes it. */ import { Label } from '@object-ui/components'; @@ -40,6 +45,8 @@ const CAPABILITY_CALLS: Partial> = { 'api.transaction': 'ctx.api.transaction(async () => { … })', 'crypto.uuid': 'ctx.crypto.randomUUID()', log: 'ctx.log.debug / info / warn / error', + 'email.send': 'ctx.email.send({ to, subject, text })', + 'activity.append': 'ctx.activity.append({ object, recordId, type, summary })', }; export interface ScriptCapabilitiesFieldProps { @@ -53,6 +60,9 @@ export interface ScriptCapabilitiesFieldProps { locale: SupportedLocale; disabled?: boolean; testId?: string; + /** The tokens this host's body cannot be granted, and the catalogue key of + * the flag a stored one carries. */ + withheld?: { tokens: readonly string[]; flagKey: string }; } export function ScriptCapabilitiesField({ @@ -62,11 +72,14 @@ export function ScriptCapabilitiesField({ locale, disabled, testId, + withheld, }: ScriptCapabilitiesFieldProps) { const granted: string[] = Array.isArray(value) ? value.filter((c): c is string => typeof c === 'string') : []; - const options = [...CAPABILITY_TOKENS, ...granted.filter((c) => !CAPABILITY_TOKENS.includes(c))]; + const isWithheld = (cap: string) => withheld?.tokens.includes(cap) === true; + const offered = CAPABILITY_TOKENS.filter((c) => !isWithheld(c)); + const options = [...offered, ...granted.filter((c) => !offered.includes(c))]; const toggle = (cap: string, on: boolean) => { const next = new Set(granted); if (on) next.add(cap); @@ -82,9 +95,13 @@ export function ScriptCapabilitiesField({
toggle(cap, on)} diff --git a/ui/packages/i18n/src/namespaces/studio/en.ts b/ui/packages/i18n/src/namespaces/studio/en.ts index 10127e2721c..3ed4425bbb2 100644 --- a/ui/packages/i18n/src/namespaces/studio/en.ts +++ b/ui/packages/i18n/src/namespaces/studio/en.ts @@ -1553,6 +1553,7 @@ const STUDIO_EN: Record = { 'engine.inspector.hook.capabilities': 'Capabilities', 'engine.inspector.hook.capabilitiesHint': 'The ctx APIs this body may call. A call it is not granted throws when the hook runs.', 'engine.inspector.hook.capabilityUnknown': '(not a capability the sandbox grants)', + 'engine.inspector.hook.capabilityNotForHook': '(a hook body cannot be granted this; send mail from an action, a job or a flow)', 'engine.inspector.hook.options': 'Options', 'engine.inspector.hook.priority': 'Priority', 'engine.inspector.hook.async': 'Run asynchronously (after commit)', diff --git a/ui/packages/i18n/src/namespaces/studio/zh.ts b/ui/packages/i18n/src/namespaces/studio/zh.ts index e9469472b14..0db4862d2c5 100644 --- a/ui/packages/i18n/src/namespaces/studio/zh.ts +++ b/ui/packages/i18n/src/namespaces/studio/zh.ts @@ -1386,6 +1386,7 @@ const STUDIO_ZH: Record = { 'engine.inspector.hook.capabilities': '能力授权', 'engine.inspector.hook.capabilitiesHint': '此函数体可调用的 ctx API。调用未授权的 API 会在钩子运行时抛错。', 'engine.inspector.hook.capabilityUnknown': '(沙箱不授予此能力)', + 'engine.inspector.hook.capabilityNotForHook': '(钩子函数体不能授予此能力;请从 action、job 或 flow 发送邮件)', 'engine.inspector.hook.options': '选项', 'engine.inspector.hook.priority': '优先级', 'engine.inspector.hook.async': '异步运行(提交之后)',