Skip to content

Commit 4b57756

Browse files
fix(runtime,cli,lint,spec)!: a sandboxed body's ctx.api.object(X).updateById(id, patch) writes the row (#38643)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9JeHmqv6CKCkW8ewrPBLekk)_ Fixes #38630 Clause-②: no (narrowing) Metadata-protocol: narrowed Skills-docs: follow-up #38655 ## 维护者速读 - 用户能看到什么变化:应用作者在脚本动作和触发器里按文档写的「按编号更新一条记录」现在真的能保存改动,之前这样写第一次运行就报错、数据不变;传错编号(比如传了一个查询条件)会得到一句清楚的拒绝,什么也不写。 - 为什么做:文档和对外类型说明都承诺有这个写法,只有脚本运行的沙箱缺了它;属于脚本动作写入能力补齐的工作。 - 出错会怎样:只影响调用这个写法的脚本,原来的另一种更新写法不变;保存检查同时变严:没有声明写权限就用这个写法的脚本动作,以及以系统身份用它改人员授权记录的脚本,保存时会被拒绝(这两种脚本以前也从来运行不成功);有问题可直接撤回。 - 要你做什么:这是收紧保存检查的改动,需要一次契约级审核后才能落地。 ## What changes - **Runtime (the fix).** The QuickJS sandbox's `ctx.api.object(X)` now installs `updateById` among its `WRITE` leaves (`installCtx`), behind the same `api.write` capability gate. It forwards by name to the host's scoped repository, as every leaf does; no per-method argument mapping was needed. - **Runtime (the id guard).** `updateById`'s id argument is judged at the crossing, before the host is called (`ID_ARGUMENT_INDEX`, `refuseNonScalarIdArgument`). Anything but a non-empty string or a non-zero number is refused as `VALIDATION_ERROR` / 400 with a sentence naming the call, the shape it was given, and the bulk form (`update(data, { where, multi: true })`). `0` and `''` are refused because `HookObjectApi.updateById` already declares them a refusal (they identify no row). - **CLI.** `objectstack build`'s `api.write` inference names `updateById` (the `api.write` regex and `OBJECT_WRITE_LEAVES`), so a lowered handler whose only write is `updateById` is granted the call. The word boundary matters: `update\b` does not match inside `updateById`. - **Lint.** `SANDBOX_API_WRITE_METHODS` gains `updateById`; its existing pin to the runner's `WRITE` list holds with both sides moved. `action-body-write-capability-undeclared` therefore finds an ungranted `updateById` call. - **Spec (save-time identity refusal).** `BODY_WRITE_METHODS` in `packages/spec/src/identity/identity-assignment-body-writes.ts`, the list that names itself the runner's `api.write` set, gains `updateById`. So `HookSchema` and `ActionSchema` refuse an elevated body (a `runAs: 'system'` hook, a `script` action) that writes `sys_user_position`, `sys_user_permission_set`, `sys_invitation` or `sys_member` through `updateById`, as they refuse the other write calls. Before this change the call threw `TypeError: not a function` in the sandbox; now that it is installed, the run-time refusal (plugin-security's data middleware) refuses the write as well. - **BREAKING, at two authoring doors** (`!`, `Clause-②: no (narrowing)`, `Metadata-protocol: narrowed`). At save and in `os validate`: an action body calling `updateById` without `api.write` is refused as `action-body-write-capability-undeclared` (FROM saved and threw at every run → TO declare `api.write`), and the elevated identity-assignment write above is refused at `body.source`. Neither body ever worked. ADR-0087: `registered` — the new v19 entry `hook-action-body-system-identity-assignment-update-by-id-refused` for the identity-assignment door, beside the existing `publish-refuses-seeds-and-actions-that-save-and-do-not-work` that covers the ungranted `api.write` write. - **Text that this change made false, fixed in the same files.** Two author-facing sentences listed the sandbox's write leaves and would have gone on saying `updateById` is not one: the `os explain action-body-write-capability-undeclared` paragraph (`rule-explanations.ts`, it said "the six `ctx.api` write leaves") and the build's `.create()` refusal (`extract-hook-body.ts`). Both now list `updateById`; "six" is dropped. - **Write-leaf lists brought to the installed set:** the comments in `validate-hook-body-writes.ts` (`API_WRITE_METHODS` note), `validate-action-body-writes.ts` (two comments that said a body has no `updateById`; the hint itself is unchanged) and `authoring-rules.ts`, and the two docs lists (`content/docs/automation/hook-bodies.mdx`, the `.create()` paragraph; `content/docs/deployment/validating-metadata.mdx`, the rule's row). - **The build's capability-inference table names every write leaf it infers from.** In `content/docs/automation/hook-bodies.mdx`, the `api.write` row of the Capability inference table now reads `insert / update / updateById / updateMany / upsert / delete / deleteMany / patch / remove / create`, the alternation `extract-hook-body.ts` matches. `updateById` is new here. `updateMany` and `deleteMany` were already inferred, and the row had omitted them before this PR; they are fixed in the same row. - **A v19 semantic entry records the identity-assignment narrowing.** `packages/spec/src/migrations/entries/semantic/19.hook-action-body-system-identity-assignment-update-by-id-refused.ts` records that a save now refuses an elevated body (a `runAs: 'system'` hook or a `script` action) that writes `sys_user_position`, `sys_user_permission_set`, `sys_invitation` or `sys_member` through `updateById`, a call that threw `TypeError: not a function` before this release. The v18 entry `hook-action-body-system-identity-assignment-write-refused` is unchanged: in v18 `updateById` was never refused, it threw. The protocol upgrade guide is projected from the registries by `gen:upgrade-guide` into the gitignored `content/docs/protocol-upgrade/`; nothing generated is committed. - **Re-read, unchanged.** `rule-explanations.ts` ~1365 / ~1376 / ~1838 and `validate-hook-body-writes.ts` ~246 / ~256 name `updateById` as a write channel; with the leaf installed each is true, so none is edited. The `hook-bodies.mdx` snippet is now true, and the `action-record-write-discarded` hint (`update({ id: ctx.recordId, … })`) stays. <details><summary>Measured before the change, and what the host does with a non-scalar id</summary> Probe on real `ObjectQL` + better-sqlite3 `SqlDriver` + `QuickJSScriptRunner`, at `origin/main` f3028c5 (throwaway file, not committed): ```text PROBE ACTION updateById :: {"err":{"name":"SandboxError","message":"action 'close' threw: TypeError: not a function"}} :: A=open,B=open PROBE ACTION typeof :: {"ok":"undefined"} PROBE ACTION update({id}) :: {"ok":"ok"} :: A=won2,B=open PROBE HOOK updateById :: {"name":"SandboxError","message":"hook 'win_deal' threw: TypeError: not a function"} :: A=open,B=open ``` The host repository called in-process (`ScopedContext.object('ubi_deal').updateById(id, …)`), two rows seeded: every non-scalar or falsy id was refused by the engine and no row moved. The messages are about filters or `options.multi`, and several carry no code: | id | host answer | |:--|:--| | `{ $ne: null }`, `{ $in: [id] }`, `null`, `''`, `0`, `NaN`, `true` | `Error: Update requires an ID or options.multi=true` (no code) | | `{}` | `INVALID_FILTER` / 400 (empty object at `where.id`) | | `[id]` | `INVALID_FILTER` / 400 (array comparand at `where.id`) | | `undefined` | `INVALID_FILTER` / 400 (undefined comparand at `where.id`) | So no shape reaches a wider write than one row today; the guard turns each into one coded refusal before the engine is called. After the change, same probe: `updateById` writes `A=won`, a `null` id answers `VALIDATION_ERROR` / 400 with `ctx.api.object('ubi_deal').updateById(id, data) needs the id of one record (a non-empty string or a non-zero number) and was given null, so nothing was written.` </details> ## Tests - `packages/runtime/src/sandbox/body-update-by-id.integration.test.ts` (new, real runner): an action body and a hook body calling `updateById(id, patch)` write that row and only that row (before/after reads of both rows); a control on `update({ id, … })` on both faces; the `api.write` gate (`INSUFFICIENT_PRIVILEGES` / 403, nothing written); one case per refused id shape (operator object, array, `null`, `undefined`, `''`, `0`), each asserting `code` + `status`, no `update` reaching the engine (an engine middleware counts them) and no row moved; and a hook body that catches the coded refusal. - `packages/cli/test/extract-hook-body.test.ts`: `updateById` alone infers exactly `['api.write']`, directly and on a bound handle; the `.create()` refusal's leaf list. - `packages/spec/src/identity/identity-assignment-body-writes.test.ts`: `updateById` joins the per-method battery (every quote form, all four objects); a `runAs: 'system'` hook and a script action writing `sys_user_position` through `updateById` are refused at `body.source` with their sentence; CONTROL: the same call on `crm_account` parses on both faces. - `packages/lint/src/validate-action-body-capabilities.test.ts`: an ungranted `updateById` is refused and named; granted, it passes. The runner-list pin is unchanged and green with both lists moved. <details><summary>Readings</summary> - New runtime file: `Test Files 1 passed (1)`, `Tests 11 passed (11)`. - Ablation 1, the leaf removed (`scripts/ablation-replace.mjs`, anchor x1 → x0, blob b52e071 → a62699b7b677): `Tests 10 failed | 1 passed (11)`, the one green being the `update({ id })` control; restored, blob == HEAD, `git diff HEAD` empty. - Ablation 2, the guard call removed (blob b52e071 → a36d5c25cb9d): `Tests 7 failed | 4 passed (11)`, the seven guard cases red (`expected undefined to be 'VALIDATION_ERROR'`, `expected 'INVALID_FILTER' to be 'VALIDATION_ERROR'`), the write pins, control and gate green; restored, `git diff HEAD` empty. - `@objectstack/cli` `test/extract-hook-body.test.ts`: `Tests 67 passed (67)`. - `@objectstack/lint` whole suite: `Test Files 246 passed (246)`, `Tests 9960 passed (9960)`. - `pnpm --filter @objectstack/runtime --filter @objectstack/cli --filter @objectstack/lint typecheck`: VERDICT command-exit 0. - `@objectstack/spec` whole suite at f7b947f: `Test Files 1007 passed (1007)`, `Tests 30504 passed | 1 todo (30505)`. - Ablation 3, `updateById` removed from the spec's `BODY_WRITE_METHODS` (blob 408d74e → b126506): `Tests 6 failed | 25 passed (31)` in `identity-assignment-body-writes.test.ts`, the four per-object method batteries and the two `updateById` refusals red, the `crm_account` control green; restored, blob == HEAD, `git diff HEAD` empty. - `@objectstack/lint` whole suite at f7b947f: `Test Files 246 passed (246)`, `Tests 9960 passed (9960)`. - New v19 entry at 4c186ea: `check-adr-0087-registration --base origin/main` exits 0 (`registered hook-action-body-system-identity-assignment-update-by-id-refused, publish-refuses-seeds-and-actions-that-save-and-do-not-work`; `1 migration entry added, each at or above PROTOCOL_MAJOR 19`); `check:spec-changes` and `check:upgrade-guide` generate in memory (protocol 19.0.0); `gen:upgrade-guide` writes the docs pages and `19.md` carries the entry; `check:generated` after a spec build: `All 14 generated artifacts are up to date`; the spec migrations, registry and upgrade-guide tests: `Test Files 8 passed (8)`, `Tests 246 passed (246)`; cli `test/migrate-meta-engine-guidance.test.ts`: `Tests 3 passed (3)`; `check-changeset-no-major --event` with this PR's body: exit 0; `overlap-check --branch=HEAD`: VERDICT clean. - `@objectstack/spec` `pnpm test` (local project) at 8e38653: `Test Files 913 passed (913)`, `Tests 28896 passed | 1 todo (28897)`; the upgrade-guide span and docs tests with the migrations tests: `Test Files 7 passed (7)`, `Tests 239 passed (239)`. `dispatch-gates --ran` at 8e38653: 124 derived, 124 run, 0 UNRUN; every family exit 0 once the cli and formula closures were built. - Inference-row edit at 60c75f9: the 45 families `dispatch-gates --commands` derives for `content/docs/automation/hook-bodies.mdx` all exit 0, among them `check:doc-anchors` (1179 fragment links resolve), `check:docs-spec-enumerations`, `check:doc-security-posture` and `check:doc-formula-expressions`; `overlap-check --branch=HEAD`: VERDICT clean. - Changeset correction at 0382b34: the BREAKING table's second FROM cell and the sentence after the table now say both bodies threw `TypeError: not a function` before this change. - Dogfood battery (`pnpm --filter @objectstack/dogfood test`, no shard, at f7b947f): VERDICT command-exit 0, `Test Files 495 passed | 3 skipped (498)`, `Tests 4187 passed | 68 skipped (4255)`. - `dispatch-gates --ran`: 121 derived, 121 run, 0 UNRUN. Four exited 3 for a prerequisite, not a finding: `check-plugin-teardown-shape --self-test` (shallow clone), `check:skill-examples` (client-react dist not built), `check:dual-build-cjs-loads`; `check:type-check-debt` re-run under the lock afterwards: `OK — 0 ledger entr(ies) re-measured … none above its recorded number`. CI's `Type Check · debt ledger` is green. </details> ## Acceptance notes - First-party bodies calling `updateById`: none, so nothing in this repository is newly refused. ## Verification Read first, by risk: 1. `packages/runtime/src/sandbox/quickjs-runner.ts`: `refuseNonScalarIdArgument` and its call at the top of `installApiMethod`'s leaf. 2. `packages/runtime/src/sandbox/body-update-by-id.integration.test.ts`: the refused-shape table. 3. `packages/cli/src/utils/extract-hook-body.ts`: the `api.write` alternation. Two-minute check: `pnpm --filter @objectstack/runtime exec vitest run --project local src/sandbox/body-update-by-id.integration.test.ts` prints `Tests 11 passed (11)`. For the save-time narrowing: `pnpm --filter @objectstack/spec exec vitest run src/identity/identity-assignment-body-writes.test.ts` prints `Tests 31 passed (31)`. --- _Generated by [Claude Code](https://claude.ai/code/session_01ADHkmSwS4mQyXWrddL4r6B)_ <!-- signed: repo:objectstack#3 · os-steve · session_01ADHkmSwS4mQyXWrddL4r6B --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 34daac1 commit 4b57756

18 files changed

Lines changed: 400 additions & 34 deletions
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
---
2+
'@objectstack/runtime': patch
3+
'@objectstack/cli': patch
4+
'@objectstack/lint': minor
5+
'@objectstack/spec': minor
6+
---
7+
8+
fix(runtime,cli,lint,spec)!: a sandboxed body's `ctx.api.object(X).updateById(id, patch)` writes the row
9+
10+
Clause-②: no (narrowing)
11+
Metadata-protocol: narrowed
12+
13+
<!-- adr-0087: registered hook-action-body-system-identity-assignment-update-by-id-refused, publish-refuses-seeds-and-actions-that-save-and-do-not-work -->
14+
15+
**BREAKING** for two authoring doors, which now refuse at save and in `os validate` a body that calls `updateById` where they already refused the same write spelled any other way:
16+
17+
| FROM | TO |
18+
|:--|:--|
19+
| a `type: 'script'` action whose body calls `ctx.api.object(X).updateById(…)` without `api.write` in `body.capabilities`: saved, then threw at every run | refused as `action-body-write-capability-undeclared`; declare `api.write` in the action's `body.capabilities` |
20+
| a `runAs: 'system'` hook, or a `type: 'script'` action, whose body calls `ctx.api.object('sys_user_position' \| 'sys_user_permission_set' \| 'sys_invitation' \| 'sys_member').updateById(…)`: saved, then threw `TypeError: not a function` at every run | refused at `body.source` with the existing prescription (a `runAs: 'user'` hook or flow, or the organization endpoints) |
21+
22+
Neither body ever worked: before this change both threw `TypeError: not a function`, because the sandbox did not install `updateById`. Now that the call is installed, the first is refused for its missing `api.write` (INSUFFICIENT_PRIVILEGES) and the second by the run-time security middleware, and both are also refused at save. Stored metadata is not rewritten or refused at boot; the next save of such a body is refused with the fix named.
23+
24+
An action body or hook body that called `ctx.api.object(X).updateById(id, patch)` threw `TypeError: not a function` and wrote nothing, although `HookObjectApi.updateById` and `IScopedObjectRepository.updateById` declare the member, the in-process repository serves it, and the hook-bodies guide teaches it as the way an action body persists. The QuickJS sandbox now installs `updateById` beside the other write leaves, behind the same `api.write` capability, so the call writes the record the id names and answers it. `update({ id, … })` is unchanged.
25+
26+
The id is judged before the host is called: anything but a non-empty string or a non-zero number (an object, an array, `null`, `undefined`, `''`, `0`) is refused with `VALIDATION_ERROR` / 400 naming the call, and nothing is written. Such ids were already refused one layer down, with messages about filters; the refusal now names the argument. To write every row a filter matches, call `update(data, { where, multi: true })`.
27+
28+
`objectstack build` now infers `api.write` for a lowered handler whose only write is `updateById`, so the body it produces is granted the call. The explanation of `action-body-write-capability-undeclared` and the build's `.create()` refusal list `updateById` among the sandbox's write leaves.

‎content/docs/automation/hook-bodies.mdx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -323,7 +323,7 @@ The dropped case is the dangerous one: nothing fails, the step reports success,
323323

324324
Which hooks these rules can *see* depends on the command, because every rule in this family opens on `body.language === 'js'`. A hook authored as an inline `handler` function carries no `body`, so it is judged only where the command has first lowered the handler to a metadata body: `objectstack build` always has (it lowers before it parses — see [How the build lowers a handler](#build-pipeline)), and since [#16095](https://github.com/objectstack-ai/objectstack/issues/16095) `objectstack lint` judges that same lowered view, so an author who runs only the pre-flight is told the same thing the build would refuse. Since [#16544](https://github.com/objectstack-ai/objectstack/issues/16544) `objectstack validate` lowers before it parses as well, so all three commands judge the same view of a handler-authored hook — a stack `objectstack validate` passes is one `objectstack build` does not refuse on this family. A handler the build cannot lower (a forbidden token, a module-scope identifier) has no body on any command and is reported by the lowering rules instead, never guessed at here.
325325

326-
Only literal object names and literal payload keys are seen; a `sudo()` chain, a dynamic object name and an object this stack does not declare are all skipped, so the rule has no opinion on them. `.create()` is skipped too, and since [#16249](https://github.com/objectstack-ai/objectstack/issues/16249) it cannot even arrive: `objectstack build` refuses `.create(` at lowering, so a handler spelling it is bundled and never becomes a `body` these rules parse, and the write-shape ledger no longer advertises the verb. The reason behind that refusal is about the **sandbox** rather than the engine: the VM-side `ctx.api.object()` installs `insert` / `update` / `delete` / `updateMany` / `deleteMany` / `upsert` and no `create` leaf, and the `IScopedObjectRepository` contract declares `insert` only — so a body calling `.create()` threw `TypeError: not a function` on its first run, aborting the triggering write under the default `onError: 'abort'`. A loud failure, never a silent drop; the same payload spelled `.insert()` is what the rules judge. The flow surface has carried the same gate as `flow-update-readonly-field` since [#3425](https://github.com/objectstack-ai/objectstack/issues/3425), and since [#15394](https://github.com/objectstack-ai/objectstack/issues/15394) it reports a non-`runAs: 'system'` `create_record` node's static-`readonly` write at the same **error**, again with no conditional finding on a create.
326+
Only literal object names and literal payload keys are seen; a `sudo()` chain, a dynamic object name and an object this stack does not declare are all skipped, so the rule has no opinion on them. `.create()` is skipped too, and since [#16249](https://github.com/objectstack-ai/objectstack/issues/16249) it cannot even arrive: `objectstack build` refuses `.create(` at lowering, so a handler spelling it is bundled and never becomes a `body` these rules parse, and the write-shape ledger no longer advertises the verb. The reason behind that refusal is about the **sandbox** rather than the engine: the VM-side `ctx.api.object()` installs `insert` / `update` / `updateById` / `delete` / `updateMany` / `deleteMany` / `upsert` and no `create` leaf, and the `IScopedObjectRepository` contract declares `insert` only — so a body calling `.create()` threw `TypeError: not a function` on its first run, aborting the triggering write under the default `onError: 'abort'`. A loud failure, never a silent drop; the same payload spelled `.insert()` is what the rules judge. The flow surface has carried the same gate as `flow-update-readonly-field` since [#3425](https://github.com/objectstack-ai/objectstack/issues/3425), and since [#15394](https://github.com/objectstack-ai/objectstack/issues/15394) it reports a non-`runAs: 'system'` `create_record` node's static-`readonly` write at the same **error**, again with no conditional finding on a create.
327327

328328
The table above is about a **hook** body. An **action** body is the one surface where the answer changes, so read this before you move a body from one to the other: an action body runs **elevated** — its `ctx.api` is built over the caller's envelope with `isSystem` set, which is the same trusted posture that lets an action bypass row and field permissions — and the static strip applies only to non-system callers. So `ctx.api.object('x').update({ someReadonlyField })` **lands** in an action, and there is no finding for it. Elevation does not waive the *conditional* lock, though, so that half does carry across: `action-api-update-readonly-when-field` — a **warning** — on an action body's literal `ctx.api` update to a `readonlyWhen` field ([#13770](https://github.com/objectstack-ai/objectstack/issues/13770)). Net effect when you move a body: a `readonly` write changes behaviour, a `readonlyWhen` write does not.
329329

@@ -452,7 +452,7 @@ The extractor scans each body for known patterns and adds the matching capabilit
452452
| Pattern in source | Inferred capability |
453453
|---|---|
454454
| `*.object(…).find / findOne / count / aggregate / get / list` | `api.read` |
455-
| `*.object(…).insert / update / upsert / delete / patch / remove / create` | `api.write` |
455+
| `*.object(…).insert / update / updateById / updateMany / upsert / delete / deleteMany / patch / remove / create` | `api.write` |
456456
| `ctx.crypto.randomUUID` | `crypto.uuid` |
457457
| `ctx.log.info / warn / error / debug` | `log` |
458458
| `*.title(<argument>)` — the related-record form only; bare `ctx.title()` names this record and needs no token | `api.read` |

‎content/docs/deployment/validating-metadata.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -522,7 +522,7 @@ orthogonal to both, and no cell here can carry it; it is written out in
522522
| Page variable declarations — each name once and never blank, a `defaultValue` of its declared type, a `source` naming a component the page holds (#28663, #28725) | ✓ | ✓ | ✓ | ✓ᵖ |
523523
| JSX / React page source parses (ADR-0080/0081) | ✓ | ✓ | ✓ | — |
524524
| Script action bodies compile in the runtime's wrapper — an L2 action's `body.source` that does not compile as the body of `(async (input, ctx) => { … })`, most often `const input = …` redeclaring a parameter; an object write runs it over its inline `actions[]`, so an object write cannot republish a refused body (`action-body-does-not-compile`, #34884) | ✓ | ✓ | ✓ | ✓ᵃᶜᵒ |
525-
| Script action bodies hold the grant they call — an L2 action body that calls a `ctx.api` write (`insert`, `update`, `delete`, `updateMany`, `deleteMany`, `upsert`) without `api.write` in its `body.capabilities`, which the sandbox refuses at every call (`action-body-write-capability-undeclared`, #35143) | ✓ | ✓ | ✓ | ✓ᵃᶜᵒ |
525+
| Script action bodies hold the grant they call — an L2 action body that calls a `ctx.api` write (`insert`, `update`, `updateById`, `delete`, `updateMany`, `deleteMany`, `upsert`) without `api.write` in its `body.capabilities`, which the sandbox refuses at every call (`action-body-write-capability-undeclared`, #35143) | ✓ | ✓ | ✓ | ✓ᵃᶜᵒ |
526526
| Seed record keys — a seed record key, or a seed `columns` key, that names no field of the dataset's object, no system column injected on it and none of `id` / `created_at` / `updated_at`; the engine's insert door refuses such a record and the seed load loads the rest (`seed-record-unknown-field`, #35143) | ✓ | ✓ | ✓ | ✓ˢ |
527527
| Hook and job bodies compile in the runtime's wrapper — an L2 hook or job `body.source` that does not compile as the body of `(async (ctx) => { … })`, most often `const ctx = …` redeclaring the parameter or one name declared twice; no door publishes a job, so the publish column is the `hook` write alone (`hook-body-does-not-compile`, `job-body-does-not-compile`, #34987) | ✓ | ✓ | ✓ | ✓ʰ |
528528
| Approval-node approvers (ADR-0090 D3) | ✓ | ✓ | ✓ | ✓ᶠ |

‎packages/cli/src/utils/extract-hook-body.ts‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -356,7 +356,7 @@ const FORBIDDEN_PATTERNS: Array<{ rx: RegExp; reason: string; face?: LoweringFac
356356
// contract `IScopedObjectRepository` declares `insert` and NOT `create`
357357
// (packages/spec/src/contracts/scoped-context.ts — `create` is listed there
358358
// as measured and deliberately excluded), and the VM installs exactly
359-
// `insert / update / delete / updateMany / deleteMany / upsert` as the
359+
// `insert / update / updateById / delete / updateMany / deleteMany / upsert` as the
360360
// `ctx.api.object()` write leaves (`installCtx`,
361361
// runtime/src/sandbox/quickjs-runner.ts). So a lowered body's `.create()` is
362362
// `TypeError: not a function` on its FIRST run, and under a hook's default
@@ -387,7 +387,8 @@ const FORBIDDEN_PATTERNS: Array<{ rx: RegExp; reason: string; face?: LoweringFac
387387
rx: /(?<!\bObject\s*)\.\s*create\s*\(/,
388388
reason:
389389
'`create()` is not reachable from a sandboxed body — the VM\'s `ctx.api.object()` installs '
390-
+ '`insert` / `update` / `delete` / `updateMany` / `deleteMany` / `upsert` and no `create` leaf, so '
390+
+ '`insert` / `update` / `updateById` / `delete` / `updateMany` / `deleteMany` / `upsert` and no '
391+
+ '`create` leaf, so '
391392
+ 'the call is a TypeError at run time (and under a hook\'s default `onError: \'abort\'` that aborts '
392393
+ 'the triggering write). Spell the same payload `.insert({ ... })`, which is the member the sandbox '
393394
+ 'actually has and the only insert verb the spec contract declares; `Object.create()` is unaffected. '
@@ -515,8 +516,10 @@ const CAPABILITY_PATTERNS: Array<{ rx: RegExp; cap: 'api.read' | 'api.write' | '
515516
// patterns at the end of this list.
516517
{ rx: /\.object\s*\([^)]+\)\s*\.\s*(?:find|findOne|count|aggregate|get|list)\b/, cap: 'api.read' },
517518
// [#35143] `updateMany` / `deleteMany` spelled out: `update\b` does not match
518-
// inside either name, and both are sandbox `api.write` leaves.
519-
{ rx: /\.object\s*\([^)]+\)\s*\.\s*(?:insert|updateMany|update|upsert|deleteMany|delete|patch|remove|create)\b/, cap: 'api.write' },
519+
// inside either name, and both are sandbox `api.write` leaves. `updateById`
520+
// likewise, for the same reason: the id-first single-record write the spec
521+
// contract declares, installed behind `api.write`.
522+
{ rx: /\.object\s*\([^)]+\)\s*\.\s*(?:insert|updateById|updateMany|update|upsert|deleteMany|delete|patch|remove|create)\b/, cap: 'api.write' },
520523
{ rx: /ctx\.crypto\.randomUUID\b/, cap: 'crypto.uuid' },
521524
// NO `ctx.crypto.hash` pattern: the `crypto.hash` token was removed in spec 17
522525
// (#4391) because the sandbox never installed the function. Inferring a
@@ -556,7 +559,7 @@ const CAPABILITY_PATTERNS: Array<{ rx: RegExp; cap: 'api.read' | 'api.write' | '
556559
];
557560

558561
/** The write leaves the `api.write` pattern above names, as one alternation. */
559-
const OBJECT_WRITE_LEAVES = 'insert|updateMany|update|upsert|deleteMany|delete|patch|remove|create';
562+
const OBJECT_WRITE_LEAVES = 'insert|updateById|updateMany|update|upsert|deleteMany|delete|patch|remove|create';
560563

561564
/** The index of the `)` closing the `(` at `open`, or -1. Counts nesting; strings are not special. */
562565
function closingParen(source: string, open: number): number {

‎packages/cli/test/extract-hook-body.test.ts‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,24 @@ describe('extractHookBody', () => {
7272
expect(extractHookBody(fn, 'hook c2').capabilities).toEqual(['api.write']);
7373
});
7474

75+
// `updateById` is a sandbox `api.write` leaf too, the id-first write the spec
76+
// contract declares. `update\b` does not match inside the name, so the verb is
77+
// named in the pattern; a handler whose only write is it must get the grant.
78+
it('infers api.write from a lone updateById', () => {
79+
const fn = async (ctx: any) => {
80+
await ctx.api.object('crm_deal').updateById(ctx.recordId, { stage: 'won' });
81+
};
82+
expect(extractHookBody(fn, 'hook c3').capabilities).toEqual(['api.write']);
83+
});
84+
85+
it('infers api.write from updateById on a bound handle', () => {
86+
const fn = async (ctx: any) => {
87+
const deals = ctx.api.object('crm_deal');
88+
await deals.updateById(ctx.recordId, { stage: 'won' });
89+
};
90+
expect(extractHookBody(fn, 'hook c4').capabilities).toEqual(['api.write']);
91+
});
92+
7593
// [#35143] The shapes the publish check `action-body-write-capability-undeclared`
7694
// reads (`bodyApiWriteCalls`) beyond a direct chain. Each lowered without a
7795
// grant before, so `os build` lowered a handler and then refused it.
@@ -414,7 +432,7 @@ describe('extractHookBody', () => {
414432
// Same family as `sudo()` above, one layer over. The host `ObjectRepository`
415433
// aliases `create(data)` to `insert(data)` and the spec contract
416434
// `IScopedObjectRepository` declares `insert` only, while the VM installs
417-
// `insert / update / delete / updateMany / deleteMany / upsert` and no
435+
// `insert / update / updateById / delete / updateMany / deleteMany / upsert` and no
418436
// `create` leaf — so a lowered body's `.create()` TypeErrors on its first
419437
// run and, under a hook's default `onError: 'abort'`, aborts the triggering
420438
// write. What made it worse than an omission: the extractor ledger in
@@ -442,7 +460,7 @@ describe('extractHookBody', () => {
442460
message = (err as Error).message;
443461
}
444462
expect(message).toMatch(/`\.insert\(\{ \.\.\. \}\)`/);
445-
expect(message).toMatch(/`insert` \/ `update` \/ `delete` \/ `updateMany` \/ `deleteMany` \/ `upsert`/);
463+
expect(message).toMatch(/`insert` \/ `update` \/ `updateById` \/ `delete` \/ `updateMany` \/ `deleteMany` \/ `upsert`/);
446464
expect(message).toMatch(/no `create` leaf/);
447465
// The carve-out is stated in the refusal itself, so an author who hits it
448466
// over an `Object.create()` false positive is told it is not the subject.

‎packages/lint/src/authoring-rules.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3385,7 +3385,7 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [
33853385
run: (stack) => validateActionBodyCompiles(stack),
33863386
},
33873387
// [#35143] An L2 action body that calls a write leaf of `ctx.api` (`insert`,
3388-
// `update`, `delete`, `updateMany`, `deleteMany`, `upsert`) without granting
3388+
// `update`, `updateById`, `delete`, `updateMany`, `deleteMany`, `upsert`) without granting
33893389
// itself `api.write` (`action-body-write-capability-undeclared`). The sandbox
33903390
// refuses the call at the call site, so the action answers 403 on every click
33913391
// that reaches it. Gating: the grant and the refusal are both facts. Read,

‎packages/lint/src/rule-explanations.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1506,10 +1506,10 @@ const ACTION_BODY_WRITE_CAPABILITY_UNDECLARED_EXPLANATION: RuleExplanation = {
15061506
covers: 'the grant a script action body\'s writes need',
15071507
paragraphs: [
15081508
'A script action body runs in the QuickJS sandbox with only the capabilities its `body.capabilities` ' +
1509-
'lists (none by default). The sandbox installs the six `ctx.api` write leaves (`insert`, `update`, ' +
1510-
'`delete`, `updateMany`, `deleteMany`, `upsert`) behind `api.write`, and a call the body was not ' +
1511-
'granted throws at the call site: the action answers `403 INSUFFICIENT_PRIVILEGES` every time it ' +
1512-
'reaches the call, and nothing is written.',
1509+
'lists (none by default). The sandbox installs the `ctx.api` write leaves (`insert`, `update`, ' +
1510+
'`updateById`, `delete`, `updateMany`, `deleteMany`, `upsert`) behind `api.write`, and a call the ' +
1511+
'body was not granted throws at the call site: the action answers `403 INSUFFICIENT_PRIVILEGES` ' +
1512+
'every time it reaches the call, and nothing is written.',
15131513
'The rule reads the body\'s source with comments, strings and template literals blanked, and finds ' +
15141514
'a write leaf called through `ctx.api` (with `?.` allowed), through a local bound once to `ctx.api` ' +
15151515
'(`const api = ctx.api`, or `api` destructured from `ctx`), or through a handle bound once to ' +

‎packages/lint/src/validate-action-body-capabilities.test.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,17 @@ describe('validateActionBodyCapabilities (#35143)', () => {
5858
expect(findings[0].hint).toContain("Add 'api.write'");
5959
});
6060

61+
// `updateById` is a write leaf the sandbox installs behind `api.write`: an
62+
// ungranted call is refused there, so it is refused here, named as the call.
63+
it('refuses an updateById write with no api.write grant, and passes it once granted', () => {
64+
const source = "await ctx.api.object('pr_task').updateById(ctx.recordId, { done: true });";
65+
const refused = validateActionBodyCapabilities({ actions: [action(source, ['api.read'])] });
66+
expect(refused).toHaveLength(1);
67+
expect(refused[0]).toMatchObject({ severity: 'error', rule: ACTION_BODY_WRITE_CAPABILITY_UNDECLARED });
68+
expect(bodyApiWriteCalls(source)).toEqual(['updateById']);
69+
expect(validateActionBodyCapabilities({ actions: [action(source, ['api.write'])] })).toEqual([]);
70+
});
71+
6172
it('refuses when capabilities is absent (the spec default is none)', () => {
6273
expect(
6374
validateActionBodyCapabilities({ actions: [action("await ctx.api.object('pr_task').insert({ name: 'x' });")] }),

0 commit comments

Comments
 (0)