Skip to content

Commit 5a77a70

Browse files
feat(cli): the hook-body extractor infers api.transaction, and api.read through a bound object handle (#38686)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9JeHmqv6CKCkW8ewrPBLekk)_ Fixes #38653 Clause-②: yes (widening) Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:应用作者把内联处理函数交给构建后,调用事务或通过对象句柄读数据的处理函数,构建时会自动获得对应权限,运行时不再被沙箱拒绝。 - 为什么做:属于“处理函数能力推断准确”这一族工作,替所有用内联函数写钩子与动作的作者解决运行时莫名被拒的问题。 - 出错会怎样:最坏是某个处理函数被多授予一个只开事务、不含读写的权限;改动只在构建期推断,撤回即可恢复原样。 - 要你做什么:无。 ## What changes `os build` lowers an inline hook `handler` / action `target` function to a `js` body and infers its `capabilities` (`packages/cli/src/utils/extract-hook-body.ts`). Two gated calls were never inferred, so a lowered handler making them was refused at the call by the sandbox: 1. **`api.transaction`** — a new `CAPABILITY_PATTERNS` entry for a call of `.transaction` (`?.` allowed on either side) and for the member destructured off its receiver (`const { transaction } = ctx.api`, nested `const { api: { transaction } } = ctx`). Measured against the runner: `installTxLeaf` gates `__txBegin` / `__txCommit` / `__txRollback` behind `api.transaction`, and the VM sugar `ctx.api.transaction` closes over the context and reads no `this`, so every receiver that reaches `ctx.api` (the context itself, a root alias such as `const api = ctx.api`, a destructured `api`, or the destructured member called bare) hits the same gate. These are the shapes the hook-face refusal of `ctx.transaction` (the `exemptCalls` limb) already leaves standing as "the body's transaction route". Receiver-loose like the `.object(...)` patterns: `api.transaction` is no door and grants no data access, so an over-inferred grant opens nothing the body does not call. 2. **`api.read` through a bound handle** — the bound-handle walk `callsObjectWriteThroughHandle` becomes `callsObjectLeafThroughHandle(source, leaves)`, asked once for the write leaves (unchanged) and once for the read leaves (`callsObjectReadThroughHandle`, new). The read leaves are the direct `api.read` pattern's own (`find|findOne|count|aggregate|get|list`, now named once as `OBJECT_READ_LEAVES`); the runner's `READ` list (`find`, `findOne`, `count`, `aggregate`) adds none. The twin also covers the two other shapes the direct read regex missed: `?.` before the leaf and an object argument holding a call. 3. **The published union** — `ExtractedBody.capabilities` on `@objectstack/cli/hook-body` widens to seven tokens, `'api.transaction'` added: exactly the `HookBodyCapability` set of `@objectstack/spec`. Contract face: this is a published type's accept set (a widening; nothing accepted before is refused), so the PR stays draft for its contract-review-tier review. 4. **Carrier note N4** — a CLI-side pin that `lowerActionCallable` still leaves a non-empty string `target` beside the minted `body` record (top-level and object-owned), the shape `@objectstack/lint`'s `isLoweredTargetBody` keys on. 5. **Docs** — the `### Capability inference` table in `content/docs/automation/hook-bodies.mdx` gains two rows: `*.transaction(…)` (with the alias, `?.` and destructured-member spellings the pattern reads) ⇒ `api.transaction`, and the read leaves on a bound handle ⇒ `api.read`. The sentences beside the table stay true as written. Changeset: `.changeset/38653-extractor-transaction-handle-read.md`, `@objectstack/cli` patch, the level `Metadata-protocol: none` takes (a widened published type with no change to what a metadata author can write). <details><summary>Read first (risk order)</summary> 1. `packages/cli/src/utils/extract-hook-body.ts` — the `api.transaction` entry in `CAPABILITY_PATTERNS` (the receiver-loose regex and its destructure limb) and `callsObjectLeafThroughHandle` (the write walk is byte-identical apart from the leaves parameter). 2. `packages/cli/test/published-subpath-hook-body.pin.test.ts` — the one line that widens the ratified union. 3. `packages/cli/test/extract-hook-body.test.ts` — the new pins and their controls. </details> ## Tests - `test/extract-hook-body.test.ts`: the `verify-delete-behaviors` control hook's body verbatim infers `['api.read', 'api.write']`; `api.read` through a bound handle, a handle off an alias of `ctx.api`, `?.` before the leaf and an argument holding a call; a write-only bound handle stays `['api.write']` (control); `api.transaction` through `ctx.api.transaction`, a root alias, `?.` on both sides, and the destructured member; a record field named `transaction` infers nothing (control). - `test/lower-callables.test.ts`: the N4 shape pin. - `test/published-subpath-hook-body.pin.test.ts`: the consumer compiled against the packed `.d.ts` asserts the seven-token union. <details><summary>Ablations (one per new behaviour, each through `scripts/ablation-replace.mjs`, mutation proven on disk and restored to the HEAD blob)</summary> - Remove `if (callsObjectReadThroughHandle(source)) inferred.add('api.read');` — 5 failed / 73 passed (the five `api.read` cases red, both controls green). - Turn the `api.transaction` entry's token into `log` — 4 failed / 74 passed (the four `api.transaction` cases red). - Delete `action.target = ref;` in `lowerActionCallable` — 2 failed / 31 passed (both N4 cases red). - Put the pin's union back to six tokens — 1 failed / 14 passed: `conformance.ts(17,3): error TS2344: Type 'false' does not satisfy the constraint 'true'.`, so the pin reads the rebuilt, packed `.d.ts`. </details> ## Acceptance notes - **Done-when 3: can `validate-action-body-capabilities.ts` now judge lowered bodies for the non-write tokens?** Measured, no `packages/lint` change here. Population: every first-party config (`examples/app-crm`, `app-multi-package`, `app-showcase`, `app-starter`, `app-todo`, `packages/apps/connector-docusign`, `connector-github`, `connector-stripe`), each loaded, normalized and lowered, then read with the rule's own `isLoweredHandlerBody` / `isLoweredTargetBody` and `bodyGatedCalls`. `packages/platform-objects` and `packages/apps/{account,setup,studio}` carry no inline callable (their hooks are installed on the engine in-process). Result: 1 lowered hook body (`crm_opportunity_stage_probability`, no gated call), 0 lowered action bodies, **0 bodies newly refused** with the lowered skips removed. The `verify-delete-behaviors` fixture (a test fixture, outside those trees) goes from one refusal (`api.read`) to none. So for `api.read`, `api.write` and `api.transaction` the extractor now reads every shape the rule reads. It does not yet for the member tokens: a body-local alias the rule reads (`const l = ctx.log; l.info(…)`, `const { log } = ctx`, `const { crypto } = ctx`, `const a = ctx.activity`, a hook's `const t = ctx.title; t(FIELD)`) infers nothing, because the extractor's patterns for those members spell `ctx.` and its rebind covers only the handler's parameter. Dropping the skips now would refuse such a lowered body naming a grant the author never wrote. That is follow-up #38690: the extractor first reads those body-local aliases, then the rule drops its lowered skips. - The union could be typed as `HookBodyCapability` from `@objectstack/spec` (it is exactly the seven tokens), but this PR keeps it restated as ordered: typing it from spec would make the published `.d.ts` import spec types, and the conformance consumer in the pin, which installs only the packed CLI and `typescript`, would need `@objectstack/spec` linked too. - The destructured-leaf call `transaction(fn)` and a nested `const { api: { transaction } } = ctx` are inferred but not read by the lint rule (a missed finding there, never a false one). ## Verification Two-minute check: `pnpm --filter @objectstack/cli exec vitest run --maxWorkers=2 test/extract-hook-body.test.ts test/lower-callables.test.ts test/published-subpath-hook-body.pin.test.ts`. Expect 3 files and 126 tests passed. Readings at head `a6f711ac84` (the source is unchanged since `6c67329b6a`; the later commits touch only the changeset, where `ffbc961a01` moves its level to `patch`, and the docs page, `c8373cd352`): <details><summary>Build, typecheck and tests (local)</summary> - `pnpm --filter '@objectstack/cli^...' build` then `pnpm --filter @objectstack/cli build`, under the verify lock: `VERDICT command-exit 0`. - `pnpm --filter @objectstack/cli typecheck`: `VERDICT command-exit 0` (`tsc --noEmit` plus `check:test-typecheck: OK`). - The three touched files: Test Files 3 passed (3), Tests 126 passed (126). - The whole `unit` project, `pnpm --filter @objectstack/cli exec vitest run --maxWorkers=2 --project unit`: Test Files 450 passed (450), Tests 6451 passed (6451), `VERDICT command-exit 0`. The `integration` project is left to CI. </details> <details><summary>Derived gates (local subset)</summary> `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` derived 69 families for the 5 changed paths; all 69 run, each exit code captured before any pipe. 68 exited 0. `pnpm check:dual-build-cjs-loads` exited 3 (PREREQUISITE NOT MET: it reads the dist of packages outside this build closure), so it is NOT MEASURED here and is CI's. Reconciliation: `dispatch-gates --ran`: 69 derived families accounted for, 68 run, 1 NOT-MEASURED (1 DERIVED from a recorded exit 3). </details> <details><summary>Docs gates for the page (local, at c8373cd)</summary> Adding the page makes `dispatch-gates --commands` derive 31 more families (100 in all). All 31 ran at `c8373cd352`, each exit code captured before any pipe, and all 31 exited 0. `pnpm --filter @objectstack/spec run check:skill-examples` first exited 3 (PREREQUISITE NOT MET: no client-react dist); after the client-react closure was built it exited 0. Reconciliation over all 100: `dispatch-gates --ran` accounts for every family, 99 run and 1 NOT-MEASURED (`check:dual-build-cjs-loads`, exit 3 in the first round). </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01ADHkmSwS4mQyXWrddL4r6B)_ <!-- signed: repo:objectstack#3 · os-steve · session_01ADHkmSwS4mQyXWrddL4r6B --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 1311136 commit 5a77a70

6 files changed

Lines changed: 181 additions & 12 deletions

File tree

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
---
2+
'@objectstack/cli': patch
3+
---
4+
5+
feat(cli): a lowered hook or action handler is granted `api.transaction` when it calls `ctx.api.transaction(…)`, and `api.read` when it reads through a bound object handle
6+
7+
Clause-②: yes (widening)
8+
Metadata-protocol: none
9+
10+
`os build` lowers an inline hook `handler` or action `target` function to a `js` body and infers the body's `capabilities` from the calls in its source. Two calls the sandbox gates were never inferred, so a lowered handler making them was refused at the call (403 INSUFFICIENT_PRIVILEGES) on every run:
11+
12+
- `ctx.api.transaction(fn)` — now infers `api.transaction`, whether it is called on `ctx.api`, on a local bound to `ctx.api` (`const api = ctx.api`), with `?.`, or after destructuring the member (`const { transaction } = ctx.api`). `api.write` stays its own grant, inferred from the writes inside the callback.
13+
- a read through a bound handle — `const rows = ctx.api.object('x'); … rows.find(…)` — now infers `api.read`, the same way a write through a bound handle already inferred `api.write`. The other read shapes the direct pattern missed (`?.` before the leaf, an object argument holding a call) are read too.
14+
15+
`ExtractedBody.capabilities`, published from `@objectstack/cli/hook-body`, widens to include `'api.transaction'` (seven tokens, the `HookBodyCapability` set of `@objectstack/spec`). A dependent with an exhaustive `switch` over the union gains one case to handle; nothing that was accepted before is refused.

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -452,7 +452,9 @@ The extractor scans each body for known patterns and adds the matching capabilit
452452
| Pattern in source | Inferred capability |
453453
|---|---|
454454
| `*.object(…).find / findOne / count / aggregate / get / list` | `api.read` |
455+
| The same read leaves on a bound handle — `const h = ctx.api.object('x'); h.find(…)` | `api.read` |
455456
| `*.object(…).insert / update / updateById / updateMany / upsert / delete / deleteMany / patch / remove / create` | `api.write` |
457+
| `*.transaction(…)` — `ctx.api.transaction(…)`, the same call on an alias of `ctx.api` (`const api = ctx.api; api.transaction(…)`), `?.` allowed on either side, or the member destructured off it (`const { transaction } = ctx.api; transaction(…)`) | `api.transaction` |
456458
| `ctx.crypto.randomUUID` | `crypto.uuid` |
457459
| `ctx.log.info / warn / error / debug` | `log` |
458460
| `*.title(<argument>)` — the related-record form only; bare `ctx.title()` names this record and needs no token | `api.read` |

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

Lines changed: 57 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -506,7 +506,7 @@ const FORBIDDEN_PATTERNS: Array<{ rx: RegExp; reason: string; face?: LoweringFac
506506
},
507507
];
508508

509-
const CAPABILITY_PATTERNS: Array<{ rx: RegExp; cap: 'api.read' | 'api.write' | 'crypto.uuid' | 'log' | 'email.send' | 'activity.append' }> = [
509+
const CAPABILITY_PATTERNS: Array<{ rx: RegExp; cap: 'api.read' | 'api.write' | 'api.transaction' | 'crypto.uuid' | 'log' | 'email.send' | 'activity.append' }> = [
510510
// Match `ctx.api.object(...)` directly OR a local alias like
511511
// `const api = ctx.api;` then `api.object(...)`. We accept any
512512
// identifier (or chain) ending in `.object(...)` followed by a known
@@ -520,6 +520,26 @@ const CAPABILITY_PATTERNS: Array<{ rx: RegExp; cap: 'api.read' | 'api.write' | '
520520
// likewise, for the same reason: the id-first single-record write the spec
521521
// contract declares, installed behind `api.write`.
522522
{ rx: /\.object\s*\([^)]+\)\s*\.\s*(?:insert|updateById|updateMany|update|upsert|deleteMany|delete|patch|remove|create)\b/, cap: 'api.write' },
523+
// [#38653] `ctx.api.transaction(fn)`, the body's one transaction route: the
524+
// sandbox installs it on `ctx.api` and gates it behind `api.transaction`
525+
// (`installTxLeaf`, quickjs-runner.ts), so a handler that calls it and is
526+
// lowered without the token is refused at the call. Read in the shapes the
527+
// hook-face refusal of `ctx.transaction` above leaves standing as this route:
528+
//
529+
// - a call of `.transaction` off any receiver, `?.` allowed on either side
530+
// (`ctx.api.transaction(…)`, `api.transaction(…)` off a root alias of
531+
// `ctx.api`, `ctx.api?.transaction?.(…)`). Receiver-loose like the
532+
// `.object(…)` patterns: `api.transaction` is no door, so an over-inferred
533+
// grant opens nothing the body does not call, and `api.write` stays a
534+
// separate grant;
535+
// - the member destructured off its receiver (`const { transaction } =
536+
// ctx.api`, nested `const { api: { transaction } } = ctx`), whose bare
537+
// `transaction(fn)` call reaches the same gate: the VM's sugar closes over
538+
// the context and reads no `this`.
539+
//
540+
// A read of a `transaction` FIELD (`ctx.input.transaction`) is no call and
541+
// infers nothing.
542+
{ rx: /\.\s*transaction\s*(?:\?\.\s*)?\(|\{[^{}]*\btransaction\b[^{}]*\}(?:\s*\})*\s*=(?![=>])/, cap: 'api.transaction' },
523543
{ rx: /ctx\.crypto\.randomUUID\b/, cap: 'crypto.uuid' },
524544
// NO `ctx.crypto.hash` pattern: the `crypto.hash` token was removed in spec 17
525545
// (#4391) because the sandbox never installed the function. Inferring a
@@ -558,6 +578,9 @@ const CAPABILITY_PATTERNS: Array<{ rx: RegExp; cap: 'api.read' | 'api.write' | '
558578
{ rx: /ctx\.activity\.append\b/, cap: 'activity.append' },
559579
];
560580

581+
/** The read leaves the `api.read` pattern above names, as one alternation. */
582+
const OBJECT_READ_LEAVES = 'find|findOne|count|aggregate|get|list';
583+
561584
/** The write leaves the `api.write` pattern above names, as one alternation. */
562585
const OBJECT_WRITE_LEAVES = 'insert|updateById|updateMany|update|upsert|deleteMany|delete|patch|remove|create';
563586

@@ -573,36 +596,58 @@ function closingParen(source: string, open: number): number {
573596
}
574597

575598
/**
576-
* [#35143] Whether the body writes through `.object(...)` in a shape the
577-
* `api.write` pattern's single regex cannot read — the shapes the publish
578-
* check `action-body-write-capability-undeclared` reads, so a handler `os build`
579-
* lowers is never refused by the next step of the same build:
599+
* [#35143] Whether the body calls one of `leaves` through `.object(...)` in a
600+
* shape the single-regex `api.read` / `api.write` patterns cannot read — the
601+
* shapes the publish checks `action-body-write-capability-undeclared` and
602+
* `action-body-capability-undeclared` / `hook-body-capability-undeclared` read,
603+
* so a handler `os build` lowers is never refused by the next step of the same
604+
* build:
580605
*
581606
* - an argument holding a call or other parentheses: `ctx.api.object(name()).update(…)`;
582607
* - `?.` before the leaf: `ctx.api.object('x')?.update(…)`;
583608
* - a bound handle: `const repo = ctx.api.object('x'); … repo.update(…)`.
584609
*
610+
* Asked twice, once per token: {@link callsObjectWriteThroughHandle} for the
611+
* write leaves and {@link callsObjectReadThroughHandle} (#38653) for the read
612+
* leaves — one walk, so a read and a write through the same handle are read
613+
* the same way.
614+
*
585615
* Receiver-loose like the patterns above, for their reason: an over-inferred
586616
* grant is one the sandbox never checks, an under-inferred one is a 403 at
587617
* every call.
588618
*/
589-
function callsObjectWriteThroughHandle(source: string): boolean {
590-
const chainedWrite = new RegExp(String.raw`^\s*\??\.\s*(?:${OBJECT_WRITE_LEAVES})\b`);
619+
function callsObjectLeafThroughHandle(source: string, leaves: string): boolean {
620+
const chainedLeaf = new RegExp(String.raw`^\s*\??\.\s*(?:${leaves})\b`);
591621
const handles: string[] = [];
592622
for (const m of source.matchAll(/\??\.\s*object\s*\(/g)) {
593623
const open = (m.index ?? 0) + m[0].length - 1;
594624
const close = closingParen(source, open);
595625
if (close < 0) continue;
596626
const after = source.slice(close + 1);
597-
if (chainedWrite.test(after)) return true;
627+
if (chainedLeaf.test(after)) return true;
598628
const bound = /\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:await\s+)?[\w$.? \t]*$/.exec(source.slice(0, m.index ?? 0));
599629
if (bound && /^\s*(?:;|\n|$)/.test(after)) handles.push(bound[1]);
600630
}
601631
return handles.some((name) =>
602-
new RegExp(String.raw`(?<![\w$.])${name.replace(/\$/g, '\\$')}\s*\??\.\s*(?:${OBJECT_WRITE_LEAVES})\s*\(`).test(source),
632+
new RegExp(String.raw`(?<![\w$.])${name.replace(/\$/g, '\\$')}\s*\??\.\s*(?:${leaves})\s*\(`).test(source),
603633
);
604634
}
605635

636+
/** [#35143] A write leaf through `.object(...)` in a shape the `api.write` regex cannot read. */
637+
function callsObjectWriteThroughHandle(source: string): boolean {
638+
return callsObjectLeafThroughHandle(source, OBJECT_WRITE_LEAVES);
639+
}
640+
641+
/**
642+
* [#38653] The read twin: a read leaf through `.object(...)` in a shape the
643+
* `api.read` regex cannot read — above all a bound handle,
644+
* `const rows = ctx.api.object('x'); … rows.find(…)`, which a handler that
645+
* reads and then writes through one handle spells.
646+
*/
647+
function callsObjectReadThroughHandle(source: string): boolean {
648+
return callsObjectLeafThroughHandle(source, OBJECT_READ_LEAVES);
649+
}
650+
606651
export interface ExtractedBody {
607652
/** Pure function-body source (without the surrounding `(ctx) => {...}`). */
608653
source: string;
@@ -612,7 +657,7 @@ export interface ExtractedBody {
612657
* is retired (see this file's header). An author whose needs differ from what
613658
* inference derives writes `body.capabilities` on the hook instead.
614659
*/
615-
capabilities: Array<'api.read' | 'api.write' | 'crypto.uuid' | 'log' | 'email.send' | 'activity.append'>;
660+
capabilities: Array<'api.read' | 'api.write' | 'api.transaction' | 'crypto.uuid' | 'log' | 'email.send' | 'activity.append'>;
616661
/** True when source is a single expression (arrow with implicit return). */
617662
isExpression: boolean;
618663
}
@@ -707,8 +752,9 @@ export function extractLoweredBody(
707752
for (const { rx, cap } of CAPABILITY_PATTERNS) {
708753
if (rx.test(source)) inferred.add(cap);
709754
}
710-
// [#35143] The `.object(...)` write shapes one regex cannot read; see the helper.
755+
// [#35143] [#38653] The `.object(...)` write and read shapes one regex cannot read; see the helper.
711756
if (callsObjectWriteThroughHandle(source)) inferred.add('api.write');
757+
if (callsObjectReadThroughHandle(source)) inferred.add('api.read');
712758
// [#22837] The ctx-anchored patterns above spell `ctx.`; a rebound body
713759
// reaches the same members through the handler's own names.
714760
for (const cap of reboundCapabilities(source, rebind)) inferred.add(cap);

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

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,87 @@ describe('extractHookBody', () => {
121121
expect(extractHookBody(fn, 'hook read handle').capabilities).not.toContain('api.write');
122122
});
123123

124+
// [#38653] The read twin of the bound-handle walk. The sandbox installs the
125+
// read leaves behind `api.read` on the same handle it installs the writes on,
126+
// so a handler that reads through a bound handle and is lowered without the
127+
// token is refused at its first read. The first case is the
128+
// `verify-delete-behaviors` control hook's shape, byte for byte in its body.
129+
it('infers api.read and api.write from a read and a write through one bound handle', () => {
130+
const fn = async (ctx: any) => {
131+
const contacts = ctx.api.object('vdb_contact');
132+
for (const row of await contacts.find({ where: { account: ctx.input.id } })) {
133+
await contacts.updateById(row.id, { account: null });
134+
}
135+
};
136+
expect(extractHookBody(fn, 'hook read+write handle').capabilities).toEqual(['api.read', 'api.write']);
137+
});
138+
139+
it.each([
140+
['a bound handle', async (ctx: any) => {
141+
const repo = ctx.api.object('foo');
142+
return repo.findOne({ where: { id: ctx.input.id } });
143+
}],
144+
['a bound handle through an alias of ctx.api', async (ctx: any) => {
145+
const api = ctx.api;
146+
const repo = api.object('foo');
147+
return repo.count({});
148+
}],
149+
['`?.` before the leaf', async (ctx: any) => {
150+
return ctx.api.object('foo')?.aggregate({});
151+
}],
152+
['an object argument holding a call', async (ctx: any) => {
153+
return ctx.api.object(String('foo')).find({});
154+
}],
155+
])('infers api.read through %s', (_shape, fn) => {
156+
expect(extractHookBody(fn, 'hook read shapes').capabilities).toEqual(['api.read']);
157+
});
158+
159+
it('infers no api.read from a bound handle that only writes (control)', () => {
160+
const fn = async (ctx: any) => {
161+
const repo = ctx.api.object('foo');
162+
await repo.updateById(ctx.input.id, { done: true });
163+
};
164+
expect(extractHookBody(fn, 'hook write handle').capabilities).toEqual(['api.write']);
165+
});
166+
167+
// [#38653] `ctx.api.transaction(fn)` is gated behind `api.transaction` in the
168+
// sandbox, and nothing inferred the token, so a lowered handler that grouped
169+
// its writes in one was refused at the call.
170+
it.each([
171+
['ctx.api.transaction', async (ctx: any) => {
172+
await ctx.api.transaction(async () => {
173+
await ctx.api.object('foo').insert({ name: 'x' });
174+
});
175+
}],
176+
['a root alias of ctx.api', async (ctx: any) => {
177+
const api = ctx.api;
178+
await api.transaction(async () => {
179+
await api.object('foo').insert({ name: 'x' });
180+
});
181+
}],
182+
['`?.` on either side of the member', async (ctx: any) => {
183+
await ctx.api?.transaction?.(async () => {
184+
await ctx.api.object('foo').insert({ name: 'x' });
185+
});
186+
}],
187+
['the member destructured off ctx.api', async (ctx: any) => {
188+
const { transaction } = ctx.api;
189+
await transaction(async () => {
190+
await ctx.api.object('foo').insert({ name: 'x' });
191+
});
192+
}],
193+
])('infers api.transaction through %s', (_shape, fn) => {
194+
expect(extractHookBody(fn, 'hook tx').capabilities).toEqual(['api.transaction', 'api.write']);
195+
});
196+
197+
it('infers no api.transaction from a record field named transaction (control)', () => {
198+
const fn = async (ctx: any) => {
199+
const ref = ctx.input.transaction;
200+
await ctx.api.object('foo').insert({ name: 'x', ref });
201+
};
202+
expect(extractHookBody(fn, 'hook tx field').capabilities).toEqual(['api.write']);
203+
});
204+
124205
it('infers log', () => {
125206
const fn = (ctx: any) => {
126207
ctx.log.info('hi');

‎packages/cli/test/lower-callables.test.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -498,3 +498,28 @@ describe('[#33214] lowerCallables — a handler hook\'s refusal catalogue', () =
498498
expect(r.error!.issues.find((i) => i.path.join('.') === 'body.source')?.message).toContain("reason 'plan_lockd'");
499499
});
500500
});
501+
502+
// [#38653] `@objectstack/lint` tells an action body the build lowered from an
503+
// inline `target` function apart from an authored one by its shape alone — a
504+
// non-empty string `target` beside a body record (`isLoweredTargetBody` in
505+
// `validate-action-body-capabilities.ts`) — and judges only the first for
506+
// `api.write`. Its own pins build that shape by hand; this one holds it to what
507+
// `lowerActionCallable` really emits, top-level and object-owned, so a lowering
508+
// that stopped leaving the string ref would surface here, not as lint judging
509+
// inferred grants as authored ones.
510+
describe('[#38653] lowerCallables — a lowered action keeps a string `target` beside its minted body', () => {
511+
const target = async (ctx: any) => {
512+
await ctx.api.object('doc').updateById(ctx.input.id, { stamped: true });
513+
};
514+
515+
it.each([
516+
['an object-owned action', { objects: [{ name: 'doc', actions: [{ name: 'stamp', type: 'script', target }] }] }, (l: any) => l.objects[0].actions[0]],
517+
['a top-level action', { actions: [{ name: 'stamp', type: 'script', target }] }, (l: any) => l.actions[0]],
518+
])('%s', (_where, input, pick) => {
519+
const action = pick(lowerCallables(input).lowered);
520+
expect(typeof action.target).toBe('string');
521+
expect(action.target).not.toBe('');
522+
expect(action.body).toEqual(expect.objectContaining({ language: 'js', capabilities: ['api.write'] }));
523+
expect(Array.isArray(action.body)).toBe(false);
524+
});
525+
});

‎packages/cli/test/published-subpath-hook-body.pin.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -283,7 +283,7 @@ type ExtractedBodyHasExactlyTheseThreeFields = Expect<Equals<keyof ExtractedBody
283283
type ExtractedBodyMembersKeepTheirRatifiedTypes = Expect<
284284
Equals<
285285
ExtractedBody,
286-
{ source: string; capabilities: Array<'api.read' | 'api.write' | 'crypto.uuid' | 'log' | 'email.send' | 'activity.append'>; isExpression: boolean }
286+
{ source: string; capabilities: Array<'api.read' | 'api.write' | 'api.transaction' | 'crypto.uuid' | 'log' | 'email.send' | 'activity.append'>; isExpression: boolean }
287287
>
288288
>;
289289

0 commit comments

Comments
 (0)