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
17 changes: 17 additions & 0 deletions .changeset/38690-extractor-local-alias.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
'@objectstack/cli': patch
---

fix(cli): a lowered hook or action handler is granted the member capability it calls through a body-local alias of `ctx.log`, `ctx.crypto`, `ctx.email`, `ctx.activity` or `ctx.title`

Clause-②: no
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. The member calls were inferred only when spelled off `ctx` itself (`ctx.log.info(…)`), so a handler that first took the member into a local was lowered without the token and refused by the sandbox at the call on every run, while `os validate` read the same body as granted. Now the extractor reads the same two alias shapes the publish check reads:

- a local bound once to the member: `const l = ctx.log; l.info(…)`;
- a plain destructure off `ctx`: `const { log } = ctx`, `const { log: l } = ctx`.

Through either, a call of `info`/`warn`/`error`/`debug` infers `log`, `randomUUID()` infers `crypto.uuid`, `send(…)` infers `email.send`, `append(…)` infers `activity.append`, and on a hook a `title(FIELD)` call with an argument infers `api.read`. A field read that is not a call, a local reassigned after its declaration, and a destructure with a default infer nothing. The `ExtractedBody.capabilities` union published from `@objectstack/cli/hook-body` is unchanged.

As with `ctx.email.send(…)` spelled directly, a hook handler that calls `send(…)` through such an alias now carries `email.send` and is refused by the hook's parse at build time (a hook body is never granted mail), instead of shipping and failing at the call. Send mail on a record change from an action, a job or a flow.
12 changes: 8 additions & 4 deletions content/docs/automation/hook-bodies.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -455,11 +455,15 @@ The extractor scans each body for known patterns and adds the matching capabilit
| 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` |
| `ctx.crypto.randomUUID`, or a `randomUUID()` call on a local alias of `ctx.crypto` (`const c = ctx.crypto; c.randomUUID()`, `const { crypto } = ctx; crypto.randomUUID()`) | `crypto.uuid` |
| `ctx.log.info / warn / error / debug`, or the same calls on a local alias of `ctx.log` (`const l = ctx.log; l.info(…)`, `const { log } = ctx; log.warn(…)`) | `log` |
| `ctx.email.send`, or a `send(…)` call on a local alias of `ctx.email` (`const e = ctx.email; e.send(…)`, `const { email } = ctx; email.send(…)`) | `email.send` |
| `ctx.activity.append`, or an `append(…)` call on a local alias of `ctx.activity` (`const a = ctx.activity; a.append(…)`, `const { activity } = ctx; activity.append(…)`) | `activity.append` |
| `*.title(<argument>)` — the related-record form only; bare `ctx.title()` names this record and needs no token. On a hook, also a call with an argument on a local alias of `ctx.title` (`const t = ctx.title; t('account_id')`, `const { title } = ctx; title('account_id')`) | `api.read` |

The matcher is deliberately over-inclusive — it names spellings the VM does not install (`patch`, `remove`, `get`, `list`, `create`) because an over-inferred token costs nothing the sandbox ever checks, while an under-inferred one surfaces as a sandbox refusal far from its cause. `create` is listed only for that reason: a body spelling it is refused at lowering (see [What the sandbox forbids](#what-the-sandbox-forbids)) and never reaches inference at all.
A local alias counts in two shapes only, the ones the publish check reads: a name bound to the member itself (`const l = ctx.log`), or a plain name destructured off `ctx` (`const { log } = ctx`, `const { log: l } = ctx`). The name must be declared once and never assigned again; a destructure with a default, an alias of an alias, and a field read that is not a call (`const f = l.info`) infer nothing.

The matcher is deliberately over-inclusive — it names spellings the VM does not install (`patch`, `remove`, `get`, `list`, `create`) because an over-inferred token costs nothing the sandbox ever checks, while an under-inferred one surfaces as a sandbox refusal far from its cause. `create` is listed only for that reason: a body spelling it is refused at lowering (see [What the sandbox forbids](#what-the-sandbox-forbids)) and never reaches inference at all. `email.send` is the one exception: a hook body is never granted it, so a hook handler that spells `ctx.email.send` or calls `send(…)` on an alias of `ctx.email` is refused at build. Send mail on a record change from an action, a job or a flow.

When inference does not derive what a body needs, declare the tokens yourself by
supplying `body` on the hook or action instead of a `handler`:
Expand Down
104 changes: 101 additions & 3 deletions packages/cli/src/utils/extract-hook-body.ts
Original file line number Diff line number Diff line change
Expand Up @@ -756,8 +756,9 @@ export function extractLoweredBody(
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);
// reaches the same members through the handler's own names, and [#38690]
// any body through a local bound to `ctx.MEMBER` or destructured off `ctx`.
for (const cap of reboundCapabilities(source, rebind, bodyMemberAliases(parsed, face))) inferred.add(cap);

return {
source,
Expand Down Expand Up @@ -1060,6 +1061,81 @@ function escapeRx(name: string): string {
return name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

/** The members a body-local alias can stand for, each to the names bound to it. */
type MemberLocals = Readonly<Record<'log' | 'crypto' | 'title' | 'email' | 'activity', readonly string[]>>;

const NO_MEMBER_LOCALS: MemberLocals = { log: [], crypto: [], title: [], email: [], activity: [] };

/** The gated leaves of each member-leaf gate, as one alternation, and the token the call needs. */
const MEMBER_LEAVES: Readonly<Record<'log' | 'crypto' | 'email' | 'activity', { leaves: string; cap: ExtractedBody['capabilities'][number] }>> = {
log: { leaves: 'info|warn|error|debug', cap: 'log' },
crypto: { leaves: 'randomUUID', cap: 'crypto.uuid' },
email: { leaves: 'send', cap: 'email.send' },
activity: { leaves: 'append', cap: 'activity.append' },
};

const ALIASABLE_MEMBERS: ReadonlySet<string> = new Set(['log', 'crypto', 'title', 'email', 'activity']);

/**
* [#38690] The body-local aliases of a capability-bearing member, in exactly
* the two shapes the publish rule (`validate-action-body-capabilities`,
* `memberReceivers`) credits as a receiver of `ctx.MEMBER`:
*
* - a local bound to the member itself: `const l = ctx.log` (not `ctx?.log`,
* not a chain or an expression built on it);
* - a plain element destructured off `ctx`: `const { log } = ctx`,
* `const { log: l } = ctx` (no default, no rest, no nesting).
*
* Either counts only when the name is declared once in the handler and never
* assigned or stepped again, so it stands for the member wherever it is read.
* Read off the handler's parse, so a string or a comment declares nothing.
* `title` is collected on the hook face alone: the host builds `ctx.title`
* only for hook bodies.
*
* Over-inferring here costs what the receiver-loose patterns above cost and no
* more: the token is inferred only for a CALL of the gated leaf off the alias,
* which is the call the sandbox gates.
*/
function bodyMemberAliases(fn: ts.FunctionLikeDeclarationBase, face: LoweringFace): MemberLocals {
const body = fn.body;
if (!body) return NO_MEMBER_LOCALS;
const declared = new Map<string, number>();
const reassigned = new Set<string>();
const candidates: Array<{ member: string; local: string }> = [];
const isCtx = (e: ts.Node): boolean => ts.isIdentifier(e) && e.text === 'ctx';
const visit = (node: ts.Node): void => {
if (ts.isVariableDeclaration(node)) {
for (const n of bindingNames(node.name)) declared.set(n, (declared.get(n) ?? 0) + 1);
const init = node.initializer;
if (init && ts.isIdentifier(node.name) && ts.isPropertyAccessExpression(init)
&& !init.questionDotToken && isCtx(init.expression) && ALIASABLE_MEMBERS.has(init.name.text)) {
candidates.push({ member: init.name.text, local: node.name.text });
} else if (init && isCtx(init) && ts.isObjectBindingPattern(node.name)) {
for (const el of node.name.elements) {
if (el.dotDotDotToken || el.initializer || !ts.isIdentifier(el.name)) continue;
const key = el.propertyName === undefined ? el.name.text : ts.isIdentifier(el.propertyName) ? el.propertyName.text : undefined;
if (key !== undefined && ALIASABLE_MEMBERS.has(key)) candidates.push({ member: key, local: el.name.text });
}
}
} else if (ts.isBinaryExpression(node) && ts.isIdentifier(node.left)
&& node.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && node.operatorToken.kind <= ts.SyntaxKind.LastAssignment) {
reassigned.add(node.left.text);
} else if ((ts.isPrefixUnaryExpression(node) || ts.isPostfixUnaryExpression(node)) && ts.isIdentifier(node.operand)
&& (node.operator === ts.SyntaxKind.PlusPlusToken || node.operator === ts.SyntaxKind.MinusMinusToken)) {
reassigned.add(node.operand.text);
}
ts.forEachChild(node, visit);
};
visit(body);
const out: Record<'log' | 'crypto' | 'title' | 'email' | 'activity', string[]> = { log: [], crypto: [], title: [], email: [], activity: [] };
for (const { member, local } of candidates) {
if (member === 'title' && face !== 'hook') continue;
if (declared.get(local) !== 1 || reassigned.has(local)) continue;
out[member as keyof typeof out].push(local);
}
return out;
}

/**
* The capability tokens a REBOUND body needs through the handler's own names
* (#22837). {@link CAPABILITY_PATTERNS} spells `ctx.log.` and
Expand All @@ -1070,10 +1146,32 @@ function escapeRx(name: string): string {
* renamed handler infers exactly what the same handler named `ctx` infers.
* `api` needs nothing here: the `.object(…)` patterns are receiver-loose, and a
* receiver-loose `.title(…)` already covers a context root.
*
* [#38690] `aliases` are the body-local names {@link bodyMemberAliases} binds
* to one member; each is read for a call of that member's gated leaf, so a
* handler that aliases `ctx.log` infers what the same handler calling
* `ctx.log.info(…)` infers.
*/
function reboundCapabilities(source: string, rebind: ParameterRebind): Array<ExtractedBody['capabilities'][number]> {
function reboundCapabilities(
source: string,
rebind: ParameterRebind,
aliases: MemberLocals = NO_MEMBER_LOCALS,
): Array<ExtractedBody['capabilities'][number]> {
const out: Array<ExtractedBody['capabilities'][number]> = [];
const root = (n: string): string => String.raw`(?<![\w$])${escapeRx(n)}`;
// [#38690] A body-local alias is read the way the publish rule reads its
// receivers: a CALL of a gated leaf off it (`?.` allowed on either side), and
// for `title` a call with an argument. A field read is no call.
const aliasRoot = (n: string): string => String.raw`(?<![\w$.])${escapeRx(n)}`;
for (const member of ['log', 'crypto', 'email', 'activity'] as const) {
const { leaves, cap } = MEMBER_LEAVES[member];
for (const l of aliases[member]) {
if (new RegExp(String.raw`${aliasRoot(l)}\s*\??\.\s*(?:${leaves})(?![\w$])\s*(?:\?\.\s*)?\(`).test(source)) out.push(cap);
}
}
for (const l of aliases.title) {
if (new RegExp(String.raw`${aliasRoot(l)}\s*(?:\?\.\s*)?\(\s*[^)\s]`).test(source)) out.push('api.read');
}
for (const r of rebind.contextRoots) {
if (new RegExp(String.raw`${root(r)}\.log\.(?:info|warn|error|debug)\b`).test(source)) out.push('log');
if (new RegExp(String.raw`${root(r)}\.crypto\.randomUUID\b`).test(source)) out.push('crypto.uuid');
Expand Down
Loading
Loading