Skip to content
Closed
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/35714-data-hooks-body-compile-refusal.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
'@objectstack/skills': patch
---

docs(skills): the hooks skill says a hook or job `js` body that does not compile is refused, and how to fix it

Clause-②: no
Metadata-protocol: none

objectstack-data's `references/data-hooks.md`, "Sandbox restrictions":

- A new bullet says a `js` source is compiled, without being run, inside the `(async (ctx) => { … })` wrapper the runtime runs it in, where `ctx` is already declared. `const ctx = ctx.input || {};` (or `let ctx`, one name declared twice, any syntax error) is `hook-body-does-not-compile`: an error from `os validate`, `os build`, `os lint` and a runtime hook save (`422 INVALID_METADATA`), naming the hook, the `SyntaxError` and its line. The fix is to use `ctx` as it is or rename the local (`const input = ctx.input || {};`). A job's `js` body runs in the same wrapper and is `job-body-does-not-compile` from the three commands. A regular-expression pattern the checking engine refuses is a warning: the runtime may accept it.
- Six restatements in the same file were removed to pay for the new text; the file is four lines shorter and no larger in tokens than before.

`evals/hooks-security-seeds-datasources.json` gains one case on the refusal and its fix.
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,16 @@
"amount_paid: 2000"
]
}
},
{
"id": 33,
"prompt": "`os validate` reports an error on this `beforeInsert` hook on `lead`, and I cannot see why: `body: { language: 'js', source: \"const ctx = ctx.input || {}; if (!ctx.status) ctx.status = 'new';\", capabilities: [] }`. What is wrong, and what should the source be?",
"expected_output": "The `js` source is compiled inside the wrapper the runtime runs it in, `(async (ctx) => { … })`, where `ctx` is already the parameter: `const ctx = …` declares it a second time, a SyntaxError before any statement runs. The finding is `hook-body-does-not-compile`, an error from `os validate`, `os build` and `os lint`, and a runtime save of the hook is refused with `422 INVALID_METADATA`. Fix: use `ctx` as it is (`if (!ctx.input.status) ctx.input.status = 'new';`) or give the local another name (`const input = ctx.input || {}; if (!input.status) input.status = 'new';`). Does not suppress the rule, and does not move the logic to a deprecated `handler`.",
"files": [],
"assertions": {
"must_contain": ["hook-body-does-not-compile", "input.status"],
"must_not_contain": []
}
}
]
}
34 changes: 15 additions & 19 deletions skills/objectstack-data/references/data-hooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,11 +123,6 @@ const myHook = defineHook({

### Key Properties Explained

#### `body` — Implementation

A `source` of statements against `ctx`; a throw aborts the write
([Sandboxed Hook Bodies](#sandboxed-hook-bodies-body--what-the-sandbox-ctx-can-call)).

#### `condition` — Declarative Filtering

Skip the hook if the condition is false. Author it as a **CEL
Expand Down Expand Up @@ -155,9 +150,7 @@ made total over the object's **declared** fields (`null` when a declared field i
in neither). So:

- Reference **any** declared field, not just the ones this update touches —
`record.done == true` works on an update that only sets `status`. (This is
unlike `ctx.input` / `ctx.result` inside the body, which stay partial — see
Gotcha 1.)
`record.done == true` works on an update that only sets `status`.
- `record` describes the record's **state**, not the diff. `record.done == true`
fires on every update of an already-done record, not only on the update that
set it. **For the transition, compare against `previous`**:
Expand Down Expand Up @@ -344,6 +337,15 @@ The body runs in an isolated QuickJS VM, **not** Node:
a name bound at module scope, e.g. a `const slugify = …` helper sitting next to
the hook. A `body` must be **self-contained**: inline the helper, or keep that
hook as a bundled (deprecated) `handler`.
- **Refused when it does not compile:** a `js` source is compiled, unrun, inside
its `(async (ctx) => { … })` wrapper, where `ctx` is already declared. So
`const ctx = ctx.input || {};` (or `let ctx`, one name declared twice, any
syntax error) is `hook-body-does-not-compile`: an **error** from `os validate`,
`os build`, `os lint` and a runtime hook save (`422 INVALID_METADATA`), naming
the hook, the `SyntaxError` and its line. Fix: use `ctx` as it is, or rename
the local (`const input = ctx.input || {};`). A job's `js` body runs in the
same wrapper: `job-body-does-not-compile`, from the three commands. A regex
pattern the checking engine refuses is a warning: the runtime may accept it.

> **A deadline stamped from an hours table is calendar hours** — nights, weekends and
> holidays count. Name it `*_CALENDAR_HOURS` (`SLA_CALENDAR_HOURS`, or its camelCase)
Expand Down Expand Up @@ -450,8 +452,7 @@ interface HookContext {
// Execution context
session?: {
userId?: string;
organizationId?: string; // Active org — the single blessed name. Matches the
// `organization_id` column + `current_user.organizationId` (RLS).
organizationId?: string; // Active org — the single blessed name.
// The former `tenantId` alias was removed in v16.
// Privilege is judged by the security service,
// never by a session claim.
Expand Down Expand Up @@ -660,11 +661,8 @@ const cascadeAccountUpdate = defineHook({

A `body` cannot do this: it writes back only `ctx.input`, and its `ctx.result` is a snapshot.

> For **static** field masking (a field is always hidden/masked for a permission
> set or position), prefer declarative **field-level metadata** (secret/masked
> fields) — it applies on every read path automatically. Use an `afterFind` hook
> only for masking that depends on runtime logic the field metadata can't
> express.
> Static masking is declarative **field-level metadata** (secret/masked fields);
> an `afterFind` hook is only for masking that depends on runtime logic.

```typescript
const maskSensitiveData = defineHook({
Expand All @@ -674,7 +672,6 @@ const maskSensitiveData = defineHook({
handler: async (ctx) => {
// Exempt the engine's own elevated reads (`isSystem`) — internal writes
// and self-reads must see the real values.
// ⚠️ Never a session claim (`ctx.session.roles` is gone, ctx table above).
const isElevated = ctx.session?.isSystem === true;

if (!isElevated) {
Expand Down Expand Up @@ -777,9 +774,8 @@ the layout both real hook modules in the repo use.

## Best Practices

✅ **DO** — use `before*` for validation and `after*` for side effects; set
`async: true` for non-critical background work; go through `ctx.api` for
cross-object operations; refuse a business rule by a
✅ **DO** — set `async: true` for non-critical background work; go through
`ctx.api` for cross-object operations; refuse a business rule by a
[declared code](#declared-refusals-refusals); test hooks in isolation.

❌ **DON'T** — do expensive work in `before*` (it blocks the transaction); write
Expand Down
Loading