diff --git a/.changeset/38690-extractor-local-alias.md b/.changeset/38690-extractor-local-alias.md new file mode 100644 index 00000000000..bbf070baaac --- /dev/null +++ b/.changeset/38690-extractor-local-alias.md @@ -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. diff --git a/content/docs/automation/hook-bodies.mdx b/content/docs/automation/hook-bodies.mdx index 44d0fdc8017..fdade0ae738 100644 --- a/content/docs/automation/hook-bodies.mdx +++ b/content/docs/automation/hook-bodies.mdx @@ -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()` — 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()` — 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`: diff --git a/packages/cli/src/utils/extract-hook-body.ts b/packages/cli/src/utils/extract-hook-body.ts index 523f0296e7f..ef1bbd64b49 100644 --- a/packages/cli/src/utils/extract-hook-body.ts +++ b/packages/cli/src/utils/extract-hook-body.ts @@ -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, @@ -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>; + +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> = { + 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 = 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(); + const reassigned = new Set(); + 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 @@ -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 { +function reboundCapabilities( + source: string, + rebind: ParameterRebind, + aliases: MemberLocals = NO_MEMBER_LOCALS, +): Array { const out: Array = []; const root = (n: string): string => String.raw`(? String.raw`(? unknown) => + new Function(`return (${src});`)() as (...a: unknown[]) => unknown; + +const infer = (body: string, face: Face): Token[] => + extractLoweredBody(handler(`async (ctx) => { ${body} }`), `${face} 'h'`, face).capabilities; + +describe('a member token is inferred through a body-local alias of ctx.MEMBER', () => { + const cases: Array<{ token: Token; shape: string; body: string; faces: readonly Face[] }> = [ + { token: 'log', shape: 'a local bound to ctx.log', body: "const l = ctx.log; l.info('x');", faces: ['hook', 'action'] }, + { token: 'log', shape: 'a destructure off ctx', body: "const { log } = ctx; log.warn('x');", faces: ['hook', 'action'] }, + { token: 'log', shape: 'a renamed destructure off ctx', body: "const { log: lg } = ctx; lg.error('x');", faces: ['hook', 'action'] }, + { token: 'crypto.uuid', shape: 'a local bound to ctx.crypto', body: 'const c = ctx.crypto; ctx.input.id = c.randomUUID();', faces: ['hook', 'action'] }, + { token: 'crypto.uuid', shape: 'a destructure off ctx', body: 'const { crypto } = ctx; ctx.input.id = crypto.randomUUID();', faces: ['hook', 'action'] }, + { token: 'email.send', shape: 'a local bound to ctx.email', body: "const e = ctx.email; await e.send({ to: 'a@b.c' });", faces: ['hook', 'action'] }, + { token: 'email.send', shape: 'a destructure off ctx', body: "const { email } = ctx; await email.send({ to: 'a@b.c' });", faces: ['hook', 'action'] }, + { token: 'activity.append', shape: 'a local bound to ctx.activity', body: "const a = ctx.activity; await a.append({ kind: 'note' });", faces: ['hook', 'action'] }, + { token: 'activity.append', shape: 'a destructure off ctx', body: "const { activity } = ctx; await activity.append({ kind: 'note' });", faces: ['hook', 'action'] }, + { token: 'api.read', shape: 'a local bound to ctx.title', body: "const t = ctx.title; ctx.input.label = await t('account_id');", faces: ['hook'] }, + { token: 'api.read', shape: 'a destructure off ctx', body: "const { title } = ctx; ctx.input.label = await title('account_id');", faces: ['hook'] }, + ]; + for (const { token, shape, body, faces } of cases) { + for (const face of faces) { + it(`${token} through ${shape} (${face} face)`, () => { + expect(infer(body, face)).toEqual([token]); + }); + } + } + + it('optional calls through the alias count as the call', () => { + expect(infer("const l = ctx.log; l?.info?.('x');", 'action')).toEqual(['log']); + }); +}); + +describe('CONTROL: what is not a gated call through a ctx.MEMBER alias infers nothing', () => { + const controls: Array<{ what: string; body: string; face: Face }> = [ + { what: 'a local bound to another object’s log member', body: "const l = ctx.input.log; l.info('x');", face: 'action' }, + { what: 'a local reassigned after its declaration', body: "let l = ctx.log; l = ctx.input; l.info('x');", face: 'action' }, + { what: 'a local bound to a member chain, not the member', body: "const l = ctx.log.child; l.info('x');", face: 'action' }, + { what: 'a field read off a log alias, not a call', body: 'const l = ctx.log; ctx.input.f = l.info;', face: 'action' }, + { what: 'a field read off a crypto destructure, not a call', body: 'const { crypto } = ctx; ctx.input.f = crypto.randomUUID;', face: 'action' }, + { what: 'a field read off an email alias, not a call', body: 'const e = ctx.email; ctx.input.f = e.send;', face: 'action' }, + { what: 'a field read off an activity destructure, not a call', body: 'const { activity } = ctx; ctx.input.f = activity.append;', face: 'action' }, + { what: 'a title alias read, not called', body: 'const t = ctx.title; ctx.input.f = t;', face: 'hook' }, + { what: 'a title alias called with no argument (this record’s own title)', body: 'const t = ctx.title; ctx.input.label = await t();', face: 'hook' }, + { what: 'an alias declaration spelled inside a string', body: "ctx.input.note = 'const l = ctx.log; l.info(1)';", face: 'action' }, + { what: 'a destructure with a default', body: "const { log = null } = ctx; log.info('x');", face: 'action' }, + ]; + for (const { what, body, face } of controls) { + it(what, () => { + expect(infer(body, face)).toEqual([]); + }); + } +}); + +/** + * Every capability gate the sandbox installs whose member is a `ctx.MEMBER` + * receiver, with one gated call spelled through that receiver. + * + * This mirrors `SANDBOX_CAPABILITY_GATES` in `@objectstack/lint`'s + * `validate-action-body-capabilities.ts`, which no entry of that package + * exports, so this file cannot import it. It is pinned to this package's own + * token list instead: `EVERY_TOKEN` must name each token of the published + * `ExtractedBody['capabilities']` union (a missing or extra key is a type + * error) and every token must have a gate row here. + */ +const CTX_MEMBER_GATES: ReadonlyArray<{ token: Token; member: string; call: (receiver: string) => string; kinds: readonly Face[] }> = [ + { token: 'api.read', member: 'api', call: (r) => `await ${r}.object('x').find({});`, kinds: ['action', 'hook'] }, + { token: 'api.write', member: 'api', call: (r) => `await ${r}.object('x').update('1', {});`, kinds: ['action', 'hook'] }, + { token: 'api.transaction', member: 'api', call: (r) => `await ${r}.transaction(async () => {});`, kinds: ['action', 'hook'] }, + { token: 'log', member: 'log', call: (r) => `${r}.debug('x');`, kinds: ['action', 'hook'] }, + { token: 'crypto.uuid', member: 'crypto', call: (r) => `ctx.input.id = ${r}.randomUUID();`, kinds: ['action', 'hook'] }, + { token: 'email.send', member: 'email', call: (r) => `await ${r}.send({});`, kinds: ['action', 'hook'] }, + { token: 'activity.append', member: 'activity', call: (r) => `await ${r}.append({});`, kinds: ['action', 'hook'] }, + { token: 'api.read', member: 'title', call: (r) => `ctx.input.label = await ${r}('account_id');`, kinds: ['hook'] }, +]; + +const EVERY_TOKEN = { + 'api.read': true, + 'api.write': true, + 'api.transaction': true, + 'crypto.uuid': true, + log: true, + 'email.send': true, + 'activity.append': true, +} as const satisfies Record; + +describe('ENUMERATION: every ctx.MEMBER gate is inferred through each receiver shape', () => { + it('the gate table covers every token of the published capability union', () => { + expect([...new Set(CTX_MEMBER_GATES.map((g) => g.token))].sort()).toEqual(Object.keys(EVERY_TOKEN).sort()); + }); + + const receivers: Array<{ shape: string; spell: (member: string) => { decl: string; receiver: string } }> = [ + { shape: 'ctx.MEMBER', spell: (m) => ({ decl: '', receiver: `ctx.${m}` }) }, + { shape: 'a local bound once to ctx.MEMBER', spell: (m) => ({ decl: `const alias_${m} = ctx.${m};`, receiver: `alias_${m}` }) }, + { shape: 'a destructure off ctx', spell: (m) => ({ decl: `const { ${m} } = ctx;`, receiver: m }) }, + { shape: 'a renamed destructure off ctx', spell: (m) => ({ decl: `const { ${m}: local_${m} } = ctx;`, receiver: `local_${m}` }) }, + ]; + for (const gate of CTX_MEMBER_GATES) { + for (const face of gate.kinds) { + for (const { shape, spell } of receivers) { + it(`${gate.token} via ctx.${gate.member} through ${shape} (${face} face)`, () => { + const { decl, receiver } = spell(gate.member); + expect(infer(`${decl} ${gate.call(receiver)}`, face)).toContain(gate.token); + }); + } + } + } +});