Skip to content

Commit c42a045

Browse files
fix(lint)!: three publish-time checks for seeds, flow nodes and actions that save and do not work (#37807)
Part of #35143 Clause-②: yes (narrowing) Metadata-protocol: narrowed Skills-docs: follow-up #37814 ## 维护者速读 - 搭应用的人在发布种子数据、流程和按钮动作以及本地校验时,会被拦下三类“保存成功却不工作”的写法:种子数据里写了对象没有的字段、种子/流程步骤/按钮绑到不存在的对象、按钮脚本要写数据却没勾写权限。 - 属于“发布期作者规则第二批”中的种子与动作一族,替搭应用的人在保存时就发现启动后少记录、流程每次运行都失败、按钮一点就报无权限这类问题。 - 已经存好的配置不会被改写也不会在启动时被拒,只是下次发布被拦并给出改法;误拦时撤回这次合并即可恢复。 - 无 ## What changes The Seeds and actions family of the card's second batch of publish-time checks, three lines, each verified on `origin/main` first (probe configs under `examples/app-todo`, removed afterwards). | Line | Verdict on main | This PR | |---|---|---| | S1 seed key that is not a field of its object | holds for a plain `data: [{ object, records }]` entry and for a `seed` saved at the runtime door: `os validate` passed a misspelt key and the runtime gate dispatched nothing for `seed`. `defineSeed` already refused it when it ran. | new error `seed-record-unknown-field` | | S2 seed, flow node or action bound to an object that does not exist | partly covered. A seed: `defineStack` refuses an unprefixed miss on the CLI, and the runtime save door already refuses a seed over an object neither the registry nor a draft answers for (#34864, pinned in `protocol.seed-external-id-refusal.test.ts`); a platform-prefixed `sys_nothing_here` seed built clean. An action: `defineStack` refuses a missing `objectName` on the CLI; the runtime `action` door judged nothing. A flow `create_record` node to `pr_nope` passed everywhere | extends the existing `object-reference-unknown` ladder (`validateObjectReferences`) to the three bindings, as the card asks; no second rule. The seed binding is judged on the CLI only: the runtime seed door stays with #34864 | | S3 action body that writes without declaring the write | holds: an L2 body calling `ctx.api.object(…).update(…)` with `capabilities: []` passed. The declaration key exists (`body.capabilities`, enum `HookBodyCapability`, `api.write`), so the line was not stopped | new error `action-body-write-capability-undeclared` | - **S1** (`packages/lint/src/validate-seed-record-keys.ts`). The column set is the object's fields as served, including fields an object extension adds, plus the system columns the platform injects on that object (`injectedColumnsFor`). So an object built with `systemFields: false` is refused `created_at`, exactly as `defineSeed` refuses it. - Record keys and seed `columns` keys are both judged. A key is reported once per dataset. - A dataset whose object is unknown is left to S2. - Runs on the runtime `seed` door. - **S2** (`validate-object-references.ts`). New sites: - a seed dataset's `object` (CLI only, see below); - `config.objectName` on `get_record` / `create_record` / `update_record` / `delete_record` and object-form `screen` nodes, nested nodes included; - a standalone action's `objectName`. - At all three, an object the stack extends resolves. An unprefixed miss is an error. A platform-prefixed miss outside the known registry is the existing warning `object-reference-unregistered-platform`. - The member now runs on the `action` door as well. The suite entry dispatches on `action`, but only the member that declares the type runs. It does **not** run on the `seed` door: #34864's save-door refusal already answers it there, accepting a draft of the object in the same package and leaving the publish promotion and restore doors to the load. A snapshot of served objects cannot reproduce those carve-outs, so a second verdict there would contradict them. Found by the metadata-protocol suite and corrected in e5a226a. - An empty object set with no package closure in force is not a verdict, as at the list-view member (#24668): a host that hands over no objects supplied no universe. Under a closure an empty set is still a verdict (#24563). Both directions are pinned. - **Package closure.** An action saved into a package (`?package=`) is judged against that package's closure, as a flow saved there already was. An object another package owns resolves only when the manifest declares that package in `dependencies`. Three fixtures (one dogfood, one runtime, one protocol) had an authored package bind another package's object without declaring it, and each now declares the dependency. This is the part of the change most likely to meet a real author; see Acceptance notes. - **S3** (`validate-action-body-capabilities.ts`). The write set is the sandbox runner's `WRITE` list (`insert`, `update`, `delete`, `updateMany`, `deleteMany`, `upsert`). A test pins it against `quickjs-runner.ts`. - The scan is a regex over a copy of the source with comments and strings masked. The runtime gate must not load a parser: the tier-1 lazy-deps fence still holds, and the PR adds an action-write leg to that fence. - It recognises three call shapes: `ctx.api` direct, `const api = ctx.api` (or its destructured form) bound once, and a handle `const repo = ctx.api.object(…)`. - Runs on the runtime `action` and `object` doors. - **M1 check (the platform's own UI producing the refused shape).** Studio's `ScriptCapabilitiesField` lets the author tick `api.write`. - `os build` lowers a handler through `extract-hook-body.ts`, which infers the grant. Measured: a handler whose only write was `updateMany` or `deleteMany` inferred **no** grant, so it was lowered into exactly the shape S3 refuses. - Fixed here (`packages/cli`, commit ee0969c), with a two-case `it.each` pin. ### Commits outside the claim's `packages/lint` surface - ee0969c `fix(cli)`: the extractor's write regex, named above (`packages/cli/src/utils/extract-hook-body.ts` plus its test). - cd83ed8 `docs`: the rule count 81 → 83 on four pages, and the `validating-metadata.mdx` rows (two new, two extended). - 4ba19b7 `chore`: the changeset and the upgrade-guide entry `packages/spec/src/migrations/entries/semantic/19.publish-refuses-seeds-and-actions-that-save-and-do-not-work.ts` (notice only, no conversion). - 0a916bb `chore`: `turbo.json` and `scripts/cross-package-test-inputs.mjs` declare `packages/runtime/src/sandbox/quickjs-runner.ts` as an input of the lint test task, which reads it (`check:cross-package-test-inputs` went red without it). - 04d056b, a683a7d `test`: the fixtures named above, in `packages/qa/dogfood`, `packages/runtime` and `packages/objectql`. The objectql orphan-action pin is the one whose FROM this PR changes: the save is now refused 422. - e5a226a also edits two `packages/metadata-protocol` fixtures that save under a package closure, so that they serve the objects their actions and flow nodes bind. - c670495: one merge of `origin/main`. It touched nothing under `packages/lint`. ## Rework after contract review 7209862537 (head `6361589d`) - M1 (c6bb575): the flow-node site of `object-reference-unknown` is a warning when no closure and no whole collection is stated (the CLI case: a binding to a dependency's object the build cannot see), and an error at the publish door, as `flow-trigger-unknown-object` splits. The changeset, the ADR-0087 entry, the explanation and the docs row no longer claim the step "fails the run on every execution" unconditionally. - S1 (295210a): the `os build` extractor infers `api.write` through a bound handle, `?.` before the leaf, and an `.object(...)` argument holding a call; pinned shape by shape; the rule header names the shapes. - S2 (c6bb575): `seed-record-unknown-field` admits `id` / `created_at` / `updated_at` (the engine's provisioned columns, pinned to the objectql source) and gives the engine's door as the reason. - N2 (c6bb575): `os explain` entries for both new ids; `@objectstack/lint` now exports the two rule-id constants (and only those) so the explanation table can carry them. - Out of scope, filed: #37815 (hook bodies, other capability tokens, `updateById` advice, ADR-0141 D1 binding list). Skills follow-up: #37814. ## Tests - New: `validate-seed-record-keys.test.ts`, `validate-action-body-capabilities.test.ts` (19 scanner shapes, write set pinned to the runner), and a `[#35143]` block in `validate-object-references.test.ts`. Each rule has a positive and a negative pin through the registry and at the runtime door. - Re-pinned fences: - `runtime-gate.inert-type-writes.test.ts`: an `action` write now reaches only `validateObjectReferences` from the suite; a `hook` write still dispatches nothing. - `runtime-gate.object-writes.test.ts`: the object-door rosters. - `runtime-lazy-deps.test.ts`: the action leg, with no parser loaded. - Ablation, with the source mutated on disk and restored with `git checkout HEAD`: - The CLI regex: the two new cases go red. - Three lint guards (the extended-object exemption, the injected columns, the `api.write` skip): four tests go red. ### Readings at head a683a7d <details><summary>Scoped suites (all at a683a7d or at e5a226a, whose lint and metadata-protocol sources a683a7d does not change)</summary> - `@objectstack/lint`, whole package: Test Files 241/241, Tests 9760/9760. The three new or extended files: 3/3, 114/114 at a683a7d. - `@objectstack/metadata-protocol`, whole package: Test Files 371 passed + 9 skipped, Tests 23450 passed + 45 skipped. Before the fixes it read 84 failed across 8 files, every one `object-reference-unknown`. - `@objectstack/cli`: the extractor test plus `migrate-meta-engine-guidance` 63/63; the `unit` tier 446/446 files, 6395/6395 tests. The `integration` tier is left to CI. - `@objectstack/objectql`: whole package 6 failed before the fixtures (all `object-reference-unknown`); the four touched files 68/68 after. - `@objectstack/runtime`: whole package 1 failed before the fixture (`object-reference-unknown`); the touched file 2/2 after. - `@objectstack/mcp` 1589/1589, `@objectstack/plugin-approvals` 1966/1966, `@objectstack/example-showcase` 554/554. - Typecheck, each exit 0: `lint`, `objectql`, `runtime`, `metadata-protocol`, `dogfood`, `cli`. The test layers compile under `tsconfig.test.json`. It caught a stray gate-input key in three new lint tests, fixed in 72b7cec. </details> <details><summary>Dogfood battery (the PR narrows)</summary> - a683a7d: `VERDICT command-exit 0`, Test Files 490 passed + 3 skipped (493), Tests 4144 passed + 68 skipped (4212). - An earlier run at 72b7cec went red, 3 failed in `action-save-packageless-other-object.dogfood.test.ts`. Its package bound an action to a showcase object without declaring the showcase package. Fixed in 04d056b; the battery above is the rerun on the final head. </details> <details><summary>Derived gates (dispatch-gates at a683a7d)</summary> - 141 derived, 140 run with exit 0. One is NOT MEASURED: `node scripts/check-plugin-teardown-shape.mjs --self-test` exits 3 because its positive control is pinned to a commit this shallow clone cannot reach. It is a checker-health self-test. - `--ran` reconciliation: 141 accounted for, 0 unrun. - `check:cross-package-test-inputs` was red at 4ba19b7 and is green at head (0a916bb). - `check-nul-bytes` OK. `check-platform-checklist --changed-from origin/main` OK (4 anchors judged, 0 lost). - Every CI-only family (type-check lanes, Build Core, Test Core shards, the merge-queue dogfood shards) is left to this PR's check-runs. </details> ## Acceptance notes - **Pins sweep.** - `os validate` and `os build` on `app-crm`, `app-multi-package`, `app-starter`, `app-todo` and `app-showcase` all exit 0 with "Running author-time rules (83)" and no new finding. - hotcrm, read at 99a4279: every action body that writes grants `api.write`; its 45 flows bind only declared or platform-provided objects; its seeds use `defineSeed`. - The `create-objectstack` template is not affected. - **Severity.** A flow node's object miss is an error, because that is the ladder's rule. The existing CLI `flow-trigger-unknown-object` stays a warning. The divergence is noted here, not changed. - **Widened door.** An `action` write is now also judged for its params' `reference` / `objectOverride` objects, as `os validate` already judged them. The changeset says so. - **Package closure on the action door (for contract review).** A package authored in Studio that adds an action to an object another package owns is now refused until its manifest declares that package. Flows have already been held to this. It comes with the ladder the card said to extend, and three in-repo fixtures needed the declaration. If actions should be judged against the whole served collection even under a closure, that is a one-line change in the member's options. The report raises it as an open question. - **Not judged, same family:** - hook bodies (`body.capabilities` on a hook has the same gap); - `ctx.api.transaction` without `api.transaction`; - the other capability tokens. - These are listed in the report for the seat. - **`updateById` is not installed by the sandbox**, yet lint's `API_WRITE_METHODS` grades it, and the `action-record-write-discarded` hint recommends `ctx.api.object(…).updateById(…)`. Reported for the seat to measure; not touched here. - **Contract review is owed.** The seat runs it. ## Verification Two-minute check: ```bash pnpm --filter @objectstack/lint exec vitest run --maxWorkers=2 src/validate-seed-record-keys.test.ts src/validate-action-body-capabilities.test.ts src/validate-object-references.test.ts ``` Expect `Test Files 3 passed (3)` and `Tests 114 passed (114)`. Read first, by risk: 1. `packages/lint/src/validate-action-body-capabilities.ts`: the masked regex scanner. A false positive here refuses a publish. The hunk to read is `bodyApiWriteCalls` and its alias / `boundOnce` handling. 2. `packages/lint/src/authoring-rules.ts` with `reference-integrity-suite.ts`: the suite entry now dispatches on `seed` and `action`. The hunk to read is the `runtimeTypes` widening and the member filter it relies on. 3. `packages/lint/src/validate-object-references.ts`: the new binding block. The hunk to read is the `extended` exemption and the flow-node type list. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01Q4EjjQkY5yXZrN9BEA3rEK <!-- signed: repo:objectstack#6 · hotlong · session_01Q4EjjQkY5yXZrN9BEA3rEK --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 91875c7 commit c42a045

32 files changed

Lines changed: 1474 additions & 34 deletions
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
---
2+
'@objectstack/lint': minor
3+
'@objectstack/spec': patch
4+
'@objectstack/cli': patch
5+
---
6+
7+
fix(lint)!: three publish-time checks for seeds, flow nodes and actions that save and do not work
8+
9+
Clause-②: yes (narrowing)
10+
Metadata-protocol: narrowed
11+
Skills-docs: follow-up #37814
12+
13+
<!-- adr-0087: registered publish-refuses-seeds-and-actions-that-save-and-do-not-work -->
14+
15+
**BREAKING** for the publish of a seed, a flow, an action or an object that carries one of the errors below: it was accepted before and is refused now, with the fix named in the finding. The schema is unchanged and stored metadata is not rewritten or refused at boot; the refusal comes at the next publish, and from `os validate` / `lint` / `compile` / `build`.
16+
17+
- `seed-record-unknown-field`: a seed record key, or a seed `columns` key, that the engine's insert door would refuse: a key that names no field of the dataset's object, no system column the platform injects on it (`owner_id`, the tenant and audit columns, unless the object opts out), and none of the columns every table carries (`id`, `created_at`, `updated_at`). The seed load writes each record through that insert, so such a record is dropped while the rest load. An object with no field map is not judged, as the engine's door does not judge it. `defineSeed` already refused such a key when it ran; a plain `data: [{ object, records }]` entry and a `seed` saved at the runtime publish door are now judged too. A field an object extension adds counts. Runs on the runtime `seed` door.
18+
- `object-reference-unknown` (and the warning `object-reference-unregistered-platform` for a platform-prefixed name no known package registers), at three more bindings: a seed dataset's `object`, a flow `get_record` / `create_record` / `update_record` / `delete_record` / object-form `screen` node's `config.objectName`, and a standalone action's `objectName`. A seed over a missing object loads nothing, and an action bound to one is carried by no page. A flow node is split as `flow-trigger-unknown-object` is: on `os validate` / `lint` / `build` an unprefixed name the stack does not define is a warning, because a package the stack declares in `dependencies` may define it and a build cannot see that package; at the runtime publish door it is an error, judged against the written package's closure, or against every object the deployment serves for a write that names no package, where a step bound to a missing object fails the run every time it executes. An object the stack extends resolves at these three. At the runtime publish door the seed binding stays with the save door's own refusal of a seed over an unknown object (#34864), which accepts a draft of the object in the same package; the rule now also runs on the runtime `action` door, so an `action` write is therefore also judged for its params' `reference` / `objectOverride` objects, as `os validate` already judged them, and an action saved into a package (`?package=`) is judged against that package's closure, as a flow saved there already was: an object another package owns resolves only when the manifest declares that package in `dependencies`.
19+
- `action-body-write-capability-undeclared`: an L2 action body that calls a `ctx.api` write (`insert`, `update`, `delete`, `updateMany`, `deleteMany`, `upsert`) without `api.write` in its `body.capabilities`. The sandbox refuses the call with `403 INSUFFICIENT_PRIVILEGES` every time the action reaches it. Runs on the runtime `action` and `object` doors.
20+
21+
`os build` now infers `api.write` for every handler write shape the new check reads: a lone `updateMany` or `deleteMany`, `?.` before the leaf, an `.object(…)` argument holding a call, and a handle bound to `.object(…)` (`const repo = ctx.api.object('x'); repo.update(…)`). Before, such a handler was lowered with no grant and refused at every call.
22+
23+
## FROM → TO
24+
25+
- `data: [{ object: 'task', records: [{ name: 'a', stauts: 'open' }] }]` → `status: 'open'`, or declare `stauts` on `task`, or drop the key.
26+
- `{ type: 'create_record', config: { objectName: 'invoce', … } }` → `objectName: 'invoice'` (the object's full, namespaced name).
27+
- `body: { language: 'js', source: "await ctx.api.object('task').update(…)", capabilities: [] }` → `capabilities: ['api.write']`.
28+
29+
`@objectstack/lint` exports two rule id constants, `SEED_RECORD_UNKNOWN_FIELD` and `ACTION_BODY_WRITE_CAPABILITY_UNDECLARED`, so `os explain` carries an entry for each; the rules themselves are not exported. `@objectstack/spec` adds only the upgrade-guide entry `publish-refuses-seeds-and-actions-that-save-and-do-not-work`.

‎content/docs/deployment/cli.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -937,7 +937,7 @@ os compile --json # JSON output for CI pipelines
937937
→ Normalizing stack definition...
938938
→ Lowering inline handlers...
939939
→ Validating protocol compliance...
940-
→ Running author-time rules (83)...
940+
→ Running author-time rules (85)...
941941
→ Checking that every required capability has a provider installable in this edition...
942942
→ Collecting package docs (ADR-0046)... 0 collected
943943
→ Writing artifact...

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

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -506,8 +506,8 @@ orthogonal to both, and no cell here can carry it; it is written out in
506506
| Filter placeholder resolvability (#3574) | ✓ | ✓ | ✓ | — |
507507
| Ordering comparands naming a date-range preset — `last_30_days` in a `>=` position (#8793) | ✓ | ✓ | ✓ | ✓ᵈᵛᵒᵖᶠʳ |
508508
| Empty filter combinators — `$and: []`, `$or: []`, `$not: {}` (#5330) | ✓ | ✓ | ✓ | ✓ᶠʳ |
509-
| Object & action name references (#3583) | ✓ | ✓ | ✓ | ✓ᶠᵈᵗ |
510-
| Reference integrity — flow node writes, template paths, read-only writes (#3583); at the publish door each write type runs only the members that declare it, and the flow members run on `flow` alone (#9313) | ✓ | ✓ | ✓ | ✓ᶠᵛᵒᵈᵗʳᵖ |
509+
| Object & action name references (#3583) — and the object a seed dataset, a flow `get_record` / `create_record` / `update_record` / `delete_record` / object-form `screen` node or a standalone action is bound to (`object-reference-unknown`, #35143); a flow node's miss is a warning on the CLI, where a declared dependency may define the object, and an error at the publish door; at the publish door a seed over an unknown object is the save door's own refusal (#34864) | ✓ | ✓ | ✓ | ✓ᶠᵈᵗᵃᶜ |
510+
| Reference integrity — flow node writes, template paths, read-only writes (#3583); at the publish door each write type runs only the members that declare it, and the flow members run on `flow` alone (#9313) | ✓ | ✓ | ✓ | ✓ᶠᵛᵒᵈᵗʳᵖᵃᶜ |
511511
| List-view field members — a list view's `sort` (a `sortable: false` field, a `formula`, an unknown name: `sort-field-unsortable`), its `searchableFields` (`searchable-field-unknown`) and its field references, columns, filter keys, grouping and the board bindings (`list-view-field-unknown`); the row merges three members, so its codes follow no one rule's order, and the `page` door runs the sort member only (#9313, #15495, #30095) | ✓ | ✓ | ✓ | ✓ᶠᵛᵒᵖ |
512512
| Page-component field bindings (#3583) | ✓ | ✓ | ✓ | ✓ᶠ |
513513
| React page block field bindings — §10 (#4340) | ✓ | ✓ | ✓ | ✓ᶠ |
@@ -520,6 +520,8 @@ orthogonal to both, and no cell here can carry it; it is written out in
520520
| 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) | ✓ | ✓ | ✓ | ✓ᵖ |
521521
| JSX / React page source parses (ADR-0080/0081) | ✓ | ✓ | ✓ | — |
522522
| 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) | ✓ | ✓ | ✓ | ✓ᵃᶜᵒ |
523+
| 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) | ✓ | ✓ | ✓ | ✓ᵃᶜᵒ |
524+
| 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) | ✓ | ✓ | ✓ | ✓ˢ |
523525
| 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) | ✓ | ✓ | ✓ | ✓ʰ |
524526
| Approval-node approvers (ADR-0090 D3) | ✓ | ✓ | ✓ | ✓ᶠ |
525527
| Security posture (ADR-0090 — e.g. every custom object declares `sharingModel`) | ✓ | ✓ | ✓ | ✓ˢᵖᵉᵇᵒ |
@@ -867,7 +869,7 @@ A clean run walks the registry and reports timing:
867869
Config: /path/to/support-desk/objectstack.config.ts
868870
Load time: 21ms
869871
→ Validating against ObjectStack Protocol...
870-
→ Running author-time rules (83)...
872+
→ Running author-time rules (85)...
871873
→ Checking that every required capability has a provider installable in this edition...
872874
→ Checking package docs (ADR-0046)...
873875

‎content/docs/getting-started/build-with-claude-code.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -318,7 +318,7 @@ visible: 'status != "resolved"'
318318
◆ Validate
319319
────────────────────────────────────────
320320
→ Validating against ObjectStack Protocol...
321-
→ Running author-time rules (83)...
321+
→ Running author-time rules (85)...
322322
323323
✗ Author-time rules failed (1 issue)
324324
• stack · action 'resolve_ticket' visible: bare reference `status` — a

‎content/docs/ui/react-pages.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -404,7 +404,7 @@ objectstack validate
404404
────────────────────────────────────────
405405
→ Loading configuration...
406406
→ Validating against ObjectStack Protocol...
407-
→ Running author-time rules (83)...
407+
→ Running author-time rules (85)...
408408
→ Checking that every required capability has a provider installable in this edition...
409409
→ Checking package docs (ADR-0046)...
410410

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

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -514,7 +514,9 @@ const CAPABILITY_PATTERNS: Array<{ rx: RegExp; cap: 'api.read' | 'api.write' | '
514514
// checks a grant only at a call. One token is the exception, see the door
515515
// patterns at the end of this list.
516516
{ rx: /\.object\s*\([^)]+\)\s*\.\s*(?:find|findOne|count|aggregate|get|list)\b/, cap: 'api.read' },
517-
{ rx: /\.object\s*\([^)]+\)\s*\.\s*(?:insert|update|upsert|delete|patch|remove|create)\b/, cap: 'api.write' },
517+
// [#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' },
518520
{ rx: /ctx\.crypto\.randomUUID\b/, cap: 'crypto.uuid' },
519521
// NO `ctx.crypto.hash` pattern: the `crypto.hash` token was removed in spec 17
520522
// (#4391) because the sandbox never installed the function. Inferring a
@@ -553,6 +555,51 @@ const CAPABILITY_PATTERNS: Array<{ rx: RegExp; cap: 'api.read' | 'api.write' | '
553555
{ rx: /ctx\.activity\.append\b/, cap: 'activity.append' },
554556
];
555557

558+
/** 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';
560+
561+
/** The index of the `)` closing the `(` at `open`, or -1. Counts nesting; strings are not special. */
562+
function closingParen(source: string, open: number): number {
563+
let depth = 0;
564+
for (let i = open; i < source.length; i++) {
565+
const ch = source[i];
566+
if (ch === '(') depth++;
567+
else if (ch === ')' && --depth === 0) return i;
568+
}
569+
return -1;
570+
}
571+
572+
/**
573+
* [#35143] Whether the body writes through `.object(...)` in a shape the
574+
* `api.write` pattern's single regex cannot read — the shapes the publish
575+
* check `action-body-write-capability-undeclared` reads, so a handler `os build`
576+
* lowers is never refused by the next step of the same build:
577+
*
578+
* - an argument holding a call or other parentheses: `ctx.api.object(name()).update(…)`;
579+
* - `?.` before the leaf: `ctx.api.object('x')?.update(…)`;
580+
* - a bound handle: `const repo = ctx.api.object('x'); … repo.update(…)`.
581+
*
582+
* Receiver-loose like the patterns above, for their reason: an over-inferred
583+
* grant is one the sandbox never checks, an under-inferred one is a 403 at
584+
* every call.
585+
*/
586+
function callsObjectWriteThroughHandle(source: string): boolean {
587+
const chainedWrite = new RegExp(String.raw`^\s*\??\.\s*(?:${OBJECT_WRITE_LEAVES})\b`);
588+
const handles: string[] = [];
589+
for (const m of source.matchAll(/\??\.\s*object\s*\(/g)) {
590+
const open = (m.index ?? 0) + m[0].length - 1;
591+
const close = closingParen(source, open);
592+
if (close < 0) continue;
593+
const after = source.slice(close + 1);
594+
if (chainedWrite.test(after)) return true;
595+
const bound = /\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:await\s+)?[\w$.? \t]*$/.exec(source.slice(0, m.index ?? 0));
596+
if (bound && /^\s*(?:;|\n|$)/.test(after)) handles.push(bound[1]);
597+
}
598+
return handles.some((name) =>
599+
new RegExp(String.raw`(?<![\w$.])${name.replace(/\$/g, '\\$')}\s*\??\.\s*(?:${OBJECT_WRITE_LEAVES})\s*\(`).test(source),
600+
);
601+
}
602+
556603
export interface ExtractedBody {
557604
/** Pure function-body source (without the surrounding `(ctx) => {...}`). */
558605
source: string;
@@ -657,6 +704,8 @@ export function extractLoweredBody(
657704
for (const { rx, cap } of CAPABILITY_PATTERNS) {
658705
if (rx.test(source)) inferred.add(cap);
659706
}
707+
// [#35143] The `.object(...)` write shapes one regex cannot read; see the helper.
708+
if (callsObjectWriteThroughHandle(source)) inferred.add('api.write');
660709
// [#22837] The ctx-anchored patterns above spell `ctx.`; a rebound body
661710
// reaches the same members through the handler's own names.
662711
for (const cap of reboundCapabilities(source, rebind)) inferred.add(cap);

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

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,53 @@ describe('extractHookBody', () => {
5656
expect(extractHookBody(fn, 'hook c').capabilities).toContain('api.write');
5757
});
5858

59+
// [#35143] `updateMany` and `deleteMany` are two of the sandbox's six
60+
// `api.write` leaves. The write pattern's `\b` after `update` / `delete` did
61+
// not match inside either name, so a handler whose only write was one of them
62+
// was lowered with no grant and refused at every call.
63+
it.each(['updateMany', 'deleteMany'])('infers api.write from a lone %s', (method) => {
64+
const fn =
65+
method === 'updateMany'
66+
? async (ctx: any) => {
67+
await ctx.api.object('foo').updateMany({ status: 'x' }, { done: true });
68+
}
69+
: async (ctx: any) => {
70+
await ctx.api.object('foo').deleteMany({ status: 'x' });
71+
};
72+
expect(extractHookBody(fn, 'hook c2').capabilities).toEqual(['api.write']);
73+
});
74+
75+
// [#35143] The shapes the publish check `action-body-write-capability-undeclared`
76+
// reads (`bodyApiWriteCalls`) beyond a direct chain. Each lowered without a
77+
// grant before, so `os build` lowered a handler and then refused it.
78+
it.each([
79+
['a bound handle', async (ctx: any) => {
80+
const repo = ctx.api.object('foo');
81+
await repo.update('id', { done: true });
82+
}],
83+
['a bound handle through an alias of ctx.api', async (ctx: any) => {
84+
const api = ctx.api;
85+
const repo = api.object('foo');
86+
await repo.deleteMany({ done: true });
87+
}],
88+
['`?.` before the leaf', async (ctx: any) => {
89+
await ctx.api.object('foo')?.insert({ name: 'x' });
90+
}],
91+
['an object argument holding a call', async (ctx: any) => {
92+
await ctx.api.object(String('foo')).upsert({ name: 'x' }, { on: ['name'] });
93+
}],
94+
])('infers api.write through %s', (_shape, fn) => {
95+
expect(extractHookBody(fn, 'hook shapes').capabilities).toContain('api.write');
96+
});
97+
98+
it('infers no api.write from a bound handle that only reads (control)', () => {
99+
const fn = async (ctx: any) => {
100+
const repo = ctx.api.object('foo');
101+
return repo.find({});
102+
};
103+
expect(extractHookBody(fn, 'hook read handle').capabilities).not.toContain('api.write');
104+
});
105+
59106
it('infers log', () => {
60107
const fn = (ctx: any) => {
61108
ctx.log.info('hi');

0 commit comments

Comments
 (0)