# Admin API v1 — route gating

The admin API lives at `/v1` on the edge. Three credentials answer there, in a fixed
precedence:

1. **`Authorization: Bearer wbt_…`** — a workbook token (see blueprint §Identity,
   tokens, and scopes). When present it always wins, so agents never depend on
   cookies and browsers never hold workbook tokens.
2. **`Authorization: Bearer wbk_…`** — a user API key (see §User API keys below).
   Also a bearer credential: it wins over the cookie, and it acts as the owning
   user across every workbook they can reach — capped by the key's scope.
3. **Better Auth session cookie** — the human dashboard credential on
   `workbook.run`; handlers resolve the member directly from the session.

No credential → the caller is an **anonymous actor**. Only one route accepts
anonymous actors; everything else returns 401 `unauthenticated`.

## User API keys

`wbk_` keys are user-scoped credentials minted by their owner — not bound to any
one workbook. Management is session-only:

| Route | Anonymous | Session cookie | Bearer (token or key) | Extra gate |
| --- | --- | --- | --- | --- |
| `POST /v1/keys` | ❌ 401 | ✅ mints a key | ❌ 403 | secret returned once, `wbk_` format |
| `GET /v1/keys` | ❌ 401 | ✅ own keys | ❌ 403 | metadata only — no secret material |
| `DELETE /v1/keys/:keyId` | ❌ 401 | ✅ own keys | ❌ 403 | 404 for another user's key (existence hidden) |
| `POST /v1/keys/:keyId/rotate` | ❌ 401 | ✅ rotates own key | ❌ 403 | issues a replacement secret; grace window for the old one |

On workbook APIs a key acts as its owner with a scope ceiling:

- **`read`** — reads resolve at viewer: workbook list and reads for workbooks the
  owner can see. Writes are 403.
- **`read-write`** — reads and writes resolve at editor. Admin-gated routes
  (delete, publish, tokens, members) still refuse: keys never carry admin scopes.

Keys are rejected once revoked or expired (401), and a failed key never reveals
whether a workbook exists — the request dies at authentication with 401.

## API-key rate limits

Every request authenticated with a `wbk_` key is rate-limited per key through a
fixed one-minute window, enforced before the key itself is verified — a throttled
caller learns nothing about whether its key is valid. The default budget is 120
requests per minute per key. Deployments can override it with the
`API_KEY_RATE_LIMIT_PER_MINUTE` Worker binding; absent, malformed, or non-positive
values fall back to the default.

Exceeded budgets answer `429 Too Many Requests` with a `Retry-After` header.
Rate-limited requests are not metered and do not refresh the key's last-used
timestamp.

## Key rotation

`POST /v1/keys/:keyId/rotate` issues a replacement secret for an active key. The
endpoint is session-only: API-key authentication is rejected with 403, so a key
can never mint keys. The new version inherits the old key's scope and label;
`expiresAt` may be set independently in the request body.

The request may carry `graceSeconds` (integer, 0–604800): how long the old secret
keeps working after the new one is issued. It defaults to 86,400 (one day). At 0,
the old secret dies immediately. During the grace window both secrets
authenticate; the old one fails 401 once it lapses.

Responses: 201 with the new raw secret (revealed once) and
`oldKey.graceExpiresAt`; 404 if the key is not owned by the caller; 409 if the
key is revoked or expired — nothing to hand over.

## Usage ledger

Authenticated `wbk_` requests are recorded in the `api_key_usage` ledger,
aggregated one row per key per UTC minute with a `requestCount`. Throttled
requests are excluded. The ledger is recorded but not forwarded to Stripe: an
API-request meter must be registered as a Stripe Billing Meter (distinct
`event_name`, deterministic idempotency identifiers per the metering procedure)
before submission becomes an outcome — that registration is a separate decision.

## Feedback

Feedback is one stored list per person (ux-review HANDOFF Addendum 16): whatever
someone sends from the signed-in shell, on any screen, lands in their list, and the
shell's badge shows how many of their items are still open. All three routes are
session-only — a workbook token or API key is never a person speaking for
themselves, and embeds have no shell to send from:

| Route | Anonymous | Session cookie | Bearer (token or key) | Extra gate |
| --- | --- | --- | --- | --- |
| `POST /v1/feedback` | ❌ 401 | ✅ stores as `pending` | ❌ 403 | 30 sends per person per rolling hour → 429 with `Retry-After` |
| `GET /v1/feedback` | ❌ 401 | ✅ own items, newest first | ❌ 403 | newest 100; `hasMore` when older items exist |
| `GET /v1/feedback/count` | ❌ 401 | ✅ `{ open }` for own items | ❌ 403 | open = every status except `completed` and `rejected` |

The create body carries the person's own words (`rawText`), the summary they
checked (`title`, up to ten `bullets`), a `kind` (`bug` / `feature` / `idea`), the
screen in words (`about`) and, optionally, the app `path` it was sent from —
same-origin only, so `//host` and `/\host` are refused. Status, rejection reason and
preview URL are never client-set. Each send writes a `feedback.create` audit row.
Contracts: `packages/contracts/src/feedback.ts`.

## Credential rules per route

| Route | Anonymous | Session cookie | Bearer token | Extra gate |
| --- | --- | --- | --- | --- |
| `POST /v1/workbooks` | ✅ (creates unclaimed) | ✅ (creates free, in own account) | ✅ (creates free; a `wbk_` key creates in its owner's account) | — |
| `GET /v1/workbooks` | ❌ 401 | ✅ own account's workbooks | ✅ its workbook only; a `wbk_` key lists the owner's account workbooks | — |
| `GET /v1/workbooks/:id` | ❌ 401 | ✅ member or account owner | ✅ bound to that workbook; a `wbk_` key uses the owner's membership, capped by scope | 404 when no access (existence hidden) |
| `PATCH /v1/workbooks/:id` | ❌ 401 | ✅ editor+ | ✅ editor+ (or any admin scope); a `wbk_` key needs `read-write` and editor+ | — |
| `DELETE /v1/workbooks/:id` | ❌ 401 | owner | `admin: [delete]` (never a `wbk_` key) | `?confirm=<workbook id>` required |
| `POST /v1/workbooks/:id/claim` | ❌ 401 | ✅ session + claim token in body | ❌ 403 (tokens and keys can't claim) | unclaimed only, within claim window |
| `POST /v1/workbooks/:id/claims` | ❌ 401 | ✅ any member | ✅ bound token only (404 when bound to another workbook); a `wbk_` key mints its owner's membership, capped by scope | 503 when claims signing is unconfigured; claims are scope-faithful, 5-min TTL |
| `POST …/publish` | ❌ 401 | owner | `admin: [publish]` | unclaimed workbooks are refused |
| `POST …/unpublish` | ❌ 401 | owner | `admin: [publish]` | published only; restores the tier the workbook had before publishing (free when the publish row predates the record) |
| `PUT …/tier` | ❌ 401 | owner | any admin-scoped token | free ⇄ paid_storage only; promotion requires a payment method on file (402, degraded mode fails closed); a published workbook is refused (409) |
| `POST …/sleep` · `/wake` | ❌ 401 | editor+ | editor+ (or any admin scope) | — |
| `POST …/upgrade` | ❌ 401 | owner | any admin-scoped token | freestyle workbooks only; awake only (409 when sleeping); forces a pre-upgrade backup through the workbook VM's own API, recreates the VM from the current golden image with boot restore, and parks the workbook `sleeping` |
| `GET/POST/DELETE …/tokens` | ❌ 401 | owner | `admin: [tokens]` | mint returns the secret once |
| `POST …/exchange-keys` · `POST /exchange-keys/redeem` | ❌ 401 | editor+ / intent-gated | editor+ / intent-gated | mint opaque `exk_` connect/claim/invite codes; redeem → private token, ownership, or membership. URLs never carry `wbt_` |
| `GET/POST/DELETE …/shares` | ❌ 401 | editor+ | editor+ (or any admin scope) | mint builds the minimum read-only scope server-side; returns `wbt_` once to the minter and an `/s/<exk_…>` URL (opaque exchange alias); DELETE revokes |
| `GET/POST/DELETE …/embeds` | ❌ 401 | editor+ | editor+ (or any admin scope) | mint builds the minimum read-only scope server-side and returns the `wbt_` credential + `/p/:id?embed=` URL once; optional `expiresInHours` (≤ 8760 h); DELETE revokes and the `/p` render gate enforces it on the next request |
| `GET/PUT/DELETE …/brand` | ❌ 401 | editor+ | editor+ (or any admin scope) | the embed brand every `/p` embed paints in (spec art_zwzSQfnY); no published tier needed. PUT validates with `brandSchema` and replaces the whole brand (fields left out take defaults); a refused value answers 422 `validation_failed` with `details: { field, message }`. DELETE resets to `null` (the workbook.run look). Every write is audited as `workbook.brand` |
| `POST /v1/shares/resolve` · `POST …/shares/resolve` | ✅ (anonymous — the link's whole point) | ✅ | ✅ | swaps a live share token for its recorded scope; revoked and expired answer the same 404 |
| `POST /v1/shares/claim` | ❌ 401 | ✅ session (403 tokens — claiming attaches a human) | ❌ 403 | converts a live link into a viewer membership; 409 when already a member |
| `GET/POST/DELETE …/members` | ❌ 401 | owner | `admin: [members]` | last owner can't be removed |

## Why session vs token is split this way

- **Anonymous create** is the product's front door for agents: a create call with
  no credentials provisions an unclaimed workbook, returns its `agentToken` and
  `claimUrl` exactly once, and the claim link expires with the workbook's 72-hour
  TTL. Unclaimed workbooks can't publish (the claim route enforces it).
- **Claim is session-only** because claiming attaches a workbook to a human
  account; a token has no account to attach it to.
- **Owner routes accept admin scopes** so an owner can delegate exactly one
  administrative capability (mint tokens, manage members) without sharing the
  account.
- **Read routes accept editor tokens** so dashboards and agents can read workbook
  metadata without owner rights.
- **The claims exchange is scope-faithful, not viewer-only.** A session mints its
  `workbookAccess`-resolved role as claims (owner→`schema` preset, editor→`write`,
  viewer and `custom`→an explicit read-only table map); a token mints its own stored
  scope, re-signed per exchange so revocation at the edge is honored on every
  VM-bound request; an API key mints its owner's membership capped by the key's
  scope. Agents need the token path to address workbook VMs the edge
  does not proxy — and the raw secret still never travels past the edge.
- **Key management is session-only** because keys act as their owner everywhere:
  a key that could mint keys would have no ceiling at all.

## Error shape

Every failure is `{ error: { code, message, details?, requestId } }` with the
`ErrorCode` union from `@workbook-run/contracts` (`unauthenticated`, `forbidden`,
`not_found`, `conflict`, `validation_failed`, …). Access denials are 404 for
existence-hiding reads and 403 where the caller demonstrably has context.

## Workbook VM: spreadsheet cell history and undo

The spreadsheet cell routes run on the workbook VM (`/api/…`), where every caller
is an edge-signed claims envelope and authorization is the claims' per-sheet
`sheets` scope — not the `/v1` key hierarchy above.

| Route | Claims kind | Scope | Notes |
| --- | --- | --- | --- |
| `GET …/api/sheets/:id/cells/:row/:col/history` | any | sheets read for that sheet | Optional inclusive ISO `since`/`until` bounds on commit time; optional `?fork=` reads that branch's lineage (main's history plus the fork's own writes). |
| `POST …/api/sheets/:id/cells/:row/:col/undo` | any | sheets write for that sheet | The branch is the caller's choice: omit `?fork=` to undo on main, or name a fork to undo there — the API no longer forces a lane. Undoes are addressed by `commitHash` from the history read; the creation entry 422s (no prior state) and unknown hashes 422. |

The undo restores the target commit's pre-edit state as a NEW committed write —
cell history is append-only and never rewritten, and the write keeps the
`(sheet_id, row, col)` fork-conflict identity. All four agent surfaces (HTTP,
CLI `sheets history`/`sheets undo`, MCP `sheet_cell_history`/`sheet_cell_undo`,
TS SDK `getSpreadsheetCellHistory`/`undoSpreadsheetCell`) share the routes; the
surface-parity test in `services/vm/src/surface-parity.test.ts` enforces the
mapping.
