# Public API — read-only surface and event stream

Source of truth: `packages/contracts/src` (the Zod contracts every route validates
against), plus the route registrations in `apps/edge/src` and `services/vm/src`. This
document is generated from those files, not from live probes. Anything the contracts
do not pin down is listed under [Open questions](#open-questions).

There are two public-facing surfaces:

1. **The published surface** — `/p/:workbookId/…` on the edge (also reachable through a
   verified custom domain, which is rewritten onto this path). It is a method + path
   allowlist of read-only workbook-API routes, rate-limited and gated to `published`
   workbooks. Every forwarded request carries edge-minted `public` claims.
2. **The workbook API** — the full surface each workbook VM serves (`/api/*`, `/e/*`)
   for holders of workbook tokens (`wbt_…`) or share tokens. Reads and writes both
   live there; this document covers the read paths and the event stream, and the
   contracts are the reference for the rest.

The control plane (`/v1/…`: workbooks, tokens, members, shares, domains, uploads,
billing) is documented separately in [`admin-api.md`](./admin-api.md).

## Authentication model

Four credential forms exist. Only the first three appear on public surfaces; the raw
secret for any of them is never accepted by the workbook API itself.

| Credential | What it is | Where it is accepted |
| --- | --- | --- |
| Workbook token | `wbt_<tok_…>_<secret>` bearer credential, kinds `session`, `agent`, `endpoint`, `share`, `claim`, `embed`. Only the SHA-256 of the secret half is stored; mint responses return it exactly once. | Control plane `/v1` (bearer), workbook API (as edge-verified claims), event stream (`?token=` / `Authorization: Bearer`) |
| Claims envelope | Edge-signed `{payload, sig}` envelope forwarded as `X-WB-Claims` (or `?claims=` where headers are impossible). Scope + token identity (`tokenId`, `kind`, `actor`), 300 s TTL. | Workbook API `/api/*` and `/e/*`, event stream |
| Share token | A `wbt_` token of kind `share`, minted only through `POST /v1/workbooks/:id/shares`. Minimum scope by construction: role `custom`, `read` on exactly the target's tables, no forks, review-mode merges. | Workbook API reads scoped to the target, `/v1/…/shares/resolve` |
| Embed grant | A `wbt_` token of kind `embed`, minted only through `POST /v1/workbooks/:id/embeds`. Minimum scope by construction (the same read-only shape as a share); optional `expiresInHours` bounds its life (≤ 8760 h; absent = until revoked). Presented as the `?embed=` parameter of the `/p/:workbookId` URL. | The `/p/:workbookId` render surface (SPA shell + edge meta read) |
| Public claims | Edge-minted identity of an anonymous viewer on a published workbook. Never a stored token row; the VM treats it as non-human (no imports, no undo). | `/p/:workbookId/*` forwards, public endpoint invocation |

Rules the contracts enforce:

- **The workbook API never sees token secrets.** The edge validates the credential and
  forwards signed claims; the VM maps each `tokenId` to its own table-scoped Dolt user,
  so scope enforcement happens in the engine, never by string-inspecting SQL.
- **Share tokens cannot be minted with caller-supplied scopes.** The generic token-mint
  route refuses kind `share`; the share-mint route constructs the scope server-side
  from the target (table, view, or dashboard — a dashboard share must name its source
  tables or it is refused).
- **Embed grants cannot be minted with caller-supplied scopes.** The generic token-mint
  route refuses kind `embed`; the embed-mint route constructs the scope server-side
  (role `custom`, `read` on every table, no forks, review-mode merges).
- **Embed revocation and expiry are enforced at the render gate, immediately.** The
  `/p` shell and edge meta read require a live `embed` grant; the gate reads the grant
  row fresh from the control-plane database on every request — the 60 s cached token
  lookup used for API-key authz is deliberately bypassed — so a
  `DELETE /v1/workbooks/:id/embeds/:tokenId` or an expiry lands on the very next
  request. Every failure (missing, malformed, wrong workbook, revoked, expired)
  answers the same 401.
- **Share tokens cannot invoke endpoints.** `/e/*` answers them 403.
- **Endpoint visibility for public claims.** A public claim resolves only endpoints
  deployed with `auth: 'public'`; anything else is a 404 (no existence leak).
  Token-authed endpoints gain no exposure through the published path.
- **Claims refresh.** Clients exchange their credential at
  `POST /v1/workbooks/:id/claims` and re-exchange before the 300 s TTL; a workbook API
  request arriving with an expired envelope is 401 `unauthenticated`.
- **User-scoped API keys** (keys that live on a user rather than a workbook) are
  arriving in a separate PR and are not covered here.

## Published read-only endpoints

All paths are relative to `/p/:workbookId`. The allowlist is exact — any other method +
path pair is a generic 404 `not_found` (missing, deleted, and unpublished workbooks
indistinguishably; whether a workbook exists is not public information).

| Method | Path | Purpose |
| --- | --- | --- |
| GET | `/api/tables` | List tables. Response: `{ tables }`. |
| GET | `/api/tables/:table` | One table's schema (`TableContract`). |
| POST | `/api/tables/:table/rows/query` | Grid page query. Body: `RowsQueryRequest`, response `{ rows, total?, cursor? }`. |
| POST | `/api/tables/:table/aggregate` | The single number a metric widget shows. Body: `TableAggregateRequest` (`{ fn, column?, filter? }`), response `{ value }`. |
| POST | `/api/tables/:table/group` | Engine-side grouping for chart/table widgets. Body: `TableGroupRequest` (`{ by, filter?, aggregates?, summaryOnly? }`), response `{ groups }` — or `{ rows }` with `summaryOnly`. |
| GET | `/api/dashboards` | List dashboards. |
| GET | `/api/dashboards/:id` | One dashboard `DashboardSpec`. |
| GET | `/e/<path>` | Invoke a public endpoint (`html=1` requests the declared `html` rendering). |
| POST | `/e/<path>` | Invoke a public endpoint with `{ params? }` body. |

Edge behavior on every published request, in order: rate limit (per IP + workbook) →
published gate (generic 404) → allowlist (generic 404) → sign public claims and forward.

The render surface — the `/p/:workbookId` SPA shell and its edge-owned meta read —
additionally runs the embed gate between the published gate and the allowlist: a live
`embed` grant carried as `?embed=` is required (401 otherwise; see the rules above).
The allowlisted data routes above stay governed by the published tier alone, so an
embedded viewer's widgets read through them exactly as a published page's do.

### Row queries (`POST /api/tables/:table/rows/query`)

The grid-filter grammar (`filterSchema`) is recursive `and` / `or` / `not` over
conditions `{ col, op, value }`. Operators: `eq`, `neq`, `lt`, `lte`, `gt`, `gte`,
`in`, `nin`, `contains`, `starts`, `ends`, `is_null`, `not_null`, `between`, `tagged`.
Identifiers are validated against `information_schema` at compile time and compiled to
parameterized SQL — never interpolated.

Other request fields: `sort` (`[{ key, dir: 'asc' | 'desc' }]`), `search`,
`vector` (`{ column, query? | embedding? }`), `offset` / `cursor` (keyset paging; prefer
`cursor`), `limit` (1–1000), `columns`, `fork` (read a fork branch; also accepted as
`?fork=`), and `asOf` (time-travel read: Dolt commit hash or ISO timestamp).

### Dashboards and widget data

A `DashboardSpec` is declarative JSON (12-column layout; widgets: metric, chart, table,
map, markdown, HTML-in-sandboxed-iframe). Widget sources are workbook tables, agent
endpoints, or SQL. Table-backed metric/chart widgets read through
`POST /api/tables/:t/aggregate` and `/group` — read-only engine queries, both on
the published allowlist — so a published dashboard renders its widgets entirely
through `/p/…`.

### Endpoint invocation (`/e/<path>`)

Endpoints are Python functions or saved parameterized SQL deployed from the `/work`
directory and pinned to a code commit SHA. Invocation body for SQL endpoints is
`{ params: { <name>: value } }`. Response shapes are declared by the endpoint's
`contract` (`shape: 'table' | 'json' | 'html'`).

## Event stream (WebSocket)

One event stream per workbook, served by the workbook's Durable Object behind the edge:

```
GET /api/events?after=<seq>&token=<wbt_…>        # on the workbook's host
GET /api/events?after=<seq>&workbook=<id>        # on hosts that are not workbook subdomains
Upgrade: websocket
```

**Auth on the upgrade.** A WS upgrade cannot carry custom headers, so the DO accepts:
`?token=<wbt_…>`, `Authorization: Bearer <wbt_…>`, or the edge-signed claims envelope
via `?claims=` (or `X-WB-Claims` for callers that can set headers). A presented token
that fails verification is final — the envelope path only opens when no token was
offered. No credential → 401 `unauthenticated`.

**Connect handshake (replay-or-resync).** Connect with `?after=<seq>` — the last seq
you processed. At connect time the server sends one of:

- `{"kind": "hello", "latest": <seq>}` — cursor is inside the replay window; the
  buffered events after your cursor follow immediately as `{"kind": "event", "event":
  …}` messages, then live events.
- `{"kind": "resync", "latest": <seq>}` — your cursor predates the replay window (the
  ring has advanced past it). No events follow; refetch state (e.g. a full
  `rows/query`) and resume from `latest`.

`after=0` (or omitted) is always answerable: it replays the whole current ring.

**Wire protocol.** Every server message is exactly one of `hello`, `resync`, `event`,
`pong` (discriminated on `kind`, so control messages can never collide with event
types). The only client message is `{"kind": "ping"}`, answered with
`{"kind": "pong"}` — the runtime answers pings to a hibernated socket without waking
the DO. The event envelope itself:

```json
{ "seq": 1284, "commit": "<dolt hash>", "at": "<iso>", "type": "rows.changed",
  "actor": "agent:tok_…", "data": { … } }
```

`seq` is the per-workbook monotonic cursor and doubles as the resume token
(`?after=<seq>`); the Dolt commit hash is the consistency marker. Event types:
`rows.changed`, `commit.created`, `schema.changed`, `fork.opened`, `fork.proposed`,
`fork.merged`, `fork.conflicted`, `fork.dropped`, `change_set.approved`,
`change_set.rejected`, `endpoint.deployed`, `endpoint.deleted`, `validation.updated`,
`dashboard.updated`, `job.progress`, `job.finished`, `backup.finished`,
`restore.drilled`, `backup.restored_in_place`, `presence.updated`, `comment.added`,
`workbook.sleeping`, `workbook.waking`, `workbook.awake`,
`workbook.deletion_scheduled`.

**Scope redaction at fan-out.** Every event is filtered per socket against that
socket's scope: an event referencing a table the token cannot read arrives reduced to
`{"table": "<name>", "count": <n>}` (or `{"tables": […], "count": <n>}`) — row payload
fields are dropped, never merely hidden. `_wb_*` system tables are readable by every
token. The same filter is applied identically on the HTTP resume path.

### Polling fallback

The same path answers plain HTTP (no `Upgrade` header):

```
GET /api/events?after=<seq>&token=<wbt_…>   →  { "events": […], "resync": false }
```

The response is the same scope-redacted slice of the ring (with the `resync` flag when
the cursor predates the window). Pollers resume from the last seen `seq`; the ring is
bounded, so a poller that falls out of the window sees `resync: true` and must refetch.
This is the documented reconnect fallback when a WebSocket cannot be held open.

## Wake semantics

A sleeping workbook is woken by any API traffic. A caller held during a wake gets
`503` with `{"error": {"code": "waking", …}}` and a `Retry-After` header (the hold
window is 25 s); the wake continues in the background, so retrying succeeds once the
workbook is up. The published surface forwards this as-is.

## Limits

| Limit | Value | Where |
| --- | --- | --- |
| Published-surface rate limit | 60 requests/min per IP per workbook; over-limit is `429` with `Retry-After` | edge, `public.routes.ts` |
| Anonymous workbook-create throttle | server-side fixed window | edge admin router |
| Event replay window | 10,000 events per workbook; older cursors get `resync` | DO lifecycle |
| Claims envelope TTL | 300 s (re-exchange before `exp`) | edge admin claims |
| Rows query page size | `limit` ≤ 1000 (`rowsQueryRequestSchema`) | contracts `query.ts` |
| SQL `maxRows` / `timeoutMs` | ≤ 10,000 rows / ≤ 30,000 ms (`sqlQueryRequestSchema`) | contracts `query.ts` |
| Search `limit` | ≤ 100, default 20 (`searchRequestSchema`) | contracts `search.ts` |
| Import payload | 2 GiB cap (2147483648 bytes) | contracts `imports.ts` `MAX_IMPORT_SOURCE_BYTES`; enforced per source kind in the VM import resolver |
| Upload signing TTL | `expiresInSec` 30–3600, default 900 (`signUploadRequestSchema`) | contracts `uploads.ts` |
| Table / column names | MySQL unquoted-identifier shape; table ≤ 64 chars (`tableCreateRequestSchema`) | contracts `api.ts` |
| Endpoint path | ≤ 200 chars, `/rollups/monthly` shape (`endpointPathSchema`) | contracts `endpoints.ts` |
| Share / token labels | ≤ 120 chars | contracts `shares.ts`, `admin.ts`, `embeds.ts` |
| Embed grant expiry | `expiresInHours` ≤ 8760 whole hours (`createEmbedRequestSchema`); absent = no expiry | contracts `embeds.ts` |

## Error shape

Every failure on every surface is one shape:

```json
{ "error": { "code": "<code>", "message": "…", "details": …?, "requestId": "…" } }
```

`code` is the `ApiErrorCode` union: `unauthenticated`, `forbidden`, `not_found`,
`conflict`, `merge_conflict`, `validation_failed`, `rate_limited`, `quota_exceeded`,
`payment_required`, `query_timeout`, `result_too_large`, `waking`, `unavailable`,
`workbook_deleted`, `sql_error`, `internal`. Access denials are 404 where they would
leak existence (unpublished/missing workbooks, endpoints under public claims) and 403
where the caller demonstrably has context.

## Provenance

| Section | Source files |
| --- | --- |
| Auth model | `contracts/src/{api,claims,shares,embeds,admin}.ts`, `edge/src/tokens/format.ts`, `edge/src/admin/{index,claims}.ts` |
| Published endpoints | `edge/src/public/{public.routes,embed-gate}.ts`, `contracts/src/{query,dashboards,endpoints}.ts` |
| Event stream | `contracts/src/events.ts`, `edge/src/do/{workbook-do,lifecycle}.ts`, `edge/src/app.ts` |
| Limits | contracts files above, `edge/src/public/rate-limit.ts`, blueprint §Limits |
| Error shape | `contracts/src/api.ts` |
