Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions .changeset/38653-extractor-transaction-handle-read.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
'@objectstack/cli': patch
---

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

Clause-②: yes (widening)
Metadata-protocol: none

`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:

- `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.
- 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.

`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.
2 changes: 2 additions & 0 deletions content/docs/automation/hook-bodies.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -452,7 +452,9 @@ The extractor scans each body for known patterns and adds the matching capabilit
| Pattern in source | Inferred capability |
|---|---|
| `*.object(…).find / findOne / count / aggregate / get / list` | `api.read` |
| The same read leaves on a bound handle — `const h = ctx.api.object('x'); h.find(…)` | `api.read` |
| `*.object(…).insert / update / updateById / updateMany / upsert / delete / deleteMany / patch / remove / create` | `api.write` |
| `*.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` |
| `ctx.crypto.randomUUID` | `crypto.uuid` |
| `ctx.log.info / warn / error / debug` | `log` |
| `*.title(<argument>)` — the related-record form only; bare `ctx.title()` names this record and needs no token | `api.read` |
Expand Down
68 changes: 57 additions & 11 deletions packages/cli/src/utils/extract-hook-body.ts
Original file line number Diff line number Diff line change
Expand Up @@ -506,7 +506,7 @@ const FORBIDDEN_PATTERNS: Array<{ rx: RegExp; reason: string; face?: LoweringFac
},
];

const CAPABILITY_PATTERNS: Array<{ rx: RegExp; cap: 'api.read' | 'api.write' | 'crypto.uuid' | 'log' | 'email.send' | 'activity.append' }> = [
const CAPABILITY_PATTERNS: Array<{ rx: RegExp; cap: 'api.read' | 'api.write' | 'api.transaction' | 'crypto.uuid' | 'log' | 'email.send' | 'activity.append' }> = [
// Match `ctx.api.object(...)` directly OR a local alias like
// `const api = ctx.api;` then `api.object(...)`. We accept any
// identifier (or chain) ending in `.object(...)` followed by a known
Expand All @@ -520,6 +520,26 @@ const CAPABILITY_PATTERNS: Array<{ rx: RegExp; cap: 'api.read' | 'api.write' | '
// likewise, for the same reason: the id-first single-record write the spec
// contract declares, installed behind `api.write`.
{ rx: /\.object\s*\([^)]+\)\s*\.\s*(?:insert|updateById|updateMany|update|upsert|deleteMany|delete|patch|remove|create)\b/, cap: 'api.write' },
// [#38653] `ctx.api.transaction(fn)`, the body's one transaction route: the
// sandbox installs it on `ctx.api` and gates it behind `api.transaction`
// (`installTxLeaf`, quickjs-runner.ts), so a handler that calls it and is
// lowered without the token is refused at the call. Read in the shapes the
// hook-face refusal of `ctx.transaction` above leaves standing as this route:
//
// - a call of `.transaction` off any receiver, `?.` allowed on either side
// (`ctx.api.transaction(…)`, `api.transaction(…)` off a root alias of
// `ctx.api`, `ctx.api?.transaction?.(…)`). Receiver-loose like the
// `.object(…)` patterns: `api.transaction` is no door, so an over-inferred
// grant opens nothing the body does not call, and `api.write` stays a
// separate grant;
// - the member destructured off its receiver (`const { transaction } =
// ctx.api`, nested `const { api: { transaction } } = ctx`), whose bare
// `transaction(fn)` call reaches the same gate: the VM's sugar closes over
// the context and reads no `this`.
//
// A read of a `transaction` FIELD (`ctx.input.transaction`) is no call and
// infers nothing.
{ rx: /\.\s*transaction\s*(?:\?\.\s*)?\(|\{[^{}]*\btransaction\b[^{}]*\}(?:\s*\})*\s*=(?![=>])/, cap: 'api.transaction' },
{ 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
Expand Down Expand Up @@ -558,6 +578,9 @@ const CAPABILITY_PATTERNS: Array<{ rx: RegExp; cap: 'api.read' | 'api.write' | '
{ rx: /ctx\.activity\.append\b/, cap: 'activity.append' },
];

/** The read leaves the `api.read` pattern above names, as one alternation. */
const OBJECT_READ_LEAVES = 'find|findOne|count|aggregate|get|list';

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

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

/**
* [#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:
* [#35143] Whether the body calls one of `leaves` through `.object(...)` in a
* shape the single-regex `api.read` / `api.write` patterns cannot read — the
* shapes the publish checks `action-body-write-capability-undeclared` and
* `action-body-capability-undeclared` / `hook-body-capability-undeclared` read,
* 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(…)`.
*
* Asked twice, once per token: {@link callsObjectWriteThroughHandle} for the
* write leaves and {@link callsObjectReadThroughHandle} (#38653) for the read
* leaves — one walk, so a read and a write through the same handle are read
* the same way.
*
* 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`);
function callsObjectLeafThroughHandle(source: string, leaves: string): boolean {
const chainedLeaf = new RegExp(String.raw`^\s*\??\.\s*(?:${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;
if (chainedLeaf.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`(?<![\w$.])${name.replace(/\$/g, '\\$')}\s*\??\.\s*(?:${OBJECT_WRITE_LEAVES})\s*\(`).test(source),
new RegExp(String.raw`(?<![\w$.])${name.replace(/\$/g, '\\$')}\s*\??\.\s*(?:${leaves})\s*\(`).test(source),
);
}

/** [#35143] A write leaf through `.object(...)` in a shape the `api.write` regex cannot read. */
function callsObjectWriteThroughHandle(source: string): boolean {
return callsObjectLeafThroughHandle(source, OBJECT_WRITE_LEAVES);
}

/**
* [#38653] The read twin: a read leaf through `.object(...)` in a shape the
* `api.read` regex cannot read — above all a bound handle,
* `const rows = ctx.api.object('x'); … rows.find(…)`, which a handler that
* reads and then writes through one handle spells.
*/
function callsObjectReadThroughHandle(source: string): boolean {
return callsObjectLeafThroughHandle(source, OBJECT_READ_LEAVES);
}

export interface ExtractedBody {
/** Pure function-body source (without the surrounding `(ctx) => {...}`). */
source: string;
Expand All @@ -612,7 +657,7 @@ export interface ExtractedBody {
* is retired (see this file's header). An author whose needs differ from what
* inference derives writes `body.capabilities` on the hook instead.
*/
capabilities: Array<'api.read' | 'api.write' | 'crypto.uuid' | 'log' | 'email.send' | 'activity.append'>;
capabilities: Array<'api.read' | 'api.write' | 'api.transaction' | 'crypto.uuid' | 'log' | 'email.send' | 'activity.append'>;
/** True when source is a single expression (arrow with implicit return). */
isExpression: boolean;
}
Expand Down Expand Up @@ -707,8 +752,9 @@ 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.
// [#35143] [#38653] The `.object(...)` write and read shapes one regex cannot read; see the helper.
if (callsObjectWriteThroughHandle(source)) inferred.add('api.write');
if (callsObjectReadThroughHandle(source)) inferred.add('api.read');
// [#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);
Expand Down
81 changes: 81 additions & 0 deletions packages/cli/test/extract-hook-body.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,87 @@ describe('extractHookBody', () => {
expect(extractHookBody(fn, 'hook read handle').capabilities).not.toContain('api.write');
});

// [#38653] The read twin of the bound-handle walk. The sandbox installs the
// read leaves behind `api.read` on the same handle it installs the writes on,
// so a handler that reads through a bound handle and is lowered without the
// token is refused at its first read. The first case is the
// `verify-delete-behaviors` control hook's shape, byte for byte in its body.
it('infers api.read and api.write from a read and a write through one bound handle', () => {
const fn = async (ctx: any) => {
const contacts = ctx.api.object('vdb_contact');
for (const row of await contacts.find({ where: { account: ctx.input.id } })) {
await contacts.updateById(row.id, { account: null });
}
};
expect(extractHookBody(fn, 'hook read+write handle').capabilities).toEqual(['api.read', 'api.write']);
});

it.each([
['a bound handle', async (ctx: any) => {
const repo = ctx.api.object('foo');
return repo.findOne({ where: { id: ctx.input.id } });
}],
['a bound handle through an alias of ctx.api', async (ctx: any) => {
const api = ctx.api;
const repo = api.object('foo');
return repo.count({});
}],
['`?.` before the leaf', async (ctx: any) => {
return ctx.api.object('foo')?.aggregate({});
}],
['an object argument holding a call', async (ctx: any) => {
return ctx.api.object(String('foo')).find({});
}],
])('infers api.read through %s', (_shape, fn) => {
expect(extractHookBody(fn, 'hook read shapes').capabilities).toEqual(['api.read']);
});

it('infers no api.read from a bound handle that only writes (control)', () => {
const fn = async (ctx: any) => {
const repo = ctx.api.object('foo');
await repo.updateById(ctx.input.id, { done: true });
};
expect(extractHookBody(fn, 'hook write handle').capabilities).toEqual(['api.write']);
});

// [#38653] `ctx.api.transaction(fn)` is gated behind `api.transaction` in the
// sandbox, and nothing inferred the token, so a lowered handler that grouped
// its writes in one was refused at the call.
it.each([
['ctx.api.transaction', async (ctx: any) => {
await ctx.api.transaction(async () => {
await ctx.api.object('foo').insert({ name: 'x' });
});
}],
['a root alias of ctx.api', async (ctx: any) => {
const api = ctx.api;
await api.transaction(async () => {
await api.object('foo').insert({ name: 'x' });
});
}],
['`?.` on either side of the member', async (ctx: any) => {
await ctx.api?.transaction?.(async () => {
await ctx.api.object('foo').insert({ name: 'x' });
});
}],
['the member destructured off ctx.api', async (ctx: any) => {
const { transaction } = ctx.api;
await transaction(async () => {
await ctx.api.object('foo').insert({ name: 'x' });
});
}],
])('infers api.transaction through %s', (_shape, fn) => {
expect(extractHookBody(fn, 'hook tx').capabilities).toEqual(['api.transaction', 'api.write']);
});

it('infers no api.transaction from a record field named transaction (control)', () => {
const fn = async (ctx: any) => {
const ref = ctx.input.transaction;
await ctx.api.object('foo').insert({ name: 'x', ref });
};
expect(extractHookBody(fn, 'hook tx field').capabilities).toEqual(['api.write']);
});

it('infers log', () => {
const fn = (ctx: any) => {
ctx.log.info('hi');
Expand Down
25 changes: 25 additions & 0 deletions packages/cli/test/lower-callables.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -498,3 +498,28 @@ describe('[#33214] lowerCallables — a handler hook\'s refusal catalogue', () =
expect(r.error!.issues.find((i) => i.path.join('.') === 'body.source')?.message).toContain("reason 'plan_lockd'");
});
});

// [#38653] `@objectstack/lint` tells an action body the build lowered from an
// inline `target` function apart from an authored one by its shape alone — a
// non-empty string `target` beside a body record (`isLoweredTargetBody` in
// `validate-action-body-capabilities.ts`) — and judges only the first for
// `api.write`. Its own pins build that shape by hand; this one holds it to what
// `lowerActionCallable` really emits, top-level and object-owned, so a lowering
// that stopped leaving the string ref would surface here, not as lint judging
// inferred grants as authored ones.
describe('[#38653] lowerCallables — a lowered action keeps a string `target` beside its minted body', () => {
const target = async (ctx: any) => {
await ctx.api.object('doc').updateById(ctx.input.id, { stamped: true });
};

it.each([
['an object-owned action', { objects: [{ name: 'doc', actions: [{ name: 'stamp', type: 'script', target }] }] }, (l: any) => l.objects[0].actions[0]],
['a top-level action', { actions: [{ name: 'stamp', type: 'script', target }] }, (l: any) => l.actions[0]],
])('%s', (_where, input, pick) => {
const action = pick(lowerCallables(input).lowered);
expect(typeof action.target).toBe('string');
expect(action.target).not.toBe('');
expect(action.body).toEqual(expect.objectContaining({ language: 'js', capabilities: ['api.write'] }));
expect(Array.isArray(action.body)).toBe(false);
});
});
2 changes: 1 addition & 1 deletion packages/cli/test/published-subpath-hook-body.pin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ type ExtractedBodyHasExactlyTheseThreeFields = Expect<Equals<keyof ExtractedBody
type ExtractedBodyMembersKeepTheirRatifiedTypes = Expect<
Equals<
ExtractedBody,
{ source: string; capabilities: Array<'api.read' | 'api.write' | 'crypto.uuid' | 'log' | 'email.send' | 'activity.append'>; isExpression: boolean }
{ source: string; capabilities: Array<'api.read' | 'api.write' | 'api.transaction' | 'crypto.uuid' | 'log' | 'email.send' | 'activity.append'>; isExpression: boolean }
>
>;

Expand Down
Loading