diff --git a/.changeset/34770-api-skill-router.md b/.changeset/34770-api-skill-router.md new file mode 100644 index 00000000000..24a55dc63ea --- /dev/null +++ b/.changeset/34770-api-skill-router.md @@ -0,0 +1,27 @@ +--- +'@objectstack/skills': patch +--- + +docs(skills): the objectstack-api entry file becomes a router + +Clause-②: no +Metadata-protocol: none + +`skills/objectstack-api/SKILL.md` goes from 21.4 KB to 9.0 KB (438 lines to 151). It now holds six things: four first checks (the installed version wins over the `compatibility` line, and an `apis:` block written before protocol 17 turns live; read the stack's `apis`, its `manifest.namespace` and the object's `apiMethods`; read the contract and never recall a key or a code; verify with `os validate` or `os build` and read a publish rejection), the generated routes, the `apiMethods` primitives and what derives from them, one type-checked declared endpoint, six traps, and a table that says where to go for the rest. No rule's teaching changes. This skill has no hand-written reference file, so no text moved: what left the entry was cut, and this entry says what now answers it. + +**What the entry keeps.** The generated routes as one listing (the `data` routes, the two `batch` routes, import and export, the metadata read), with the two request contracts a client gets wrong: the metadata list reads a closed query set and narrows by `?names=`, and an import mapping's entry form, `{ sourceField, targetField, applyOn }`, is the only one that carries `applyOn`. The section `## API Methods (Operations)` keeps its heading and every one of the six authorable primitives, with the eight derived operations and what each derives from. The declared endpoint keeps its example: the path carve-out, `object_operation` with `objectParams`, `cacheTtlSeconds`. The six traps, each a declaration or a call that passes and then answers wrong at run time: `authRequired: false` needs `rateLimit.enabled: true`, because a budget with only `windowMs` / `maxRequests` meters nothing; an app never mounts on `http.server`, handler code runs in a flow's `script` or `connector_action` node, an inbound webhook is a `type: 'api'` flow verified by `x-objectstack-signature` or a declared `config.signature`, and three cases have no app surface; `DELETE` keeps a business object's rows in the recycle bin, with the restore door and its two grants; a `PATCH` with no version token skips the concurrency check; a public form answers `404 FORM_NOT_FOUND` unless its `sharing` declares `enabled`, `allowAnonymous` and `publicLink`, strips fields outside its sections, and is withheld on a walled posture with only a warning at save and publish; a person is shown `userMessage`, never `message`, on a batch publish's `probes.issues[]`, and a failed flow door renders `userMessage`, then `details.innerRefusal`, then `message`. + +**What left, and what answers it now.** + +- The publish gates one by one, and the mapping refusals beyond `transform` (`inputMapping` on a `find` / `get` / `delete` operation, two entries writing one target path): https://objectstack.ai/docs/api/declarative-endpoints, and the rejection itself, which names the endpoint, the key and the fix. `os validate` runs the same gates. +- The steps for an `apis:` block written before protocol 17 (move every `path` into the carve-out, review every `authRequired: false`): the `declarative-apis-endpoints-live` entry of the protocol upgrade guide, which the entry still names. +- The endpoint naming table: cut. Its two patterns (`/api/v1/{object}/:id/{action}`, `/api/v1/{domain}/{action}`) are not paths an app can declare: a declared path lives under `/api/v1/apps//`, and the endpoint vocabulary has no path-template syntax. +- The per-primitive route table, the four `RESTORE_*` refusals of a restore, the list, purge and empty doors of the recycle bin, the one metadata type whose list refuses `names`, and the discovery route: https://objectstack.ai/docs/protocol/kernel/http-protocol. The quoted-empty entity-tag refusal (`400 VALIDATION_FAILED`): https://objectstack.ai/docs/api/wire-format. The `ApiOperation` vocabulary: `data/object.zod.ts`. Each refusal among them is loud when hit. The health and readiness routes are cut: nothing in a stack declares them. +- The dispatcher's four codes, the two envelope shapes, the two-tier `error.code` vocabulary and the downstream-ledger recipe (`envelopeViolations`, `makeApiErrorSchema`): `api/errors.zod.ts`, `api/dispatcher.zod.ts`, `api/error-code-ledger.zod.ts` and `api/contract.zod.ts` under `node_modules/@objectstack/spec/src/`, and https://objectstack.ai/docs/api/error-catalog. The entry keeps that a code in no ledger fails CI. +- The realtime pointers (`api/realtime.zod.ts`, `api/websocket.zod.ts`): `references/_index.md`, which lists both. +- The login request's field list, and the flat `public` + `permissions` pair of `RestApiEndpointSchema` (the plugin route registry, `api/plugin-rest-api.zod.ts`): the contract. The entry keeps `AuthProvider` with its members, `LoginRequestSchema`, and that a declared endpoint has `authRequired` and no nested `auth` block (the strict endpoint shape refuses `auth` and names `authRequired`). +- A public form's file-field rule (`public-form-file-field`, an error at `os validate` and at publish) and the `guest_portal` name: https://objectstack.ai/docs/ui/forms. The form contracts: `ui/view.zod.ts` (`FormViewSchema`) and `ui/sharing.zod.ts` (`SharingConfigSchema`). +- The locale ladder's subtag steps, the `advisories[]` / 422 `issues[]` element (`RuntimeAuthoringIssueSchema`), and the `errorMessage` and `summary` keys of a failed flow's details: `api/protocol.zod.ts` and `api/automation-api.zod.ts`. An app-authored refusal having no `en` floor is in objectstack-i18n. +- The skill-boundaries table: the frontmatter description and the last routing row. + +**Anchors that no longer exist in `SKILL.md`.** `#skill-boundaries`, `#auto-generated-vs-custom-apis`, `#auto-generated-apis`, `#metadata-api-meta`, `#public-anonymous-form-endpoints`, `#declarative-endpoints-apis--no-handler-code`, `#choosing-between-apis-and-a-code-handler`, `#the-path-carve-out-adr-0121-d1d2`, `#five-publish-gates-each-with-a-prescription`, `#authrequired-and-the-d6-pairing`, `#mapping-keys-projection-only`, `#upgrading-a-pre-17-stack`, `#endpoint-naming-conventions`, `#discovery--health`, `#dispatcher-error-codes`, `#realtime-subscriptions`, `#authentication--authorization`, `#auth-configuration`, `#auth-providers`, `#error-envelopes--the-code-ledger-adr-0112`, `#best-practices`, `#common-pitfalls`, `#verify-your-work`, `#references`. `#api-methods-operations` stays. The new ones are `#first-checks`, `#generated-routes`, `#a-declared-endpoint`, `#traps` and `#where-to-go`. No file in this repository linked an anchor of the old entry. diff --git a/scripts/check-skills-token-ratchet.mjs b/scripts/check-skills-token-ratchet.mjs index 1e3fc5acaca..ef087bcd731 100644 --- a/scripts/check-skills-token-ratchet.mjs +++ b/scripts/check-skills-token-ratchet.mjs @@ -578,7 +578,22 @@ export const CEILINGS = new Map([ // longer has. Lowered to the measurement, per the shrink-only discipline. // 6319 -> 6314: A2′ — the release-stamp line left the count (see // STAMP_LINE_REPIN); the file's count fell by the same 5, headroom unchanged. - ['skills/objectstack-api/SKILL.md', 5333], // -981 to the measurement (was 6314) + // 6314 -> 5333: lowered to the measurement (-981). + // 5333 -> 2240 (#34770): the entry becomes a router. It keeps four first checks, the + // generated routes with the two request contracts a client gets wrong (the closed query set + // of the metadata list, an import mapping's `applyOn`), the `apiMethods` primitives and what + // derives from them, one type-checked declared endpoint, six traps (each passes the build + // and then answers wrong at run time, or is refused only at publish with the form to write) + // and a routing table. This skill has no hand-authored reference file, so nothing MOVED: the + // rest is CUT behind a pointer, to the contract (`api/*.zod.ts`, whose strict endpoint shape + // refuses a wrong key with the key to write), to the publish gates (`os validate` runs them + // and each rejection carries its fix) or to the published API pages. No row rises and no + // row is added. The file is 21359 bytes (21332 priced) -> 8986 (8959 priced) -> 2240 + // tokens, pinned AT the measurement; the sum of all ceilings falls by the same 3093. + // Authority: the ruling of record that orders the entry file down to router size, decision + // record #34691 S3 = A. + // ceil(($(wc -c < skills/objectstack-api/SKILL.md) - 27) / 4) == ceil(8959 / 4) + ['skills/objectstack-api/SKILL.md', 2240], // 12511 -> 12643 (#11348): the flow value-expression section documented the // expression surface but not the function vocabulary (round/floor/ceil/abs/ // min/max); an unknown function fails at RUNTIME, not at flow-save, so the diff --git a/skills/objectstack-api/SKILL.md b/skills/objectstack-api/SKILL.md index c8bfc646021..9a5e3216c7b 100644 --- a/skills/objectstack-api/SKILL.md +++ b/skills/objectstack-api/SKILL.md @@ -21,418 +21,131 @@ metadata: # API Design — ObjectStack API Protocol -## Skill Boundaries +A custom endpoint is **metadata** (`defineStack({ apis })`), never a route an app mounts. -| Need | Use instead | -|:-----|:------------| -| Model objects, fields, permissions, or datasources (`rules/datasources.md`) | **objectstack-data** | -| Pick a driver package | **objectstack-platform** → Driver Selection Guide | -| Filter, sort, paginate, or aggregate a request | **objectstack-query** | -| Register a kernel service, or read one from a plugin | **objectstack-platform** | -| CEL in a route guard or auth predicate | **objectstack-formula** | +## First checks ---- - -## Auto-Generated vs Custom APIs +1. **Version.** Where the installed `@objectstack/spec` version differs from this skill's + `compatibility` line, the installed contract is right. Declared endpoints are live from + protocol 17: an older `apis:` block turns from inert text into an execution entry point + (the protocol upgrade guide's `declarative-apis-endpoints-live` entry). +2. **Read what exists**: the stack's `apis` and `manifest.namespace`, the object's + `apiMethods`. Prefer a generated route. +3. **Read the contract** ([references/_index.md](./references/_index.md)); an endpoint is + `node_modules/@objectstack/spec/src/api/endpoint.zod.ts`. Never recall a key or a code. +4. **Verify**: `os validate` or `os build`. A declaration this runtime cannot serve is + rejected one publish gate at a time: read the rejection, it carries the fix. -### Auto-Generated APIs +## Generated routes -Every ObjectStack object with `apiEnabled: true` (the default) automatically -gets a full REST API: +Served with nothing authored (`data`: an object with `apiEnabled: true`, the default): ``` -GET /api/v1/data/{object} # List records (with filter, sort, pagination) -GET /api/v1/data/{object}/:id # Get single record -POST /api/v1/data/{object} # Create record -PATCH /api/v1/data/{object}/:id # Update record -DELETE /api/v1/data/{object}/:id # Delete record (business-object rows → recycle bin) -POST /api/v1/data/{object}/query # Complex queries + aggregation (QueryAST in body) -POST /api/v1/data/{object}/batch # Per-object batch operations -POST /api/v1/batch # Cross-object atomic batch +GET|POST /api/v1/data/{object} # list | create +GET|PATCH|DELETE /api/v1/data/{object}/:id # get | update | delete (→ recycle bin) +POST /api/v1/data/{object}/query # QueryAST body, aggregation +POST /api/v1/data/{object}/batch # per-object batch +POST /api/v1/batch # cross-object atomic batch +POST /api/v1/data/{object}/import, GET …/export +GET /api/v1/meta/:type[/:name] # metadata read (object, view, flow, …) ``` -There is no `/bulk` route and no `GET .../aggregate` route — batch writes go -through the `batch` endpoints. - -> **Key rule:** If your object defines `apiMethods`, only those operations (and -> what derives from them) are exposed; `[]` means deny-all. - -### Metadata API (`/meta`) +There is no `/bulk` route and no `GET …/aggregate`. -The metadata read surface lives under `/api/v1/meta` (separate from the data -CRUD routes above): - -``` -GET /api/v1/meta/:type # List metadata items of a type (object, view, flow, doc, …) -GET /api/v1/meta/:type/:name # Read a single metadata item -``` - -The list reads a closed query set — `package`, `preview` (`draft`), `object`, -`include` (`content`, `grants`), `id`, `names`, `locale` — and refuses any other key with -`400 VALIDATION_ERROR` instead of ignoring it. `?names=a,b,c` (one -comma-separated value) narrows the list to the named items the caller may see: -an unknown name is simply absent, an empty value is refused `400`, and the -`package` list (keyed by id) refuses the key. These are **client** contracts — -nothing in a stack declares them. - -### Public (anonymous) Form Endpoints - -A `FormView` is served by the anonymous form endpoints only when its -`sharing` declares all three: `enabled: true` (the schema default is -`false`), `allowAnonymous: true` and a `publicLink` slug. Miss any one and -both endpoints answer `404 FORM_NOT_FOUND`. The form is then mounted at: - -``` -GET /api/v1/forms/:slug # returns form spec + restricted objectSchema -POST /api/v1/forms/:slug/submit # whitelist-filtered INSERT, no auth header -``` +- **`GET /api/v1/meta/:type` reads a closed query set** (`package`, `preview`, `object`, + `include`, `id`, `names`, `locale`) and refuses any other key with `400 VALIDATION_ERROR`. + `?names=a,b,c` (one comma-separated value) narrows the list to the named items the caller + may see: an unknown name is absent, an empty value is refused `400`. +- **An import** takes `mapping` as `{ Column: field }` or as `FieldMappingEntry[]` + (`api/export.zod.ts`). Only an entry, `{ sourceField, targetField, applyOn }`, carries + `applyOn` (default `'always'`): `'create'` writes the column only when the row is + created, so a re-run `upsert` keeps a value an admin set since. -These bypass `enforceAuth` (Web-to-Lead / Web-to-Case flows). The form's own -declaration authorizes the submit: a `publicFormGrant` on its target object -(create and read-back of its new row, nothing else), decided before any permission -set resolves. The submit context's `guest_portal` name admits nothing and needs -no set; a set so named only feeds the grant's result masker. The framework -strips fields outside the form's `sections[].fields[]` list; a -`beforeInsert` hook on the target object should stamp safe defaults -(`status='new'`, `lead_source='web'`, …) and `delete` privileged keys -(`owner`, `internal_notes`, …). On a walled posture (`group`/`isolated`), a -form on an object walled by an organization column is withheld too — both -endpoints `404`, and save / publish warn `public-form-intake-unavailable`; -declare `tenancy: { enabled: false }` on an object whose rows belong to no -organization to offer it again. For the full contract, read -`node_modules/@objectstack/spec/src/ui/view.zod.ts` (`FormViewSchema`) and -`node_modules/@objectstack/spec/src/ui/sharing.zod.ts` (`SharingConfigSchema` -with `enabled` / `allowAnonymous` / `publicLink`). - -A form open to anonymous intake declares no file field. A section field whose -object type is in `FILE_REFERENCE_TYPES` (`image`, `file`, `avatar`, `video`, -`audio`) is refused by the gating lint rule `public-form-file-field` — at -`os validate` / `os build` / `os lint`, and at the view's publish — because a -visitor has no upload door to mint a `sys_file` id. A form published before that -rule meets the same refusal at submit: a file value answers the flat `400 -VALIDATION_FAILED` with `fields[].code: 'invalid_value'`. Collect the file on a -signed-in form instead. - ---- - -## Declarative Endpoints (`apis:`) — no handler code - -`defineStack({ apis })` declares an HTTP endpoint as **metadata**. Declared -endpoints are **live from protocol 17**: the runtime matches -`METHOD` + `path`, runs the endpoint's policy keys, and delegates to the *same* -pipelines the built-in routes use — `object_operation` to the data pipeline -behind `/api/v1/data/{object}`, `flow` to the automation pipeline behind -`POST /api/v1/automation/{name}/trigger`. An endpoint is a stable URL plus a -policy layer over an existing pipeline, never a second execution dialect. +## API Methods (Operations) -### Choosing between `apis:` and a code handler +`apiMethods` whitelists the six authorable primitives (`ApiMethod`): `get`, `list`, +`create`, `update`, `delete`, `bulk` (the `/batch` route); unset is all, `[]` none. Every +other operation derives and is never declared (a declared one is stripped at parse, with a +warning): `aggregate`, `export` and, where `searchable`, `search` (the global +`GET /api/v1/search`) from `list`; `import` from `create` ∨ `update`; `history` from `get` +∧ `trackHistory`; `restore` and `purge` (trap 3) from `delete`; `upsert` from `create` ∧ +`update`, with no route: query by the external ID, then create or update through `/batch`. -| Use | When | -|:---|:---| -| **`defineStack({ apis })`** | The endpoint is a *projection* of something the platform already executes: query/return records, or trigger a flow. No code, no deploy artifact, publish-gated. **Prefer this.** | -| **A flow that runs your code** | The endpoint needs real handler CODE: point a `type: 'flow'` endpoint at a flow whose `script` node names a stack function (`defineStack({ functions })`; which one runs: [objectstack-automation](../objectstack-automation/SKILL.md#valid-but-silently-wrong-passes-build-fails-at-runtime) item 3), or whose `connector_action` node calls a declared connector (outbound). The URL stays declarative; the code runs where the automation surface already runs it. | +## A declared endpoint -An inbound webhook is a `type: 'api'` flow (objectstack-automation → -**Inbound webhook (`api`) triggers**): it verifies ObjectStack's own -`x-objectstack-signature`, or a vendor's own HMAC-SHA256 header its start node -declares as `config.signature` (DocuSign Connect, Stripe-style), enqueues, and -answers `202`. -**An app never mounts on `http.server`** — that service is the platform -plugins' own door-building primitive, and a code-mounted route gets no caller -identity, auth gate, rate limit, namespace carve-out or OpenAPI entry. Three -cases have no app surface today; say so rather than invent one: a third-party -callback signed in a form `config.signature` cannot declare (not HMAC-SHA256), -a streaming response (a declared endpoint answers one JSON envelope), and a -protocol the platform does not speak. +`type` is `object_operation` or `flow`, the pipelines of `/api/v1/data/{object}` and +`POST /api/v1/automation/{name}/trigger`; `script` and `proxy` are rejected at publish. ```typescript import type { ApiEndpoint } from '@objectstack/spec/api'; -// The stack declares `manifest: { namespace: 'acme', … }` — required, see below. +// `manifest: { namespace: 'acme', … }` is required, never derived from `id`. export const leadFeed: ApiEndpoint = { name: 'acme_lead_feed', path: '/api/v1/apps/acme/leads', // /api/v1/apps// method: 'GET', - summary: 'Lead feed', type: 'object_operation', objectParams: { object: 'acme_lead', operation: 'find' }, - cacheTtlSeconds: 30, // GET-only; rides success answers only + cacheTtlSeconds: 30, // GET-only }; ``` -### The path carve-out (ADR-0121 D1/D2) - -A declared path must be `/api/v1/apps//`. Only the -subpath is yours to name, and the ordinary naming rules below apply inside it. -`manifest.namespace` must be declared **explicitly** — it is never derived from -`manifest.id`. A path outside the carve-out is rejected at publish. - -### Five publish gates, each with a prescription - -A declaration this runtime cannot serve is **rejected at publish**, one gate at -a time. Do not memorise the gate texts; **read the rejection**, it carries the -fix. The five: **namespace** (the carve-out above), **supported target** -(`script` / `proxy` do not execute in 17.x; an `object_operation` needs both -`objectParams.object` and `.operation`; a `flow` needs a `target`), -**mapping** (below), **policy** (below), and **uniqueness** (one `METHOD` + -path claim per stack). - -### `authRequired` and the D6 pairing - -`authRequired` defaults to `true`, so **omitting it is safe**. An explicit -`false` is the only thing that opens an anonymous, unauthenticated execution -entry point — and ADR-0121 **D6** pairs it with an *armed* budget: - -```typescript -authRequired: false, -rateLimit: { enabled: true, windowMs: 60_000, maxRequests: 100 }, -``` - -The gate's predicate is `rateLimit.enabled === true`, **not** the key's presence: -`RateLimitConfigSchema.enabled` (`@objectstack/spec/shared`) itself defaults to `false`, so writing only -`windowMs` / `maxRequests` declares a budget that meters nothing. Endpoint -budgets are metered independently of the server-level `server.security.rateLimit`. - -### Mapping keys: projection only - -`inputMapping` / `outputMapping` **move and rename fields by dot path, and -nothing more**. `inputMapping` maps the REQUEST BODY, applied after the policy -chain and before delegation (so a mapping can never buy a caller past -`authRequired` or the rate limiter); `outputMapping` is applied to a **successful** -response body only. Three consequences worth knowing before you author one: - -- `transform` is rejected — there is no transformation-function registry. - Compute the value where it is produced (a flow, or a formula field). -- `inputMapping` is rejected on a `find` / `get` / `delete` `object_operation`, - which never reads a request body. -- Two entries cannot write the same target path, nor one inside the other - (`x` and `x.y`). - -### Upgrading a pre-17 stack - -An `apis:` block written against an older major **changes meaning without -changing a byte** — inert documentation becomes an execution entry point. Work -through the `declarative-apis-endpoints-live` entry of the protocol upgrade -guide before upgrading; it is a security review, not a rename. Its two -load-bearing steps: move every `path` into the carve-out, and grep every entry -for `authRequired: false`. - ---- - -## Endpoint Naming Conventions - -| Pattern | Use Case | Example | -|:--------|:---------|:--------| -| `/api/v1/{object}/:id/{action}` | Custom action on record | `/api/v1/cases/:id/close` | -| `/api/v1/{domain}/{action}` | Domain-level action | `/api/v1/ai/chat` | - -**Rules:** - -- Always use **plural nouns** for collection paths (`accounts`, not `account`). -- Use **snake_case** for multi-word paths (`project_tasks`, not `projectTasks`). -- Use **verbs** only for actions, not for CRUD (`/close`, `/approve`). - ---- - -## API Methods (Operations) - -The authorable `ApiMethod` enum is the SIX PRIMITIVES. The wider EFFECTIVE -vocabulary (`ApiOperation`, 14 values) is what gates and responses speak; its -eight extra verbs are never declared in `apiMethods`: - -**Authorable primitives:** - -| Method | HTTP surface today | Purpose | -|:-------|:-------------------|:--------| -| `get` | `GET /data/{object}/:id` | Retrieve a single record | -| `list` | `GET /data/{object}` | List records with filter/sort/pagination | -| `create` | `POST /data/{object}` | Create a new record | -| `update` | `PATCH /data/{object}/:id` | Update an existing record | -| `delete` | `DELETE /data/{object}/:id` | Delete a record | -| `bulk` | `POST /data/{object}/batch` | Batch create/update/delete (bulk ∧ child op) | - -**Derived operations (granted automatically, never authored):** - -| Operation | Derives from | HTTP surface today | -|:----------|:-------------|:-------------------| -| `upsert` | `create` ∧ `update` | none generated | -| `aggregate` | `list` | `POST /data/{object}/query` with `groupBy`/`aggregations` | -| `search` | `list` ∧ `searchable` | global `GET /api/v1/search`, not per-object | -| `import` | `create` ∨ `update` (writeMode-precise) | `POST /data/{object}/import` | -| `export` | `list` | `GET /data/{object}/export` | - -`history` (from `get` ∧ `trackHistory`) gates only. `restore` / `purge` derive -from `delete` and open the recycle-bin doors (pitfall 2). Declaring any -derived verb in `apiMethods` is stripped at parse with a FROM → TO warning. - -`POST /data/{object}/import` takes `mapping` as `{ Column: field }` or as -`FieldMappingEntry[]` (`api/export.zod.ts`); only the entry form carries -`applyOn`. `'always'` (default) writes the column on every row the import -creates or updates; `'create'` writes it only when the row is created, so a -re-run `upsert` refreshes the `always` columns and leaves a value an admin set -since (an owner, a stage) as it is. A create-only column is still read for -matching. Any other value is `400 INVALID_REQUEST`. - ---- - -## Discovery & Health - -`GET /api/v1/health`, `GET /ready` (200 running / 503 booting) and -`GET /api/v1/discovery` (per-service status) exist on **every** deployment. -All three are **response** surfaces — nothing to author. - ---- - -## Dispatcher Error Codes - -The **HttpDispatcher** is the central request router; it answers: - -| HTTP Status | Error Code | When | -|:------------|:-----------|:-----| -| 404 | `ROUTE_NOT_FOUND` | No route matches the path | -| 405 | `METHOD_NOT_ALLOWED` | Route exists but method not supported | -| 501 | `NOT_IMPLEMENTED` | Route declared but handler is a stub | -| 503 | `SERVICE_UNAVAILABLE` | Service is registered but not ready | - ---- - -## Realtime Subscriptions - -- `node_modules/@objectstack/spec/src/api/realtime.zod.ts` — `TransportProtocol` - (`websocket` | `sse` | `polling`), `SubscriptionSchema` (`id`, `events[]`, - `transport`, optional `channel`), `RealtimeEventSchema`, and - `RealtimeConfigSchema`. -- `node_modules/@objectstack/spec/src/api/websocket.zod.ts` — the WebSocket - message protocol: subscribe/unsubscribe messages, event delivery, presence, - cursor and collaborative-edit messages, and ack/error/ping/pong frames. - ---- - -## Authentication & Authorization - -### Auth Configuration - -There is no nested `auth` block on an endpoint, and no `name` / `request` / -`response` field: auth is the flat `public` + `permissions` pair on -`RestApiEndpointSchema`, and declarative `ApiEndpointSchema` endpoints (and the -dispatcher) use `authRequired: boolean` (D6 above). - -### Auth Providers - -Provider and login contracts live in -`node_modules/@objectstack/spec/src/api/auth.zod.ts`: `AuthProvider` is -`'local' | 'google' | 'github' | 'microsoft' | 'ldap' | 'saml'`, and -`LoginRequestSchema` carries `type` (login method), plus optional `email`, -`username`, `password`, `provider`, and `redirectTo`. Read that file for the -session and token response shapes before wiring an auth flow. - ---- - -## Error Envelopes & the Code Ledger (ADR-0112) - -`error.code` is **two-tier**: the closed `StandardErrorCode` catalog plus the -codes registered per owning package in `api/error-code-ledger.zod.ts`. -`ApiErrorSchema.code` validates the union, so an **unregistered code fails -parse → fails the envelope conformance suites → fails CI**. - -That ledger takes **framework packages only**. A downstream repo keeps its OWN -ledger and composes the two checks itself — `envelopeViolations(body)` for the -SHAPE, `makeApiErrorSchema(yourCodes)` for the VOCABULARY (both in -`api/contract.zod.ts`). What no repo may do is emit a code in no ledger at all. - -`userMessage` is producer-marked user-facing text in the REQUEST's locale; render it as -received and keep no per-code translation table. Platform-composed text follows one ladder -over the platform locale table (`PLATFORM_LOCALES`, `@objectstack/spec/system`): the locale -the request names (its `Accept-Language`, or `?locale` on the REST door), else the workspace -default, else `en`, each code read whole and then one subtag shorter at a time (`fr-FR` → -`fr`, `zh-Hant-US` → `zh-Hant`). App-authored text, such as a hook's catalogued refusal, is -not on this ladder: it is served in the caller's locale from the app's own translations, -otherwise as declared, with no `en` floor. The save / publish doors' `advisories[]` and the -422 `issues[]` share one element, `RuntimeAuthoringIssueSchema` (`api/protocol.zod.ts`): it -carries an optional `userMessage` beside the stable `rule`, while `message` / `hint` stay -developer-facing English; absent, render `message`. -A batch publish (`POST /api/v1/packages/:id/publish-drafts`) may answer `probes`, its runtime -findings (`BuildProbeReportSchema`, same file; ADR-0038). Each `issues[]` element -(`RuntimeBuildIssueSchema`) has two readers: `message` / `fix` are English for the agent that -built the app, the optional `userMessage` is the sentence for the person who published. Show -a person `userMessage`, never `message`; absent, show your own generic sentence. This door -reads the request's locale from `Accept-Language` alone. - -A flow door — `POST /api/v1/automation/{name}/trigger`, resume, `/actions`, a -declared `type: 'flow'` endpoint — answers a failed run with `400 FLOW_FAILED`; -its `error.details` is `FlowFailureDetailsSchema` (`api/automation-api.zod.ts`): -`errorMessage?` (the flow author's text), `summary?` (which node failed) and -`innerRefusal?`, the `{ code, message }` refusal a node met (a data node's read -or write, a `script` node's function name), `code` an `ErrorCode` member in wire -spelling (e.g. `UNIQUE_VIOLATION`, `PERMISSION_DENIED`, `RESOURCE_CONFLICT`). -Render it as a record form renders a refused save: -top-level `userMessage`, then `details.innerRefusal`, then `message`. Absent -keys mean the run produced none — never invent an empty. - ---- - -## Best Practices - -1. **Use auto-generated APIs** whenever possible. Only create custom endpoints - for business logic that cannot be expressed through CRUD + triggers. -2. **Return consistent error shapes.** The dispatcher envelope is - `DispatcherErrorResponseSchema`: `{ success: false, error: { code, message, - httpStatus?, route?, service?, hint? } }`, where `code` is the **semantic** - string and `code`/`message` are required. General API errors use - `ErrorResponseSchema` (`errors.zod.ts`). Be aware the shipped data routes - return flat `{ error, code }` bodies instead (e.g. `CONCURRENT_UPDATE` → - 409, `VALIDATION_FAILED` → 400). -3. **Design idempotent writes deliberately.** No upsert route is generated, so - an external integration queries by its unique external ID and branches to - create or update — group those writes through - `POST /api/v1/data/{object}/batch`. - ---- - -## Common Pitfalls - -1. **Not handling 409 Conflict.** The generated `PATCH /api/v1/data/{object}/:id` - route does optimistic concurrency with two spellings: the `If-Match` header - **or** an `expectedVersion` field in the JSON body — **the body wins** when - both are sent, and the token is typically the `updated_at` value the client - read. Sending neither skips the check; a mismatch answers **409 - `CONCURRENT_UPDATE`**; the quoted-empty entity-tag (`""`) is refused **400 - `VALIDATION_FAILED`**, not treated as omitted. -2. **Treating `DELETE` as final.** A by-id delete keeps a business object's - rows in the recycle bin (`sys_recycle_bin`, 30 days by default; not - `multi: true` deletes, platform rows or rows deleted before the bin existed) - and answers `recycleBinEntryId`. Under `/api/v1/data/{object}/recycle-bin`: - `POST /:entryId/restore` (`allowRestoreOwnDeleted` for your own deletes, - `manageRecycleBin` for others'); `GET` lists, `DELETE /:entryId` purges, - `DELETE` empties (`manageRecycleBin`). A refused restore answers `409` - `RESTORE_UNIQUE_VALUE_TAKEN`, `RESTORE_PARENT_PURGED`, - `RESTORE_PARENT_IN_RECYCLE_BIN` (restore that parent's entry first) or - `RESTORE_PACKAGE_UNINSTALLED`, and keeps the entry. No soft-delete. - ---- - -## Verify your work - -After adding a `*.endpoint.ts`, a custom route, or an auth provider, run the -author-time gate before reporting done: - -```bash -os validate # Zod schema + CEL predicate validation + bindings (no artifact) -# or: os build # the same gates, plus emits dist/ -``` - -Route-guard and auth predicates are CEL; the gate parses them and fails -non-zero with a located message instead of letting a malformed guard fall -through at runtime. In a scaffolded project the gate is `npm run validate`. See -objectstack-platform → **Verify your work** for the full gate list. - ---- - -## References - -See [references/_index.md](./references/_index.md) for the full list of Zod -schemas (with one-line descriptions) — pointers into -`node_modules/@objectstack/spec/src/`. Always `Read` the source for exact field -shapes; do not rely on memory of property names. - +`inputMapping` / `outputMapping` only move and rename fields by dot path; `transform` is +rejected: compute the value in a flow or a formula field. + +## Traps + +1. **`authRequired: false` needs an ARMED budget.** Omitting the key is safe (default + `true`); an explicit `false` opens an anonymous execution entry point and pairs with + `rateLimit: { enabled: true, windowMs: 60_000, maxRequests: 100 }`. The gate reads + `rateLimit.enabled === true`, not the key's presence: `enabled` defaults to `false`, so + `windowMs` / `maxRequests` alone meter nothing. Endpoint budgets are metered apart from + `server.security.rateLimit`. +2. **An app never mounts on `http.server`**, the platform plugins' own primitive: a + code-mounted route gets no caller identity, auth gate or rate limit. Handler code runs in + a flow: a `type: 'flow'` endpoint names it in `target`; its `script` node names a stack + function (`defineStack({ functions })`; which one runs: + [objectstack-automation](../objectstack-automation/SKILL.md)), or its `connector_action` + node calls a declared connector. An inbound webhook is a `type: 'api'` flow: it verifies + ObjectStack's own `x-objectstack-signature`, or a vendor's HMAC-SHA256 header its start + node declares as `config.signature` (DocuSign Connect, Stripe-style), enqueues, and + answers `202`. No app surface exists for a callback signed in a form `config.signature` + cannot declare, a streaming response or a protocol the platform does not speak: say so, + never invent one. +3. **`DELETE` is not final.** A by-id delete keeps a business object's rows in the recycle + bin (`sys_recycle_bin`, 30 days by default; not `multi: true` deletes or platform rows) + and answers `recycleBinEntryId`. `POST /api/v1/data/{object}/recycle-bin/:entryId/restore` + restores it (`allowRestoreOwnDeleted` for your own deletes, `manageRecycleBin` for + others'); listing, purging and emptying the bin need `manageRecycleBin`. No soft-delete. +4. **A `PATCH` with no version token skips the concurrency check.** Send `If-Match`, or + `expectedVersion` in the JSON body (the body wins; the token is typically the + `updated_at` the client read). A mismatch answers `409 CONCURRENT_UPDATE`. +5. **A public form answers `404 FORM_NOT_FOUND` unless its `sharing` declares all three**: + `enabled: true` (default `false`), `allowAnonymous: true` and a `publicLink` slug. Then + `GET /api/v1/forms/:slug` and `POST /api/v1/forms/:slug/submit` bypass auth; the + declaration grants only the create and read-back of its row. Fields outside + `sections[].fields[]` are stripped; write a `beforeInsert` hook that stamps safe defaults + and deletes privileged keys (`owner`, …). On a walled posture a form on an + organization-walled object is withheld too, and save and publish only warn + (`public-form-intake-unavailable`): declare `tenancy: { enabled: false }` where the rows + belong to no organization. +6. **`userMessage` is the sentence for a person**: render it as received and keep no + per-code translation table. It is in the REQUEST's locale (platform text: + `Accept-Language`, or `?locale` on the REST door, else the workspace default, else `en`). + On a batch publish's `probes.issues[]` (`POST /api/v1/packages/:id/publish-drafts`; + `RuntimeBuildIssueSchema`, `api/protocol.zod.ts`; `Accept-Language` alone) `message` / + `fix` are developer English: show `userMessage`, never `message`, and with none your own + generic sentence. A flow door's `400 FLOW_FAILED`: `userMessage`, then + `details.innerRefusal` (`api/automation-api.zod.ts`), then `message`. + +## Where to go + +| Need | Open | +|:-|:-| +| An endpoint key, a publish gate, a mapping refusal | `api/endpoint.zod.ts`; https://objectstack.ai/docs/api/declarative-endpoints | +| A generated route's request and answer; discovery | https://objectstack.ai/docs/protocol/kernel/http-protocol | +| An error code or envelope; a new `error.code` (one in no ledger fails CI) | `api/errors.zod.ts`, `api/dispatcher.zod.ts`, `api/error-code-ledger.zod.ts`; https://objectstack.ai/docs/api/error-catalog | +| Auth (an endpoint has no nested `auth` block: `authRequired`) | `api/auth.zod.ts`: `AuthProvider` (`local`, `google`, `github`, `microsoft`, `ldap`, `saml`), `LoginRequestSchema` | +| A public form | https://objectstack.ai/docs/ui/forms | +| Objects, permissions; filters; kernel services, drivers | **objectstack-data**; **objectstack-query**; **objectstack-platform** |