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/26726-hook-capabilities-control.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
'@object-ui/i18n': patch
---

fix(app-shell,i18n): the Studio hook editor grants a sandboxed-JS body its capabilities

Clause-②: no
Metadata-protocol: none

A hook body that calls `ctx.api`, `ctx.log` or `ctx.crypto` needs the matching token in `body.capabilities`, or the sandbox throws when the hook runs. The Studio hook editor had no control for that list, so a hook that read data could only be fixed through the metadata API.

- **Studio (Data › Hooks, and the metadata admin's hook editor).** A sandboxed-JS body now shows a "Capabilities" checkbox per `HookBodyCapability` token (`api.read`, `api.write`, `api.transaction`, `crypto.uuid`, `log`), each with the `ctx` call it unlocks. Ticking one writes `body.capabilities`; unticking the last writes `[]`, the spec's default. An expression body shows no control, and switching a body to an expression drops its grant and its `timeoutMs` / `memoryMb` limits, since an expression body refuses those keys. A stored token the spec does not list stays on screen, flagged, until it is unticked. Nothing is inferred from the body's source.
- **`@object-ui/i18n`.** The `studio` namespace gains `engine.inspector.hook.capabilities`, `engine.inspector.hook.capabilitiesHint` and `engine.inspector.hook.capabilityUnknown` in `en` and `zh`.

No metadata key is added or changed, and the sandbox's capability check is as strict as before. What to do: nothing.
Original file line number Diff line number Diff line change
@@ -0,0 +1,224 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* objectstack#26726 — the Hook inspector authors `body.capabilities`.
*
* The sandbox throws on a `ctx` call the body was not granted, and the grant
* list was reachable from no control: `body` is a curated key as a whole, so
* the "More fields" form never drew its members either. A Studio-authored hook
* that read data could only be fixed through the API.
*
* FIXTURE DISCIPLINE (the #3218 method): every draft is the authored hook fed
* through `HookSchema.parse`, and every written body is parsed back through the
* same schema, so a case cannot pass on a shape the spec refuses.
*/

import { describe, it, expect, vi, afterEach } from 'vitest';
import { render, screen, fireEvent, cleanup, within } from '@testing-library/react';
import { HookSchema, HookBodyCapability } from '@objectstack/spec/data';

// The object picker fetches on mount; every fixture uses `object: '*'`, so
// stub the shared client and keep that fetch off the network.
const state = vi.hoisted(() => ({
metadataClient: { get: vi.fn(async () => undefined), list: vi.fn(async () => [] as unknown[]) },
}));
vi.mock('../useMetadata', () => ({
useMetadataClient: () => state.metadataClient,
}));

import { t } from '../i18n';
import { HookDefaultInspector } from './HookDefaultInspector';
// `engine.inspector.*` rows live in the lazy `studio` namespace (objectstack#25922).
import { loadStudioCatalogue } from '@object-ui/i18n/namespaces/studio';
await loadStudioCatalogue('zh');

afterEach(cleanup);

function hookDraft(body: Record<string, unknown>): Record<string, unknown> {
return HookSchema.parse({
name: 'reads_accounts',
object: '*',
events: ['beforeInsert'],
body,
}) as unknown as Record<string, unknown>;
}

const JS_BODY = { language: 'js', source: 'await ctx.api.object("account").find({});' };

function renderInspector(
draft: Record<string, unknown>,
{ serverSchema, locale = 'en-US' }: { serverSchema?: Record<string, unknown>; locale?: string } = {},
) {
const onPatch = vi.fn();
render(
<HookDefaultInspector
type="hook"
name={String(draft.name)}
draft={draft}
onPatch={onPatch}
readOnly={false}
locale={locale as never}
serverSchema={serverSchema}
/>,
);
return onPatch;
}

/** The body the last patch wrote. */
function writtenBody(onPatch: ReturnType<typeof vi.fn>): Record<string, unknown> {
expect(onPatch).toHaveBeenCalled();
const patch = onPatch.mock.calls.at(-1)![0] as Record<string, unknown>;
return patch.body as Record<string, unknown>;
}

/** The saved hook — the draft with the patch applied — through the spec. */
function savedHook(draft: Record<string, unknown>, body: Record<string, unknown>) {
return HookSchema.parse({ ...draft, body });
}

const box = (name: string) => screen.getByRole('checkbox', { name }) as HTMLInputElement;

describe('HookDefaultInspector — body capabilities (objectstack#26726)', () => {
it('offers one checkbox per spec token on a js body, read from the enum', () => {
renderInspector(hookDraft(JS_BODY));
const control = screen.getByTestId('hook-body-capabilities');
const names = within(control)
.getAllByRole('checkbox')
.map((el) => el.closest('label')!.textContent);
expect(names).toEqual([...HookBodyCapability.options]);
// Each token names the ctx call it unlocks.
expect(within(control).getByText('ctx.api.object(…).find / findOne / count / aggregate')).toBeInTheDocument();
expect(within(control).getByText('ctx.log.debug / info / warn / error')).toBeInTheDocument();
});

it('picking api.read writes body.capabilities ["api.read"], and the saved hook parses', () => {
const draft = hookDraft(JS_BODY);
const onPatch = renderInspector(draft);

fireEvent.click(box('api.read'));

const body = writtenBody(onPatch);
expect(body).toEqual({ ...draft.body as object, capabilities: ['api.read'] });
expect(savedHook(draft, body).body).toMatchObject({ language: 'js', capabilities: ['api.read'] });
});

it('an existing grant round-trips: shown ticked, and a new grant is written in spec order beside it', () => {
const draft = hookDraft({ ...JS_BODY, capabilities: ['log', 'api.read'] });
const onPatch = renderInspector(draft);

expect(box('api.read').checked).toBe(true);
expect(box('log').checked).toBe(true);
expect(box('api.write').checked).toBe(false);

fireEvent.click(box('api.write'));

const body = writtenBody(onPatch);
expect(body.capabilities).toEqual(['api.read', 'api.write', 'log']);
expect(body.source).toBe(JS_BODY.source);
expect(savedHook(draft, body).body).toMatchObject({ capabilities: ['api.read', 'api.write', 'log'] });
});

it('clearing the last grant writes [], the spec default', () => {
const draft = hookDraft({ ...JS_BODY, capabilities: ['api.read'] });
const onPatch = renderInspector(draft);

fireEvent.click(box('api.read'));

const body = writtenBody(onPatch);
expect(body.capabilities).toEqual([]);
expect(savedHook(draft, body).body).toEqual(hookDraft(JS_BODY).body);
});

it('an expression body shows no control and its edits never write the key', () => {
const draft = hookDraft({ language: 'expression', source: 'record.amount >= 0' });
const onPatch = renderInspector(draft);

expect(screen.queryByTestId('hook-body-capabilities')).toBeNull();
expect(screen.queryByRole('checkbox', { name: 'api.read' })).toBeNull();

fireEvent.change(screen.getByTestId('hook-body-source'), { target: { value: 'record.amount > 0' } });
const body = writtenBody(onPatch);
expect(body).not.toHaveProperty('capabilities');
expect(savedHook(draft, body).body).toEqual({ language: 'expression', source: 'record.amount > 0' });
});

it('switching a granted js body to expression drops the grant, so the save still parses', async () => {
const draft = hookDraft({ language: 'js', source: 'true', capabilities: ['api.read'] });
const onPatch = renderInspector(draft);

// The language select is a Radix combobox button; pick through its listbox.
const language = screen.getAllByRole('combobox').find((el) => el.tagName === 'BUTTON')!;
fireEvent.click(language);
fireEvent.click(await screen.findByRole('option', { name: t('engine.inspector.hook.bodyLang.expression', 'en-US') }));

const body = writtenBody(onPatch);
expect(body).toEqual({ language: 'expression', source: 'true' });
expect(() => savedHook(draft, body)).not.toThrow();
});

it('switching a js body with limits to expression drops every L2-only key, so the save still parses', async () => {
const draft = hookDraft({ language: 'js', source: 'true', capabilities: ['log'], timeoutMs: 250, memoryMb: 64 });
const onPatch = renderInspector(draft);

const language = screen.getAllByRole('combobox').find((el) => el.tagName === 'BUTTON')!;
fireEvent.click(language);
fireEvent.click(await screen.findByRole('option', { name: t('engine.inspector.hook.bodyLang.expression', 'en-US') }));

const body = writtenBody(onPatch);
expect(body).toEqual({ language: 'expression', source: 'true' });
expect(savedHook(draft, body).body).toEqual({ language: 'expression', source: 'true' });
});

it('a stored token the spec does not list stays visible, flagged, and is kept on the next write', () => {
// Not parsed: the spec refuses this token, which is why it must not vanish unseen.
const draft = {
name: 'reads_accounts',
object: '*',
events: ['beforeInsert'],
body: { ...JS_BODY, capabilities: ['api.read', 'crypto.hash'] },
};
const onPatch = renderInspector(draft);

const flagged = box(`crypto.hash ${t('engine.inspector.hook.capabilityUnknown', 'en-US')}`);
expect(flagged.checked).toBe(true);

fireEvent.click(box('log'));
expect(writtenBody(onPatch).capabilities).toEqual(['api.read', 'log', 'crypto.hash']);

fireEvent.click(flagged);
expect(writtenBody(onPatch).capabilities).toEqual(['api.read']);
});

it('"More fields" does not draw the key a second time', () => {
const serverSchema = {
type: 'object',
properties: {
body: {
type: 'object',
properties: {
language: { type: 'string', enum: ['js', 'expression'] },
capabilities: { type: 'array', items: { type: 'string', enum: [...HookBodyCapability.options] } },
},
},
timeout: { type: 'number', title: 'Timeout' },
},
};
renderInspector(hookDraft(JS_BODY), { serverSchema });

expect(screen.getAllByRole('checkbox', { name: 'api.read' })).toHaveLength(1);
const moreFields = screen.getByText(t('engine.inspector.moreFields', 'en-US')).closest('.border-t') as HTMLElement;
// Positive control: the form is drawn, with the uncurated key in it.
expect(within(moreFields).getAllByText(/timeout/i).length).toBeGreaterThan(0);
expect(within(moreFields).queryByText(/capabilit/i)).toBeNull();
expect(within(moreFields).queryByRole('checkbox', { name: 'api.read' })).toBeNull();
});

it('reads its words in the designer locale', () => {
renderInspector(hookDraft(JS_BODY), { locale: 'zh-CN' });
const control = screen.getByTestId('hook-body-capabilities');
const zh = t('engine.inspector.hook.capabilities', 'zh-CN');
expect(zh).not.toBe(t('engine.inspector.hook.capabilities', 'en-US'));
expect(within(control).getByText(zh)).toBeInTheDocument();
expect(within(control).getByText(t('engine.inspector.hook.capabilitiesHint', 'zh-CN'))).toBeInTheDocument();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,23 @@
* free-text box — the reason this exists)
* 2. Events — the lifecycle events it subscribes to (write + query)
* 3. Function — language (expression / sandboxed JS) + the handler body in a
* DEDICATED code editor (the second reason this exists)
* DEDICATED code editor (the second reason this exists), and
* for a sandboxed-JS body the capabilities it is granted
* 4. Options — priority / async / a CEL run condition
*
* Rare/advanced props (handler ref, js capabilities/timeout/memory, …) fall
* through to a collapsed "More fields" SchemaForm fed the live server schema,
* with the curated keys hidden so nothing is double-edited or lost.
* Rare/advanced props (handler ref, …) fall through to a collapsed "More
* fields" SchemaForm fed the live server schema, with the curated keys hidden
* so nothing is double-edited or lost. `body` is one of those curated keys, as
* a whole, so none of its members reaches that form.
*
* Capabilities (objectstack#26726). The sandbox throws on a `ctx` call the body
* was not granted, and `body.capabilities` was reachable from no control here,
* so a Studio-authored hook that read data could only be fixed through the
* API. The grant list is a checkbox per `HookBodyCapability` token, read from
* the spec enum, shown for a `js` body only. An expression body is strict and
* refuses every L2-only key by name (`capabilities`, `timeoutMs`, `memoryMb`),
* so a switch away from `js` drops them rather than carrying keys the save
* would refuse. Nothing is inferred from the source text.
*
* `object` is spec `string | string[]` (or `'*'` for every object). The picker
* normalises to/from that: `'*'` ⇒ all, one selection ⇒ a string, many ⇒ an
Expand Down Expand Up @@ -47,6 +58,7 @@ import {
flagUnknownValue,
rosterFrom,
} from './_shared.js';
import { ExpressionBodySchema, HookBodyCapability, ScriptBodySchema } from '@objectstack/spec/data';
import { useObjectOptions } from '../previews/useObjectOptions.js';
import { ConditionBuilder, RECORD_CONDITION_SUBJECTS } from './ConditionBuilder.js';
import { expressionSource, writeExpressionSource } from './expression-envelope.js';
Expand Down Expand Up @@ -77,6 +89,25 @@ const QUERY_EVENTS = [

const ALL_OBJECTS = '*';

/** The grantable tokens, in the spec's order — the order a grant is written in. */
const CAPABILITY_TOKENS: readonly string[] = HookBodyCapability.options;

/** The `ctx` call each token unlocks, shown under its checkbox: the methods
* the sandbox runner gates on that token. Code, so it reads the same in every
* locale; a token with no entry shows none. */
const CAPABILITY_CALLS: Partial<Record<HookBodyCapability, string>> = {
'api.read': 'ctx.api.object(…).find / findOne / count / aggregate',
'api.write': 'ctx.api.object(…).insert / update / delete / updateMany / deleteMany / upsert',
'api.transaction': 'ctx.api.transaction(async () => { … })',
'crypto.uuid': 'ctx.crypto.randomUUID()',
log: 'ctx.log.debug / info / warn / error',
};

/** The keys only a `js` body admits, read off the spec's two body shapes. */
const L2_ONLY_BODY_KEYS: readonly string[] = Object.keys(ScriptBodySchema.shape).filter(
(k) => !(k in ExpressionBodySchema.shape),
);

/**
* objectui#11820 — what the host knows about where the hook is authored: the
* names of the objects of that package, published and draft. Membership is
Expand Down Expand Up @@ -209,6 +240,29 @@ export function HookDefaultInspector({

const patchBody = (p: Record<string, unknown>) => onPatch({ body: { ...body, ...p } });

// objectstack#26726 — a stored token the spec does not list (a typo, a
// retired `crypto.hash`) stays on screen, flagged, so it is never dropped
// unseen; the save's parse names it, and unticking it removes it.
const granted: string[] = Array.isArray(body.capabilities)
? body.capabilities.filter((c): c is string => typeof c === 'string')
: [];
const capabilityOptions = [
...CAPABILITY_TOKENS,
...granted.filter((c) => !CAPABILITY_TOKENS.includes(c)),
];
const toggleCapability = (cap: string, on: boolean) => {
const next = new Set(granted);
if (on) next.add(cap);
else next.delete(cap);
// Unticking the last grant writes `[]`, the spec's default.
patchBody({ capabilities: capabilityOptions.filter((c) => next.has(c)) });
};
const setLanguage = (v: string) => {
const next: Record<string, unknown> = { ...body, language: v };
if (v !== 'js') for (const key of L2_ONLY_BODY_KEYS) delete next[key];
onPatch({ body: next });
};

const toggleObject = (name: string, on: boolean) => {
const next = on ? [...new Set([...objectNames, name])] : objectNames.filter((n) => n !== name);
onPatch({ object: writeObjects(false, next) });
Expand Down Expand Up @@ -385,7 +439,7 @@ export function HookDefaultInspector({
label={tr('engine.inspector.hook.language')}
value={language}
options={BODY_LANG_OPTS.map((o) => ({ value: o.value, label: tr(o.labelKey) }))}
onCommit={(v) => patchBody({ language: v })}
onCommit={setLanguage}
disabled={readOnly}
/>
<div className="space-y-1">
Expand All @@ -406,6 +460,33 @@ export function HookDefaultInspector({
: tr('engine.inspector.hook.bodyHint.js')}
</div>
</div>
{language === 'js' && (
<div className="space-y-1" data-testid="hook-body-capabilities">
<Label className="text-xs text-muted-foreground">{tr('engine.inspector.hook.capabilities')}</Label>
<div className="space-y-1 rounded-md border p-2">
{capabilityOptions.map((cap) => (
<div key={cap} className="space-y-0.5">
<InspectorCheckboxField
label={
CAPABILITY_TOKENS.includes(cap)
? cap
: flagUnknownValue(cap, tr('engine.inspector.hook.capabilityUnknown'), locale)
}
value={granted.includes(cap)}
onCommit={(on) => toggleCapability(cap, on)}
disabled={readOnly}
/>
{CAPABILITY_CALLS[cap as HookBodyCapability] && (
<div className="pl-5 font-mono text-[10px] text-muted-foreground/70">
{CAPABILITY_CALLS[cap as HookBodyCapability]}
</div>
)}
</div>
))}
</div>
<div className="text-[11px] text-muted-foreground/70">{tr('engine.inspector.hook.capabilitiesHint')}</div>
</div>
)}
</div>

{/* 4 ─ Options */}
Expand Down
3 changes: 3 additions & 0 deletions ui/packages/i18n/src/namespaces/studio/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1342,6 +1342,9 @@ const STUDIO_EN: Record<string, string> = {
'engine.inspector.hook.handlerBody': 'Handler body',
'engine.inspector.hook.bodyHint.expression': 'A single L1 expression evaluated against the record / ctx.',
'engine.inspector.hook.bodyHint.js': 'Runs in the sandbox as (ctx) => Promise<void>.',
'engine.inspector.hook.capabilities': 'Capabilities',
'engine.inspector.hook.capabilitiesHint': 'The ctx APIs this body may call. A call it is not granted throws when the hook runs.',
'engine.inspector.hook.capabilityUnknown': '(not a capability the sandbox grants)',
'engine.inspector.hook.options': 'Options',
'engine.inspector.hook.priority': 'Priority',
'engine.inspector.hook.async': 'Run asynchronously (after commit)',
Expand Down
3 changes: 3 additions & 0 deletions ui/packages/i18n/src/namespaces/studio/zh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1206,6 +1206,9 @@ const STUDIO_ZH: Record<string, string> = {
'engine.inspector.hook.handlerBody': '处理函数主体',
'engine.inspector.hook.bodyHint.expression': '针对 record / ctx 求值的单个 L1 表达式。',
'engine.inspector.hook.bodyHint.js': '在沙箱中以 (ctx) => Promise<void> 的形式运行。',
'engine.inspector.hook.capabilities': '能力授权',
'engine.inspector.hook.capabilitiesHint': '此函数体可调用的 ctx API。调用未授权的 API 会在钩子运行时抛错。',
'engine.inspector.hook.capabilityUnknown': '(沙箱不授予此能力)',
'engine.inspector.hook.options': '选项',
'engine.inspector.hook.priority': '优先级',
'engine.inspector.hook.async': '异步运行(提交之后)',
Expand Down
Loading