# API v1 contract

The detailed, field-by-field contract behind the REST API, SDKs and MCP server.

Base path: `/api/v1` (served by the existing Fastify API). `/api/rest` (the original REST API) is frozen and untouched.
Content type: JSON (`application/json`), snake_case, UTF-8. Media upload is `multipart/form-data`.

## 0. Conventions

**Auth.** `Authorization: Bearer <project token>` on every call. Existing token table and scopes are reused in wave 1: `read` (all GET), `write` (template/media/webhook changes), `render:preview` (watermarked, 720 px max), `render:final` (clean output). A preview-only token that asks for `output_mode:"final"` gets a **preview** and header `X-Render-Output: preview` (same rule as `/api/rest`).

**Request id.** Every response (all routes, v1 or not) carries `X-Request-Id`. If the caller sent a valid `X-Request-Id` (8..64 chars of `[A-Za-z0-9._-]`) it is echoed, else generated (`req_` + 20 base36).

**Errors.** v1 only. `Content-Type: application/problem+json` (RFC 9457):
```json
{
  "type": "about:blank",
  "title": "Validation failed",
  "status": 422,
  "detail": "One or more fields are invalid.",
  "code": "invalid_input",
  "request_id": "req_k3j9...",
  "param": null,
  "errors": [{ "pointer": "/fields/price", "field": "price", "code": "invalid_value", "detail": "price must be a number" }],
  "resource": { "type": "template", "id": "ospo24ysn" },
  "retryable": false,
  "retry_after": null
}
```
- `code` is a stable snake_case string. Mapping from existing codes: `INVALID_INPUT`->`invalid_input`, `bw_not_found`->`not_found`, `bw_unauthorized`->`unauthorized`, `bw_forbidden`->`forbidden`, `bw_scope_required`->`insufficient_scope`, `bw_rate_limited`->`rate_limited`, `bw_payload_too_large`->`payload_too_large`, `bw_service_unavailable`->`service_unavailable`, `bw_conflict`->`conflict`, `bw_bad_request`->`bad_request`, `bw_feature_disabled`->`feature_disabled`, `INTERNAL`->`internal_error`, render failure codes are lower-cased (`media_download_failed`, `font_load_failed`, `render_timeout`, `encoding_failed`, `storage_failed`, `cancelled`, ...). Unknown -> `internal_error`.
- `type` is `about:blank` until the docs site exists (then `https://<docs>/errors/<code>`).
- `retryable`: true for 429, 502, 503, 504 and transient render failures. `retry_after` seconds (also `Retry-After` header) for 429/503.
- Validation errors list EVERY problem (`errors[]`), each with a JSON-pointer into the request body.
- Never include stack traces, SQL, file paths, storage keys, tokens, or internal hostnames. 5xx returns only `internal_error` + `request_id`.
- Status codes: 200/201/202/204 success; 400 malformed; 401 no/bad token; 402 `insufficient_credits` (final without credit); 403 scope; 404 unknown or other-project resource; 405; 409 conflict (idempotency key in flight, stale `base_revision`, delete blocked); 413; 415; 422 validation (and idempotency-key reuse with a different body); 429; 500; 502; 503 (DB/queue down; NOT 500); 504.

**Rate limit headers.** Existing `X-RateLimit-Limit|Remaining|Reset` stay; ADD `RateLimit-Policy` / `RateLimit` (IETF draft form) on v1 responses; 429 adds `Retry-After`.

**Pagination.** Cursor based: `?limit=1..100` (default 20) `&cursor=<opaque>`. Envelope: `{ "object":"list", "data":[...], "has_more":true, "next_cursor":"..." }` (`next_cursor` null at the end). Cursors are opaque; keyset on `(created_at,id)` preferred over OFFSET.

**Idempotency.** `Idempotency-Key` (1..255 chars) on `POST /renders` and `POST /templates`. Same key + same canonical body -> original response replayed with header `Idempotent-Replayed: true`. Same key still in flight -> 409 `conflict`. Same key, different body -> 422 `idempotency_key_reused`. Retention 24 h (existing table). Scope is per token.

**Caching.** All API responses `Cache-Control: no-store`.

## 1. Discovery

### `GET /api/v1/me`
`{ "object":"account", "project":{ "id","name" }, "token":{ "id","prefix","scopes":[...],"created_at","last_used_at" }, "limits":{ "rate_per_min": 60, "max_upload_bytes": 26214400, "max_concurrent_renders": 4 }, "features":{ "video":true, "pdf":true, "bulk":true } }`

### `GET /api/v1/field-types`
`{ "object":"list","data":[{ "kind":"text","json_type":"string","description":"Free text","validation":["max_length","pattern"] }, { "kind":"image", "json_type":"string|object", ... }, ...] }` for kinds: `text, money, phone, till, color, image, select, number`. `validation` lists which constraint keys may be present on a field of that kind. (Source: scene-schema `FieldKind`.)

### `GET /api/v1/templates`
Query: `kind=poster|video|pdf` (from `templates.x_kind`), `q` (title substring), `tag`, `collection`, `listed=true|false|all` (default `true`), `limit`, `cursor`, `order=created_at|-created_at|title|-title|updated_at|-updated_at` (default `-created_at`).
Template summary:
```json
{ "object":"template","id":"ospo24ysn","kind":"poster","title":"Data bundle: weekly","description":null,
  "tags":["data","whatsapp"],"width":1080,"height":1350,"duration_ms":null,"page_count":null,
  "thumbnail_url":"https://.../files/...?exp=..&sig=..","listed":true,"revision":7,"field_count":9,
  "created_at":"2026-11-01T10:00:00Z","updated_at":"2026-11-10T08:30:00Z" }
```
`duration_ms` for video, `page_count` for pdf, else null. `thumbnail_url` may be null while regenerating.

### `GET /api/v1/templates/{id}`
Summary plus `"fields":[Field,...]` and `"instructions": string|null` (existing AI instructions).

### `GET /api/v1/templates/{id}/fields`
`{ "object":"list","data":[Field,...] }`. **Field**:
```json
{ "key":"price","label":"Price","layer":"price","property":"text","layer_type":"text","kind":"money",
  "required":true,"max_length":12,"pattern":null,"options":null,"default":"KES 100","description":"Bundle price in KES",
  "accepts":"string" }
```
- `key` is the exact string to use in `fields` when rendering. `key` = layer name when the layer has exactly one dynamic property, else `layer.property`. Special field `"$canvas"` (property `background`) for canvas colour when dynamic.
- `kind` from `FieldMeta.kind`, defaulting by layer type (text->text, picture->image, shape color->color).
- `accepts`: `string | number | color | url_or_media`. `options` (array of `{value,label}`) when `kind=select`.
- `default` is the current scene value (so the demo can pre-fill).
- Order = layer z-order/reading order.

### `GET /api/v1/library`
Original starter templates the admin can instantiate. Query `kind`, `size`, `tag`, `q`, `limit`, `cursor`. Item: `{ "object":"library_template","id","title","kind","width","height","tags","preview_url" }`. `GET /api/v1/library/{id}/preview` returns the PNG (token auth).

## 2. Media

### `POST /api/v1/media` (scope `write`)
`multipart/form-data`, field `file` (png/jpg/webp/svg/gif; max `MAX_UPLOAD_BYTES`). Returns 201 `{ "object":"media","id":"m_...","url":"https://...signed...","content_type":"image/png","bytes":12345,"width":512,"height":512,"created_at":"..." }`. SVG is sanitised (existing). The returned `id` is usable as an image field value (see 3).

## 3. Renders

### `POST /api/v1/renders` (scope `render:preview` or `render:final`)
Headers: `Idempotency-Key` (optional), `Prefer: wait=N` (optional, 1..10 seconds; honoured for `poster` only; video/pdf always return immediately).
Body (JSON), common keys: `kind` (required: `poster|video|pdf`), `output_mode` (`preview|final`, default `preview`), `webhook_url` (https only; called once on finish, signed with the project webhook secret), `metadata` (object, <=16 keys, string values <=256 chars, returned verbatim).

**poster**
```json
{ "kind":"poster","template_id":"ospo24ysn",
  "fields":{ "title":"Weekly data","price":"KES 100","logo":{"media_id":"m_8f2"},"photo":"https://example.com/a.jpg","$canvas":"#0D774D" },
  "options":{ "format":"png","width":1080,"filename":"weekly-data","color_mode":"rgb" },
  "output_mode":"preview","metadata":{"order":"1042"} }
```
**video** (one clip shorthand, or `clips`)
```json
{ "kind":"video","template_id":"abc123","fields":{ "headline":"Weekly data" },
  "options":{ "width":1080,"height":1920,"fps":25,"canvas_background":"#000000" } }
{ "kind":"video","clips":[ {"template_id":"abc123","fields":{...}}, {"template_id":"def456","fields":{...}} ], "options":{...} }
```
**pdf** (one page shorthand, or `pages`)
```json
{ "kind":"pdf","template_id":"pdf001","fields":{...},"options":{ "filename":"agent-flyer","dpi":150,"color_mode":"rgb" } }
{ "kind":"pdf","pages":[ {"template_id":"pdf001","fields":{...}}, {"template_id":"pdf002","fields":{...}} ] }
```
Rules:
- `fields` keys must be `key` values from the template's field list. **Unknown key -> 422** (stricter than `/api/rest`, which only warns). Missing `required` field -> 422. Wrong value type, `max_length`, `pattern`, `select` option -> 422. Collect all errors.
- Image field value: `"https://..."` URL (fetched through the SSRF-safe fetcher) or `{"media_id":"m_..."}`. Colour: `#RGB|#RRGGBB|#RRGGBBAA`. Number: JSON number. `kind` money/phone/till: string, formatted server-side exactly as `/api/rest` does.
- `options` keys by kind: poster `format(png|jpg|webp|auto) width height filename color_mode`; video `width height fps(1-30) canvas_background`; pdf `filename dpi(96|150|300) color_mode`. Unknown option -> 422.
- Mapping to existing code: `poster`->`createImageJob`, `video`->`createVideoJob`, `pdf`->`createPdfJob`. `fields` are translated to the REST `layers` structure via each field's `layer`/`property`; no second render path.
- Response: **200** when the render finished within the `Prefer: wait` window, **202** otherwise. Both carry the Render body and `Location: /api/v1/renders/{id}`; 202 also carries `Retry-After: 2`.

### Render object
```json
{ "object":"render","id":"123","kind":"poster","status":"succeeded","template_id":"ospo24ysn",
  "output_mode":"preview","progress":100,
  "outputs":[{ "format":"png","url":"https://.../files/...?exp=..&sig=..","expires_at":"2026-11-11T12:05:00Z",
               "bytes":184233,"width":1080,"height":1350,"duration_ms":null,"pages":null,"content_type":"image/png" }],
  "error":null,"metadata":{"order":"1042"},
  "created_at":"...","started_at":"...","finished_at":"...","polling_url":"https://<host>/api/v1/renders/123" }
```
- `status`: `queued | processing | succeeded | failed | cancelled` (mapping from jobs: queued->queued, running->processing, finished->succeeded, error->failed, cancelled->cancelled).
- `progress`: 0..100 or null.
- `error` (failed only): `{ "code":"media_download_failed","detail":"...","retryable":true,"layers":[{"field":"photo","detail":"Could not download image"}] }`.
- `outputs` empty until succeeded. URLs are signed and short lived: **call `GET /renders/{id}` again to mint a fresh URL**. `expires_at` is always present.

### Other render endpoints
- `GET /api/v1/renders/{id}` (scope `read`) -> Render.
- `GET /api/v1/renders` (scope `read`): filters `kind`, `status`, `template_id`, `created_after`, `created_before`, `limit`, `cursor`; list envelope; newest first.
- `POST /api/v1/renders/{id}/cancel` (scope `render:*`): queued -> cancelled immediately; running -> best effort (`cancel_requested`); finished -> 409 `conflict`. Returns the Render.
- `DELETE /api/v1/renders/{id}` (scope `write`): deletes the job and its stored output; 204.

**Renders: resolved ambiguities (implementation notes).**
- `metadata` is stored in the job's `passthrough` column (no migration); the shared job services cap it at 1024 JSON characters in total, so v1 enforces that on top of 16 keys / 256 chars per value. Response `metadata` is `{}` when none was sent.
- A body reference that does not resolve (unknown or other-project `template_id`, `media_id`, wrong template kind) is a 422 `invalid_input` with code `template_not_found` / `media_not_found` / `template_kind_mismatch` in `errors[]` (404 is only for path resources). A template's kind must equal the render `kind`.
- A bad body reports shape errors and field errors in the same response (one pass).
- Response is 200 for any terminal state reached inside the wait window (including `failed`), 202 otherwise; `Prefer: wait` above 10 is clamped to 10 and answered with `Preference-Applied: wait=N`.
- Cancel: the existing queue cancels a `running` job at once (status `cancelled`, the worker stops at its next check) instead of `cancel_requested`; cancelling an already cancelled render returns 200, a finished or failed one 409.
- Idempotency replays return the render's CURRENT state (not a frozen copy); keys are per project (existing table), and v1 never writes `jobs.idempotency_key`.
- Extra fields on the Render object: `warnings[]` (`{field, detail}`, e.g. forced to preview) and, for video outputs, `outputs[0].thumbnail_url`. `outputs[0].pages` for pdf is read from the stored file (cached per render).
- A `preview` PDF is rasterised (watermarked) and has no selectable text; a `final` PDF has selectable text.

## 4. Template management (scope `write`)

- `POST /api/v1/templates` -> 201 Template. Body: `{ "title", "kind":"poster|video|pdf", "width"?, "height"?, "tags"?, "description"?, "listed"?, "scene"? | "library_id"? }`. Exactly one of `scene` (scene-schema `SceneDoc`), `library_id`, or none (blank). The scene is validated with the shared zod schema; kind must be consistent with the scene (a video scene needs a timeline etc.), otherwise 422 with pointers.
- `PUT /api/v1/templates/{id}/scene` -> 200 Template. Body `{ "scene":{...}, "base_revision": 7 }`. Stale `base_revision` -> 409 `conflict` with `detail` showing the current revision.
- `PATCH /api/v1/templates/{id}`: `title, tags, description, listed, kind`.
- `DELETE /api/v1/templates/{id}` -> 204. Existing rule: block (409) if referenced where the existing delete rules block.
- `GET /api/v1/templates/{id}/scene` (scope `read`) -> `{ "scene":{...}, "revision": 7 }` so an admin can export/edit.
- Reuse the existing studio services in `services/templates` etc.; do not duplicate logic. DB change: migration `0018_template_listed.sql` adds `templates.listed boolean not null default true` and `templates.description text`.

## 5. OpenAPI

`GET /api/v1/openapi.json` (no auth) serves OpenAPI 3.1 generated from the same zod schemas used for validation; also checked in at `docs/integration/openapi.v1.json` with a drift test. Error responses use a shared `Problem` schema; security scheme `bearerAuth`.

## 6. Not in wave 1 (next waves)

Webhook subscription management on v1 + Standard Webhooks headers + `render.failed` event (wave 2); per-key concurrent-render and queue-depth caps, audit log, retention sweeper, CORS opt-in (wave 2); `POST /renders/batch`, API key management endpoints (wave 2); OAuth for hosted MCP (phase 2).

## 7. Acceptance for wave 1

1. All endpoints above exist, covered by `apps/api/test/v1-*.test.ts` (auth, scopes, project isolation, validation, errors shape, request id, pagination, idempotency).
2. Real renders through v1: one poster (PNG decodes at expected size), one video (ffprobe: h264, expected duration/fps), one PDF (page count, text selectable) using library templates; output bytes verified in tests or in a recorded script run.
3. `/api/rest` golden + contract suites still green (`pnpm gate`).
4. OpenAPI valid 3.1 and drift test green.

## 8. Implementation notes (foundation, resolved ambiguities)

- Field `property` is the REST property name of the layer (`text`, `text_color`, `background_color`, `image`), so `fields` translate 1:1 to `layers`; the canvas is layer `$canvas` with `background_color` / `image` (not `background`). One scene field key can expose several properties (e.g. `border` -> `border_color`, `border_width`); each is its own field, so such a layer uses `layer.property` keys.
- Field validation codes in `errors[].code`: `unknown_field`, `required`, `invalid_type`, `invalid_value`, `too_long`, `pattern_mismatch`, `invalid_option`, `kind_mismatch`, `conflicting_fields`, `stale_revision`. `null` for a field means "use the template default" and does NOT satisfy `required`. A `money` field also accepts a JSON number.
- Media ids are `m_` + the 32 hex digits of the media uuid; `{"media_id"}` becomes the internal `asset:<uuid>` ref and is ownership-checked by the existing render path.
- Library items always have `kind:"poster"`; `size` is a size preset id; `preview_url` is absolute and needs the bearer token; `GET /library/{id}/preview?size=<preset>`.
- Template kind vs scene (create, PUT scene, PATCH kind): poster = no fps/audio/animation and one page; video = has `canvas.fps`, audio or layer timing/animation; pdf = has `pages`, no video features. Mismatch -> 422 `kind_mismatch`.
- `DELETE /templates/{id}` never returns 409 today: the existing rules (Studio and /api/rest) do not block a template delete (jobs keep history, links cascade).
- Idempotency rows are per project (existing table), not per token. `POST /templates` replays the current state of the created template (not a stored byte copy). Migration 0018 also adds `resource_type`/`resource_id` to `idempotency_keys` for this. A reused key on the render path surfaces as 422 `idempotency_key_reused` (mapped from the shared job inserter).
- Rate limit bucket for v1 is separate from /api/rest (`v1:tok:<id>`), same limits. A route can override its scope with Fastify `config: { v1Scope: [...] }`; default is `read` for GET/HEAD, `write` otherwise.
- 405 is not produced separately: an unmatched method is a 404 `not_found`.
- OpenAPI is generated by `routes/v1/openapi.ts` from `routes/v1/schemas.ts` (zod `toJSONSchema`); regenerate the checked-in file with `WRITE_OPENAPI=1 npx vitest run test/v1-foundation.test.ts` from apps/api.

## 9. Webhooks (wave 2)

Subscriptions are managed with the token API (scope `read` for GET, `write` for the rest). Implementation: `routes/v1/webhooks.ts`, `services/v1/webhook-events.ts`, migration `0019_webhooks_v1.sql`; sent by the shared dispatcher (`services/webhooks.ts`). Included in the generated OpenAPI file.

| Endpoint | Result |
|---|---|
| `GET /webhooks` | list envelope (cursor), newest first |
| `POST /webhooks` | 201 Webhook **with `secret`** (the only time besides rotate). Body `{url, events?, description?, active?}`; `events` default = all three below; max 100 per project |
| `GET /webhooks/{id}`, `PATCH /webhooks/{id}` (`url, events, description, active`), `DELETE /webhooks/{id}` (204) | `active:true` on a disabled endpoint clears `disabled_at` and the failure streak |
| `POST /webhooks/{id}/rotate-secret` | 200 Webhook with the new `secret`; the old one stays valid 24 h (`previous_secret_expires_at`) |
| `POST /webhooks/{id}/test` | 202 Delivery of a `webhook.test` event (1 attempt); 409 while the endpoint is disabled |
| `GET /webhooks/{id}/deliveries` | list (cursor), filters `status`, `type` |
| `POST /webhooks/{id}/deliveries/{delivery_id}/replay` | 202 new Delivery (`replay_of`), same `event_id` / `webhook-id`; 409 while disabled |

**Webhook**: `{object:"webhook", id, url, events, description, active, disabled_at, disabled_reason ("endpoint_gone"|"sustained_failure"|null), failure_streak, last_delivery_at, last_status, previous_secret_expires_at, created_at, updated_at}`. **Delivery**: `{object:"webhook_delivery", id, webhook_id, event_id, type, render_id, status (pending|delivering|delivered|failed), attempts, max_attempts, next_attempt_at, response_status, response_snippet (<=512 chars), duration_ms, error, replay_of, created_at, delivered_at}`.

**URL policy** (create and patch, 422 with pointer `/url`): `https` only; `http` only with the dev flag `WEBHOOK_ALLOW_PRIVATE`. Host must resolve to public addresses only (loopback, private, link-local, metadata `169.254.169.254` are rejected, codes `blocked_address`, `insecure_scheme`, `invalid_url`, `dns_failed`) via the shared SSRF-safe resolver in `packages/security`. Delivery uses the same fetcher: no redirects followed, 10 s timeout.

**Events** (`events[]`): `render.completed`, `render.failed`, `render.cancelled`. Envelope, under 20 KB, outputs as links (fresh signed URL on every attempt):
```json
{ "id":"evt_123_completed", "type":"render.completed", "created_at":"2026-11-11T12:00:00Z",
  "data":{ "render": { "object":"render", "id":"123", "status":"succeeded", "outputs":[{"format":"png","url":"https://...","expires_at":"..."}], "error":null, "metadata":{}, "...":"the v1 Render object" } } }
```
`id` is stable per render and type (retries and replays reuse it): **receivers dedupe on `webhook-id`**. Test events: `type:"webhook.test"`, `data:{test:true, render:{sample}}`.

**Headers on every delivery**: Standard Webhooks `webhook-id`, `webhook-timestamp` (unix s), `webhook-signature: v1,<base64 HMAC-SHA256 of "id.timestamp.rawbody">`; key = base64 decode of the secret after `whsec_`. During a rotation overlap the header holds two signatures separated by a space. Reject timestamps more than 5 minutes off. The existing `X-Render-Signature: t=,v1=<hex>` (extra `,v1=` for the previous secret), `X-Render-Delivery-Id` and `X-Render-Event` stay. A standalone verifier/sink: `tests/api-v1/webhook-sink.mjs`.

**Delivery**: 6 attempts, exponential backoff with jitter; 4xx other than 408/429 is permanent. Endpoints created through v1 are auto-disabled (`active:false`, `disabled_at`, `disabled_reason`) on an HTTP `410` or after about 3 days of consecutive failure (env `WEBHOOK_AUTO_DISABLE_AFTER_MS`); any success resets the streak.

**Per-request `webhook_url`** on `POST /renders`: gets the same envelope and Standard headers for completed, failed and cancelled, signed with the project webhook secret (`render.jobs.api_version = 1` marks these jobs). `/api/rest` jobs (`webhook_success`) keep the old body (plus the Standard headers; `webhook-id` = the delivery id) and only fire on finish. Subscriptions created through v1 receive the events of every non-system render in the project, whatever API created it.

## 10. Protection and operations (wave 2)

All of this is `/api/v1` only; `/api/rest` is unchanged (it ignores token expiry, CORS lists, caps and the audit log).

**Env vars** (all optional): `RENDER_MAX_CONCURRENT_PER_TOKEN` (4), `RENDER_MAX_QUEUED_PER_PROJECT` (50), `RENDER_DAILY_COST_CAP` (0 = off), `RETENTION_OUTPUT_DAYS` (30), `RETENTION_JOB_DAYS` (90), `AUDIT_LOG_RETENTION_DAYS` (90), `RETENTION_DRY_RUN` (false), `RETENTION_BATCH_SIZE` (200). A retention value of 0 switches that step off. Migration `0020_limits_audit.sql`.

**Caps on `POST /renders`** (checked after validation, before anything is created; real `render.jobs` rows are counted, so a cancel or a finished render frees the slot at once; idempotent replays are not counted):
- in-flight (queued + running) renders per API key > `RENDER_MAX_CONCURRENT_PER_TOKEN`, or queued renders per project > `RENDER_MAX_QUEUED_PER_PROJECT`: `429 concurrency_limit_reached` with `Retry-After` and `retry_after` (5 s per key, 10 s per project), `retryable: true`.
- Cost units: poster 1, video 10, pdf 2 per started group of 10 pages (`jobs.cost_units`). When `RENDER_DAILY_COST_CAP` > 0, a key whose UTC-day total would exceed it gets `429 daily_cost_cap_reached`; `Retry-After` = seconds to 00:00 UTC. On several API replicas the caps are soft by the size of a burst.

**Headers.** Every authenticated v1 response (success or error, including 403 and 429) carries `X-RateLimit-*`, `RateLimit-Policy: <limit>;w=<window>` and `RateLimit: limit=, remaining=, reset=`. Unauthenticated responses (401, unmatched route, openapi.json) have no limit and so no such headers.

**Token expiry.** Studio token create/PATCH accept `expires_at` (ISO 8601, future; `null` clears). An expired key gets `401 token_expired` on v1 (not retryable); `/api/rest` ignores it.

**CORS, opt-in per key.** Studio token create/PATCH accept `allowed_origins`: up to 20 exact origins, `https://host[:port]` or `http://localhost[:port]` (no wildcard, path or credentials); `null`/`[]` = off. With no list, v1 sends no CORS headers at all. With a list: a preflight (`OPTIONS` with `Origin` + `Access-Control-Request-Method`) is answered `204` when some live key lists that origin (a preflight carries no credentials, so the key cannot be identified; unlisted origin = the normal 404, no headers); on real requests `Access-Control-Allow-Origin` is added only when the authenticated key lists the caller's `Origin` (also on its error responses). Allowed headers: `Authorization, Content-Type, Idempotency-Key, Prefer, X-Request-Id`; exposed: `X-Request-Id, RateLimit, RateLimit-Policy, X-RateLimit-*, Retry-After, Location`; no credentials mode. A 401 for an unknown key cannot carry CORS headers.

**Audit log.** One row per v1 request in `render.api_audit_log` (token, project, method, route *pattern*, status, ip, request id, `bytes_in`, `duration_ms`), written fire-and-forget after the response (a logging failure never affects a request; no bodies, headers, query strings or tokens are stored; unmatched routes are `(unmatched)`). Pruned after `AUDIT_LOG_RETENTION_DAYS`.
`GET /api/v1/audit-log` (scope `read`, own project only): list envelope, newest first. Filters: `status` (`404` or class `4xx`), `route` (exact pattern, or prefix with a trailing `*`, e.g. `/api/v1/renders*`), `since` (ISO 8601), `limit`, `cursor`. Item: `{ "object":"audit_entry","id","token_id","method","route","status","ip","request_id","bytes_in","duration_ms","created_at" }`.

**Retention sweeper** (hourly maintenance, batched, `RETENTION_DRY_RUN` only counts and logs): finished outputs older than `RETENTION_OUTPUT_DAYS` are deleted from storage and the job is marked `output_expired_at`; job rows older than `RETENTION_JOB_DAYS` are soft-deleted (their output is removed first). Only finished/failed/cancelled jobs are ever touched (queued and running never), and URL-API jobs and system thumbnails are skipped. Previews keep their 7-day storage TTL.
Decision for an expired output: the job is **not** gone. `GET /renders/{id}` stays `200`, `status: "succeeded"`, `outputs: []`, `error: null`, plus `outputs_expired: true` and `outputs_expired_at` (fields exist only on expired renders). Clients that need the file must download it before `RETENTION_OUTPUT_DAYS`. A soft-deleted job row answers `404` like any deleted render.

**DB down.** A transient database failure on any v1 route (auth lookup or handler) is `503 service_unavailable`, `Retry-After: 2`, `retryable: true`; a real bug stays `500 internal_error`.

New codes: `concurrency_limit_reached` (429), `daily_cost_cap_reached` (429), `token_expired` (401).

## Changelog

- 2026-11-11: `GET /api/v1/me` reports real `limits.max_concurrent_renders` (`RENDER_MAX_CONCURRENT_PER_TOKEN`, default 4 instead of `null`); completed `openapi.v1.json` with `/webhooks*` and `/audit-log` endpoints, header parameters, response headers, problem codes (`kind_mismatch` et al.), discriminated `RenderCreate`, and `poster`/`video`/`pdf` request/response examples (breaking: no).
- 2026-11-11: T6 OAuth 2.1 (behind `FEATURE_OAUTH`, default off): `/api/v1` additionally accepts `oa_` OAuth access tokens whose audience is `MCP_PUBLIC_URL` (or `MCP_PUBLIC_URL/{project_id}`) and whose user still owns the project; added internal `GET /api/v1/mcp/config` (flag-gated, not in openapi.v1.json); `/oauth/*` endpoints documented in `OAUTH.md`. API keys unchanged (breaking: no).
