Skip to content

Commit 855c3e1

Browse files
fix(cli): the hook-body extractor infers member tokens through a body-local alias of ctx.MEMBER (#38731)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9JeHmqv6CKCkW8ewrPBLekk)_ Refs #38690 (step 1) Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:开发者把钩子或动作处理函数里的日志、编号、邮件、动态、关联标题先取成局部变量再调用时,构建现在会自动授予对应权限,运行时不再在调用处被沙箱拒绝。 - 为什么做:属于构建期处理函数降级这一组修复,替写内联处理函数的开发者补上发布检查已认、构建却没推断出的写法。 - 出错会怎样:最坏是多授予一个函数体确实调用了的权限;钩子里经别名发邮件会像直接写法一样在构建时被拒;可直接撤回。 - 要你做什么:无。 ## What changes `os build` lowers an inline hook `handler` / action `target` to a `js` body and infers `body.capabilities` from its source. The member patterns spelled `ctx.` (`ctx.log.info`, `ctx.crypto.randomUUID`, `ctx.email.send`, `ctx.activity.append`), and the rebind followed only the handler's own parameter, so a body-local alias inferred nothing and the sandbox refused the call at run time, while the publish check (`validate-action-body-capabilities`, `memberReceivers`) reads the same alias as a receiver of `ctx.MEMBER`. - `bodyMemberAliases` (new, `packages/cli/src/utils/extract-hook-body.ts`) reads the handler's parse for exactly the two alias shapes the lint rule credits: `const l = ctx.MEMBER` (not `ctx?.MEMBER`, not a chain) and a plain element destructured off `ctx` (`const { log } = ctx`, `const { log: l } = ctx`; no default, rest or nesting). A name counts only when declared once and never assigned or stepped again (the rule's `boundOnce`). `title` is collected on the hook face only (the host builds `ctx.title` only for hook bodies). - `reboundCapabilities` takes those aliases as a third argument and reads them the way the rule reads its receivers: a CALL of a gated leaf (`?.` allowed on either side), and for `title` a call with an argument. A field read infers nothing. - The published `ExtractedBody.capabilities` union is unchanged (seven tokens). No spec, no `packages/lint` edit. - `content/docs/automation/hook-bodies.mdx` `### Capability inference` (claim amendment 1): the `crypto.uuid` and `log` rows name the alias shapes, new `email.send` and `activity.append` rows (which the table never had) name theirs, the `*.title(…)` row names the hook-face alias form, one sentence defines the two alias shapes and what infers nothing, and the over-inclusive paragraph now names `email.send` as its exception (a hook body is never granted it, so a hook that spells or alias-calls it is refused at build). Read first (by risk): `bodyMemberAliases` (the shape set must equal the rule's), the call-shaped alias loop at the top of `reboundCapabilities`, then the docs table hunk (every sentence there must hold for the extractor as built). ## Tests New `packages/cli/test/extract-hook-body-local-alias-38690.test.ts` (93 cases): - refused-before / inferred-now, per member and shape on each face the gate is installed on: `log` (local, destructure, renamed destructure), `crypto.uuid`, `email.send` (measured here; the card had it unmeasured), `activity.append` (local, destructure), and a hook's `title(FIELD)` giving `api.read`. At base `d2caaec40d` this file ran 49 failed / 44 passed. - controls that infer nothing: a local bound to `ctx.input.log`, a reassigned `let`, a local bound to `ctx.log.child`, field reads (not calls) off each member alias, a title alias read or called with no argument, an alias spelled inside a string, a destructure with a default. - enumeration: every sandbox gate whose member is a `ctx.MEMBER` receiver (all eight rows of lint's `SANDBOX_CAPABILITY_GATES`, `api` included), through `ctx.MEMBER`, a bound local, a destructure and a renamed destructure. `SANDBOX_CAPABILITY_GATES` is exported by none of `@objectstack/lint`'s three entries (`.`, `./runtime`, `./rule-explanations`), and a relative import into `packages/lint/src` would need a `cross-package-test-inputs` declaration outside this card's file surface, so the table is mirrored in the test and pinned to the cli's own published union (`satisfies Record` over `ExtractedBody['capabilities']`, plus a coverage assertion). <details><summary>Ablations (one per member family, scripts/ablation-replace.mjs)</summary> Each removes one member from `ALIASABLE_MEMBERS`, runs the new file, restores; every restore printed `blob == HEAD` and `git diff HEAD is empty`. - `log` removed: 13 failed of 93 (the six `log` alias cases, six `log` enumeration rows, the optional-call case). - `crypto` removed: 10 failed (four alias cases, six enumeration rows). - `email` removed: 10 failed. - `activity` removed: 10 failed. - `title` removed: 5 failed (two alias cases, three enumeration rows). </details> <details><summary>Local readings at head (cli unit layer, typecheck, gates)</summary> - Build: `pnpm --filter '@objectstack/cli^...' build` under the verify lock: `VERDICT command-exit 0`. - `pnpm --filter @objectstack/cli exec vitest run --project unit --maxWorkers=2`: Test Files 451 passed (451), Tests 6544 passed (6544), `VERDICT command-exit 0`. The `integration` layer is CI's. - `pnpm --filter @objectstack/cli typecheck`: `VERDICT command-exit 0` (test layer OK under `tsconfig.test.json`). - Six extractor files (`extract-hook-body`, the new file, `hook-body-parameter-rebind`, `hook-body-mail-grant`, `lower-callables`, `published-subpath-hook-body.pin`): 259 passed. No existing expected capability list changed. - Round 1 (`bcd5926dbc`), `dispatch-gates --commands`: 69 families; 68 exit 0; `check:dual-build-cjs-loads` exit 3 PREREQUISITE NOT MET, NOT MEASURED there. - Round 2 (`2ed55579aa`, docs page added), `dispatch-gates --commands`: 100 families, all exit 0 (nine first exited 3 on a fresh tree's missing builds and were re-run after building their closures, `check:dual-build-cjs-loads` among them). Docs families include `check:doc-anchors`, `check:docs-section-name`, `check:doc-frontmatter`, `check:docs-single-h1`, `check:docs-spec-enumerations`, `check:docs-transcript-drift`, `check:doc-route-spelling --advisory`, `check:section-landing-index`, `spec check:docs`. `--ran` reconciliation: 100 derived, 100 run, 0 NOT-MEASURED, 0 UNRUN. </details> ## Acceptance notes - First-party bodies, before and after (every body in `examples/app-crm`, `app-multi-package`, `app-showcase`, `app-starter`, `app-todo`, `packages/apps/connector-docusign`, `connector-github`, `connector-stripe`, loaded, normalized and lowered): 134 body rows, inferred lists byte-identical. No first-party body uses an alias shape. - Parity is kept with the rule, no wider: an alias reached through a renamed context root (`async (c) => { const l = c.log; l.info('x') }`, `const { log } = c`, or `const c = ctx; const l = c.log`) still infers nothing here, and the rule does not read it either. Reported to the seat as a finding, not fixed here. - A hook body that calls `send(...)` through an `email` alias now carries `email.send`, so the hook's parse refuses it at build, exactly as `ctx.email.send(...)` spelled directly already is. Before, it shipped and failed at the call. - The alias calls are matched on the body text (the receiver-loose machinery `reboundCapabilities` already uses), so a string containing such a call next to a real alias over-infers; for `email.send` on a hook that is a build refusal, the same edge the direct pattern documents. - Step 2 (lint dropping its lowered skips) stays on the card. ## Verification Two-minute check: `pnpm --filter @objectstack/cli exec vitest run --maxWorkers=2 test/extract-hook-body-local-alias-38690.test.ts`. Expect 1 file, 93 tests passed. Docs: the `### Capability inference` table on the hook-bodies page has five member rows (`crypto.uuid`, `log`, `email.send`, `activity.append`, `title`), each naming its alias shapes. --- _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 95ffacc commit 855c3e1

4 files changed

Lines changed: 261 additions & 7 deletions

File tree

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
---
2+
'@objectstack/cli': patch
3+
---
4+
5+
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`
6+
7+
Clause-②: no
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. 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:
11+
12+
- a local bound once to the member: `const l = ctx.log; l.info(…)`;
13+
- a plain destructure off `ctx`: `const { log } = ctx`, `const { log: l } = ctx`.
14+
15+
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.
16+
17+
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.

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

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -455,11 +455,15 @@ The extractor scans each body for known patterns and adds the matching capabilit
455455
| The same read leaves on a bound handle — `const h = ctx.api.object('x'); h.find(…)` | `api.read` |
456456
| `*.object(…).insert / update / updateById / updateMany / upsert / delete / deleteMany / patch / remove / create` | `api.write` |
457457
| `*.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` |
458-
| `ctx.crypto.randomUUID` | `crypto.uuid` |
459-
| `ctx.log.info / warn / error / debug` | `log` |
460-
| `*.title(<argument>)` — the related-record form only; bare `ctx.title()` names this record and needs no token | `api.read` |
458+
| `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` |
459+
| `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` |
460+
| `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` |
461+
| `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` |
462+
| `*.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` |
461463

462-
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.
464+
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.
465+
466+
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.
463467

464468
When inference does not derive what a body needs, declare the tokens yourself by
465469
supplying `body` on the hook or action instead of a `handler`:

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

Lines changed: 101 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -756,8 +756,9 @@ export function extractLoweredBody(
756756
if (callsObjectWriteThroughHandle(source)) inferred.add('api.write');
757757
if (callsObjectReadThroughHandle(source)) inferred.add('api.read');
758758
// [#22837] The ctx-anchored patterns above spell `ctx.`; a rebound body
759-
// reaches the same members through the handler's own names.
760-
for (const cap of reboundCapabilities(source, rebind)) inferred.add(cap);
759+
// reaches the same members through the handler's own names, and [#38690]
760+
// any body through a local bound to `ctx.MEMBER` or destructured off `ctx`.
761+
for (const cap of reboundCapabilities(source, rebind, bodyMemberAliases(parsed, face))) inferred.add(cap);
761762

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

1064+
/** The members a body-local alias can stand for, each to the names bound to it. */
1065+
type MemberLocals = Readonly<Record<'log' | 'crypto' | 'title' | 'email' | 'activity', readonly string[]>>;
1066+
1067+
const NO_MEMBER_LOCALS: MemberLocals = { log: [], crypto: [], title: [], email: [], activity: [] };
1068+
1069+
/** The gated leaves of each member-leaf gate, as one alternation, and the token the call needs. */
1070+
const MEMBER_LEAVES: Readonly<Record<'log' | 'crypto' | 'email' | 'activity', { leaves: string; cap: ExtractedBody['capabilities'][number] }>> = {
1071+
log: { leaves: 'info|warn|error|debug', cap: 'log' },
1072+
crypto: { leaves: 'randomUUID', cap: 'crypto.uuid' },
1073+
email: { leaves: 'send', cap: 'email.send' },
1074+
activity: { leaves: 'append', cap: 'activity.append' },
1075+
};
1076+
1077+
const ALIASABLE_MEMBERS: ReadonlySet<string> = new Set(['log', 'crypto', 'title', 'email', 'activity']);
1078+
1079+
/**
1080+
* [#38690] The body-local aliases of a capability-bearing member, in exactly
1081+
* the two shapes the publish rule (`validate-action-body-capabilities`,
1082+
* `memberReceivers`) credits as a receiver of `ctx.MEMBER`:
1083+
*
1084+
* - a local bound to the member itself: `const l = ctx.log` (not `ctx?.log`,
1085+
* not a chain or an expression built on it);
1086+
* - a plain element destructured off `ctx`: `const { log } = ctx`,
1087+
* `const { log: l } = ctx` (no default, no rest, no nesting).
1088+
*
1089+
* Either counts only when the name is declared once in the handler and never
1090+
* assigned or stepped again, so it stands for the member wherever it is read.
1091+
* Read off the handler's parse, so a string or a comment declares nothing.
1092+
* `title` is collected on the hook face alone: the host builds `ctx.title`
1093+
* only for hook bodies.
1094+
*
1095+
* Over-inferring here costs what the receiver-loose patterns above cost and no
1096+
* more: the token is inferred only for a CALL of the gated leaf off the alias,
1097+
* which is the call the sandbox gates.
1098+
*/
1099+
function bodyMemberAliases(fn: ts.FunctionLikeDeclarationBase, face: LoweringFace): MemberLocals {
1100+
const body = fn.body;
1101+
if (!body) return NO_MEMBER_LOCALS;
1102+
const declared = new Map<string, number>();
1103+
const reassigned = new Set<string>();
1104+
const candidates: Array<{ member: string; local: string }> = [];
1105+
const isCtx = (e: ts.Node): boolean => ts.isIdentifier(e) && e.text === 'ctx';
1106+
const visit = (node: ts.Node): void => {
1107+
if (ts.isVariableDeclaration(node)) {
1108+
for (const n of bindingNames(node.name)) declared.set(n, (declared.get(n) ?? 0) + 1);
1109+
const init = node.initializer;
1110+
if (init && ts.isIdentifier(node.name) && ts.isPropertyAccessExpression(init)
1111+
&& !init.questionDotToken && isCtx(init.expression) && ALIASABLE_MEMBERS.has(init.name.text)) {
1112+
candidates.push({ member: init.name.text, local: node.name.text });
1113+
} else if (init && isCtx(init) && ts.isObjectBindingPattern(node.name)) {
1114+
for (const el of node.name.elements) {
1115+
if (el.dotDotDotToken || el.initializer || !ts.isIdentifier(el.name)) continue;
1116+
const key = el.propertyName === undefined ? el.name.text : ts.isIdentifier(el.propertyName) ? el.propertyName.text : undefined;
1117+
if (key !== undefined && ALIASABLE_MEMBERS.has(key)) candidates.push({ member: key, local: el.name.text });
1118+
}
1119+
}
1120+
} else if (ts.isBinaryExpression(node) && ts.isIdentifier(node.left)
1121+
&& node.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && node.operatorToken.kind <= ts.SyntaxKind.LastAssignment) {
1122+
reassigned.add(node.left.text);
1123+
} else if ((ts.isPrefixUnaryExpression(node) || ts.isPostfixUnaryExpression(node)) && ts.isIdentifier(node.operand)
1124+
&& (node.operator === ts.SyntaxKind.PlusPlusToken || node.operator === ts.SyntaxKind.MinusMinusToken)) {
1125+
reassigned.add(node.operand.text);
1126+
}
1127+
ts.forEachChild(node, visit);
1128+
};
1129+
visit(body);
1130+
const out: Record<'log' | 'crypto' | 'title' | 'email' | 'activity', string[]> = { log: [], crypto: [], title: [], email: [], activity: [] };
1131+
for (const { member, local } of candidates) {
1132+
if (member === 'title' && face !== 'hook') continue;
1133+
if (declared.get(local) !== 1 || reassigned.has(local)) continue;
1134+
out[member as keyof typeof out].push(local);
1135+
}
1136+
return out;
1137+
}
1138+
10631139
/**
10641140
* The capability tokens a REBOUND body needs through the handler's own names
10651141
* (#22837). {@link CAPABILITY_PATTERNS} spells `ctx.log.` and
@@ -1070,10 +1146,32 @@ function escapeRx(name: string): string {
10701146
* renamed handler infers exactly what the same handler named `ctx` infers.
10711147
* `api` needs nothing here: the `.object(…)` patterns are receiver-loose, and a
10721148
* receiver-loose `.title(…)` already covers a context root.
1149+
*
1150+
* [#38690] `aliases` are the body-local names {@link bodyMemberAliases} binds
1151+
* to one member; each is read for a call of that member's gated leaf, so a
1152+
* handler that aliases `ctx.log` infers what the same handler calling
1153+
* `ctx.log.info(…)` infers.
10731154
*/
1074-
function reboundCapabilities(source: string, rebind: ParameterRebind): Array<ExtractedBody['capabilities'][number]> {
1155+
function reboundCapabilities(
1156+
source: string,
1157+
rebind: ParameterRebind,
1158+
aliases: MemberLocals = NO_MEMBER_LOCALS,
1159+
): Array<ExtractedBody['capabilities'][number]> {
10751160
const out: Array<ExtractedBody['capabilities'][number]> = [];
10761161
const root = (n: string): string => String.raw`(?<![\w$])${escapeRx(n)}`;
1162+
// [#38690] A body-local alias is read the way the publish rule reads its
1163+
// receivers: a CALL of a gated leaf off it (`?.` allowed on either side), and
1164+
// for `title` a call with an argument. A field read is no call.
1165+
const aliasRoot = (n: string): string => String.raw`(?<![\w$.])${escapeRx(n)}`;
1166+
for (const member of ['log', 'crypto', 'email', 'activity'] as const) {
1167+
const { leaves, cap } = MEMBER_LEAVES[member];
1168+
for (const l of aliases[member]) {
1169+
if (new RegExp(String.raw`${aliasRoot(l)}\s*\??\.\s*(?:${leaves})(?![\w$])\s*(?:\?\.\s*)?\(`).test(source)) out.push(cap);
1170+
}
1171+
}
1172+
for (const l of aliases.title) {
1173+
if (new RegExp(String.raw`${aliasRoot(l)}\s*(?:\?\.\s*)?\(\s*[^)\s]`).test(source)) out.push('api.read');
1174+
}
10771175
for (const r of rebind.contextRoots) {
10781176
if (new RegExp(String.raw`${root(r)}\.log\.(?:info|warn|error|debug)\b`).test(source)) out.push('log');
10791177
if (new RegExp(String.raw`${root(r)}\.crypto\.randomUUID\b`).test(source)) out.push('crypto.uuid');

0 commit comments

Comments
 (0)