diff --git a/.changeset/35143-seeds-actions-checks.md b/.changeset/35143-seeds-actions-checks.md new file mode 100644 index 00000000000..35bed7e900f --- /dev/null +++ b/.changeset/35143-seeds-actions-checks.md @@ -0,0 +1,29 @@ +--- +'@objectstack/lint': minor +'@objectstack/spec': patch +'@objectstack/cli': patch +--- + +fix(lint)!: three publish-time checks for seeds, flow nodes and actions that save and do not work + +Clause-②: yes (narrowing) +Metadata-protocol: narrowed +Skills-docs: follow-up #37814 + + + +**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`. + +- `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. +- `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`. +- `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. + +`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. + +## FROM → TO + +- `data: [{ object: 'task', records: [{ name: 'a', stauts: 'open' }] }]` → `status: 'open'`, or declare `stauts` on `task`, or drop the key. +- `{ type: 'create_record', config: { objectName: 'invoce', … } }` → `objectName: 'invoice'` (the object's full, namespaced name). +- `body: { language: 'js', source: "await ctx.api.object('task').update(…)", capabilities: [] }` → `capabilities: ['api.write']`. + +`@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`. diff --git a/content/docs/deployment/cli.mdx b/content/docs/deployment/cli.mdx index 84b2fca29bf..4f8873b9e80 100644 --- a/content/docs/deployment/cli.mdx +++ b/content/docs/deployment/cli.mdx @@ -937,7 +937,7 @@ os compile --json # JSON output for CI pipelines → Normalizing stack definition... → Lowering inline handlers... → Validating protocol compliance... - → Running author-time rules (83)... + → Running author-time rules (85)... → Checking that every required capability has a provider installable in this edition... → Collecting package docs (ADR-0046)... 0 collected → Writing artifact... diff --git a/content/docs/deployment/validating-metadata.mdx b/content/docs/deployment/validating-metadata.mdx index 60e04ddd919..c26b0ffc8a1 100644 --- a/content/docs/deployment/validating-metadata.mdx +++ b/content/docs/deployment/validating-metadata.mdx @@ -506,8 +506,8 @@ orthogonal to both, and no cell here can carry it; it is written out in | Filter placeholder resolvability (#3574) | ✓ | ✓ | ✓ | — | | Ordering comparands naming a date-range preset — `last_30_days` in a `>=` position (#8793) | ✓ | ✓ | ✓ | ✓ᵈᵛᵒᵖᶠʳ | | Empty filter combinators — `$and: []`, `$or: []`, `$not: {}` (#5330) | ✓ | ✓ | ✓ | ✓ᶠʳ | -| Object & action name references (#3583) | ✓ | ✓ | ✓ | ✓ᶠᵈᵗ | -| 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) | ✓ | ✓ | ✓ | ✓ᶠᵛᵒᵈᵗʳᵖ | +| 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) | ✓ | ✓ | ✓ | ✓ᶠᵈᵗᵃᶜ | +| 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) | ✓ | ✓ | ✓ | ✓ᶠᵛᵒᵈᵗʳᵖᵃᶜ | | 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) | ✓ | ✓ | ✓ | ✓ᶠᵛᵒᵖ | | Page-component field bindings (#3583) | ✓ | ✓ | ✓ | ✓ᶠ | | 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 | 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) | ✓ | ✓ | ✓ | ✓ᵖ | | JSX / React page source parses (ADR-0080/0081) | ✓ | ✓ | ✓ | — | | 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) | ✓ | ✓ | ✓ | ✓ᵃᶜᵒ | +| 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) | ✓ | ✓ | ✓ | ✓ᵃᶜᵒ | +| 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) | ✓ | ✓ | ✓ | ✓ˢ | | 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) | ✓ | ✓ | ✓ | ✓ʰ | | Approval-node approvers (ADR-0090 D3) | ✓ | ✓ | ✓ | ✓ᶠ | | Security posture (ADR-0090 — e.g. every custom object declares `sharingModel`) | ✓ | ✓ | ✓ | ✓ˢᵖᵉᵇᵒ | @@ -867,7 +869,7 @@ A clean run walks the registry and reports timing: Config: /path/to/support-desk/objectstack.config.ts Load time: 21ms → Validating against ObjectStack Protocol... - → Running author-time rules (83)... + → Running author-time rules (85)... → Checking that every required capability has a provider installable in this edition... → Checking package docs (ADR-0046)... diff --git a/content/docs/getting-started/build-with-claude-code.mdx b/content/docs/getting-started/build-with-claude-code.mdx index 71933220a9c..1050043c233 100644 --- a/content/docs/getting-started/build-with-claude-code.mdx +++ b/content/docs/getting-started/build-with-claude-code.mdx @@ -318,7 +318,7 @@ visible: 'status != "resolved"' ◆ Validate ──────────────────────────────────────── → Validating against ObjectStack Protocol... - → Running author-time rules (83)... + → Running author-time rules (85)... ✗ Author-time rules failed (1 issue) • stack · action 'resolve_ticket' visible: bare reference `status` — a diff --git a/content/docs/ui/react-pages.mdx b/content/docs/ui/react-pages.mdx index 21db3941a4f..42f0c623de9 100644 --- a/content/docs/ui/react-pages.mdx +++ b/content/docs/ui/react-pages.mdx @@ -404,7 +404,7 @@ objectstack validate ──────────────────────────────────────── → Loading configuration... → Validating against ObjectStack Protocol... - → Running author-time rules (83)... + → Running author-time rules (85)... → Checking that every required capability has a provider installable in this edition... → Checking package docs (ADR-0046)... diff --git a/packages/cli/src/utils/extract-hook-body.ts b/packages/cli/src/utils/extract-hook-body.ts index c86c9429d60..0efa13cd7ed 100644 --- a/packages/cli/src/utils/extract-hook-body.ts +++ b/packages/cli/src/utils/extract-hook-body.ts @@ -514,7 +514,9 @@ const CAPABILITY_PATTERNS: Array<{ rx: RegExp; cap: 'api.read' | 'api.write' | ' // checks a grant only at a call. One token is the exception, see the door // patterns at the end of this list. { rx: /\.object\s*\([^)]+\)\s*\.\s*(?:find|findOne|count|aggregate|get|list)\b/, cap: 'api.read' }, - { rx: /\.object\s*\([^)]+\)\s*\.\s*(?:insert|update|upsert|delete|patch|remove|create)\b/, cap: 'api.write' }, + // [#35143] `updateMany` / `deleteMany` spelled out: `update\b` does not match + // inside either name, and both are sandbox `api.write` leaves. + { rx: /\.object\s*\([^)]+\)\s*\.\s*(?:insert|updateMany|update|upsert|deleteMany|delete|patch|remove|create)\b/, cap: 'api.write' }, { rx: /ctx\.crypto\.randomUUID\b/, cap: 'crypto.uuid' }, // NO `ctx.crypto.hash` pattern: the `crypto.hash` token was removed in spec 17 // (#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' | ' { rx: /ctx\.activity\.append\b/, cap: 'activity.append' }, ]; +/** The write leaves the `api.write` pattern above names, as one alternation. */ +const OBJECT_WRITE_LEAVES = 'insert|updateMany|update|upsert|deleteMany|delete|patch|remove|create'; + +/** The index of the `)` closing the `(` at `open`, or -1. Counts nesting; strings are not special. */ +function closingParen(source: string, open: number): number { + let depth = 0; + for (let i = open; i < source.length; i++) { + const ch = source[i]; + if (ch === '(') depth++; + else if (ch === ')' && --depth === 0) return i; + } + return -1; +} + +/** + * [#35143] Whether the body writes through `.object(...)` in a shape the + * `api.write` pattern's single regex cannot read — the shapes the publish + * check `action-body-write-capability-undeclared` reads, so a handler `os build` + * lowers is never refused by the next step of the same build: + * + * - an argument holding a call or other parentheses: `ctx.api.object(name()).update(…)`; + * - `?.` before the leaf: `ctx.api.object('x')?.update(…)`; + * - a bound handle: `const repo = ctx.api.object('x'); … repo.update(…)`. + * + * Receiver-loose like the patterns above, for their reason: an over-inferred + * grant is one the sandbox never checks, an under-inferred one is a 403 at + * every call. + */ +function callsObjectWriteThroughHandle(source: string): boolean { + const chainedWrite = new RegExp(String.raw`^\s*\??\.\s*(?:${OBJECT_WRITE_LEAVES})\b`); + const handles: string[] = []; + for (const m of source.matchAll(/\??\.\s*object\s*\(/g)) { + const open = (m.index ?? 0) + m[0].length - 1; + const close = closingParen(source, open); + if (close < 0) continue; + const after = source.slice(close + 1); + if (chainedWrite.test(after)) return true; + const bound = /\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:await\s+)?[\w$.? \t]*$/.exec(source.slice(0, m.index ?? 0)); + if (bound && /^\s*(?:;|\n|$)/.test(after)) handles.push(bound[1]); + } + return handles.some((name) => + new RegExp(String.raw`(? {...}`). */ source: string; @@ -657,6 +704,8 @@ export function extractLoweredBody( for (const { rx, cap } of CAPABILITY_PATTERNS) { if (rx.test(source)) inferred.add(cap); } + // [#35143] The `.object(...)` write shapes one regex cannot read; see the helper. + if (callsObjectWriteThroughHandle(source)) inferred.add('api.write'); // [#22837] The ctx-anchored patterns above spell `ctx.`; a rebound body // reaches the same members through the handler's own names. for (const cap of reboundCapabilities(source, rebind)) inferred.add(cap); diff --git a/packages/cli/test/extract-hook-body.test.ts b/packages/cli/test/extract-hook-body.test.ts index 9f302daf1b7..0d20d642f81 100644 --- a/packages/cli/test/extract-hook-body.test.ts +++ b/packages/cli/test/extract-hook-body.test.ts @@ -56,6 +56,53 @@ describe('extractHookBody', () => { expect(extractHookBody(fn, 'hook c').capabilities).toContain('api.write'); }); + // [#35143] `updateMany` and `deleteMany` are two of the sandbox's six + // `api.write` leaves. The write pattern's `\b` after `update` / `delete` did + // not match inside either name, so a handler whose only write was one of them + // was lowered with no grant and refused at every call. + it.each(['updateMany', 'deleteMany'])('infers api.write from a lone %s', (method) => { + const fn = + method === 'updateMany' + ? async (ctx: any) => { + await ctx.api.object('foo').updateMany({ status: 'x' }, { done: true }); + } + : async (ctx: any) => { + await ctx.api.object('foo').deleteMany({ status: 'x' }); + }; + expect(extractHookBody(fn, 'hook c2').capabilities).toEqual(['api.write']); + }); + + // [#35143] The shapes the publish check `action-body-write-capability-undeclared` + // reads (`bodyApiWriteCalls`) beyond a direct chain. Each lowered without a + // grant before, so `os build` lowered a handler and then refused it. + it.each([ + ['a bound handle', async (ctx: any) => { + const repo = ctx.api.object('foo'); + await repo.update('id', { done: true }); + }], + ['a bound handle through an alias of ctx.api', async (ctx: any) => { + const api = ctx.api; + const repo = api.object('foo'); + await repo.deleteMany({ done: true }); + }], + ['`?.` before the leaf', async (ctx: any) => { + await ctx.api.object('foo')?.insert({ name: 'x' }); + }], + ['an object argument holding a call', async (ctx: any) => { + await ctx.api.object(String('foo')).upsert({ name: 'x' }, { on: ['name'] }); + }], + ])('infers api.write through %s', (_shape, fn) => { + expect(extractHookBody(fn, 'hook shapes').capabilities).toContain('api.write'); + }); + + it('infers no api.write from a bound handle that only reads (control)', () => { + const fn = async (ctx: any) => { + const repo = ctx.api.object('foo'); + return repo.find({}); + }; + expect(extractHookBody(fn, 'hook read handle').capabilities).not.toContain('api.write'); + }); + it('infers log', () => { const fn = (ctx: any) => { ctx.log.info('hi'); diff --git a/packages/lint/src/authoring-rules.ts b/packages/lint/src/authoring-rules.ts index 8b0511588e7..251a5b950bf 100644 --- a/packages/lint/src/authoring-rules.ts +++ b/packages/lint/src/authoring-rules.ts @@ -155,6 +155,8 @@ import { } from './validate-membership-key-declarations.js'; import { validateRuleCompilability } from './validate-rule-compilability.js'; import { validateActionBodyCompiles } from './validate-action-body-compiles.js'; +import { validateActionBodyCapabilities } from './validate-action-body-capabilities.js'; +import { validateSeedRecordKeys } from './validate-seed-record-keys.js'; import { validateHookAndJobBodyCompiles } from './validate-hook-body-compiles.js'; import { validateRuleSchemaFormats } from './validate-rule-schema-formats.js'; import { validateActionLocations } from './validate-action-locations.js'; @@ -1422,6 +1424,16 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ // tier 1 («the parsers load NEVER») from a standing fact into a red. The // measurement that named their bridge named `validateStackExpressions`, a // CEL-only rule, for exactly this reason. + // [#35143] `action` joins anyway, and the reason above still holds: since + // #9313 a write dispatches only the MEMBERS that declare its type, and the + // four body-writes members keep the frozen `flow` default, so an `action` + // write reaches `validateObjectReferences` alone (an action's `objectName`, + // the Seeds and actions family's binding line) and no parser loads — + // `runtime-lazy-deps.test.ts` gates an action write carrying a body to prove + // it. `seed` stays out: the save door already refuses a seed over an object + // nothing resolves (#34864), with the draft and publish-promotion carve-outs + // a snapshot of served objects cannot see. `hook` stays out: no member + // judges a hook write. // [#30023] `page` joins, NARROW by the same mechanism: a page write reaches // exactly `validateSortableFields`, the one member that declares `page`, // so a stored page sort naming a field the list door refuses @@ -1429,7 +1441,7 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ // does not have, as `page-field-unknown`) is refused at publish rather // than at its first fetch. Every other member keeps its declaration. surfaces: CLI_AND_RUNTIME, - runtimeTypes: ['flow', 'view', 'object', 'dataset', 'report', 'page'], + runtimeTypes: ['flow', 'view', 'object', 'dataset', 'report', 'page', 'action'], run: (stack, ctx) => validateReferenceIntegrity(stack, ctx), }, // ADR-0078 / #5068 — the SDUI component-props gate. `PageComponent.properties` @@ -2073,6 +2085,27 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ surfaceReason: RUNTIME_NEEDS_FULL_SNAPSHOT, run: (stack) => validateSeedStateMachine(stack), }, + // [#35143] A seed record key, or a seed `columns` key, that names no column + // of the dataset's object (`seed-record-unknown-field`). The seed load writes + // each record through the engine's insert, whose declared-field door refuses + // the key, so the record is dropped at boot while the build read as passed. + // `defineSeed` refuses it when it runs; a plain `data[]` entry and a `seed` + // saved at the runtime door were judged by nothing before the load. GATING + // on all three commands and on the runtime `seed` door. The columns are the + // object's fields as served — the stack's own extensions folded in on the + // CLI; at the door the deployment's served objects (`context.objects`) — plus + // the system columns injected on that object. A dataset whose object the + // snapshot does not hold is not judged here. + { + name: 'validateSeedRecordKeys', + tier: 'gating', + input: 'parsed', + commands: ALL, + source: 'packages/lint/src/validate-seed-record-keys.ts', + surfaces: CLI_AND_RUNTIME, + runtimeTypes: ['seed'], + run: (stack, ctx) => validateSeedRecordKeys(stack, objectsAsServed(stack, ctx.storedObjectExtensions ?? []).objects), + }, // An active state machine with no (or an empty) `initialStates`: a record // can be born in any state. Gating: the declaration works against its author // on every create. Reads the object's own body alone, so it judges an `object` write @@ -3203,6 +3236,25 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ runtimeTypes: ['action', 'object'], run: (stack) => validateActionBodyCompiles(stack), }, + // [#35143] An L2 action body that calls a write leaf of `ctx.api` (`insert`, + // `update`, `delete`, `updateMany`, `deleteMany`, `upsert`) without granting + // itself `api.write` (`action-body-write-capability-undeclared`). The sandbox + // refuses the call at the call site, so the action answers 403 on every click + // that reaches it. Gating: the grant and the refusal are both facts. Read, + // never parsed (the source parsers load at no runtime door), so it crosses + // the runtime publish gate for `action` writes and for `object` writes, whose + // inline `actions[]` the same walk reads; the differential charges a write + // only with the bodies it adds. + { + name: 'validateActionBodyCapabilities', + tier: 'gating', + input: 'parsed', + commands: ALL, + source: 'packages/lint/src/validate-action-body-capabilities.ts', + surfaces: CLI_AND_RUNTIME, + runtimeTypes: ['action', 'object'], + run: (stack) => validateActionBodyCapabilities(stack), + }, // The same compile check over an L2 hook body and an L2 job body, in the // wrapper the runtime runs both in (`(async (ctx) => { SOURCE })`, built from // the same function the rule compiles inside). Gating for the action rule's diff --git a/packages/lint/src/index.ts b/packages/lint/src/index.ts index 6c0f818e34b..d0a3884fa19 100644 --- a/packages/lint/src/index.ts +++ b/packages/lint/src/index.ts @@ -1138,6 +1138,12 @@ export { judgeBodyCompile, ACTION_BODY_DOES_NOT_COMPILE, } from './validate-action-body-compiles.js'; +// [#35143] The Seeds and actions family's two new rule ids, exported so +// `os explain` can carry an entry for each (the explanation table holds an +// entry only for an id the barrel exports). The rules themselves run through +// the registry and are not exported. +export { ACTION_BODY_WRITE_CAPABILITY_UNDECLARED } from './validate-action-body-capabilities.js'; +export { SEED_RECORD_UNKNOWN_FIELD } from './validate-seed-record-keys.js'; export type { ActionBodyCompileFinding, HostCompileFailure, diff --git a/packages/lint/src/reference-integrity-suite.ts b/packages/lint/src/reference-integrity-suite.ts index e9058b4acae..0954d55f274 100644 --- a/packages/lint/src/reference-integrity-suite.ts +++ b/packages/lint/src/reference-integrity-suite.ts @@ -249,11 +249,33 @@ export const REFERENCE_INTEGRITY_RULES: readonly ReferenceIntegrityRule[] = [ // prescription the flow and view doors print (declare the dependency, // ADR-0141 D1). Absent — the CLI, or a write that names no package — the // rule prints the hint it always did. The verdict and severity do not move. + // + // [#35143] `action` joins: the member now resolves the object a standalone + // action (`objectName`) is bound to, and the action write is the door that + // binding arrives through (Studio, REST `/meta`, an MCP/AI author). Safe for + // the reason above: the binding resolves against `stack.objects`, which every + // per-write snapshot carries, and the member's other rungs find no such + // collection on an action snapshot. A flow node's `config.objectName` rides + // the `flow` door the member already gates. `seed` does not join: the save + // door already refuses a seed over an object nothing resolves (#34864), with + // a draft of the object in the same package accepted and the publish + // promotion and restore doors left to the load, which a snapshot of served + // objects cannot reproduce. A seed dataset's `object` is judged on the CLI. { name: 'validateObjectReferences', - runtimeTypes: ['flow', 'dataset'], + runtimeTypes: ['flow', 'dataset', 'action'], + // [#35143] `wholeCollection` as the list-view member states it (#24668): + // a gated write that names no package is judged against everything the + // host serves, so the flow-node site refuses there; the CLI advises. run: (stack, ctx) => - validateObjectReferences(stack, ctx?.packageScope ? { packageScope: ctx.packageScope } : {}), + validateObjectReferences( + stack, + ctx?.packageScope + ? { packageScope: ctx.packageScope } + : ctx?.runtimeWriteType !== undefined + ? { wholeCollection: true } + : {}, + ), }, // [#9313] `runtimeTypes` gains `view` on this member and its sort sibling: // both judge a LIST VIEW's field references, and a standalone list view is diff --git a/packages/lint/src/rule-explanations.ts b/packages/lint/src/rule-explanations.ts index ab83db8b28c..8b6d437d37c 100644 --- a/packages/lint/src/rule-explanations.ts +++ b/packages/lint/src/rule-explanations.ts @@ -1501,6 +1501,47 @@ const ACTION_BODY_DOES_NOT_COMPILE_EXPLANATION: RuleExplanation = { ], }; +const ACTION_BODY_WRITE_CAPABILITY_UNDECLARED_EXPLANATION: RuleExplanation = { + rule: 'action-body-write-capability-undeclared', + covers: 'the grant a script action body\'s writes need', + paragraphs: [ + 'A script action body runs in the QuickJS sandbox with only the capabilities its `body.capabilities` ' + + 'lists (none by default). The sandbox installs the six `ctx.api` write leaves (`insert`, `update`, ' + + '`delete`, `updateMany`, `deleteMany`, `upsert`) behind `api.write`, and a call the body was not ' + + 'granted throws at the call site: the action answers `403 INSUFFICIENT_PRIVILEGES` every time it ' + + 'reaches the call, and nothing is written.', + 'The rule reads the body\'s source with comments, strings and template literals blanked, and finds ' + + 'a write leaf called through `ctx.api` (with `?.` allowed), through a local bound once to `ctx.api` ' + + '(`const api = ctx.api`, or `api` destructured from `ctx`), or through a handle bound once to ' + + '`.object(…)` (`const repo = ctx.api.object(\'x\'); repo.update(…)`). It does not parse or run ' + + 'the body: the runtime save door may load no parser. A write spelled another way is not found, ' + + 'which leaves the author where the sandbox would.', + 'To fix it, add `\'api.write\'` to the action\'s `body.capabilities` (Studio\'s action inspector ' + + 'draws the list), or remove the write. A body `os build` lowers from a handler gets the grant ' + + 'inferred from the same shapes, so a handler is not refused by its own build.', + ], +}; + +const SEED_RECORD_UNKNOWN_FIELD_EXPLANATION: RuleExplanation = { + rule: 'seed-record-unknown-field', + covers: 'which keys a seed record may carry', + paragraphs: [ + 'The seed load writes each record through the engine\'s insert, keys as authored. The insert door ' + + 'refuses a key the object does not declare, and the load runs in partial mode, so that record is ' + + 'dropped while the rest land: the build and the publish read as passed, and the first sign is a ' + + '`[Seeder] … dropped record(s)` line at boot.', + 'A key is accepted when the engine\'s door accepts it: a field of the object as served (fields an ' + + 'object extension adds count), a system column the platform injects on that object (the owner, ' + + 'tenant and audit columns, unless the object opts out), or one of the columns every table carries ' + + '(`id`, `created_at`, `updated_at`). A seed `columns` key that names none of them is refused too: ' + + 'its policy governs nothing, and the column it was meant for keeps the `always` default. A dataset ' + + 'whose object is not known, or whose object has no field map, is not judged.', + 'To fix it, spell the key as the field it means, declare the field on the object, or remove the ' + + 'key. `defineSeed` refuses such a key when it runs; this rule asks the same of a plain ' + + '`data: [{ object, records }]` entry and of a seed saved at the runtime save door.', + ], +}; + /** Shared by the hook and job compile rules: the two bodies run in one wrapper. */ const CTX_BODY_COMPILE: readonly string[] = [ 'The rule compiles the body inside the same expression the runtime builds, from the same function, ' + @@ -4891,8 +4932,11 @@ const OBJECT_REFERENCE_SITES = 'Judged: the object names no other rule resolves, each a plain string the schema ships as ' + 'written: a `lookup`, `master_detail` or `user` field\'s `reference`; a view container\'s own ' + '`object`; an action param\'s `reference` and `objectOverride`; a dashboard global filter\'s ' + - '`optionsFrom.object`; a dataset\'s base `object`; and a nav entry\'s `requiresObject`, with ' + - 'the `objectName` of an entry that carries one. Interpolated names (`${…}`) resolve at render ' + + '`optionsFrom.object`; a dataset\'s base `object`; a nav entry\'s `requiresObject`, with ' + + 'the `objectName` of an entry that carries one; and the object a seed dataset (`data[].object`), a ' + + 'flow `get_record` / `create_record` / `update_record` / `delete_record` / object-form `screen` node ' + + '(`config.objectName`) or a standalone action (`objectName`) is bound to, where an object the stack ' + + 'extends (`objectExtensions`) also resolves. Interpolated names (`${…}`) resolve at render ' + 'time and are skipped.'; /** The resolution ladder — both object-reference ids. Held to `PLATFORM_OBJECT_PREFIXES` by the rule's test. */ @@ -4918,7 +4962,10 @@ const OBJECT_REFERENCE_MISS_COST = '(ADR-0021), so every one of them queries nothing. A nav entry\'s `requiresObject`: the entry is ' + 'hidden unless the object is registered, so a typo hides it for good, and it suppresses the nav ' + 'cross-reference check that would have caught the target; the gated `objectName` is exempt from ' + - 'the build-time check, so it is verified only here.'; + 'the build-time check, so it is verified only here. A seed dataset: the seed load finds no object ' + + 'and loads none of its records. A flow node: when no installed package defines the object either, ' + + 'the step asks the engine for an object that is not there and fails the run every time it executes. ' + + 'A standalone action: it registers against no object, so no list or record page carries it.'; const OBJECT_REFERENCE_UNKNOWN_EXPLANATION: RuleExplanation = { rule: 'object-reference-unknown', @@ -4929,6 +4976,15 @@ const OBJECT_REFERENCE_UNKNOWN_EXPLANATION: RuleExplanation = { OBJECT_REFERENCE_LADDER, 'An error: a stack\'s own objects are namespace-prefixed and present, so an unprefixed name that ' + 'resolves nowhere has no legitimate elsewhere. Nothing reports the miss at run time.', + // [#35143] The flow-node split, as `flow-trigger-unknown-object` draws it. + 'One site is split by what the run can see. A flow node\'s `config.objectName` is a warning on ' + + '`os validate`, `os build` and `os lint`: a package the stack declares in `dependencies` may define ' + + 'the object, and a build cannot see that package\'s objects, so the step may well run. At the ' + + 'runtime save door it is an error: a write into a package is judged against that package\'s ' + + 'closure, and a write that names no package against every object the deployment serves, so a ' + + 'name outside either exists nowhere the run can reach. A stack that defines no object at all is ' + + 'not judged at the seed, flow-node and action sites, nor is a door write when the host hands ' + + 'over no objects.', OBJECT_REFERENCE_MISS_COST, 'To fix it, point the reference at an object this stack or its artifact defines, or at a platform ' + 'object by its full name (the platform user object is `sys_user`, not `user`). The verdict names ' + @@ -7024,6 +7080,8 @@ export const RULE_EXPLANATIONS: Readonly> = Obje [ACTION_RECORD_WRITE_DISCARDED_EXPLANATION.rule]: ACTION_RECORD_WRITE_DISCARDED_EXPLANATION, [ACTION_BODY_SOURCE_UNPARSEABLE_EXPLANATION.rule]: ACTION_BODY_SOURCE_UNPARSEABLE_EXPLANATION, [ACTION_BODY_DOES_NOT_COMPILE_EXPLANATION.rule]: ACTION_BODY_DOES_NOT_COMPILE_EXPLANATION, + [ACTION_BODY_WRITE_CAPABILITY_UNDECLARED_EXPLANATION.rule]: ACTION_BODY_WRITE_CAPABILITY_UNDECLARED_EXPLANATION, + [SEED_RECORD_UNKNOWN_FIELD_EXPLANATION.rule]: SEED_RECORD_UNKNOWN_FIELD_EXPLANATION, [HOOK_BODY_DOES_NOT_COMPILE_EXPLANATION.rule]: HOOK_BODY_DOES_NOT_COMPILE_EXPLANATION, [JOB_BODY_DOES_NOT_COMPILE_EXPLANATION.rule]: JOB_BODY_DOES_NOT_COMPILE_EXPLANATION, [ACTION_BODY_WRITE_UNPROVISIONED_ANCHOR_EXPLANATION.rule]: ACTION_BODY_WRITE_UNPROVISIONED_ANCHOR_EXPLANATION, diff --git a/packages/lint/src/runtime-gate.inert-type-writes.test.ts b/packages/lint/src/runtime-gate.inert-type-writes.test.ts index 4b2c2beafed..c9c2bf48eaf 100644 --- a/packages/lint/src/runtime-gate.inert-type-writes.test.ts +++ b/packages/lint/src/runtime-gate.inert-type-writes.test.ts @@ -981,18 +981,22 @@ describe('#19542 — group C: wired, dispatched, and silent by ledger (email_tem // ─── The fences ────────────────────────────────────────────────────────────── describe('#19542 — DARK: what the five crossings did NOT widen', () => { - it('`action` and `hook` writes do NOT dispatch the reference-integrity suite', () => { - // The one crossing that would turn `runtime-lazy-deps.test.ts` tier 1 - // («typescript / sucrase load NEVER») from a standing fact into a red: the - // suite carries the four body-writes members, and an action/hook write is - // exactly the snapshot that WOULD carry an authored JS body for them to - // parse. Their bridge is `validateStackExpressions`, which judges CEL. - for (const type of ['action', 'hook'] as const) { - expect( - runtimeAuthoringRulesFor(type).map((r) => r.name), - `'${type}' writes must not reach the suite — the body-writes members parse JS`, - ).not.toContain('validateReferenceIntegrity'); - } + it('a `hook` write does NOT dispatch the reference-integrity suite, and an `action` write reaches ONE member', () => { + // The fence's reason stands: the suite carries the four body-writes + // members, which parse JS, and an action/hook write is exactly the snapshot + // that WOULD carry an authored body for them to parse (tier 1 of + // `runtime-lazy-deps.test.ts`: «typescript / sucrase load NEVER»). + // [#35143] An `action` write now dispatches the suite for the binding of an + // action to its object, and the per-member `runtimeTypes` is what keeps the + // parsers out: exactly `validateObjectReferences` declares `action`, and + // none of the body-writes members does. The lazy-deps file gates an action + // write carrying a body and reads the require cache to prove it. + expect(runtimeAuthoringRulesFor('hook').map((r) => r.name)).not.toContain('validateReferenceIntegrity'); + expect(runtimeAuthoringRulesFor('action').map((r) => r.name)).toContain('validateReferenceIntegrity'); + const membersFor = (type: string) => + REFERENCE_INTEGRITY_RULES.filter((m) => (m.runtimeTypes ?? ['flow']).includes(type)).map((m) => m.name); + expect(membersFor('action')).toEqual(['validateObjectReferences']); + expect(membersFor('hook')).toEqual([]); }); it('a `report` write reaches exactly THREE suite members, and a `skill` write none', () => { diff --git a/packages/lint/src/runtime-gate.object-writes.test.ts b/packages/lint/src/runtime-gate.object-writes.test.ts index cf1a044fa0a..a80a5bc2f67 100644 --- a/packages/lint/src/runtime-gate.object-writes.test.ts +++ b/packages/lint/src/runtime-gate.object-writes.test.ts @@ -204,6 +204,10 @@ describe('the object write door dispatches at the adjudicated scope (#4716)', () // in the runtime's wrapper is refused here as at the `action` door. Its // door cases are in `validate-action-body-compiles.test.ts`. 'validateActionBodyCompiles', + // [#35143] The same reading, one question over: an inline action body that + // writes through `ctx.api` with no `api.write` grant. Door cases in + // `validate-action-body-capabilities.test.ts`. + 'validateActionBodyCapabilities', 'validateRuleSchemaFormats', ]); }); @@ -582,6 +586,7 @@ describe('the object write door dispatches at the adjudicated scope (#4716)', () 'validateMembershipKeyDeclarations', // [#25234] 'validateRuleCompilability', 'validateActionBodyCompiles', // see the roster pin above + 'validateActionBodyCapabilities', // [#35143] — see the roster pin above 'validateRuleSchemaFormats', ]); }); diff --git a/packages/lint/src/runtime-lazy-deps.test.ts b/packages/lint/src/runtime-lazy-deps.test.ts index 8f3928676ed..55f2d370095 100644 --- a/packages/lint/src/runtime-lazy-deps.test.ts +++ b/packages/lint/src/runtime-lazy-deps.test.ts @@ -154,6 +154,20 @@ const OBJECT_CONTEXT = [ { name: 'leave_request', sharingModel: 'private', fields: { owner: { type: 'text' } } }, ]; +/** + * [#35143] An action write whose L2 body writes through `ctx.api` with no + * `api.write` grant: refused by `validateActionBodyCapabilities`, which is what + * keeps the action leg's clean parser read falsifiable. + */ +const GATED_ACTION = { + name: 'leave_approve', + label: 'Approve', + objectName: 'leave_request', + type: 'script', + locations: ['record_header'], + body: { language: 'js', source: "await ctx.api.object('leave_request').update({ id: ctx.recordId, owner: 'x' });" }, +}; + // Same shape as lazy-deps.test.ts: a spawned child is the only place a native // require-cache probe means anything, because vitest inlines static imports // through its transform and they never reach that cache. @@ -210,6 +224,25 @@ const childBody = ` } } + // [#35143] An ACTION write carrying an L2 body: the reference suite and the + // body-capability rule both gate it, and neither may reach a source parser + // — the suite dispatches only the members that declare \`action\`, and the + // capability rule reads the source without parsing it. + const actionResult = mod.runRuntimeAuthoringRules({ + type: 'action', + item: ${JSON.stringify(GATED_ACTION)}, + context: { objects: ${JSON.stringify(OBJECT_CONTEXT)} }, + }); + if (!actionResult.rulesRun.includes('validateReferenceIntegrity')) { + fail('the reference suite is not dispatched for action writes — the action leg would assert nothing'); + } + if (!actionResult.errors.some((f) => f.rule === 'action-body-write-capability-undeclared')) { + fail('the gate did not refuse the action body that writes with no api.write grant — the probe below would be vacuously true'); + } + for (const dep of ${JSON.stringify(PARSER_DEPS)}) { + if (loaded(dep)) fail(dep + ' was loaded while gating an action write — no written type may reach a source parser'); + } + // Tier 3 (#4716): the SAME write carrying a json_schema validation must be // REFUSED by name, ajv must have loaded to judge it, and the parsers must // still be absent. Last, deliberately: after this the cache is dirty. diff --git a/packages/lint/src/validate-action-body-capabilities.test.ts b/packages/lint/src/validate-action-body-capabilities.test.ts new file mode 100644 index 00000000000..da64303bf55 --- /dev/null +++ b/packages/lint/src/validate-action-body-capabilities.test.ts @@ -0,0 +1,164 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { readFileSync } from 'node:fs'; +import { dirname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { describe, expect, it } from 'vitest'; +import { explainRule } from './rule-explanations.js'; + +import { + SANDBOX_API_WRITE_METHODS, + bodyApiWriteCalls, + validateActionBodyCapabilities, +} from './validate-action-body-capabilities.js'; +import { runRuntimeAuthoringRules, runtimeAuthoringRulesFor } from './runtime-gate.js'; + +import { ACTION_BODY_WRITE_CAPABILITY_UNDECLARED } from './validate-action-body-capabilities.js'; +const HERE = dirname(fileURLToPath(import.meta.url)); +const RUNNER = resolve(HERE, '../../runtime/src/sandbox/quickjs-runner.ts'); + +const TASK = { + name: 'pr_task', + label: 'Task', + sharingModel: 'private', + fields: { name: { type: 'text', label: 'Name' }, done: { type: 'boolean', label: 'Done' } }, +}; + +const action = (source: string, capabilities?: string[], extra: Record = {}) => ({ + name: 'pr_close', + label: 'Close', + objectName: 'pr_task', + type: 'script', + locations: ['record_header'], + body: { language: 'js', source, ...(capabilities ? { capabilities } : {}) }, + ...extra, +}); + +describe('validateActionBodyCapabilities (#35143)', () => { + it('the write set is the sandbox runner’s `api.write` leaves, exactly', () => { + const runner = readFileSync(RUNNER, 'utf8'); + const m = /const WRITE = \[([^\]]*)\] as const;/.exec(runner); + expect(m, 'the runner no longer declares `const WRITE = [...]`').not.toBeNull(); + const declared = [...m![1].matchAll(/'([^']+)'/g)].map((x) => x[1]); + expect([...SANDBOX_API_WRITE_METHODS].sort()).toEqual(declared.sort()); + }); + + it('refuses a body that writes through ctx.api with no api.write grant', () => { + const findings = validateActionBodyCapabilities({ + actions: [action("await ctx.api.object('pr_task').update({ id: ctx.recordId, done: true });", ['api.read'])], + }); + expect(findings).toHaveLength(1); + expect(findings[0]).toMatchObject({ + severity: 'error', + rule: ACTION_BODY_WRITE_CAPABILITY_UNDECLARED, + where: 'action "pr_close" › body', + path: 'actions[0].body.capabilities', + }); + expect(findings[0].message).toContain("'api.write'"); + expect(findings[0].hint).toContain("Add 'api.write'"); + }); + + it('refuses when capabilities is absent (the spec default is none)', () => { + expect( + validateActionBodyCapabilities({ actions: [action("await ctx.api.object('pr_task').insert({ name: 'x' });")] }), + ).toHaveLength(1); + }); + + it('passes the same body once api.write is granted', () => { + expect( + validateActionBodyCapabilities({ + actions: [action("await ctx.api.object('pr_task').update({ id: ctx.recordId, done: true });", ['api.write'])], + }), + ).toEqual([]); + }); + + it('reads an inline action on an object', () => { + const findings = validateActionBodyCapabilities({ + objects: [{ ...TASK, actions: [action("await ctx.api.object('pr_task').delete({ id: ctx.recordId });", [])] }], + }); + expect(findings.map((f) => f.path)).toEqual(['objects[0].actions[0].body.capabilities']); + }); + + it('does not read a non-script action or an expression body', () => { + expect( + validateActionBodyCapabilities({ + actions: [ + action("await ctx.api.object('pr_task').insert({});", [], { type: 'flow', target: 'x' }), + { ...action('1'), body: { language: 'expression', source: "ctx.api.object('pr_task').insert({})" } }, + ], + }), + ).toEqual([]); + }); + + describe('which calls are read', () => { + it.each([ + ['direct', "await ctx.api.object('a').insert({});", ['insert']], + ['optional chain', "await ctx?.api?.object('a')?.upsert({});", ['upsert']], + ['optional chain after ctx.api', "await ctx.api?.object('a')?.upsert({});", ['upsert']], + ['the Many leaves', "await ctx.api.object('a').updateMany({}, {}); await ctx.api.object('a').deleteMany({});", ['updateMany', 'deleteMany']], + ['a dynamic object name', 'await ctx.api.object(name).update({ id });', ['update']], + ['an alias of ctx.api', "const api = ctx.api; await api.object('a').update({});", ['update']], + ['a typed alias', "const api = ctx.api as HookApi | undefined; await api?.object('a').update({});", ['update']], + ['a destructured alias', "const { api } = ctx; await api.object('a').delete({});", ['delete']], + ['a renamed destructure', "const { api: a } = ctx; await a.object('x').insert({});", ['insert']], + ['a bound handle', "const repo = ctx.api.object('a');\nawait repo.update({ id: 1 });", ['update']], + ['reads only', "await ctx.api.object('a').find({}); await ctx.api.object('a').count({});", []], + ['a write spelled in a string', "const s = \"ctx.api.object('a').insert({})\"; return s;", []], + ['a write spelled in a template literal', 'return `ctx.api.object(x).update({})`;', []], + ['a write in a comment', "// await ctx.api.object('a').insert({});\nreturn 1;", []], + ['a block comment', "/* ctx.api.object('a').delete({}) */ return 1;", []], + ['a reassigned alias', "let api = ctx.api; api = other; await api.object('a').insert({});", []], + ['an alias declared twice', "const api = ctx.api; function f() { const api = x; return api.object('a').insert({}); }", []], + ['an alias of ctx.api.sudo()', "const api = ctx.api.sudo(); await api.object('a').insert({});", []], + ['another receiver', "await other.api.object('a').insert({});", []], + ])('%s', (_label, source, expected) => { + expect(bodyApiWriteCalls(source)).toEqual(expected); + }); + }); +}); + +describe('validateActionBodyCapabilities at the runtime publish door (#35143)', () => { + it('is dispatched for action and object writes', () => { + expect(runtimeAuthoringRulesFor('action').map((r) => r.name)).toContain('validateActionBodyCapabilities'); + expect(runtimeAuthoringRulesFor('object').map((r) => r.name)).toContain('validateActionBodyCapabilities'); + }); + + it('refuses an action write whose body writes with no api.write grant, and passes it granted', () => { + const refused = runRuntimeAuthoringRules({ + type: 'action', + item: action("await ctx.api.object('pr_task').update({ id: ctx.recordId, done: true });", []), + context: { objects: [TASK] }, + }); + expect(refused.errors.map((e) => [e.rule, e.severity, e.path])).toEqual([ + [ACTION_BODY_WRITE_CAPABILITY_UNDECLARED, 'error', 'actions[0].body.capabilities'], + ]); + + const granted = runRuntimeAuthoringRules({ + type: 'action', + item: action("await ctx.api.object('pr_task').update({ id: ctx.recordId, done: true });", ['api.write']), + context: { objects: [TASK] }, + }); + expect(granted.errors).toEqual([]); + expect(granted.rulesRun).toContain('validateActionBodyCapabilities'); + }); + + it('refuses an object write that adds an inline action with the same body', () => { + const result = runRuntimeAuthoringRules({ + type: 'object', + item: { ...TASK, actions: [action("await ctx.api.object('pr_task').insert({ name: 'x' });", [])] }, + context: { objects: [] }, + }); + // The object door locates an object write by name. + expect(result.errors.filter((e) => e.rule === ACTION_BODY_WRITE_CAPABILITY_UNDECLARED).map((e) => e.path)).toEqual([ + 'objects.pr_task.actions[0].body.capabilities', + ]); + }); +}); + +describe('`os explain action-body-write-capability-undeclared` (#35143)', () => { + it('has an entry that names the remedy', () => { + const entry = explainRule('action-body-write-capability-undeclared'); + expect(entry?.rule).toBe('action-body-write-capability-undeclared'); + expect(entry?.paragraphs.join('\n')).toContain('api.write'); + }); +}); diff --git a/packages/lint/src/validate-action-body-capabilities.ts b/packages/lint/src/validate-action-body-capabilities.ts new file mode 100644 index 00000000000..01222d90333 --- /dev/null +++ b/packages/lint/src/validate-action-body-capabilities.ts @@ -0,0 +1,224 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * An L2 action body that calls a write method of `ctx.api` without granting + * itself `api.write` (#35143, Seeds and actions family). + * + * ## Why + * + * An action body runs in the QuickJS sandbox with exactly the capabilities its + * `body.capabilities` grants (`HookBodyCapability`, `@objectstack/spec/data`). + * The sandbox installs the six write leaves of `ctx.api.object(name)` — + * `insert`, `update`, `delete`, `updateMany`, `deleteMany`, `upsert` — behind + * the `api.write` token (`installCtx`, `packages/runtime/src/sandbox/ + * quickjs-runner.ts`), and a call the body was not granted throws at the call + * site: the action answers `403 INSUFFICIENT_PRIVILEGES` on every click that + * reaches it, and nothing is written. Until this rule nothing at authoring time + * compared the calls with the grant; the save and `os validate` passed. + * + * The grant is the author's to write: Studio's action inspector draws the + * capability list (`ScriptCapabilitiesField`), and a body `os build` lowers + * from a handler gets the grant inferred from its calls: the extractor + * (`packages/cli/src/utils/extract-hook-body.ts`) reads each shape listed + * below — a direct chain, `?.` before the leaf, an argument holding a call, a + * handle bound to `.object(…)` — so a handler the build lowers is not refused + * by the next step of the same build. Its pins hold that shape by shape. + * + * ## How the source is read + * + * Read, never parsed or run: this rule gates the runtime `action` and `object` + * publish doors, where the source parsers may never load + * (`runtime-lazy-deps.test.ts`, tier 1). Strings, template literals and + * comments are blanked first, so a call spelled inside one is never read as + * code. Then three shapes are recognised: + * + * - a write called on `ctx.api.object(…)` itself (`?.` allowed); + * - the same on a local bound to `ctx.api` — `const api = ctx.api` or + * `const { api } = ctx` / `const { api: a } = ctx` — declared once and + * never reassigned; + * - a write called on a local bound to the handle — + * `const repo = ctx.api.object('x')` then `repo.update(…)` — declared once + * and never reassigned. + * + * Anything else is not judged (a dynamic method, `ctx.api['object']`, an alias + * of an alias): a missed finding, never a false one. A regular-expression + * literal is not blanked; one that spells a whole write call is the accepted + * remainder. + * + * ## Severity + * + * `error`: the grant is a fact of the metadata and the refusal is a fact of + * the sandbox, so a body that reaches the call fails every time. The one + * reading under which the body works is that the call is never reached, and a + * write the author wrote and never runs is no reason to publish it. + */ + +import { collectActionBodies } from './validate-action-body-writes.js'; + +type AnyRec = Record; + +export const ACTION_BODY_WRITE_CAPABILITY_UNDECLARED = 'action-body-write-capability-undeclared'; + +/** + * The write leaves the sandbox installs on `ctx.api.object(name)` behind + * `api.write` — `WRITE` in `installCtx`. Pinned equal to the runner's list by + * this rule's test. + */ +export const SANDBOX_API_WRITE_METHODS: readonly string[] = [ + 'insert', + 'update', + 'delete', + 'updateMany', + 'deleteMany', + 'upsert', +]; + +export interface ActionBodyCapabilityFinding { + severity: 'error'; + rule: string; + where: string; + path: string; + message: string; + hint: string; +} + +/** Blank string, template-literal and comment contents, keeping every offset. */ +export function maskBodySource(source: string): string { + const out = source.split(''); + const blank = (from: number, to: number): void => { + for (let k = from; k < to; k++) if (out[k] !== '\n') out[k] = ' '; + }; + let i = 0; + while (i < source.length) { + const ch = source[i]; + if (ch === '/' && source[i + 1] === '/') { + const nl = source.indexOf('\n', i); + const end = nl === -1 ? source.length : nl; + blank(i, end); + i = end; + } else if (ch === '/' && source[i + 1] === '*') { + const close = source.indexOf('*/', i + 2); + const end = close === -1 ? source.length : close + 2; + blank(i, end); + i = end; + } else if (ch === '"' || ch === "'" || ch === '`') { + let j = i + 1; + while (j < source.length && source[j] !== ch) { + if (source[j] === '\\') j++; + else if (ch !== '`' && source[j] === '\n') break; + j++; + } + blank(i + 1, Math.min(j, source.length)); + i = j + 1; + } else { + i++; + } + } + return out.join(''); +} + +const IDENT = String.raw`[A-Za-z_$][\w$]*`; +const WRITE_ALT = [...SANDBOX_API_WRITE_METHODS].sort((a, b) => b.length - a.length).join('|'); +/** `.update(` / `?.insert(` — a write leaf called on what precedes it. */ +const WRITE_CALL = new RegExp(String.raw`^\s*\??\.\s*(${WRITE_ALT})(?![\w$])\s*\(`); + +function escapeIdentifier(name: string): string { + return name.replace(/\$/g, '\\$'); +} + +/** The index just past the `)` that closes the `(` at `open`, or -1. */ +function closeParen(masked: string, open: number): number { + let depth = 0; + for (let k = open; k < masked.length; k++) { + const c = masked[k]; + if (c === '(') depth++; + else if (c === ')') { + depth--; + if (depth === 0) return k + 1; + } + } + return -1; +} + +/** `name` is declared exactly once (`const|let|var`) and never assigned again. */ +function boundOnce(masked: string, name: string, declarations: number): boolean { + const id = escapeIdentifier(name); + const declared = masked.match(new RegExp(String.raw`\b(?:const|let|var)\s+${id}(?![\w$])`, 'g'))?.length ?? 0; + const inPattern = masked.match(new RegExp(String.raw`\b(?:const|let|var)\s*\{[^}]*(?>>?|&&|\|\||\?\?)?=(?![=>])`, 'g'))?.length ?? 0; + const stepped = masked.match(new RegExp(String.raw`(?:\+\+|--)\s*${id}(?![\w$])|(?.object(…)` with nothing chained after it. + const before = masked.slice(0, m.index ?? 0); + const bound = new RegExp(String.raw`\b(?:const|let|var)\s+(${IDENT})\s*=\s*$`).exec(before); + if (bound && /^\s*(?:;|\n|$)/.test(masked.slice(close)) && boundOnce(masked, bound[1], 1)) handles.push(bound[1]); + } + } + for (const name of handles) { + const call = new RegExp(String.raw`(? `${c}(…)`).join(', '); + findings.push({ + severity: 'error', + rule: ACTION_BODY_WRITE_CAPABILITY_UNDECLARED, + where: `action "${site.name}" › body`, + path: site.path.replace(/\.source$/, '.capabilities'), + message: + `body calls ctx.api.object(…).${listed} but its capabilities do not grant 'api.write', so the sandbox ` + + 'refuses the call (403 INSUFFICIENT_PRIVILEGES) every time the action reaches it, and nothing is written.', + hint: "Add 'api.write' to the action's body.capabilities, or remove the write.", + }); + } + return findings; +} diff --git a/packages/lint/src/validate-action-body-writes.ts b/packages/lint/src/validate-action-body-writes.ts index 47f1a6942b7..159935cc9bb 100644 --- a/packages/lint/src/validate-action-body-writes.ts +++ b/packages/lint/src/validate-action-body-writes.ts @@ -209,6 +209,12 @@ export interface ActionBodySite { name: string; source: string; path: string; + /** + * [#35143] The body's `capabilities` grant as written (`[]` when absent, the + * spec default) — read by `validate-action-body-capabilities.ts`, which asks + * whether the body calls what it was granted. + */ + capabilities: readonly unknown[]; } /** The object an action binds to, by the same rule `collectBundleActions` uses. */ @@ -285,7 +291,12 @@ export function collectActionBodies(stack: AnyRec): ActionBodySite[] { const key = `${actionObjectBinding(action, parentObject) ?? ''}\u0000${name}\u0000${source}`; if (seen.has(key)) return; seen.add(key); - sites.push({ name, source, path: `${pathPrefix}[${index}].body.source` }); + sites.push({ + name, + source, + path: `${pathPrefix}[${index}].body.source`, + capabilities: Array.isArray(body.capabilities) ? body.capabilities : [], + }); }); }; diff --git a/packages/lint/src/validate-object-references.test.ts b/packages/lint/src/validate-object-references.test.ts index 6bc9564d719..b962559ac51 100644 --- a/packages/lint/src/validate-object-references.test.ts +++ b/packages/lint/src/validate-object-references.test.ts @@ -10,6 +10,7 @@ import { runAuthoringRules, splitBySeverity } from './authoring-rules.js'; import { PLATFORM_OBJECT_PREFIXES } from '@objectstack/spec/system'; import { defineStack } from '@objectstack/spec'; import { explainRule } from './rule-explanations.js'; +import { runRuntimeAuthoringRules } from './runtime-gate.js'; // [#22161] Each `object-reference-unregistered-platform` finding is one // verdict sentence; the reasoning it used to carry is @@ -445,6 +446,202 @@ describe('validateObjectReferences — ADR-0021 dataset base object (#14105)', ( }); }); +describe('[#35143] validateObjectReferences — the object a seed, a flow node or an action is bound to', () => { + const flow = (nodes: Record[]) => ({ + name: 'crm_flow', + label: 'F', + type: 'autolaunched', + nodes: [{ id: 'start', type: 'start', label: 'Start' }, ...nodes], + edges: [], + }); + + it('errors on a seed dataset over an object that does not exist, and warns on a platform-shaped one', () => { + const findings = validateObjectReferences({ + ...baseStack(), + data: [ + { object: 'crm_led', externalId: 'name', records: [] }, + { object: 'sys_nothing_here', externalId: 'name', records: [] }, + { object: 'crm_lead', externalId: 'name', records: [] }, + { object: 'sys_user', externalId: 'name', records: [] }, + ], + }); + expect(findings.map((f) => [f.severity, f.rule, f.path])).toEqual([ + ['error', OBJECT_REFERENCE_UNKNOWN, 'data[0].object'], + ['warning', OBJECT_REFERENCE_UNREGISTERED_PLATFORM, 'data[1].object'], + ]); + expect(findings[0].message).toContain('Did you mean "crm_lead"?'); + }); + + const crudFlowStack = () => ({ + ...baseStack(), + flows: [ + flow([ + { id: 'g', type: 'get_record', label: 'Get', config: { objectName: 'crm_lead' } }, + { id: 'c', type: 'create_record', label: 'Make', config: { objectName: 'crm_nope', fields: {} } }, + { id: 'u', type: 'update_record', label: 'Upd', config: { objectName: 'crm_acount', fields: {} } }, + { id: 'd', type: 'delete_record', label: 'Del', config: { objectName: 'crm_gone' } }, + { id: 's', type: 'screen', label: 'Form', config: { objectName: 'crm_form_obj' } }, + { id: 't', type: 'create_record', label: 'Tpl', config: { objectName: '{target}' } }, + { + id: 'loop', + type: 'loop', + label: 'Loop', + config: { collection: 'xs', body: { nodes: [{ id: 'n', type: 'get_record', label: 'Inner', config: { objectName: 'crm_inner' } }] } }, + }, + ]), + ], + }); + const CRUD_MISS_PATHS = [ + 'flows[0].nodes[2].config.objectName', + 'flows[0].nodes[3].config.objectName', + 'flows[0].nodes[4].config.objectName', + 'flows[0].nodes[5].config.objectName', + 'flows[0].nodes[7].config.body.nodes[0].config.objectName', + ]; + + it('advises (not refuses) on the CLI a flow CRUD or object-form screen node bound to a name the stack does not define', () => { + // No closure and no whole collection: a dependency package the build cannot + // see may define the name, so the trigger rule's split applies (#24669). + const findings = validateObjectReferences(crudFlowStack()); + expect(findings.map((f) => [f.severity, f.rule])).toEqual(CRUD_MISS_PATHS.map(() => ['warning', OBJECT_REFERENCE_UNKNOWN])); + expect(findings.map((f) => f.path)).toEqual(CRUD_MISS_PATHS); + expect(findings[1].message).toContain('Did you mean "crm_account"?'); + expect(findings[0].hint).toContain('`dependencies`'); + }); + + it('refuses the same nodes against the whole served collection, and under a closure', () => { + for (const options of [ + { wholeCollection: true }, + { packageScope: { packageId: 'com.acme.crm', dependencies: [] } }, + ]) { + const findings = validateObjectReferences(crudFlowStack(), options); + expect(findings.map((f) => [f.severity, f.path])).toEqual(CRUD_MISS_PATHS.map((p) => ['error', p])); + } + }); + + it('CLI: a stack that declares a dependency it does not carry builds, with the flow node advised and nothing refused', () => { + // The dependency's object is not in the stack: `os validate` / `build` / + // `lint` cannot see it, so the step bound to it must not fail the build. + const stack = { + ...baseStack(), + manifest: { id: 'com.acme.ext', name: 'ext', version: '1.0.0', type: 'app', dependencies: { 'com.acme.billing': '^1.0.0' } }, + flows: [flow([{ id: 'c', type: 'create_record', label: 'Bill', config: { objectName: 'billing_invoice', fields: {} } }])], + }; + for (const command of ['validate', 'build', 'lint'] as const) { + const { errors, advisories } = splitBySeverity(runAuthoringRules(command, { normalized: stack as never })); + expect(errors.filter((f) => f.rule === OBJECT_REFERENCE_UNKNOWN), command).toEqual([]); + expect(advisories.filter((f) => f.rule === OBJECT_REFERENCE_UNKNOWN).map((f) => f.path), command) + .toEqual(['flows[0].nodes[1].config.objectName']); + } + }); + + it('leaves the start node to the trigger rule', () => { + expect( + validateObjectReferences({ + ...baseStack(), + flows: [{ name: 'f', nodes: [{ id: 'start', type: 'start', config: { objectName: 'crm_nope' } }], edges: [] }], + }), + ).toEqual([]); + }); + + it('errors on a standalone action bound to an object that does not exist; an embedded one is not read', () => { + const findings = validateObjectReferences({ + objects: [ + ...baseStack().objects, + { name: 'crm_note', fields: { name: { type: 'text' } }, actions: [{ name: 'inline', objectName: 'crm_wrong' }] }, + ], + actions: [ + { name: 'go', label: 'Go', objectName: 'crm_lead' }, + { name: 'bad', label: 'Bad', objectName: 'crm_laed' }, + { name: 'headless', label: 'H' }, + ], + }); + expect(findings.map((f) => [f.rule, f.path, f.where])).toEqual([ + [OBJECT_REFERENCE_UNKNOWN, 'actions[1].objectName', 'action "bad"'], + ]); + }); + + describe('at the runtime publish doors', () => { + const objects = baseStack().objects.map((o) => ({ ...o, sharingModel: 'private' })); + const objectRefErrors = (r: { errors: Array<{ rule: string; path: string }> }) => + r.errors.filter((e) => e.rule === OBJECT_REFERENCE_UNKNOWN).map((e) => e.path); + + it('a `seed` write does not run the ladder: the save door owns a seed over an unknown object (#34864)', () => { + // The save door refuses it with the draft and publish-promotion carve-outs + // a snapshot of served objects cannot see, so the member stays off `seed`. + const result = runRuntimeAuthoringRules({ + type: 'seed', + item: { object: 'crm_led', externalId: 'name', records: [{ name: 'a' }] }, + context: { objects }, + }); + expect(objectRefErrors(result)).toEqual([]); + expect(result.rulesRun).not.toContain('validateReferenceIntegrity'); + }); + + it('an `action` write bound to an object the deployment does not serve is refused; bound to a served one it passes', () => { + const write = (objectName: string) => + runRuntimeAuthoringRules({ + type: 'action', + item: { name: 'go', label: 'Go', objectName, type: 'script', locations: ['record_header'], body: { language: 'js', source: 'return 1;' } }, + context: { objects }, + }); + expect(objectRefErrors(write('crm_laed'))).toEqual(['actions[0].objectName']); + expect(write('crm_lead').errors).toEqual([]); + }); + + it('an empty object set with no closure is no universe, so no verdict; under a closure it is one (#24668, #24563)', () => { + const write = (packageScope?: { packageId: string; dependencies: string[] }) => + runRuntimeAuthoringRules({ + type: 'action', + item: { name: 'go', label: 'Go', objectName: 'crm_lead', type: 'script', locations: ['record_header'], body: { language: 'js', source: 'return 1;' } }, + context: { objects: [] }, + ...(packageScope ? { packageScope } : {}), + }); + expect(objectRefErrors(write())).toEqual([]); + expect(objectRefErrors(write({ packageId: 'com.acme.ext', dependencies: [] }))).toEqual(['actions[0].objectName']); + }); + + it('an `action` saved into a package is judged against its closure: another package\'s object resolves only once declared', () => { + // `crm_lead` is owned by `com.acme.crm`; the action is saved into `com.acme.ext`. + const owned = objects.map((o) => ({ ...o, _packageId: 'com.acme.crm' })); + const write = (dependencies: string[]) => + runRuntimeAuthoringRules({ + type: 'action', + item: { name: 'go', label: 'Go', objectName: 'crm_lead', type: 'script', locations: ['record_header'], body: { language: 'js', source: 'return 1;' } }, + context: { objects: owned }, + packageScope: { packageId: 'com.acme.ext', dependencies }, + }); + const refused = write([]).errors.filter((e) => e.rule === OBJECT_REFERENCE_UNKNOWN); + expect(refused.map((e) => [e.path, e.severity])).toEqual([['actions[0].objectName', 'error']]); + expect(refused[0].hint).toContain('com.acme.ext'); + expect(write(['com.acme.crm']).errors).toEqual([]); + }); + + it('a `flow` write whose create_record node names an object the deployment does not serve is refused', () => { + const write = (objectName: string) => + runRuntimeAuthoringRules({ + type: 'flow', + item: flow([{ id: 'c', type: 'create_record', label: 'Make', config: { objectName, fields: { name: 'x' } } }]), + context: { objects }, + }); + expect(objectRefErrors(write('crm_nope'))).toEqual(['flows[0].nodes[1].config.objectName']); + expect(objectRefErrors(write('crm_lead'))).toEqual([]); + }); + }); + + it('resolves an object the stack extends at the three bindings', () => { + expect( + validateObjectReferences({ + ...baseStack(), + objectExtensions: [{ extend: 'hr_employee', fields: {} }], + data: [{ object: 'hr_employee', externalId: 'name', records: [] }], + actions: [{ name: 'go', label: 'Go', objectName: 'hr_employee' }], + flows: [flow([{ id: 'c', type: 'create_record', label: 'C', config: { objectName: 'hr_employee', fields: {} } }])], + }), + ).toEqual([]); + }); +}); + describe('validateObjectReferences — the severity ladder', () => { // The `sys_approval_process` case: platform-shaped but registered by nothing. // ADR-0019 removed the process object when approval became a flow node. diff --git a/packages/lint/src/validate-object-references.ts b/packages/lint/src/validate-object-references.ts index 34497a2c53f..ce8c0b848fe 100644 --- a/packages/lint/src/validate-object-references.ts +++ b/packages/lint/src/validate-object-references.ts @@ -51,6 +51,11 @@ * views belong to. `getViewsByObject()` indexes views by exactly this key, * so a container bound to a name nothing registers is dead at runtime — * none of its views is ever found — while authoring stayed green. + * - [#35143] the object a seed dataset, a flow CRUD / object-form screen + * node or a standalone action is bound to — `data[].object`, + * `config.objectName`, `actions[].objectName`. A miss is work that never + * happens: the seed loads nothing, the step fails every run, the action is + * carried by no page. An object the stack extends resolves at these three. * * ── Severity ladder (the point of the rule) ────────────────────────────── * @@ -87,8 +92,23 @@ import { import { referenceCarrierOf, referenceTargetOf } from '@objectstack/spec/data'; import { closureDependencyRemedy, packagesOf, recordsOf, suggestName } from './object-graph.js'; +import { walkFlowNodes } from './flow-walk.js'; import type { UserTextParams } from './finding-user-text.js'; +/** + * [#35143] The flow node types whose `config.objectName` names the object the + * step reads, writes or renders — the four CRUD executors (`crud-nodes.ts`, + * `@objectstack/service-automation`) and an object-form `screen`. Each takes the + * name as written and asks the engine for it at run time. + */ +const OBJECT_BOUND_FLOW_NODE_TYPES: ReadonlySet = new Set([ + 'get_record', + 'create_record', + 'update_record', + 'delete_record', + 'screen', +]); + /** Materialized once for the repeated edit-distance scans in `suggestName`. */ const PLATFORM_NAMES: readonly string[] = [...PLATFORM_PROVIDED_OBJECT_NAMES]; @@ -205,10 +225,20 @@ function artifactProvidedObjectNames(stack: AnyRec): string[] { * it: the gate dispatches this rule on `flow` and `dataset` writes, a flow * body carries none of this rule's sites, and the differential cancels what * the context collections already hold. + * @param options.wholeCollection [#35143] `true` when `stack.objects` is the + * whole collection a runtime host serves (a gated write that names no + * package), as the list-view member reads it (#24668). It decides only the + * flow-node site's severity: with neither it nor a closure — the CLI — a + * flow node bound to a name this stack does not define is advised, not + * refused, because a dependency package may define it and a build cannot + * see that package (`flow-trigger-unknown-object`'s split, #24669). */ export function validateObjectReferences( stack: AnyRec, - options: { packageScope?: { readonly packageId: string; readonly dependencies: readonly string[] } } = {}, + options: { + packageScope?: { readonly packageId: string; readonly dependencies: readonly string[] }; + wholeCollection?: boolean; + } = {}, ): ObjectRefFinding[] { const findings: ObjectRefFinding[] = []; if (!stack || typeof stack !== 'object') return findings; @@ -262,6 +292,7 @@ export function validateObjectReferences( subject: string, remedy = '', userTextOf?: UserTextParams, + advisory = false, ) => { const name = strName(target); if (!name) return; @@ -294,6 +325,25 @@ export function validateObjectReferences( // ② Unprefixed and unresolved — a stack's own objects are namespace- // prefixed and present here, so there is no legitimate elsewhere. + // [#35143] Except where the caller says this stack cannot know (a flow + // node judged with no closure and no whole collection): a dependency + // package may define the name, so the miss is advised with that hedge. + if (advisory) { + findings.push({ + severity: 'warning', + rule: OBJECT_REFERENCE_UNKNOWN, + where, + path, + message: + `${subject} "${name}" is not defined by this stack. If no installed package defines it, ` + + 'the step fails the run every time it executes.' + + suggestName(name, resolvable), + hint: + 'Point it at an object this stack defines, or declare the package that defines it in the manifest\'s ' + + '`dependencies`; ignore this if a declared dependency does', + }); + return; + } findings.push({ severity: 'error', rule: OBJECT_REFERENCE_UNKNOWN, @@ -543,6 +593,97 @@ export function validateObjectReferences( ); } + // ── [#35143] Seeds, flow nodes and actions → the object they are bound to ── + // Three bindings that name the object a write lands on, so a miss is not a + // degraded control but work that never happens: + // + // - a seed dataset's `object`. `defineStack` refuses an unprefixed miss + // already, but answers a platform-prefixed name by its prefix alone + // (`isPlatformObjectName`), so `sys_nothing_here` built clean. The seed + // load looks the object up, finds none and loads no record of it. This + // site is the CLI's: at the runtime `seed` door the save door's own + // refusal (#34864) answers it, so the member does not run there. + // - a flow node's `config.objectName` — `get_record`, `create_record`, + // `update_record`, `delete_record`, and a `screen` that renders an + // object's form. Nothing resolved it at all: when no installed package + // defines the name either, the step reaches the engine with a name no + // object carries and fails the run every time it executes. Advised on + // the CLI, refused at the door (`flowNodeAdvisory` below). The + // START node's `objectName` is `flow-trigger-unknown-object`'s subject + // (`validate-flow-trigger-readiness.ts`) and is not read here. + // - a standalone action's `objectName`, the object `defineStack` folds it + // into and the runtime keys its dispatch by. `defineStack` refuses a miss + // on the CLI; at the runtime `action` publish door nothing did, and the + // action registered against no object, so no list or record page carries + // it and its object route answers 404. + // + // The same ladder as every site above, with one addition: an object this + // stack EXTENDS (`objectExtensions[].extend`) resolves, because the stack's + // own metadata says the object exists in another package — the exemption + // `defineStack` already grants an action's `objectName` for the same reason. + // An embedded action (`objects[].actions[]`) is bound by the object it is + // written on and is not read. + const extended = new Set(); + for (const ext of recordsOf(stack.objectExtensions)) { + const n = strName(ext.extend); + if (n) extended.add(n); + } + // An empty object set with no closure in force is not a verdict, as at the + // list-view member (#24668): no deployment serves zero objects, so a runtime + // host that hands none over supplied no universe, and an app that declares + // none binds objects its dependencies own. Under a stated closure an empty + // set is still a verdict (#24563): every binding is then outside it. + const noUniverse = resolvable.size === 0 && !closure; + const checkBound = (target: string | undefined, where: string, path: string, subject: string, advisory = false) => { + if (noUniverse) return; + const name = strName(target); + if (name && extended.has(name)) return; + check(name, where, path, subject, '', undefined, advisory); + }; + // [#35143] A flow node's miss is refused only where this stack is enough to + // know: under a stated closure, or against the whole served collection. On + // the CLI a dependency package the build cannot see may define the name, + // so it is advised there — `flow-trigger-unknown-object`'s split (#24669). + // The seed and action sites keep the error: `defineStack` refuses the same + // misses on the CLI already. + const flowNodeAdvisory = !closure && options.wholeCollection !== true; + + const seeds = Array.isArray(stack.data) ? (stack.data as unknown[]) : []; + for (let si = 0; si < seeds.length; si++) { + const seed = seeds[si]; + if (!seed || typeof seed !== 'object') continue; + checkBound(strName((seed as AnyRec).object), `seed #${si}`, `data[${si}].object`, 'seed object'); + } + + const flows = recordsOf(stack.flows); + for (let fi = 0; fi < flows.length; fi++) { + const flow = flows[fi]; + const flowName = strName(flow.name) ?? `#${fi}`; + for (const { node, path } of walkFlowNodes(flow, `flows[${fi}]`)) { + if (typeof node.type !== 'string' || !OBJECT_BOUND_FLOW_NODE_TYPES.has(node.type)) continue; + const config = node.config; + if (!config || typeof config !== 'object' || Array.isArray(config)) continue; + checkBound( + strName((config as AnyRec).objectName), + `flow "${flowName}" · node "${strName(node.label) ?? strName(node.id) ?? '?'}"`, + `${path}.config.objectName`, + `${node.type} object`, + flowNodeAdvisory, + ); + } + } + + for (let ai = 0; ai < globalActions.length; ai++) { + const action = globalActions[ai]; + if (!action || typeof action !== 'object') continue; + checkBound( + strName(action.objectName), + `action "${strName(action.name) ?? `#${ai}`}"`, + `actions[${ai}].objectName`, + 'action object', + ); + } + // ── App navigation → requiresObject gates (and gated objectName) ── const apps = recordsOf(stack.apps); for (let ai = 0; ai < apps.length; ai++) { diff --git a/packages/lint/src/validate-seed-record-keys.test.ts b/packages/lint/src/validate-seed-record-keys.test.ts new file mode 100644 index 00000000000..a152a245de1 --- /dev/null +++ b/packages/lint/src/validate-seed-record-keys.test.ts @@ -0,0 +1,152 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { readFileSync } from 'node:fs'; +import { dirname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { describe, expect, it } from 'vitest'; +import { explainRule } from './rule-explanations.js'; + +import { validateSeedRecordKeys } from './validate-seed-record-keys.js'; +import { AUTHORING_RULES } from './authoring-rules.js'; +import { runRuntimeAuthoringRules, runtimeAuthoringRulesFor } from './runtime-gate.js'; + +import { SEED_RECORD_UNKNOWN_FIELD } from './validate-seed-record-keys.js'; +const HERE = dirname(fileURLToPath(import.meta.url)); +const entry = AUTHORING_RULES.find((r) => r.name === 'validateSeedRecordKeys')!; + +const TASK = { + name: 'pr_task', + label: 'Task', + sharingModel: 'private', + fields: { name: { type: 'text', label: 'Name' }, done: { type: 'boolean', label: 'Done' } }, +}; + +const seed = (records: Record[], extra: Record = {}) => ({ + object: 'pr_task', + externalId: 'name', + records, + ...extra, +}); + +describe('validateSeedRecordKeys (#35143)', () => { + it('refuses a record key that is not a field of the object, naming the near miss', () => { + const findings = validateSeedRecordKeys({ objects: [TASK], data: [seed([{ name: 'a', dnoe: true }])] }); + expect(findings).toHaveLength(1); + expect(findings[0]).toMatchObject({ + severity: 'error', + rule: SEED_RECORD_UNKNOWN_FIELD, + path: 'data[0].records[0].dnoe', + where: 'seed "pr_task" · records[0]', + }); + expect(findings[0].message).toContain('"dnoe" is not a field of "pr_task"'); + expect(findings[0].hint).toContain("'done'"); + }); + + it('reports a key once per dataset, at the first record that carries it', () => { + const findings = validateSeedRecordKeys({ + objects: [TASK], + data: [seed([{ name: 'a' }, { name: 'b', bogus: 1 }, { name: 'c', bogus: 2 }])], + }); + expect(findings.map((f) => f.path)).toEqual(['data[0].records[1].bogus']); + }); + + it('refuses a `columns` key that names no column', () => { + const findings = validateSeedRecordKeys({ + objects: [TASK], + data: [seed([{ name: 'a' }], { columns: { stauts: { applyOn: 'create' } } })], + }); + expect(findings).toHaveLength(1); + expect(findings[0].path).toBe('data[0].columns.stauts'); + expect(findings[0].message).toContain('governs nothing'); + }); + + it('accepts declared fields and the system columns injected on the object', () => { + expect( + validateSeedRecordKeys({ + objects: [TASK], + data: [seed([{ name: 'a', done: true, created_at: '2026-01-01T00:00:00Z', owner_id: 'u1' }], { + columns: { done: { applyOn: 'create' } }, + })], + }), + ).toEqual([]); + }); + + it('admits the columns the engine provisions on every table even when the object opts out of system columns', () => { + // The engine's insert door accepts `PLATFORM_PROVISIONED_COLUMNS` undeclared + // on every object; read the list from its source so the two cannot drift. + const source = readFileSync(resolve(HERE, '../../objectql/src/declared-read-columns.ts'), 'utf8'); + const listed = /export const PLATFORM_PROVISIONED_COLUMNS = \[([^\]]*)\]/.exec(source)?.[1] ?? ''; + const provisioned = [...listed.matchAll(/'([a-z_]+)'/g)].map((m) => m[1]); + expect(provisioned).toEqual(['id', 'created_at', 'updated_at']); + + const record = Object.fromEntries([['name', 'a'], ...provisioned.map((c) => [c, 'x'])]); + expect(validateSeedRecordKeys({ objects: [{ ...TASK, systemFields: false }], data: [seed([record])] })).toEqual([]); + // Control: an injected column the object opts out of and the engine does + // not provision is still refused — the engine's door refuses it too. + const refused = validateSeedRecordKeys({ + objects: [{ ...TASK, systemFields: false }], + data: [seed([{ name: 'a', created_by: 'u1' }])], + }); + expect(refused.map((f) => f.path)).toEqual(['data[0].records[0].created_by']); + }); + + it('judges no object whose field map is empty, as the engine\'s door has no opinion on one', () => { + expect( + validateSeedRecordKeys({ objects: [{ ...TASK, fields: {} }], data: [seed([{ name: 'a', anything: 1 }])] }), + ).toEqual([]); + }); + + it('judges no dataset whose object the snapshot does not hold', () => { + expect( + validateSeedRecordKeys({ objects: [TASK], data: [{ object: 'crm_other', externalId: 'name', records: [{ x: 1 }] }] }), + ).toEqual([]); + }); + + it('reads a field an object extension adds (served objects)', () => { + const stack = { + objects: [TASK], + objectExtensions: [{ extend: 'pr_task', fields: { priority: { type: 'text', label: 'Priority' } } }], + data: [seed([{ name: 'a', priority: 'high' }])], + }; + expect(entry.run(stack, {})).toEqual([]); + // Control: the same key without the extension is refused by the registry entry. + expect( + entry.run({ objects: [TASK], data: [seed([{ name: 'a', priority: 'high' }])] }, {}).map((f) => [f.rule, f.path]), + ).toEqual([[SEED_RECORD_UNKNOWN_FIELD, 'data[0].records[0].priority']]); + }); +}); + +describe('validateSeedRecordKeys at the runtime `seed` publish door (#35143)', () => { + it('is dispatched for seed writes', () => { + expect(runtimeAuthoringRulesFor('seed').map((r) => r.name)).toContain('validateSeedRecordKeys'); + }); + + it('refuses a seed write whose record carries a key the served object does not have', () => { + const result = runRuntimeAuthoringRules({ + type: 'seed', + item: seed([{ name: 'a', bogus_key: 1 }]), + context: { objects: [TASK] }, + }); + expect(result.errors.map((e) => [e.rule, e.severity, e.path])).toEqual([ + [SEED_RECORD_UNKNOWN_FIELD, 'error', 'data[0].records[0].bogus_key'], + ]); + }); + + it('passes the same write once the key is a field', () => { + const result = runRuntimeAuthoringRules({ + type: 'seed', + item: seed([{ name: 'a', done: true }]), + context: { objects: [TASK] }, + }); + expect(result.errors).toEqual([]); + expect(result.rulesRun).toContain('validateSeedRecordKeys'); + }); +}); + +describe('`os explain seed-record-unknown-field` (#35143)', () => { + it('has an entry that names the remedy', () => { + const entry = explainRule('seed-record-unknown-field'); + expect(entry?.rule).toBe('seed-record-unknown-field'); + expect(entry?.paragraphs.join('\n')).toContain('`created_at`'); + }); +}); diff --git a/packages/lint/src/validate-seed-record-keys.ts b/packages/lint/src/validate-seed-record-keys.ts new file mode 100644 index 00000000000..ecd478c71cf --- /dev/null +++ b/packages/lint/src/validate-seed-record-keys.ts @@ -0,0 +1,149 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A seed record key, or a seed `columns` key, that is not a column of the + * dataset's object (#35143, Seeds and actions family). + * + * ## Why + * + * The seed load writes each record through the engine's insert, and the + * engine's declared-field door refuses a payload key the object does not have + * (`INVALID_FIELD` / 400, `engine-insert.ts`). The load runs in partial mode, + * so the record is culled and the rest land: the build reads as passed and the + * first sign is a `[Seeder] … dropped record(s)` line at boot. + * + * `defineSeed` already refuses such a key when it runs (`assertSeedKeysDeclared` + * in `@objectstack/spec/data`). A dataset written without it — a plain + * `data: [{ object, records }]` entry in the stack, or a `seed` saved through the + * runtime publish door — was judged by nothing until the load. This rule is the + * same question asked of every dataset, before the load: the column set is the + * engine's own declared set for the insert door — the object's fields as served + * (an object extension may add one), the system columns the platform injects on + * THAT object (`injectedColumnsFor`, the registry's own plan), and the columns + * every physical table carries whether declared or not (`id`, `created_at`, + * `updated_at`: the engine's `PLATFORM_PROVISIONED_COLUMNS`, mirrored here and + * pinned to it by test). So an object built with `systemFields: false` still + * admits `created_at`, because the engine's door does; `defineSeed` refuses it + * for its own reason, which this rule does not claim. An object with an empty + * field map is not judged: the engine's door has no opinion on it either. + * + * A `columns` key that names no column is refused for `defineSeed`'s reason: + * the policy governs nothing, and the column it was meant for keeps the + * `always` default. + * + * Not judged: a dataset whose object the stack (or, at the publish door, the + * deployment) does not hold, which is `object-reference-unknown`'s question; and + * an object whose field map is not readable. + */ + +import { findClosestMatches, formatSuggestion } from '@objectstack/spec/shared'; + +import { recordsOf } from './object-graph.js'; +import { injectedColumnsFor } from './system-fields.js'; + +type AnyRec = Record; + +/** + * The columns the engine provisions on every physical table and its insert + * door accepts undeclared (`PLATFORM_PROVISIONED_COLUMNS`, + * `packages/objectql/src/declared-read-columns.ts`). Mirrored, not imported: + * `@objectstack/objectql` depends on this package. The test pins the two + * lists equal by reading that source. + */ +const ENGINE_PROVISIONED_COLUMNS = ['id', 'created_at', 'updated_at'] as const; + +export const SEED_RECORD_UNKNOWN_FIELD = 'seed-record-unknown-field'; + +export interface SeedRecordKeyFinding { + severity: 'error'; + rule: string; + where: string; + path: string; + message: string; + hint: string; +} + +const isRec = (v: unknown): v is AnyRec => !!v && typeof v === 'object' && !Array.isArray(v); + +/** + * The column names of one served object: its fields (array or record form) and + * the system columns the platform injects on it. + */ +function columnsOf(obj: AnyRec): Set | undefined { + const declared = obj.fields; + let names: string[]; + if (Array.isArray(declared)) { + names = declared.filter(isRec).map((f) => f.name).filter((n): n is string => typeof n === 'string'); + } else if (isRec(declared)) { + names = Object.keys(declared); + } else { + return undefined; + } + if (names.length === 0) return undefined; + return new Set([...names, ...injectedColumnsFor(obj), ...ENGINE_PROVISIONED_COLUMNS]); +} + +/** + * Every seed key that names no column of its dataset's object. + * + * @param servedObjects The objects as served — the stack's own with its object + * extensions folded in (the CLI), or the deployment's served objects (the + * runtime publish gate). Defaults to `stack.objects`. + */ +export function validateSeedRecordKeys(stack: AnyRec, servedObjects?: readonly unknown[]): SeedRecordKeyFinding[] { + const findings: SeedRecordKeyFinding[] = []; + if (!isRec(stack) || !Array.isArray(stack.data)) return findings; + + const columnsByObject = new Map | undefined>(); + for (const obj of recordsOf(servedObjects ?? stack.objects)) { + if (typeof obj.name !== 'string' || columnsByObject.has(obj.name)) continue; + columnsByObject.set(obj.name, columnsOf(obj)); + } + + stack.data.forEach((dataset: unknown, di: number) => { + if (!isRec(dataset) || typeof dataset.object !== 'string') return; + const object = dataset.object; + const columns = columnsByObject.get(object); + if (!columns) return; + const known = [...columns]; + + const report = (key: string, path: string, where: string, surface: 'record' | 'columns'): void => { + if (columns.has(key)) return; + const suggestion = formatSuggestion(findClosestMatches(key, known)); + findings.push({ + severity: 'error', + rule: SEED_RECORD_UNKNOWN_FIELD, + where, + path, + message: + surface === 'record' + ? `seed key "${key}" is not a field of "${object}", so the seed load refuses this record ` + + '(the engine refuses a key the object does not declare) and drops it while the rest load.' + : `seed \`columns\` key "${key}" is not a field of "${object}", so its policy governs nothing and ` + + 'the column it was meant for keeps the `always` default.', + hint: + `${suggestion ? `${suggestion} ` : ''}Fix the key's spelling, declare the field "${key}" on "${object}", ` + + 'or remove the key.', + }); + }; + + const reported = new Set(); + recordsOf(dataset.records).forEach((record, ri) => { + for (const key of Object.keys(record)) { + // One finding per dataset and key: a misspelt key is usually misspelt + // on every record, and the record index of the first names it. + if (reported.has(key)) continue; + if (columns.has(key)) continue; + reported.add(key); + report(key, `data[${di}].records[${ri}].${key}`, `seed "${object}" · records[${ri}]`, 'record'); + } + }); + if (isRec(dataset.columns)) { + for (const key of Object.keys(dataset.columns)) { + report(key, `data[${di}].columns.${key}`, `seed "${object}" · columns`, 'columns'); + } + } + }); + + return findings; +} diff --git a/packages/metadata-protocol/src/protocol-publish-drafts-advisories.test.ts b/packages/metadata-protocol/src/protocol-publish-drafts-advisories.test.ts index be4b1b474e0..0f8f0cb4357 100644 --- a/packages/metadata-protocol/src/protocol-publish-drafts-advisories.test.ts +++ b/packages/metadata-protocol/src/protocol-publish-drafts-advisories.test.ts @@ -175,6 +175,12 @@ function makeStubEngine(refusedSync: ReadonlySet = new Set()) { registry: { registerItem: () => {}, registerObject: () => {}, + // [#35143] The deployment serves the object the flows' delete node + // is bound to: the flow door refuses a CRUD node bound to an object + // it does not serve. + listItems: (type: string) => (type === 'object' + ? [{ name: 'audit_logs', label: 'Audit logs', fields: { name: { type: 'text', label: 'Name' } } }] + : []), // The base the drafts are bound to is INSTALLED — a flow may be // saved only into a package the registry holds (#20863) — and its // manifest declares no namespace → publishPackageDrafts skips the diff --git a/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts b/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts index 89ac4f95852..1b0950729c5 100644 --- a/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts +++ b/packages/metadata-protocol/src/protocol.packageless-save-address.test.ts @@ -107,6 +107,11 @@ function matches(row: Row, where: Record = {}): boolean { * A stub engine that keeps rows, and a registry holding what a code package's * loader registered (each artifact as `applyProtection` leaves it). */ +/** The objects the actions here are bound to, as the deployment serves them. */ +const SERVED_OBJECTS = ['invoice', 'product', 'task'].map((name) => ({ + name, label: name, fields: { name: { type: 'text', label: 'Name' } }, +})); + function makeProtocol(artifacts: Array<{ type: string; item: Record }> = []) { const tables = new Map(); const table = (name: string) => { @@ -159,7 +164,13 @@ function makeProtocol(artifacts: Array<{ type: string; item: Record {}, getArtifactItem: (type: string, name: string) => shipped(type, name).find((item) => isCodeArtifactBody(item)), getItem: (type: string, name: string) => shipped(type, name)[0], - listItems: (type: string) => artifacts.filter((a) => a.type === type).map((a) => a.item), + // [#35143] The deployment serves the objects this file's actions are + // bound to: the action door refuses a binding to an object it does + // not serve. + listItems: (type: string) => [ + ...(type === 'object' ? SERVED_OBJECTS : []), + ...artifacts.filter((a) => a.type === type).map((a) => a.item), + ], getObject: () => undefined, // [#26708] Every package this file names is installed — an // authored base through the package door, the code package by its diff --git a/packages/objectql/src/bound-action-foreign-object.test.ts b/packages/objectql/src/bound-action-foreign-object.test.ts index 7a2ed187def..625b259e4a5 100644 --- a/packages/objectql/src/bound-action-foreign-object.test.ts +++ b/packages/objectql/src/bound-action-foreign-object.test.ts @@ -494,10 +494,14 @@ describe('a bound action saved at runtime through the metadata door reaches its expect(actionNames(engine.registry.getArtifactItem('object', 'ba_org'))).toEqual(['own_action', 'rename_org']); }); - it('a runtime action naming an object no package registers is listed nowhere, and the boot audit stays code-only', async () => { + // [#35143] Before, the save answered 200 and the action registered against + // no object, listed nowhere. The publish gate now refuses the binding. + it('a runtime action naming an object no package registers is refused at the save, registered nowhere, and the boot audit stays code-only', async () => { const { engine, protocol } = await hostWith([OWNER]); - await save(protocol, { ...RUNTIME, name: 'rt_orphan', objectName: 'ba_missing' }); - expect(engine.registry.getItem('action', 'rt_orphan')).toBeDefined(); + const err: any = await save(protocol, { ...RUNTIME, name: 'rt_orphan', objectName: 'ba_missing' }).then(() => null, (e: unknown) => e); + expect({ code: err?.code, status: err?.status }).toEqual({ code: 'INVALID_METADATA', status: 422 }); + expect((err.issues ?? []).map((i: any) => [i.rule, i.path])).toEqual([['object-reference-unknown', 'actions[0].objectName']]); + expect(engine.registry.getItem('action', 'rt_orphan')).toBeUndefined(); expect(actionNames(engine.registry.getObject('ba_org'))).toEqual(['own_action']); expect(engine.registry.findUnboundActionTargets()).toEqual([]); }); diff --git a/packages/objectql/src/publish-meta-response-conformance.test.ts b/packages/objectql/src/publish-meta-response-conformance.test.ts index 5800200be70..9b1b92a7f4c 100644 --- a/packages/objectql/src/publish-meta-response-conformance.test.ts +++ b/packages/objectql/src/publish-meta-response-conformance.test.ts @@ -160,6 +160,9 @@ async function makeProtocol() { await engine.init(); engine.registry.registerObject(sysMetadataObject, 'test-package'); for (const o of [SysMetadataHistoryObject, SysMetadataAuditObject, SysMetadataCommitObject]) engine.registry.registerObject(o as any, 'test-package'); + // [#35143] The object the advisory flow's delete node is bound to: the flow + // door refuses a CRUD node bound to an object the deployment does not serve. + engine.registry.registerObject({ name: 'audit_logs', label: 'Audit logs', fields: { name: { type: 'text', label: 'Name' } } } as any, 'test-package'); return new ObjectStackProtocolImplementation(engine); } diff --git a/packages/objectql/src/publish-package-drafts-response-conformance.test.ts b/packages/objectql/src/publish-package-drafts-response-conformance.test.ts index a6f3ade559b..d662af2fa89 100644 --- a/packages/objectql/src/publish-package-drafts-response-conformance.test.ts +++ b/packages/objectql/src/publish-package-drafts-response-conformance.test.ts @@ -144,6 +144,9 @@ async function makeProtocol() { await engine.init(); engine.registry.registerObject(sysMetadataObject, 'test-package'); for (const o of [SysMetadataHistoryObject, SysMetadataAuditObject, SysMetadataCommitObject]) engine.registry.registerObject(o as any, 'test-package'); + // [#35143] The object the advisory flow's delete node is bound to: the flow + // door refuses a CRUD node bound to an object the deployment does not serve. + engine.registry.registerObject({ name: 'audit_logs', label: 'Audit logs', fields: { name: { type: 'text', label: 'Name' } } } as any, PKG); // The base every draft here is bound to is INSTALLED: a flow may be saved // only into a package the registry holds (#20863). Its manifest declares // no namespace, so the ADR-0028 prefix pre-flight is unchanged. diff --git a/packages/objectql/src/save-meta-response-conformance.test.ts b/packages/objectql/src/save-meta-response-conformance.test.ts index 52e6b02041b..fe931c0a61f 100644 --- a/packages/objectql/src/save-meta-response-conformance.test.ts +++ b/packages/objectql/src/save-meta-response-conformance.test.ts @@ -165,6 +165,9 @@ async function makeProtocol() { await engine.init(); engine.registry.registerObject(sysMetadataObject, 'test-package'); for (const o of [SysMetadataHistoryObject, SysMetadataAuditObject, SysMetadataCommitObject]) engine.registry.registerObject(o as any, 'test-package'); + // [#35143] The object the advisory flow's delete node is bound to: the flow + // door refuses a CRUD node bound to an object the deployment does not serve. + engine.registry.registerObject({ name: 'audit_logs', label: 'Audit logs', fields: { name: { type: 'text', label: 'Name' } } } as any, 'test-package'); return new ObjectStackProtocolImplementation(engine); } diff --git a/packages/qa/dogfood/test/action-save-packageless-other-object.dogfood.test.ts b/packages/qa/dogfood/test/action-save-packageless-other-object.dogfood.test.ts index a16c72f34de..b7cc445dc01 100644 --- a/packages/qa/dogfood/test/action-save-packageless-other-object.dogfood.test.ts +++ b/packages/qa/dogfood/test/action-save-packageless-other-object.dogfood.test.ts @@ -45,7 +45,14 @@ describe('[ADR-0150 D4] a package-less action save on an object the package does stack = await bootShowcase(); admin = await stack.signIn(); const created = await stack.apiAs(admin, 'POST', '/packages', { - manifest: { id: PKG, name: 'QA save other object', version: '0.1.0', type: 'app', namespace: 'qasaveother' }, + // P binds an action to `showcase_invoice`, which the showcase package + // owns, so P declares that package: the publish gate refuses an action + // bound to an object outside the package's closure (#35143), as it + // already refused a flow there. + manifest: { + id: PKG, name: 'QA save other object', version: '0.1.0', type: 'app', namespace: 'qasaveother', + dependencies: { 'com.example.showcase': '*' }, + }, }); expect(created.status, await created.clone().text()).toBe(201); }, 240_000); diff --git a/packages/runtime/src/domains/packages-uninstall-handlers-withdrawn.test.ts b/packages/runtime/src/domains/packages-uninstall-handlers-withdrawn.test.ts index c1cfee943d4..23d89972478 100644 --- a/packages/runtime/src/domains/packages-uninstall-handlers-withdrawn.test.ts +++ b/packages/runtime/src/domains/packages-uninstall-handlers-withdrawn.test.ts @@ -172,7 +172,12 @@ const holdersOf = (name: string) => ql.listRegisteredActions() /** An authored package: installed through `POST /packages`, an action and a body hook saved under it through the metadata door. */ async function authorPackage(id: string, by: string) { - const installed = await http('POST', '/packages', { manifest: { id, name: id.replace(/\./g, '_'), version: '1.0.0', type: 'app', namespace: `qauh${by}` } }); + // The action binds `TICKET`, which the host package owns, so the authored + // package declares the host: the publish gate refuses an action bound to an + // object outside the package's closure (#35143), as it refuses a flow. + const installed = await http('POST', '/packages', { + manifest: { id, name: id.replace(/\./g, '_'), version: '1.0.0', type: 'app', namespace: `qauh${by}`, dependencies: { [HOST]: '*' } }, + }); expect(installed.status, JSON.stringify(installed.body)).toBe(201); const savedAction = await http('PUT', `/meta/action/qa_uh_run_${by}`, action(`qa_uh_run_${by}`, by), { package: id }); expect(savedAction.status, JSON.stringify(savedAction.body)).toBe(200); diff --git a/packages/spec/src/migrations/entries/semantic/19.publish-refuses-seeds-and-actions-that-save-and-do-not-work.ts b/packages/spec/src/migrations/entries/semantic/19.publish-refuses-seeds-and-actions-that-save-and-do-not-work.ts new file mode 100644 index 00000000000..089e2e1dbb2 --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/19.publish-refuses-seeds-and-actions-that-save-and-do-not-work.ts @@ -0,0 +1,42 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// The upgrade-guide entry of the Seeds and actions family of the second batch +// of author-time rules (#35143) that refuse, at publish and in `os validate` / +// `build`, a seed, a flow node or an action the schema still accepts but whose +// work never happens. Notice only: no key is removed and no D2 conversion +// exists, because each fix is a choice only the author can make (which field a +// seed key meant, which object a binding meant, whether a body may write). +export const entry: SemanticMigration = { + id: 'publish-refuses-seeds-and-actions-that-save-and-do-not-work', + surface: + 'Three author-time errors, run by the runtime publish gate and by `os validate` / `lint` / `compile` / `build`: ' + + 'a seed record key or seed `columns` key the engine\'s insert door refuses, naming no field of the dataset\'s ' + + 'object, no system column the platform injects on it and none of `id` / `created_at` / `updated_at` ' + + '(`seed-record-unknown-field`); a seed dataset, a flow `get_record` / `create_record` / ' + + '`update_record` / `delete_record` / object-form `screen` node, or a standalone action bound to an object that ' + + 'does not exist (`object-reference-unknown`, a warning `object-reference-unregistered-platform` for a ' + + 'platform-prefixed name no known package registers; the seed binding on the CLI only, because at the publish ' + + 'door the save door already refuses a seed over an unknown object; the flow node a warning on the CLI, where a ' + + 'declared dependency the build cannot see may define the object, and an error at the publish door); an L2 action body that calls a `ctx.api` write without ' + + '`api.write` in its `body.capabilities` (`action-body-write-capability-undeclared`)', + replacement: + 'Spell the seed key as the field it means, declare the field, or drop the key; point the binding at an object the ' + + 'stack or its artifact defines, an object it extends, or a platform object by its full name; add `api.write` to ' + + 'the action body\'s `capabilities`, or remove the write', + reason: + 'Each one parses and publishes, then does not work: the seed load refuses a record with a key the engine\'s ' + + 'insert door refuses and loads the rest, so the record is missing at boot; a seed over a missing object loads ' + + 'nothing, a flow step bound to an object no installed package defines fails the run every time it executes, and ' + + 'an action bound to one is carried by no page; the ' + + 'sandbox refuses a body\'s write it was not granted (403 INSUFFICIENT_PRIVILEGES) every time the action reaches ' + + 'it. Stored metadata is not rewritten or refused at boot. The next publish of a seed, flow, action or object ' + + 'that carries one of these is refused with the fix named. An `action` write is also judged for its params\' ' + + '`reference` / `objectOverride` objects, as `os validate` already judged them, and an action saved into a ' + + '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`.', + acceptanceCriteria: + 'os validate reports none of the three errors; a publish of every seed, flow, action and object the package carries ' + + 'succeeds.', +}; diff --git a/scripts/cross-package-test-inputs.mjs b/scripts/cross-package-test-inputs.mjs index 2ad106183af..1dfdda2dba8 100644 --- a/scripts/cross-package-test-inputs.mjs +++ b/scripts/cross-package-test-inputs.mjs @@ -1025,6 +1025,15 @@ export const CROSS_PACKAGE_TEST_INPUTS = { // them. A real read: the enumeration changes if the mask does. 'scripts/js-comment-mask.mjs', 'scripts/js-comment-mask.d.mts', + // src/validate-action-body-capabilities.test.ts (#35143) READS the + // sandbox runner's source and pins the rule's write-method set to its + // `WRITE` list, so a method the runner starts gating on `api.write` + // turns this suite red instead of leaving the rule a method short. + 'packages/runtime/src/sandbox/quickjs-runner.ts', + // src/validate-seed-record-keys.test.ts (#35143) READS the engine's + // `PLATFORM_PROVISIONED_COLUMNS` and pins the rule's mirror of it, so + // a column the engine starts provisioning turns this suite red. + 'packages/objectql/src/declared-read-columns.ts', ], heldBy: { // `const commandsDir = join(repoRoot, 'packages/cli/src/commands')` diff --git a/turbo.json b/turbo.json index 1798b083236..7ff2d730092 100644 --- a/turbo.json +++ b/turbo.json @@ -377,7 +377,9 @@ "$TURBO_ROOT$/examples/app-showcase/src/ui/views/task.view.ts", "$TURBO_ROOT$/sdui.manifest.json", "$TURBO_ROOT$/scripts/js-comment-mask.mjs", - "$TURBO_ROOT$/scripts/js-comment-mask.d.mts" + "$TURBO_ROOT$/scripts/js-comment-mask.d.mts", + "$TURBO_ROOT$/packages/runtime/src/sandbox/quickjs-runner.ts", + "$TURBO_ROOT$/packages/objectql/src/declared-read-columns.ts" ] }, "@objectstack/cloud-connection#test": {