# Spoonity CMS API

Spoonity CMS is the content-management and delivery system vendor teams use to publish dynamic
content — banners, promos, onboarding slides, FAQs and more — into their branded apps and web
properties. Two audiences call this API: **vendor operators and integrations** (dashboard users,
CI jobs, agents) manage content, spaces, media, experiments and webhooks through the management
API; and **the vendor's own end-user-facing apps** fetch published content at runtime through the
public, unauthenticated Content Delivery API. Almost everything under `/api/v1` other than content
delivery, remote app config, tracking and experiment conversions requires authentication and is
scoped to one vendor.

**Base URL:** `https://cms.spoonity.com` — all management, delivery and tracking routes below are
mounted under `/api/v1`. A Cloud Run domain mapping fronts the underlying
`https://spoonity-cms-285397558465.us-central1.run.app`, which still answers directly; prefer the
branded host. Local development runs at `http://localhost:3700`. `https://content.spoonity.com` is
the CMS MCP server, not an API base URL: it forwards some paths to this service, but integrations
should call `cms.spoonity.com`. Uploaded media is served from `https://media.spoonity.com`.

**Rate limits:** the management API (spaces, blocks, media, experiments, analytics, webhooks,
users, search, activity, vendor settings, api-keys, brand, targeting lookups, legacy content
import) is limited to 100 requests/min/IP by default (`RATE_LIMIT_API_RPM`); the Content Delivery,
remote App Config, and Tracking APIs get a higher budget of 500 requests/min/IP
(`RATE_LIMIT_DELIVERY_RPM`); `POST /api/v1/auth/login` and `POST /api/v1/auth/select-vendor` are
limited to 10 requests/min/IP. All three send standard `RateLimit-*` headers and a `429` with
`{ "error": "rate_limit", "message": "..." }` when exceeded.

The management limiter is mounted once per router, and several routers share the bare `/api/v1`
prefix, so one request can be counted more than once as it falls through them. A request to
`/media`, `/analytics`, `/experiments`, `/users`, `/brand`, `/activity`, `/search`, `/lookups`,
`/webhooks`, `/vendor/api-keys` or `/blocks/{id}/rules` costs about 3 units; the Translations routes
cost 4; `/auth/*`, `/vendor/settings` and `/vendor/api-key/*` cost 5; `POST /spaces/{spaceId}/blocks`,
`PUT /spaces/{spaceId}/reorder` and the legacy import cost 2; the other `/spaces` routes and
`/blocks/{id}` cost 1. The effective per-minute budget on a route is the limit divided by its cost,
so plan for about 20 requests/min/IP on `/vendor/settings`, for example.

**Versioning:** every request is implicitly `v1`. Send `Accept-Version: v1` to be explicit — no
other value is currently recognized, and an unrecognized value silently falls back to `v1` rather
than erroring. Every response carries `X-API-Version: v1`.

**Timestamps:** datetime fields accept ISO 8601 on input (`2026-07-28T15:04:05.000Z`) and are
returned as `'YYYY-MM-DD HH:MM:SS'` (UTC, space separator, no `Z`). The one exception is the
preview-token `expires_at`, a JWT expiry computed in-process and returned as true ISO 8601.

**Errors:** most error responses are `{ "error": "<machine_code>", "message": "<human text>" }`.
Several routes omit `message` entirely and return bare `{ "error": "<machine_code>" }`: every error
in the Webhooks group except the URL rejections, which carry a `message` (`invalid_events` and
`not_found` stay bare; see [Webhook URL rules](#webhook-url-rules)); every
Personalization error except `missing_fields`; the 404 on `DELETE /users/{id}`; the 404 on
`GET /translations/coverage/{spaceId}`; the Experiments `already_running` and `not_running` 400s;
and every Experiments `404 not_found` except the one on `GET /experiments/{id}` (so
`PUT /experiments/{id}`, `POST /experiments/{id}/start`, `POST /experiments/{id}/stop`,
`POST /experiments/{id}/winner`, `DELETE /experiments/{id}` and the public
`POST /experiments/{id}/convert`). These are called out because they deviate
from the shape used everywhere else.

## Authentication

CMS accepts three credential types, checked in this order by every authenticated route.

### 1. Dashboard JWT sessions

`Authorization: Bearer <jwt>`. Issued by `POST /auth/login` (→ `/auth/select-vendor` for a
multi-vendor user, or auto-completed for a single-vendor one), or re-scoped to another vendor with
`POST /auth/switch-vendor`. A JWT session carries no `scopes` array, so it has **full scope
access** to every resource — scope checks exist only to narrow what an *API key* can do, never a
signed-in human. What a JWT session may *do* is bounded by its `role` (`admin` | `editor` |
`viewer`), looked up from `vendor_users` at login time. An email with no `vendor_users` row for the
vendor gets `admin`, so a vendor's first user is an admin by default.

### 2. Scoped API keys

`X-API-Key: sck_<64 hex chars>`. Minted per-vendor via `POST /vendor/api-keys` (dashboard session
only — see [Vendor Settings & API Keys](#vendor-settings--api-keys)). A key carries:

- a **scopes array**, drawn from a fixed vocabulary and checked against the resource's scope area:

  | Scope | Gates |
  |---|---|
  | `content:read` / `content:write` | Spaces, Blocks, Personalization rules, Translations |
  | `media:read` / `media:write` | Media assets |
  | `analytics:read` | Analytics (read-only resource; there is no `analytics:write`) |
  | `experiments:read` / `experiments:write` | Experiments |
  | `webhooks:read` / `webhooks:write` | Webhooks |
  | `vendor:read` / `vendor:write` | Vendor settings, legacy API key status/rotation, Brand |
  | `*` | Every scope |

  A `:write` scope implicitly grants the matching `:read`. The required scope is derived from the
  HTTP method: `GET`/`HEAD` need `<area>:read`, everything else needs `<area>:write`. **Not every
  resource enforces this.** `GET /activity`, `GET /search`, all of `GET/POST/DELETE /users`,
  `GET /auth/me`, `POST /auth/switch-vendor`, `GET /links/search` and `GET /vendor/links-domain` run
  with no `requireScope` check at all, so any authenticated key (any scope, or none) can reach
  them; only their `role` requirements (where present) gate access. The Targeting Lookups routes
  go the other way: they check a `spaces` scope that is not in the mintable vocabulary, so only a
  `*` key can reach them (see [Targeting Lookups](#targeting-lookups)).
- an optional **role** (`admin` | `editor` | `viewer`), which only an admin dashboard session may
  grant at mint time. A **roleless** key can draft content (create/update spaces, blocks,
  translations, personalization rules — anything gated by scope alone) but is rejected by every
  `role`-gated action (publish, approve, delete, manage team members, etc.).

### 3. Legacy vendor-wide API key

`X-API-Key: <key>`. A single, unscoped key stored directly on the vendor row (rotated via
`POST /vendor/api-key/rotate`, a dashboard-session-only route). It authenticates as
`scopes: ['*']` and `role: 'admin'` — full read/write access to everything for that vendor, with no
per-resource scoping. It carries the same `sck_` prefix as a scoped key, so the prefix alone does not
tell the two apart. Prefer a named scoped key for new integrations; the legacy key exists for
vendors that provisioned before scoped keys shipped.

### 4. Service-to-service (not a public integration path)

A Google-signed OIDC ID token in `Authorization: Bearer <id_token>` from a Google Cloud service
account on a server-side allowlist (`TRUSTED_SERVICE_ACCOUNTS`), plus a required
`X-Spoonity-Vendor: <spoonity_vendor_id>` header to select the tenant (vendors are
auto-provisioned on first call). This exists for Spoonity-operated infrastructure (e.g. an internal
MCP server) — it is not something a vendor integrator configures, and it is not documented further
here.

### Vendor context

Every management request needs a resolved vendor: a JWT session carries `vendorId` in its payload,
an API key resolves it from the row it was minted against, and a service token resolves it from
`X-Spoonity-Vendor`. A request that authenticates but resolves no vendor gets `403 forbidden`
(`"No vendor context. Authentication required."`).

---

## Content Delivery API

This is the **public read surface** — the one vendor-integrator apps actually hit at runtime to
render content. No authentication, no vendor scoping headers: the vendor and space are named
directly in the URL. Responses are cacheable (`ETag` + `Cache-Control: public, max-age=…`) and
rate-limited at the higher 500 req/min/IP delivery budget.

**Surviving a database outage.** Both endpoints below serve from an in-process "last-known-good"
cache when the database is unreachable, instead of a bare `500`: the most recent successful
response for the exact same request (vendor, space, every query parameter, `X-Spoonity-User`, and
the experiment `client_id`) is replayed with `X-Content-Stale: true`, `X-Content-Stale-Age: <seconds
since it was cached>`, and `Cache-Control: no-store` — no `ETag`, so a stale response can never be
revalidated into a `304` and pinned in a client cache. The response body also carries `"_stale":
true` and `"_stale_age_seconds": <n>`. A request whose exact shape has never been served
successfully (or whose cached entry has aged past 24h) gets a `503` with `Retry-After: 5` instead —
never an invented empty content payload, which would tell an app "this vendor has no content" and
get cached as such. This never affects the happy path: every request still queries the database and
gets fully fresh content; the cache is consulted only on a database error, and a preview-token
request is never cached or replayed. A genuine application bug still surfaces as a `500` — only a
database-connectivity failure degrades.

### GET /content/{vendorSlug}

List every currently-published space for a vendor (used by apps to discover available content).
Only spaces with `status: published` inside their `start_at`/`end_at` window are listed, ordered by
`priority` descending. The response sends `Cache-Control: public, max-age=60, s-maxage=300` and a
weak `ETag`.

**Auth:** None — public.

**Path parameters:**

| Name | Type | Description |
|---|---|---|
| `vendorSlug` | string | The vendor's slug, e.g. `acme-cafe`. |

**Query parameters:**

| Name | Type | Description |
|---|---|---|
| `platform` | string | One of `all, app, web, mobile_web, desktop_web, watch, tv, car`. `mobile_web`/`desktop_web` also match spaces tagged `web`; a plain `web` request only matches `web` (never a sub-channel-only space). |
| `category` | string | Filter by space `category`. |
| `region` | string | Filter by space `region` (spaces with no region always match). |
| `daypart` | string | Filter by space `daypart` (spaces with no daypart always match). |
| `tags` | string | Comma-separated tag list; a space matches if it has any of the listed tags. |

**Request example:**

```bash
curl "https://cms.spoonity.com/api/v1/content/acme-cafe?platform=app&category=promotion"
```

**Response example:**

```json
{
  "spaces": [
    {
      "id": 42,
      "name": "Summer Promo",
      "slug": "summer-promo",
      "platform": "app",
      "description": "Iced drinks banner",
      "published_at": "2026-06-01 14:00:00",
      "category": "promotion",
      "campaign_id": "summer26",
      "tags": ["seasonal", "lto"],
      "priority": 10,
      "region": null,
      "daypart": null,
      "default_locale": "en-CA",
      "start_at": null,
      "end_at": null,
      "block_count": 3,
      "targeting": {
        "region": null,
        "daypart": null,
        "store_ids": null,
        "audience": null,
        "min_visits": null,
        "max_visits": null,
        "active_hours": null,
        "active_days": null
      }
    }
  ],
  "vendor": { "name": "Acme Cafe", "slug": "acme-cafe" }
}
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 404 | not_found | No vendor with that slug |
| 503 | service_unavailable | Database unreachable and nothing cached for this vendor yet (`Retry-After: 5`) |

### GET /content/{vendorSlug}/{spaceSlug}

Fetch one space's published content: blocks, resolved against scheduling, targeting, dayparting,
audience segmentation, running A/B/n experiments, translation overlays and personalization rules.
This is the single most important endpoint in the CMS API — it is what a rendered app screen calls.

**Auth:** None — public. Optional `X-Spoonity-User` header lets the CMS resolve verified audience
context (loyalty tier, visit count, segments) server-side against the Spoonity platform when
configured; when it isn't, or resolution fails, client-declared query params are used instead
(content availability never depends on the loyalty API being reachable).

**Path parameters:**

| Name | Type | Description |
|---|---|---|
| `vendorSlug` | string | The vendor's slug. |
| `spaceSlug` | string | The space's slug. |

**Query parameters:**

| Name | Type | Description |
|---|---|---|
| `platform` | string | Channel filter — see the list endpoint above for umbrella-matching semantics. |
| `device_type` | string | `phone`, `tablet`, or `desktop`. Drives `device_type` personalization rules only — never filters which blocks are returned. |
| `locale` | string | Preferred locale, e.g. `fr-CA`. Overlays a block's translation for that locale when one exists and differs from the space's default. |
| `region` | string | Region filter (blocks/spaces with no region always match). |
| `store_id` | string | Store-level targeting filter. |
| `local_time` | string | Client local time `HH:mm`, used for `active_hours` dayparting. |
| `timezone` | string | Client timezone — informational only, not currently applied server-side. |
| `daypart` | string | Explicit daypart filter and personalization-rule input. |
| `loyalty_tier` | string | Client-declared loyalty tier (overridden by `X-Spoonity-User` resolution when available). |
| `visit_count` | integer | Client-declared visit count (same override behavior). |
| `segments` | string | Comma-separated Spoonity segment ids (same override behavior). |
| `country` | string | Drives `country` personalization rules only. |
| `client_id` | string | Stable per-client id for deterministic experiment bucketing (hashed modulo 100). May also be sent as the `X-Client-Id` header. |
| `fallback` | string | `false` disables graceful fallback resolution — an eligibility miss returns a plain `404` instead of trying the space's own or the vendor's default fallback. |
| `preview_token` | string | A JWT from `POST /spaces/{id}/preview-token`. Bypasses status/window/targeting eligibility entirely for the exact space it was minted for; an invalid/expired/mismatched token is a hard `401`, never a silent fallback to the published view. |

**Request example:**

```bash
curl "https://cms.spoonity.com/api/v1/content/acme-cafe/summer-promo?platform=app&locale=fr-CA&loyalty_tier=gold"
```

**Response example:**

```json
{
  "space": {
    "name": "Summer Promo",
    "slug": "summer-promo",
    "platform": "app",
    "published_at": "2026-06-01 14:00:00",
    "category": "promotion",
    "campaign_id": "summer26",
    "tags": ["seasonal", "lto"],
    "priority": 10,
    "region": null,
    "daypart": null,
    "default_locale": "en-CA",
    "start_at": null,
    "end_at": null,
    "targeting": { "region": null, "daypart": null, "store_ids": null, "audience": null, "min_visits": null, "max_visits": null, "active_hours": null, "active_days": null }
  },
  "blocks": [
    {
      "id": 101,
      "block_type": "hero_banner",
      "title": "Cold Brew Season",
      "subtitle": "Now $2 off",
      "body": null,
      "image_url": "https://media.spoonity.com/abc123_opt.webp",
      "background_url": null,
      "video_url": null,
      "poster_url": null,
      "image_asset": { "width": 1920, "height": 1080, "variants": { "thumb": { "url": "https://media.spoonity.com/abc123_thumb.webp", "width": 200, "height": 113 } } },
      "cta_text": "Order now",
      "cta_url": "https://links.spoonity.com/x7Qp9",
      "cta_deeplink": null,
      "cta_link_id": "88",
      "config": {},
      "platform": null,
      "sort_order": 0,
      "tags": [],
      "menu_item_id": null,
      "region": null,
      "store_ids": [],
      "audience": {},
      "_locale": "fr-CA"
    }
  ],
  "vendor": { "name": "Acme Cafe", "slug": "acme-cafe" },
  "_locale": "fr-CA",
  "_tracking": { "endpoint": "/api/v1/track/acme-cafe", "space_id": 42, "campaign_id": "summer26" },
  "_user_context": "declared"
}
```

Other response markers: `_fallback: true` and `_fallback_for: "<requested slug>"` on a fallback
serve; `_personalization: [{ field, rule_id, label }]` on a block where a personalization rule fired;
`_preview: true` on a preview-token serve, where non-published blocks also carry `_status`.
`_user_context` is `verified` or `declared`, and is omitted when neither source supplied audience
context. The response sends an `ETag` and `Cache-Control: public, max-age=<space cache_ttl, default
60>, stale-while-revalidate=30` (max-age at most 30 for a fallback serve); a matching
`If-None-Match` gets a `304`. When the request carries `X-Spoonity-User`, the response adds
`Vary: X-Spoonity-User`. A preview serve is `Cache-Control: no-store, private` with no `ETag`.

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 401 | invalid_preview_token | `preview_token` is malformed, expired, or minted for a different space |
| 404 | not_found | Unknown vendor/space, or the space failed eligibility with no fallback available |
| 503 | service_unavailable | Database unreachable and nothing cached for this exact request shape yet (`Retry-After: 5`) |

---

## Remote App Configuration

> **Editor entry hidden as of 2026-11-19.** The Spaces-page "Remote config" shortcut and the `app_config` entry in the block palette are hidden in the dashboard and in Prism. The server, `GET /api/v1/app-config`, block validation, MCP, the `AppConfigForm` (for existing blocks opened from a space) and the block labels/icons are unchanged. Remote config and switches are managed in Spoonity Flags (Prism -> Flags) and via MCP `cms_set_app_config`.

A convenience read endpoint for apps that want one small, cacheable document describing runtime
config (API host, feature flags, legal/support links, theme, minimum app version) instead of
walking the general Content Delivery API for it. Backed by a reserved content space (slug
`app-config`) holding exactly one `app_config` block — see [Content Blocks](#content-blocks) below
for that block type's full field schema and how it's provisioned.

### GET /app-config/{vendorSlug}

Fetch the vendor's published `app_config`, plus a computed app-update status for the calling app's
version. Serves only from a *published* `app-config` space with a *published* `app_config` block —
a draft/half-edited config never reaches a production app, the same rule the content-delivery
endpoints enforce.

**Auth:** None — public.

**Path parameters:**

| Name | Type | Description |
|---|---|---|
| `vendorSlug` | string | The vendor's slug. |

**Query parameters:**

| Name | Type | Description |
|---|---|---|
| `version` | string | The calling app's own version (semver `X.Y.Z`), compared against `app_version.min_version`/`latest_version` to compute `update.status`. Omitted or unparseable → always `"open"`. |

Responses are `ETag`'d (derived from the config content and its update timestamp) and cacheable —
`Cache-Control: public, max-age=<space's cache_ttl, default 60>, stale-while-revalidate=30`; a
matching `If-None-Match` gets a `304`.

**Request example:**

```bash
curl "https://cms.spoonity.com/api/v1/app-config/acme-cafe?version=2.4.0"
```

**Response example:**

```json
{
  "config": {
    "api_host": "https://api.acme-cafe.com",
    "feature_flags": { "wallet": true, "egift": true, "ordering": false },
    "app_version": { "min_version": "2.0.0", "latest_version": "2.5.0" }
  },
  "update": {
    "status": "soft",
    "min_version": "2.0.0",
    "latest_version": "2.5.0",
    "update_url": null,
    "message": null
  }
}
```

`update.status` is one of `open` (no update needed, or no version info to compare against),
`soft` (caller is below `latest_version` but at/above `min_version` — nag, don't block), or `hard`
(caller is below `min_version` — block until updated).

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 404 | vendor_not_found | No vendor with that slug |
| 404 | app_config_not_found | No published `app-config` space, or no published `app_config` block in it, for this vendor |

---

## Tracking

### POST /track/{vendorSlug}

Public, batched endpoint for reporting impressions, clicks and conversions — the counterpart to
`_tracking.endpoint` in every delivery response. Also public and rate-limited at the delivery
budget.

**Degraded mode on a database outage.** This endpoint never fails a client over a database problem.
If the database is unreachable — for the whole batch, or partway through it — the events that
couldn't be persisted are **dropped, not buffered or retried**: the response is still `200`, with
`degraded: true` and a `dropped` count added alongside the usual `accepted`/`rejected`. A batch that
completes normally never carries `degraded`/`dropped` at all. Do not retry a degraded batch — the
dropped events are gone by design (an in-memory buffer on an autoscaled instance isn't durable
enough to be worth the risk of a retry storm against a database that just came back). A cold
instance that has never yet reached the database answers every `/api/v1/*` request, this one
included, with a plain `503` (`Retry-After: 5`) instead — there is nothing to degrade into until the
database has been reached at least once.

**Auth:** None — public.

**Path parameters:**

| Name | Type | Description |
|---|---|---|
| `vendorSlug` | string | The vendor's slug. |

**Request body:**

| Name | Type | Required | Description |
|---|---|---|---|
| `events` | array (max 50) | Yes | Array of event objects. |
| `events[].type` | string | Yes | `impression`, `click`, or `conversion`. Anything else is rejected. |
| `events[].space_slug` | string | No | Resolved to a space id; an unknown slug rejects that event. |
| `events[].block_id` | integer | No | |
| `events[].client_id` | string | No | An `impression` with a `client_id` is deduplicated per `(client_id, block_id, UTC day)` — a duplicate is counted in `rejected`, not an error. |
| `events[].platform` | string | No | |
| `events[].locale` | string | No | |
| `events[].region` | string | No | |
| `events[].campaign_id` | string | No | Auto-filled from the space's `campaign_id` when omitted. |

**Request example:**

```bash
curl -X POST https://cms.spoonity.com/api/v1/track/acme-cafe \
  -H "Content-Type: application/json" \
  -d '{
    "events": [
      { "type": "impression", "space_slug": "summer-promo", "block_id": 101, "client_id": "device-abc123" },
      { "type": "click", "space_slug": "summer-promo", "block_id": 101, "client_id": "device-abc123" }
    ]
  }'
```

**Response example:**

```json
{ "accepted": 2, "rejected": 0 }
```

Degraded (database unreachable mid-batch):

```json
{ "accepted": 0, "rejected": 0, "dropped": 2, "degraded": true }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | `events` missing, empty, not an array, or longer than 50 |
| 404 | not_found | Unknown vendor slug |
| 503 | service_unavailable | The service has never yet reached the database (`Retry-After: 5`) |

---

## Spaces

A content space moves through a workflow: `draft → review → approved → (scheduled) → published →
archived`. Only the transition endpoints below (plus an admin-only `draft`/`archived` escape hatch
on `PUT /spaces/{id}`) may change `status`; every transition is activity-logged and fires a
webhook. All Spaces and Blocks endpoints require an API key with `content:read`/`content:write`
scope, or a dashboard JWT session.

### GET /spaces

List content spaces for the vendor.

**Auth:** `content:read` scope, or dashboard JWT.

**Query parameters:**

| Name | Type | Description |
|---|---|---|
| `platform` | string | Filter by platform (also matches `all`-platform spaces). |
| `status` | string | Filter by workflow status. |
| `search` | string | Substring match on `name` or `slug`. |
| `page` | integer | Default `1`. |
| `per_page` | integer | Default `50`, max `200`. |

**Request example:**

```bash
curl "https://cms.spoonity.com/api/v1/spaces?status=published&page=1" \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{
  "data": [ { "id": 42, "name": "Summer Promo", "slug": "summer-promo", "status": "published", "block_count": 3 } ],
  "total": 1,
  "meta": { "page": 1, "per_page": 50, "total": 1, "total_pages": 1 }
}
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 401 | unauthorized | Missing/invalid credentials |
| 403 | insufficient_scope | Key lacks `content:read` |

### POST /spaces

Create a content space. Always created in `draft` — `status` in the body is ignored; the publish
window (`start_at`/`end_at`) is not settable here either.

**Auth:** `content:write` scope, or dashboard JWT — any role except `viewer` (a roleless key is
allowed).

**Request body:**

| Name | Type | Required | Description |
|---|---|---|---|
| `name` | string | Yes | |
| `slug` | string | No | Auto-derived from `name` when omitted. |
| `description` | string | No | |
| `platform` | string | No | One of `all, app, web, mobile_web, desktop_web, watch, tv, car`. Default `all`. |
| `category`, `campaign_id` | string, nullable | No | |
| `tags` | string[] | No | |
| `priority` | integer | No | Default `0`. |
| `region`, `city`, `country`, `daypart` | string | No | `country` defaults `CA`. |
| `store_ids` | string[] | No | |
| `active_hours` | `{ start, end }` | No | |
| `active_days` | string[] (`sun`..`sat`) | No | |
| `audience` | `{ loyalty_tier?: string[], segments?: string[] }` | No | |
| `min_visits`, `max_visits` | integer | No | |
| `default_locale` | string | No | Default `en-CA`. Not validated; use one of `en-CA, fr-CA, en-US, es-US, fr-FR, pt-BR`, the locales Translations supports. |
| `fallback_space_id` | integer, nullable | No | Must reference an existing space of the same vendor. |

**Request example:**

```bash
curl -X POST https://cms.spoonity.com/api/v1/spaces \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{ "name": "Fall Promo", "platform": "app", "category": "promotion" }'
```

**Response example (201):**

```json
{ "id": 55, "vendor_id": 7, "name": "Fall Promo", "slug": "fall-promo", "status": "draft", "platform": "app", "sort_order": 3 }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | `name` missing, unknown `platform`, or invalid `fallback_space_id` |
| 403 | forbidden | Caller is a viewer |
| 409 | conflict | A space with that slug already exists for this vendor |

### POST /spaces/{id}/clone

Server-side, all-or-nothing copy of a space (spoonity-cms #37). The copy is a `draft` with the
source's settings and targeting (description, platform, category, campaign, tags, priority, region,
city, country, store ids, daypart, active hours/days, audience, visit bounds, default locale), and
every block is copied **as a draft**, in the same order, with all content columns. It is placed at
the end of the vendor's space order. Translations, personalization rules and experiments are
**not** copied. If any step fails the partial copy is deleted, so a caller never sees half a space.

**Auth:** `content:write` scope, or dashboard JWT — any role except `viewer`.

**Path parameters:**

| Name | Type | Description |
|---|---|---|
| `id` | integer | Source space id. |

**Request body** (the body itself is optional):

| Name | Type | Required | Description |
|---|---|---|---|
| `name` | string | No | Default `"<source name> (copy)"`. |
| `slug` | string | No | Default `"<source slug>-copy-<base36 timestamp>"`. |

**Request example:**

```bash
curl -X POST https://cms.spoonity.com/api/v1/spaces/42/clone \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{ "name": "Summer Promo (Copy)", "slug": "summer-promo-2" }'
```

**Response example (201):** the new space row plus `blocks_copied`. Logs a `duplicated` activity
entry and fires `space.created` for the copy.

```json
{ "id": 56, "vendor_id": 7, "name": "Summer Promo (Copy)", "slug": "summer-promo-2", "status": "draft", "platform": "app", "blocks_copied": 3 }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 403 | forbidden | Caller is a viewer |
| 404 | not_found | No such space for this vendor |
| 409 | conflict | A space with that slug already exists (`message`: `A space with slug "<slug>" already exists.`) |
| 500 | clone_failed | `Failed to clone the space; nothing was created` — the partial copy was rolled back |

### GET /spaces/{id}

Get a single space with its blocks.

**Auth:** `content:read` scope, or dashboard JWT.

**Path parameters:**

| Name | Type | Description |
|---|---|---|
| `id` | integer | Space id. |

**Request example:**

```bash
curl https://cms.spoonity.com/api/v1/spaces/42 \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "id": 42, "name": "Summer Promo", "slug": "summer-promo", "status": "published", "blocks": [ { "id": 101, "block_type": "hero_banner", "title": "Cold Brew Season" } ] }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 404 | not_found | No such space for this vendor |

### PUT /spaces/{id}

Update a space's content, scheduling and targeting fields. `status` is **not** freely writable: it
may only be changed to `draft` or `archived` (every other value, including workflow states, is a
`400` directing you to the workflow endpoint that owns the transition and its side effects), and
only by an admin. Omitting `status`, or resending the current value, is always a plain content
edit open to any non-viewer.

**Auth:** `content:write` scope, or dashboard JWT — non-viewer for a plain edit; **admin** required
only when `status` is being changed to `draft`/`archived`.

**Path parameters:**

| Name | Type | Description |
|---|---|---|
| `id` | integer | Space id. |

**Request body:** same fields as `POST /spaces` (all optional — only supplied fields are updated),
plus `status` (`draft`/`archived` only, as a *change*), `start_at`/`end_at` (ISO 8601 in).

**Request example:**

```bash
curl -X PUT https://cms.spoonity.com/api/v1/spaces/42 \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{ "priority": 20, "region": "QC" }'
```

**Response example:**

```json
{ "id": 42, "name": "Summer Promo", "slug": "summer-promo", "status": "published", "priority": 20, "region": "QC" }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | Unknown `platform`, invalid `fallback_space_id`, or a `status` value the workflow reserves (echoes `current_status`/`requested_status`) |
| 403 | forbidden | Caller is a viewer, or a non-admin tried to change `status` |
| 404 | not_found | No such space for this vendor |

### DELETE /spaces/{id}

Delete a space and all of its blocks.

**Auth:** `content:write` scope, or dashboard JWT — **admin** role required.

**Path parameters:**

| Name | Type | Description |
|---|---|---|
| `id` | integer | Space id. |

**Request example:**

```bash
curl -X DELETE https://cms.spoonity.com/api/v1/spaces/42 \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "success": true, "message": "Space deleted" }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 403 | forbidden | Caller is not an admin |
| 404 | not_found | No such space for this vendor |

### POST /spaces/{id}/submit

`draft` → `review`. Stamps `submitted_by`/`submitted_at`.

**Auth:** `content:write` scope, or dashboard JWT — **admin or editor** (viewers rejected).

**Path parameters:** `id` (integer, space id).

**Request example:**

```bash
curl -X POST https://cms.spoonity.com/api/v1/spaces/42/submit \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "id": 42, "status": "review", "submitted_by": "editor@acme-cafe.com", "message": "Space submitted for review" }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 403 | forbidden | Caller is a viewer or has no role |
| 404 | not_found | No such space for this vendor |
| 409 | invalid_transition | Space is not currently `draft` |

### POST /spaces/{id}/approve

`review` → `approved`. Stamps `approved_by`/`approved_at`, clears `rejection_reason`.

**Auth:** `content:write` scope, or dashboard JWT — **admin**.

**Path parameters:** `id` (integer, space id).

**Request example:**

```bash
curl -X POST https://cms.spoonity.com/api/v1/spaces/42/approve \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "id": 42, "status": "approved", "approved_by": "admin@acme-cafe.com", "message": "Space approved" }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 403 | forbidden | Caller is not an admin |
| 404 | not_found | No such space for this vendor |
| 409 | invalid_transition | Space is not currently `review` |

### POST /spaces/{id}/reject

`review` → `draft`. Stores an optional `reason`.

**Auth:** `content:write` scope, or dashboard JWT — **admin**.

**Path parameters:** `id` (integer, space id).

**Request body:**

| Name | Type | Required | Description |
|---|---|---|---|
| `reason` | string, nullable | No | Blank/omitted stores `null`. |

**Request example:**

```bash
curl -X POST https://cms.spoonity.com/api/v1/spaces/42/reject \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{ "reason": "Needs French translation before review" }'
```

**Response example:**

```json
{ "id": 42, "status": "draft", "rejection_reason": "Needs French translation before review", "message": "Space rejected — returned to draft" }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 403 | forbidden | Caller is not an admin |
| 404 | not_found | No such space for this vendor |
| 409 | invalid_transition | Space is not currently `review` |

### POST /spaces/{id}/schedule

`approved` → `scheduled`. The background scheduler publishes the space once `start_at` passes.

**Auth:** `content:write` scope, or dashboard JWT — **admin**.

**Path parameters:** `id` (integer, space id).

**Request body:**

| Name | Type | Required | Description |
|---|---|---|---|
| `start_at` | string (ISO 8601) | No\* | \*Required unless already set on the space. Past dates allowed. |
| `end_at` | string (ISO 8601), nullable | No | |

**Request example:**

```bash
curl -X POST https://cms.spoonity.com/api/v1/spaces/42/schedule \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{ "start_at": "2026-09-01T08:00:00.000Z" }'
```

**Response example:**

```json
{ "id": 42, "status": "scheduled", "start_at": "2026-09-01 08:00:00", "message": "Space scheduled to publish at 2026-09-01 08:00:00" }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | Malformed `start_at`/`end_at`, or no `start_at` set anywhere |
| 403 | forbidden | Caller is not an admin |
| 404 | not_found | No such space for this vendor |
| 409 | invalid_transition | Space is not currently `approved` |

### POST /spaces/{id}/publish

Publish a space. Legal from `approved` or `scheduled` (or any status with `force: true`, logged as
forced). Snapshots current blocks as a new version, promotes draft blocks, enriches image
variants, and — when `settings.auto_shorten_cta` is `true` — rewrites CTA URLs to short links.

**Auth:** `content:write` scope, or dashboard JWT — **admin**.

**Path parameters:** `id` (integer, space id).

**Request body:**

| Name | Type | Required | Description |
|---|---|---|---|
| `force` | boolean | No | Default `false`. Publishes from any status, bypassing the `approved`/`scheduled` requirement. |

**Request example:**

```bash
curl -X POST https://cms.spoonity.com/api/v1/spaces/42/publish \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "id": 42, "status": "published", "published_at": "2026-08-31 12:00:00", "version": 4, "message": "Space published (v4)" }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 403 | forbidden | Caller is not an admin |
| 404 | not_found | No such space for this vendor |
| 409 | invalid_transition | Space is not `approved`/`scheduled` and `force` was not set |

### POST /spaces/{id}/unpublish

Revert a space to `draft` from any status — the sanctioned `published → draft` path.

**Auth:** `content:write` scope, or dashboard JWT — **admin**.

**Path parameters:** `id` (integer, space id).

**Request example:**

```bash
curl -X POST https://cms.spoonity.com/api/v1/spaces/42/unpublish \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "id": 42, "status": "draft", "message": "Space reverted to draft" }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 403 | forbidden | Caller is not an admin |
| 404 | not_found | No such space for this vendor |

### POST /spaces/{id}/preview-token

Mint a 30-minute JWT that serves this space through the real delivery pipeline **regardless of
workflow status**, with draft blocks included. Append it to the delivery URL as `?preview_token=…`.

**Auth:** `content:write` scope, or dashboard JWT — **admin or editor** (viewers cannot mint tokens).

**Path parameters:** `id` (integer, space id).

**Request example:**

```bash
curl -X POST https://cms.spoonity.com/api/v1/spaces/42/preview-token \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{
  "token": "eyJhbGciOiJIUzI1NiJ9...",
  "expires_at": "2026-08-31T12:30:00.000Z",
  "preview_url": "https://cms.spoonity.com/api/v1/content/acme-cafe/summer-promo?preview_token=eyJhbGciOiJIUzI1NiJ9..."
}
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 403 | forbidden | Caller is a viewer or has no role |
| 404 | not_found | No such space (or vendor) |

### GET /spaces/{id}/versions

List a space's publish-version history (newest first). Each row carries `block_count` derived from
the snapshot; the snapshot itself is not returned.

**Auth:** `content:read` scope, or dashboard JWT.

**Path parameters:** `id` (integer, space id).

**Request example:**

```bash
curl https://cms.spoonity.com/api/v1/spaces/42/versions \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "data": [ { "id": 9, "space_id": 42, "version_number": 4, "message": "Version 4", "published_by": "admin@acme-cafe.com", "created_at": "2026-08-31 12:00:00", "block_count": 3 } ] }
```

**Errors:** none beyond auth — an unknown space id returns an empty list, not a 404.

### POST /spaces/{id}/versions/{versionId}/restore

Restore a space's blocks from a version's snapshot **in place** (spoonity-cms #37; it used to delete
and re-insert everything). Blocks that still exist keep their ids, so their translations,
personalization rules and experiment links survive, and they keep their current `status`, so a
published space keeps delivering while the content is swapped. Blocks that were removed since the
snapshot are re-created (new ids; published if the space is published, otherwise drafts). Blocks
added **after** the snapshot are deleted. Every content column is written back (`block_type`,
`title`, `subtitle`, `body`, `image_url`, `background_url`, `video_url`, `poster_url`, `cta_text`,
`cta_url`, `cta_deeplink`, `cta_link_id`, `config`, `platform`, `tags`, `menu_item_id`, `region`,
`store_ids`, `audience`) and `sort_order` follows snapshot order. Both snapshot shapes (a bare block
array and `{ blocks }`) are accepted. The space's own `status` is untouched and no webhook fires.

**Auth:** `content:write` scope, or dashboard JWT — **admin**.

**Path parameters:**

| Name | Type | Description |
|---|---|---|
| `id` | integer | Space id. |
| `versionId` | integer | Version id. |

**Request example:**

```bash
curl -X POST https://cms.spoonity.com/api/v1/spaces/42/versions/9/restore \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "success": true, "message": "Restored to version 4", "blocks_restored": 3 }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 403 | forbidden | Caller is not an admin |
| 404 | not_found | No such version for this space |

---

## Content Blocks

Blocks are the individual content units inside a space (`hero_banner`, `promo_card`,
`featured_items`, `announcement`, `custom_json`, `text_block`, `image_gallery`, `video`, `faq`,
`onboarding_slide`, `carousel`, `app_icon`, `points_program`, `egift_artwork`, `app_config`). `faq`,
`carousel`, `onboarding_slide`, `app_icon`, `points_program`, `egift_artwork` and `app_config` have
a validated `config` shape; other types accept opaque JSON.

### `points_program` and `egift_artwork` config

Both types carry `config.items[]`, like `faq`/`carousel` above them.

- **`points_program`** — a redeemable-rewards catalog. Each item: `title` and `image_url` (both
  required, non-empty strings), plus optional `cost` (non-negative number), `reward_id` (string or
  number), and the plain-string fields `subtitle`, `description`, `badge`, `catalog_id`, `plu`,
  `deeplink`. `plu` is the current name for this field — a legacy-import mapping renames the older
  `deliverect_plu` name on the way in, but the block's own config always stores `plu`.
- **`egift_artwork`** — selectable eGift card artwork. Each item needs a `media_id` (a
  [Media](#media) asset id) **or** an `image_url` — at least one — plus optional `label` (string),
  `is_default` (boolean; at most one item per block may set it `true`), `sort_order` (number), and
  `denominations` (array of non-negative numbers). `config.default_artwork_id` (string) may name the
  default item at the block level instead. When an item has a `media_id` but no `image_url`, the
  Content Delivery API resolves it to that media asset's CDN URL before serving the block — so a
  well-formed item always delivers a usable `image_url` regardless of which one the editor set.
  `deeplink` on `points_program` items and `cta_url`/`cta_deeplink` on `carousel` items are the
  in-scope navigation fields for [Spoonity Links enforcement](#spoonity-links-enforcement-cms_links_mode) below.

### `app_config` — remote app configuration

At most **one** `app_config` block per space (a second `POST` to the same space is a `409`). Every
top-level section is optional — draft incrementally and only the sections you send are validated:

| Field | Type | Notes |
|---|---|---|
| `api_host` | string | Must be an `https://` URL. |
| `locales.default` | string | |
| `locales.supported` | string[] | |
| `feature_flags.{wallet,egift,ordering,credit,journey,scan,messages,stores,home_barcode,wallet_pass,meta_events,geo_promotions,auth_engine,qa_feedback,transaction_rating}` | boolean | Unknown keys under `feature_flags` are rejected. `qa_feedback` enables the in-app QA feedback control (spoonity-cms #35). |
| `qa_feedback.testers` | string[] | At most **200** entries, each at most 254 characters: a full email (`name@example.com`) or a whole-domain entry (`@example.com`). Trimmed, lowercased and de-duplicated (first occurrence wins) on save. An invalid entry is a `400 bad_request` naming its index. |
| `flags.{clientKey,baseUrl,enabled}` | object | How native apps get their Spoonity Flags client key remotely (#33). `clientKey` must be a client key (`sdk_c_` + 26 base32 chars) — a server key (`sdk_s_…`) is rejected by name because the public endpoint serves this section; `baseUrl` must be `https://`; `enabled: true` requires a `clientKey`; unknown fields are rejected. |
| `legal.{terms_url,privacy_url,faq_url}` | string (URL) | http(s). |
| `support.{email,phone,whatsapp}` | string | Plain contact strings, not URLs — never Links-enforced. |
| `support.url` | string | Must be `https://`. Links-eligible at **warn only**, regardless of `CMS_LINKS_MODE` — see below. |
| `social.website` | string (URL) | Links-eligible at **warn only**. |
| `social.{instagram,facebook,tiktok,x}` | string | Handles, not URLs — never Links-enforced. |
| `store_order.url_template` | string | Excluded from Links enforcement outright — it carries placeholders (e.g. `{store_id}`), not a literal navigable URL. |
| `store_order.mode` | string | One of `pickup`, `delivery`, `both`. |
| `store_order.doxi_handoff` | boolean | |
| `loyalty.primary_currency_id` | number | |
| `loyalty.display_divisor` | number | Must be positive. |
| `loyalty.display_currency` | string | |
| `loyalty.progress_currencies[]` | array of `{ currency_id, label, target }` | All three fields required per entry. |
| `theme.colors.{primary,secondary,background,text,accent}` | string | `#RRGGBB` hex. |
| `theme.fonts.{heading,body}` | string | |
| `app_version.min_version`, `app_version.latest_version` | string | Semver `X.Y.Z` (optional `-prerelease` suffix). |
| `app_version.status` | string | One of `open`, `soft`, `hard` — informational; [`GET /app-config/{vendorSlug}`](#get-app-configvendorslug) computes its own `update.status` from `min_version`/`latest_version` against the caller's version rather than trusting this field. |
| `app_version.update_url.{android,ios}` | string (URL) | Excluded from Links enforcement outright — must point at the OS app store, not a short link. |
| `app_version.message.{en,es}` | string | |

`legal.terms_url`/`legal.privacy_url`/`legal.faq_url`, `social.website`, and `support.url` are the
only `app_config` fields Spoonity Links enforcement touches, and only ever at **warn** semantics — a
raw external URL there adds a `link_warnings` entry, but an `app_config` save **never** hard-fails
(`require` mode) or gets silently rewritten (`auto` mode) over these fields, regardless of the
vendor's `CMS_LINKS_MODE`. `api_host`, `store_order.url_template`, and `app_version.update_url` are
excluded from Links enforcement entirely — see [Spoonity Links enforcement](#spoonity-links-enforcement-cms_links_mode).

`feature_flags.*`, `store_order.doxi_handoff` and
`qa_feedback.testers` are now **legacy bootstrap/fallback values**: their source of truth is
Spoonity Flags, where the flag key is the same field name. The CMS keeps validating and serving
them so apps can seed the Flags SDK and fall back when a brand has no active Flags block.
[`GET /app-config/{vendorSlug}`](#get-app-configvendorslug) serves `flags` normalized to exactly
`{ clientKey, baseUrl, enabled }` (`enabled` is `false` unless a valid client key is present).

### POST /vendors/{vendorSlug}/app-config

Create-or-update the vendor's one reserved `app_config` space+block in a single call — the
operator/automation "just set it" path, not the editorial draft→review→approve workflow. Idempotent:
finds or creates the `app-config` space (platform `app`) and its one `app_config` block, **merges**
the request body into the stored config at top-level-section granularity (each top-level key present
in the body replaces that whole section; omitted keys keep their previous value), validates the
merged result against the schema above, and immediately publishes both the block and the space.

**Auth:** `content:write` scope, or dashboard JWT — non-viewer. `vendorSlug` must match the
authenticated vendor (a mismatch is a `403`, not a `404` — this is a service/admin-only path, not a
lookup).

**Path parameters:**

| Name | Type | Description |
|---|---|---|
| `vendorSlug` | string | Must match the authenticated vendor. |

**Request body:** any subset of the `app_config` fields documented above, at top-level-section
granularity.

**Request example:**

```bash
curl -X POST https://cms.spoonity.com/api/v1/vendors/acme-cafe/app-config \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{ "feature_flags": { "wallet": true, "egift": true }, "app_version": { "min_version": "2.0.0" } }'
```

**Response example:**

```json
{
  "space": { "id": 60, "slug": "app-config", "status": "published" },
  "block": { "id": 210, "block_type": "app_config", "status": "published", "config": { "feature_flags": { "wallet": true, "egift": true }, "app_version": { "min_version": "2.0.0" } } }
}
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | Merged config fails schema validation (see the field table above) |
| 403 | forbidden | Caller is a viewer, or `vendorSlug` doesn't match the authenticated vendor |

### Spoonity Links enforcement (`CMS_LINKS_MODE`)

Every navigation-URL field on a block create/update — block-level `cta_url`/`cta_deeplink`, plus
the item-level `cta_url`/`cta_deeplink` on `carousel` items and `deeplink` on `points_program`
items — is checked against `CMS_LINKS_MODE` (env var; one of `require`, `auto`, `warn`; **default
`auto`**) whenever it carries a raw `http(s)://` value that isn't already a Spoonity Link: a URL on
the default short domain (`links.spoonity.com`), or under the vendor's own Links base (its
`x.spnty.co/<vendor slug>` path on the shared host, or its verified custom domain). In `warn` mode
only the default short domain is recognised, so a shared-host or custom-domain URL still gets a
warning there. An app-scheme deep link (anything that doesn't parse as an `http(s)` URL, e.g.
`myapp://`) is always left untouched, in every mode. `auto` is the code default;
`cms.spoonity.com` currently runs with `warn`.

- **`require`** — a raw URL rejects the whole save with `422 link_required`. Both `422` failure
  bodies are shaped `{ "error": "link_required" | "link_creation_failed", "message": "...", "field":
  "cta_url", "item_id": "abc123def0" }` — `item_id` is present only for an item-level field.
- **`auto`** (default) — the CMS mints a `links.spoonity.com` short link for it transparently and
  saves that instead; the field's true original is preserved (`config.cta_url_original` for
  block-level `cta_url`, `<field>_original` on the item otherwise) and never overwritten on a later
  re-shorten. If the Links service call itself fails, the save is rejected with
  `422 link_creation_failed` rather than silently storing the raw URL.
  `content_blocks.cta_link_id` persists the converted block-level link's id.
  `settings.auto_shorten_cta` on the vendor (see [Vendor Settings](#put-vendorsettings)) is a
  separate, older mechanism that does the same rewrite for `cta_url` specifically at publish time.
- **`warn`** — the raw URL is stored as-is; the response carries a `link_warnings` array
  (`{ field, item_id?, message }` per flagged field) instead of failing the request.

`app_config` blocks are the one exception: their eligible fields
(`legal.terms_url`/`legal.privacy_url`/`legal.faq_url`, `social.website`, `support.url`) are always
evaluated at **warn** semantics regardless of the configured mode — see the [`app_config`
section](#app_config--remote-app-configuration) above. `app_config.api_host`,
`store_order.url_template`, and `app_version.update_url` are excluded from enforcement outright.

### POST /spaces/{spaceId}/blocks

Add a block to a space, created as `draft`.

**Auth:** `content:write` scope, or dashboard JWT — non-viewer.

**Path parameters:** `spaceId` (integer).

**Request body:**

| Name | Type | Required | Description |
|---|---|---|---|
| `block_type` | string | Yes | One of the 15 types above. |
| `title`, `subtitle`, `body` | string | No | |
| `image_url`, `background_url`, `video_url`, `poster_url` | string | No | |
| `cta_text`, `cta_url`, `cta_deeplink` | string | No | Subject to [Spoonity Links enforcement](#spoonity-links-enforcement-cms_links_mode). |
| `config` | object | No | Validated for `faq`/`carousel`/`onboarding_slide`/`app_icon`/`points_program`/`egift_artwork`/`app_config`; empty/absent always allowed. |
| `platform` | string | No | Overrides the space's platform for this block; `null` inherits. |
| `tags` | string[] | No | |
| `menu_item_id`, `region` | string, nullable | No | |
| `store_ids` | string[], nullable | No | |
| `audience` | object, nullable | No | |

**Request example:**

```bash
curl -X POST https://cms.spoonity.com/api/v1/spaces/42/blocks \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{ "block_type": "hero_banner", "title": "Cold Brew Season", "cta_text": "Order now", "cta_url": "https://acme-cafe.com/menu" }'
```

**Response example:**

```json
{ "id": 101, "space_id": 42, "block_type": "hero_banner", "title": "Cold Brew Season", "status": "draft", "sort_order": 0 }
```

A response carries a top-level `link_warnings` array (see above) only in `warn` mode, and only when
at least one in-scope field held a raw URL.

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | Unknown `block_type`/`platform`, or `config` fails type-specific validation |
| 403 | forbidden | Caller is a viewer |
| 404 | not_found | No such space for this vendor |
| 409 | conflict | `block_type` is `app_config` and the space already has one |
| 422 | link_required | (`require` mode) An in-scope field holds a raw URL |
| 422 | link_creation_failed | (`auto` mode) Minting a short link for an in-scope field failed |

### PUT /blocks/{id}

Update a block. Any subset of fields.

**Auth:** `content:write` scope, or dashboard JWT — non-viewer.

**Path parameters:** `id` (integer, block id).

**Request body:** same fields as create, plus `status` (`draft`/`published` — block-level
visibility within its space; freely editor-settable, no workflow bypass since delivery only ever
serves blocks of a *space* that is itself published) and `sort_order`.

**Request example:**

```bash
curl -X PUT https://cms.spoonity.com/api/v1/blocks/101 \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{ "title": "Cold Brew Season — Extended" }'
```

**Response example:**

```json
{ "id": 101, "space_id": 42, "title": "Cold Brew Season — Extended", "status": "draft" }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | Unknown `platform`, or `config` fails validation |
| 403 | forbidden | Caller is a viewer |
| 404 | not_found | No such block for this vendor |
| 422 | link_required | (`require` mode) An in-scope field holds a raw URL |
| 422 | link_creation_failed | (`auto` mode) Minting a short link for an in-scope field failed |

### DELETE /blocks/{id}

Permanently delete a content block.

**Auth:** `content:write` scope, or dashboard JWT — **admin**.

**Path parameters:** `id` (integer, block id).

**Request example:**

```bash
curl -X DELETE https://cms.spoonity.com/api/v1/blocks/101 \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "success": true, "message": "Block deleted" }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 403 | forbidden | Caller is not an admin |
| 404 | not_found | No such block for this vendor |

### POST /blocks/{id}/duplicate

Clone a block into the same space as a new `draft`, titled "<title> (copy)" and appended at the
end of the sort order. Only the content, CTA, `config` and `platform` fields are copied: `tags`,
`menu_item_id`, `region`, `store_ids` and `audience` are not. Returns `201`. No webhook fires.

**Auth:** `content:write` scope, or dashboard JWT — non-viewer.

**Path parameters:** `id` (integer, block id).

**Request example:**

```bash
curl -X POST https://cms.spoonity.com/api/v1/blocks/101/duplicate \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "id": 102, "space_id": 42, "title": "Cold Brew Season (copy)", "status": "draft" }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 403 | forbidden | Caller is a viewer |
| 404 | not_found | No such block for this vendor |

### POST /blocks/{id}/shorten-cta

Replace the block's `cta_url` with a tracked [Spoonity Links](https://links.spoonity.com) short
link, preserving the original in `config.cta_url_original` (never clobbered on re-shorten). The
same rewrite happens automatically at publish time when `settings.auto_shorten_cta` is `true`.

**Auth:** `content:write` scope, or dashboard JWT — **admin or editor**.

**Path parameters:** `id` (integer, block id).

**Request example:**

```bash
curl -X POST https://cms.spoonity.com/api/v1/blocks/101/shorten-cta \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "id": 101, "cta_url": "https://links.spoonity.com/x7Qp9", "short_url": "https://links.spoonity.com/x7Qp9", "code": "x7Qp9" }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | The block has no `cta_url` to shorten |
| 403 | forbidden | Caller is a viewer or has no role |
| 404 | not_found | No such block for this vendor |
| 502 | links_error | The Links service did not return a short link |
| 503 | links_not_configured | Not running on GCP and `LINKS_API_KEY` is unset |

### POST /blocks/{id}/shorten-field

Generalized version of `shorten-cta` above: replaces **any** in-scope navigation-URL field — block-
level `cta_url`/`cta_deeplink`, or an item-level field inside `config.items[]` (`cta_url`/
`cta_deeplink` on a `carousel` item, `deeplink` on a `points_program` item) — with a tracked
`links.spoonity.com` short link. The original value is preserved the first time a field is
shortened (`config.cta_url_original` for block-level `cta_url`, `<field>_original` on the item
otherwise) and never clobbered on re-shorten.

**Auth:** `content:write` scope, or dashboard JWT — **admin or editor**.

**Path parameters:** `id` (integer, block id).

**Request body:**

| Name | Type | Required | Description |
|---|---|---|---|
| `field` | string | Yes | The field name to shorten. |
| `item_id` | string | Only for an item-level field | The item's stable `id` within `config.items[]`. A field name valid at both block and item scope (e.g. `cta_url`) is disambiguated by whether `item_id` is present. |

**Request example:**

```bash
curl -X POST https://cms.spoonity.com/api/v1/blocks/101/shorten-field \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{ "field": "deeplink", "item_id": "abc123def0" }'
```

**Response example (item-level):**

```json
{ "id": 101, "short_url": "https://links.spoonity.com/aZ3kq", "code": "aZ3kq", "link_id": 77, "item_id": "abc123def0" }
```

A block-level shorten instead returns the full updated block plus `short_url`/`code`/`link_id`, the
same shape as `shorten-cta`.

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | `field` is not a valid field for this block type at the given scope; `item_id` is required for an item-level field and was omitted; or the field is already empty |
| 404 | not_found | No such block for this vendor, or (item-level) no item with that `item_id` |
| 502 | links_error | The Links service did not return a short link |
| 503 | links_not_configured | Not running on GCP and `LINKS_API_KEY` is unset |

### GET /links/search

Proxy to the Links API's own link search, so an editor can pick an existing Spoonity Link instead
of always minting a new one. Never a hard error — an unavailable Links integration or a failed
search call returns an empty list rather than a 5xx (this is a UX affordance, not load-bearing data).

**Auth:** Any valid API key or dashboard JWT — **not scope-gated**.

**Query parameters:**

| Name | Type | Description |
|---|---|---|
| `q` | string | Search text. |

**Request example:**

```bash
curl "https://cms.spoonity.com/api/v1/links/search?q=summer" \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "links": [ { "id": 88, "short_url": "https://links.spoonity.com/x7Qp9", "code": "x7Qp9", "destination_url": "https://acme-cafe.com/menu", "title": "Summer Promo" } ] }
```

**Errors:** none — an unavailable Links integration or a failed search resolves to `{ "links": [] }`.

### GET /vendor/links-domain

The domain(s) a URL must be on to count as "already a tracked Spoonity Link" for this vendor: the
default short domain, plus whatever Links domain the vendor is enrolled on. `mode` is the vendor's
Links **domain** mode (`shared`, `custom` or `none`), not `CMS_LINKS_MODE`. `short_link_base` is the
base editors should build and recognise the vendor's links against: `x.spnty.co/<vendor slug>` for a
shared-host vendor, the custom domain for a custom-domain vendor, and the default short domain
otherwise. `custom_domain` is set only when `mode` is `custom`. The Links lookup is cached for 5
minutes and falls back to `mode: "none"` when Links is unreachable.

**Auth:** Any valid API key or dashboard JWT — **not scope-gated**.

**Request example:**

```bash
curl https://cms.spoonity.com/api/v1/vendor/links-domain \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "short_domain": "links.spoonity.com", "custom_domain": null, "mode": "shared", "short_link_base": "x.spnty.co/acme-cafe" }
```

**Errors:** none beyond auth.

### PUT /spaces/{spaceId}/reorder

Rewrite every listed block's `sort_order` to its index in `block_ids`.

**Auth:** `content:write` scope, or dashboard JWT — non-viewer.

**Path parameters:** `spaceId` (integer).

**Request body:**

| Name | Type | Required | Description |
|---|---|---|---|
| `block_ids` | integer[] | Yes | Block ids in their new display order. |

**Request example:**

```bash
curl -X PUT https://cms.spoonity.com/api/v1/spaces/42/reorder \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{ "block_ids": [102, 101] }'
```

**Response example:**

```json
{ "success": true, "blocks": [ { "id": 102, "sort_order": 0 }, { "id": 101, "sort_order": 1 } ] }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | `block_ids` missing or not an array |
| 403 | forbidden | Caller is a viewer |
| 404 | not_found | No such space for this vendor |

---

## Media

Uploaded raster images (JPEG/PNG/WebP) are optimized server-side: the stored original is
re-encoded, EXIF-stripped and capped at 2560px (`original_url`), a size-budgeted WebP primary
becomes `url`, and responsive WebP `variants` (`thumb`/`md`/`lg`) are generated. GIF/SVG/video/PDF
pass through untouched. **Wallet-pass integrations must reference `original_url`** (format-
preserved PNG/JPEG), never the WebP `url`. In production, newly stored assets are served from
`https://media.spoonity.com/<filename>` (`MEDIA_CDN_BASE_URL`); older rows keep the URL recorded at
upload time.

### GET /media

List media assets.

**Auth:** `media:read` scope, or dashboard JWT.

**Query parameters:**

| Name | Type | Description |
|---|---|---|
| `page` | integer | Default `1`. |
| `limit` | integer | Default `50`, max `100`. |
| `folder` | string | Use `__unfiled__` for assets with no folder. |
| `tag` | string | Single tag filter. |
| `q` | string | Substring match on `original_name`/`alt_text`. |

**Request example:**

```bash
curl "https://cms.spoonity.com/api/v1/media?folder=hero-images" \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{
  "data": [ { "id": 9, "filename": "abc123.jpg", "url": "https://media.spoonity.com/abc123_opt.webp", "original_url": "https://media.spoonity.com/abc123.jpg", "width": 1920, "height": 1080, "variants": { "thumb": { "url": "...", "width": 200, "height": 113 } }, "tags": [], "protected": false, "deleted_at": null } ],
  "pagination": { "page": 1, "limit": 50, "total": 1, "total_pages": 1 }
}
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 403 | insufficient_scope | Key lacks `media:read` |

### GET /media/folders

Distinct folders with asset counts, for the media library sidebar.

**Auth:** `media:read` scope, or dashboard JWT.

**Request example:**

```bash
curl https://cms.spoonity.com/api/v1/media/folders \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "data": [ { "folder": "hero-images", "count": 4 } ], "total": 10, "unfiled": 6 }
```

**Errors:** none beyond auth.

### POST /media

Upload a media file. Allowed types: `jpg, jpeg, png, gif, webp, svg, mp4, webm, pdf`; default max
size 10 MB (`UPLOAD_MAX_SIZE_MB`). `multipart/form-data`. When the client reports a generic
`application/octet-stream` (or no) content type, the type is taken from the file extension, so
WebP, mp4 and webm uploads from curl are still optimised and served with the right `Content-Type`.

**Auth:** `media:write` scope, or dashboard JWT. No role restriction — any authenticated role
(including `viewer`) may upload.

**Request body (multipart/form-data):**

| Name | Type | Required | Description |
|---|---|---|---|
| `file` | binary | Yes | |
| `alt_text` | string | No | |
| `folder` | string | No | |

**Request example:**

```bash
curl -X POST https://cms.spoonity.com/api/v1/media \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -F "file=@hero.jpg" \
  -F "folder=hero-images"
```

**Response example:**

```json
{ "id": 9, "filename": "abc123.jpg", "url": "https://media.spoonity.com/abc123_opt.webp", "original_url": "https://media.spoonity.com/abc123.jpg", "width": 1920, "height": 1080, "folder": "hero-images" }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | No `file` part in the upload |
| 413 | file_too_large | File over the size limit; `message`: `File is too large. The maximum upload size is <n> MB.` (spoonity-cms #37; was a `500`) |
| 415 | unsupported_file_type | Extension not in `jpg, jpeg, png, gif, webp, svg, mp4, webm, pdf`; `message` lists the accepted types (was a `500`) |
| 400 | bad_request | Any other malformed multipart upload (`message`: `Invalid upload: ...`) |
| 500 | upload_failed | Storage write or processing failed |

### POST /media/reprocess-all

Re-run the optimization pipeline for every raster asset of the vendor with current settings.
Non-raster assets are skipped; unreadable/undecodable ones count as failed.

**Auth:** `media:write` scope, or dashboard JWT — **admin**.

**Request example:**

```bash
curl -X POST https://cms.spoonity.com/api/v1/media/reprocess-all \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "processed": 8, "skipped": 2, "failed": 0, "bytes_saved": 412300 }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 403 | forbidden | Caller is not an admin |

### POST /media/{id}/reprocess

Re-run optimization for one asset.

**Auth:** `media:write` scope, or dashboard JWT — **admin or editor**.

**Path parameters:** `id` (integer, asset id).

**Request example:**

```bash
curl -X POST https://cms.spoonity.com/api/v1/media/9/reprocess \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "asset": { "id": 9, "url": "https://media.spoonity.com/abc123_opt.webp" }, "bytes_saved": 51200 }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | not_optimizable | Not a still raster image |
| 403 | forbidden | Caller is a viewer or has no role |
| 404 | not_found | No such asset for this vendor |
| 422 | reprocess_failed | Stored original could not be read or decoded |

### PATCH /media/{id}

Update `alt_text`, `folder` and/or `tags`.

**Auth:** `media:write` scope, or dashboard JWT — **admin or editor**; changing `protected`
additionally requires **admin** even if other fields in the same body would be allowed for an
editor.

**Path parameters:** `id` (integer, asset id).

**Request body:**

| Name | Type | Required | Description |
|---|---|---|---|
| `alt_text` | string, nullable | No | |
| `folder` | string, nullable | No | |
| `tags` | string[], nullable | No | `[]`/`null` clears all tags. |
| `protected` | boolean | No | Admin-only. Blocks a `?hard=true` delete while `true`. |

**Request example:**

```bash
curl -X PATCH https://cms.spoonity.com/api/v1/media/9 \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{ "alt_text": "Iced coffee with cream", "tags": ["hero", "summer"] }'
```

**Response example:**

```json
{ "id": 9, "alt_text": "Iced coffee with cream", "tags": ["hero", "summer"], "protected": false }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | No updatable field supplied, or a malformed value |
| 403 | forbidden | Caller is a viewer/roleless, or an editor attempted to set `protected` |
| 404 | not_found | No such asset for this vendor |

### DELETE /media/{id}

Default is a **soft delete** (`deleted_at` stamped, hidden from listings, file keeps serving so
existing references never 404). `?hard=true` permanently destroys the file, its variants, and the
row; refused while `protected`.

**Auth:** `media:write` scope, or dashboard JWT — **admin**.

**Path parameters:** `id` (integer, asset id).

**Query parameters:**

| Name | Type | Description |
|---|---|---|
| `hard` | boolean | Default `false`. |

**Request example:**

```bash
curl -X DELETE "https://cms.spoonity.com/api/v1/media/9?hard=false" \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "success": true, "message": "Asset removed from library. Its file stays online so existing references (wallet passes, published content) keep working; use ?hard=true to permanently destroy it.", "soft": true }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 403 | forbidden | Caller is not an admin |
| 404 | not_found | No such asset for this vendor |
| 409 | protected | `?hard=true` requested but the asset is marked `protected` |

---

## Personalization

Block-level rules that override a field at delivery time based on request context (e.g. "if
`loyalty_tier=gold`, override `image_url`"). Higher-`priority` rules win per field. **These write
routes carry no role restriction.** Any authenticated caller with `content:write` scope may
create, update or delete rules, a viewer-role session included, because no `denyRole('viewer')` is
applied here.

> **Response shape note:** the 404s in this section are bare `{ "error": "not_found" }`, and the enum
> validation failures are `{ "error": "<code>", "valid": [...] }`. Neither includes a `message`
> field, unlike the rest of the API. `missing_fields` is the exception: it is the usual
> `{ "error", "message" }` shape.

### GET /blocks/{blockId}/rules

List a block's personalization targeting rules.

**Auth:** `content:read` scope, or dashboard JWT.

**Path parameters:** `blockId` (integer).

**Request example:**

```bash
curl https://cms.spoonity.com/api/v1/blocks/101/rules \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "data": [ { "id": 5, "block_id": 101, "condition_type": "loyalty_tier", "condition_value": "gold", "override_field": "image_url", "override_value": "https://media.spoonity.com/gold-hero.jpg", "priority": 10, "label": "Gold tier hero" } ] }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 404 | not_found | No such block for this vendor (no `message` field) |

### POST /blocks/{blockId}/rules

Add a personalization targeting rule to a block.

**Auth:** `content:write` scope, or dashboard JWT.

**Path parameters:** `blockId` (integer).

**Request body:**

| Name | Type | Required | Description |
|---|---|---|---|
| `condition_type` | string | Yes | `loyalty_tier, platform, device_type, region, country, daypart, segment, visit_count_gte, visit_count_lte`. |
| `condition_value` | string | Yes | For `device_type`: `phone`/`tablet`/`desktop`. For `visit_count_*`: a number (as a string). |
| `override_field` | string | Yes | `title, subtitle, body, image_url, background_url, cta_text, cta_url, cta_deeplink`. |
| `override_value` | string | Yes | |
| `priority` | integer | No | Default `0`. |
| `label` | string, nullable | No | |

**Request example:**

```bash
curl -X POST https://cms.spoonity.com/api/v1/blocks/101/rules \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{ "condition_type": "loyalty_tier", "condition_value": "gold", "override_field": "image_url", "override_value": "https://media.spoonity.com/gold-hero.jpg", "priority": 10 }'
```

**Response example:**

```json
{ "data": { "id": 5, "block_id": 101, "condition_type": "loyalty_tier", "condition_value": "gold", "override_field": "image_url", "override_value": "https://media.spoonity.com/gold-hero.jpg", "priority": 10, "label": null } }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | missing_fields | A required field is absent (`{ error, message }`) |
| 400 | invalid_condition / invalid_field / invalid_condition_value | Unrecognized enum value (`{ error, valid: [...] }`) |
| 404 | not_found | No such block for this vendor (no `message` field) |

### PUT /blocks/{blockId}/rules/{ruleId}

Omitted fields are left unchanged, and a `null` value also leaves the field unchanged, so
`priority` and `label` cannot be cleared here. The rule is looked up by `ruleId` within the vendor;
the `blockId` in the path is not checked against it.

**Auth:** `content:write` scope, or dashboard JWT.

**Path parameters:** `blockId`, `ruleId` (integers).

**Request body:** `condition_value`, `override_value`, `priority`, `label` — all optional.

**Request example:**

```bash
curl -X PUT https://cms.spoonity.com/api/v1/blocks/101/rules/5 \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{ "priority": 20 }'
```

**Response example:**

```json
{ "data": { "id": 5, "priority": 20 } }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 404 | not_found | No rule with that id for this vendor (no `message` field) |

### DELETE /blocks/{blockId}/rules/{ruleId}

Remove a personalization targeting rule. As with `PUT`, the rule is looked up by `ruleId` within
the vendor and the path's `blockId` is not checked.

**Auth:** `content:write` scope, or dashboard JWT.

**Path parameters:** `blockId`, `ruleId` (integers).

**Request example:**

```bash
curl -X DELETE https://cms.spoonity.com/api/v1/blocks/101/rules/5 \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "success": true }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 404 | not_found | No rule with that id for this vendor (no `message` field) |

---

## Translations

Block-level localized overrides. Like Personalization, **write routes carry no role restriction**
beyond `content:write` scope: any authenticated caller with that scope may write translations, a
viewer-role session included.
Supported locales: `en-CA, fr-CA, en-US, es-US, fr-FR, pt-BR`.

### GET /blocks/{blockId}/translations

List a block's locale overrides.

**Auth:** `content:read` scope, or dashboard JWT.

**Path parameters:** `blockId` (integer).

**Request example:**

```bash
curl https://cms.spoonity.com/api/v1/blocks/101/translations \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{
  "data": [ { "block_id": 101, "locale": "fr-CA", "title": "Saison café glacé", "updated_at": "2026-08-01 09:00:00" } ],
  "meta": { "block_id": 101, "supported_locales": ["en-CA", "fr-CA", "en-US", "es-US", "fr-FR", "pt-BR"], "translated_locales": ["fr-CA"], "coverage": "1/5" }
}
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 404 | not_found | No such block for this vendor |

### GET /blocks/{blockId}/translations/{locale}

Get a block's override for one locale.

**Auth:** `content:read` scope, or dashboard JWT.

**Path parameters:** `blockId` (integer), `locale` (string, one of the supported locales).

**Request example:**

```bash
curl https://cms.spoonity.com/api/v1/blocks/101/translations/fr-CA \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "data": { "block_id": 101, "locale": "fr-CA", "title": "Saison café glacé" } }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 404 | not_found | No such block for this vendor, or no translation for that locale |

### PUT /blocks/{blockId}/translations/{locale}

Upsert. At least one translatable field must be present; unsupplied fields keep their previous
value (`COALESCE`).

**Auth:** `content:write` scope, or dashboard JWT.

**Path parameters:** `blockId` (integer), `locale` (string).

**Request body:**

| Name | Type | Required | Description |
|---|---|---|---|
| `title`, `subtitle`, `body`, `cta_text`, `image_url`, `video_url`, `poster_url` | string | At least one | |

**Request example:**

```bash
curl -X PUT https://cms.spoonity.com/api/v1/blocks/101/translations/fr-CA \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{ "title": "Saison café glacé", "cta_text": "Commander" }'
```

**Response example:**

```json
{ "data": { "block_id": 101, "locale": "fr-CA", "title": "Saison café glacé", "cta_text": "Commander", "updated_at": "2026-08-31 12:00:00" } }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | unsupported_locale | `locale` is not one of the six supported values |
| 400 | empty_translation | No translatable field supplied |
| 404 | not_found | No such block for this vendor |

### DELETE /blocks/{blockId}/translations/{locale}

Remove a block's override for one locale, falling back to the default.

**Auth:** `content:write` scope, or dashboard JWT.

**Path parameters:** `blockId` (integer), `locale` (string).

**Request example:**

```bash
curl -X DELETE https://cms.spoonity.com/api/v1/blocks/101/translations/fr-CA \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "success": true, "message": "Translation for fr-CA removed" }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 404 | not_found | No such block for this vendor, or no translation for that locale |

### Item-level translations

The block-level translation overlay above only ever translates a block's own top-level fields
(`title`, `subtitle`, …) — it never reaches inside `config.items[]`. Item-level translations extend
the same overlay model to fields *inside* a block's config: `faq` question/answer, `carousel` item
titles, `points_program` reward titles, and so on. Each override is addressed by a path
`config.<key>[<ref>].<field>`, where `<key>` is the item-array key for the block type (`items`
everywhere except `image_gallery`, which uses `images`), `<ref>` is the item's stable `id` (or a
plain array index as a legacy fallback for items saved before ids existed), and `<field>` is one of
that block type's translatable item fields:

| Block type | Translatable item fields |
|---|---|
| `faq` | `question`, `answer` |
| `carousel` | `title`, `subtitle`, `cta_text` |
| `featured_items` | `label` |
| `image_gallery` | `alt` |
| `points_program` | `title`, `subtitle`, `description`, `badge` |
| `egift_artwork` | `label` |

This is purely additive to the 7-field block-level overlay — neither existing translations nor
existing stored blocks are affected.

### GET /blocks/{blockId}/translations/{locale}/items

Item-level translations for one block/locale, as a flat `{ path: value }` map.

**Auth:** `content:read` scope, or dashboard JWT.

**Path parameters:** `blockId` (integer), `locale` (string).

**Request example:**

```bash
curl https://cms.spoonity.com/api/v1/blocks/101/translations/fr-CA/items \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "data": { "config.items[abc123def0].question": "Quelle est votre politique de retour ?" } }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 404 | not_found | No such block for this vendor |

### PUT /blocks/{blockId}/translations/{locale}/items

Upsert (and clear) item-level translations for one block/locale in a single call.

**Auth:** `content:write` scope, or dashboard JWT.

**Path parameters:** `blockId` (integer), `locale` (string).

**Request body:**

| Name | Type | Required | Description |
|---|---|---|---|
| `translations` | object (`{ path: string \| null }`) | Yes, at least one entry | A `null` or empty-string value **deletes** that path's translation — unlike the block-level `PUT` above, item translations map 1:1 to rows, so clearing one doesn't need a separate `DELETE` call. |

Every path is validated against the block's type and its **current** `config` — the array key must
match the type (`items`/`images`), the field must be translatable for the type, and the referenced
item must actually exist (by id, or by index as the legacy fallback). An unknown/malformed path
`400`s the **whole** request before anything is written. Value types are checked later, while
writing: a value that is neither a string nor `null` `400`s at that entry, and entries processed
before it stay applied.

**Request example:**

```bash
curl -X PUT https://cms.spoonity.com/api/v1/blocks/101/translations/fr-CA/items \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{ "translations": { "config.items[abc123def0].question": "Quelle est votre politique de retour ?" } }'
```

**Response example:**

```json
{ "data": { "config.items[abc123def0].question": "Quelle est votre politique de retour ?" } }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | unsupported_locale | `locale` is not one of the six supported values |
| 400 | bad_request | `translations` missing/empty/not an object, a value isn't a string or `null`, or a path is unknown/malformed for this block's current config (`details.path` names the offending path) |
| 404 | not_found | No such block for this vendor |

### DELETE /blocks/{blockId}/translations/{locale}/items

Remove one item-level translation.

**Auth:** `content:write` scope, or dashboard JWT.

**Path parameters:** `blockId` (integer), `locale` (string).

**Query parameters:**

| Name | Type | Required | Description |
|---|---|---|---|
| `path` | string | Yes | The exact path to remove. |

**Request example:**

```bash
curl -X DELETE "https://cms.spoonity.com/api/v1/blocks/101/translations/fr-CA/items?path=config.items%5Babc123def0%5D.question" \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "success": true, "message": "Item translation at config.items[abc123def0].question removed" }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | Query param `path` is missing |
| 404 | not_found | No such block for this vendor, or no item translation at that path |

### GET /translations/coverage/{spaceId}

Per-locale translation completeness across all blocks in a space — both the block-level overlay
and, additively, the item-level fields above.

**Auth:** `content:read` scope, or dashboard JWT.

**Path parameters:** `spaceId` (integer).

**Request example:**

```bash
curl https://cms.spoonity.com/api/v1/translations/coverage/42 \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{
  "data": {
    "fr-CA": {
      "translated": 2, "total": 3, "pct": 67,
      "item_fields": { "translated": 4, "total": 6, "pct": 67 }
    }
  },
  "total_blocks": 3,
  "total_item_fields": 6,
  "default_locale": "en-CA"
}
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 404 | not_found | No such space for this vendor (no `message` field — undocumented in the prior spec) |

---

## Experiments (A/B/n testing)

Multivariate testing with two or more variants and deterministic `client_id`-hash bucket
assignment. Legacy 2-variant fields (`variant_a`, `variant_b`, `split_pct`) still work but are
deprecated (sunset 2026-12-31) in favor of the `variants[]` array; using them on `POST /experiments`
sets `Deprecation: true` and `Sunset: 2026-12-31` response headers and adds `_deprecated_fields` and
`_migration` to the body.

### GET /experiments

List A/B/n experiments for this vendor.

**Auth:** `experiments:read` scope, or dashboard JWT.

**Query parameters:**

| Name | Type | Description |
|---|---|---|
| `page` | integer | Default `1`. |
| `per_page` | integer | Default `20`, max `100`. |

**Request example:**

```bash
curl https://cms.spoonity.com/api/v1/experiments \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{
  "data": [ { "id": 3, "name": "Hero CTA test", "space_id": 42, "status": "running", "variants": [ { "label": "a", "block_id": 101, "traffic_pct": 50, "impressions": 1200, "conversions": 90, "conversion_rate": 0.075 }, { "label": "b", "block_id": 102, "traffic_pct": 50, "impressions": 1180, "conversions": 110, "conversion_rate": 0.0932, "confidence_vs_control": 90, "lift_pct": 24.3 } ], "total_impressions": 2380, "total_conversions": 200 } ],
  "meta": { "page": 1, "per_page": 20, "total": 1, "total_pages": 1 }
}
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 403 | insufficient_scope | Key lacks `experiments:read` |

### POST /experiments

Create an experiment in `draft`. Provide either `variants[]` (two or more entries; no maximum is
enforced) or legacy `variant_a`/`variant_b`. Returns `201`.

**Auth:** `experiments:write` scope, or dashboard JWT.

**Request body:**

| Name | Type | Required | Description |
|---|---|---|---|
| `name` | string | Yes | |
| `space_id` | integer | Yes | |
| `hypothesis` | string, nullable | No | |
| `variants` | array of `{ label, block_id, traffic_pct }` | No\* | \*Either this or `variant_a`+`variant_b`. `traffic_pct` values must sum to exactly 100 — **the route enforces no per-variant minimum/maximum**, only the sum. Labels and block ids must be unique within the array, and each block must belong to `space_id`. |
| `variant_a`, `variant_b` | integer (block id) | No\* | Legacy 2-variant path. |
| `split_pct` | integer | No | Legacy: variant A's traffic share. Default `50`. |
| `flags_flag_key` | string, nullable | No | Key of an existing flag in the vendor's Spoonity Flags environment (`^[a-z0-9][a-z0-9_-]{0,63}$`; `flagsFlagKey` is accepted as an alias). Empty/`null` clears it. See [Flags-assigned experiments](#flags-assigned-experiments). |

**Request example:**

```bash
curl -X POST https://cms.spoonity.com/api/v1/experiments \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{ "name": "Hero CTA test", "space_id": 42, "variants": [ { "label": "a", "block_id": 101, "traffic_pct": 50 }, { "label": "b", "block_id": 102, "traffic_pct": 50 } ] }'
```

**Response example:**

```json
{ "data": { "id": 3, "name": "Hero CTA test", "space_id": 42, "status": "draft", "variants": [ { "label": "a", "block_id": 101, "traffic_pct": 50 }, { "label": "b", "block_id": 102, "traffic_pct": 50 } ] } }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | missing_fields | `name`/`space_id` absent, or neither `variants` nor `variant_a`+`variant_b` provided |
| 400 | duplicate_labels / duplicate_blocks / invalid_traffic / invalid_blocks / invalid_variants | Variant validation failure |
| 400 | invalid_flags_flag_key | `flags_flag_key` does not match the flag-key pattern (`message` explains) |

### Flags-assigned experiments

Experiments carry two extra read fields (spoonity-cms #33): `flags_flag_key` (string or `null`) and
`flags_assignment_active` (boolean) — `true` when the server runs with `EXPERIMENTS_ASSIGNMENT=flags`
(default `legacy`) **and** the experiment has a key. When active, the Content Delivery API asks
Spoonity Flags for the visitor's treatment (a dry-run `POST /sdk/v1/evaluate` for `flags_flag_key`,
using the request's platform, locale, region, store, daypart, tier, visit count and segments as
targeting attributes) and maps it to a variant: treatment name equal to the variant label
(case-insensitive), or `variant-<label>` / `variant_<label>`, or a treatment config JSON with
`"variant": "<label>"`. Anything else — Flags unreachable, no server key for the vendor, unknown flag,
`control`, an unmapped treatment, or no `client_id` — falls back to the legacy bucket
(`hash(client_id) mod 100` over cumulative `traffic_pct`). The CMS's own impression counts always run
(they feed stats and the winner view); when Flags assigned, the exposure is also forwarded to Flags
in batches. The CMS never creates or edits the flag.

### GET /experiments/{id}

Get experiment details, per-variant stats and a 30-day daily time series.

**Auth:** `experiments:read` scope, or dashboard JWT.

**Path parameters:** `id` (integer).

**Request example:**

```bash
curl https://cms.spoonity.com/api/v1/experiments/3 \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "data": { "id": 3, "name": "Hero CTA test", "status": "running", "variants": [ { "label": "a", "impressions": 1200, "conversions": 90 } ] }, "daily": [ { "date": "2026-08-30", "variant": "a", "cnt": 400, "type": "impression" } ] }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 404 | not_found | No such experiment for this vendor |

### PUT /experiments/{id}

Update `name`, `hypothesis`, `split_pct`, `variants[]` or `flags_flag_key`. Cannot edit a `running` experiment.
When the experiment has a `flags_flag_key` and Flags assignment is active, the response also carries
`flags_warnings` (string[], never an error): flag missing, Flags unreachable, no server key for the
vendor, or a treatment that does not map to a variant (and vice versa).

**Auth:** `experiments:write` scope, or dashboard JWT.

**Path parameters:** `id` (integer).

**Request example:**

```bash
curl -X PUT https://cms.spoonity.com/api/v1/experiments/3 \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{ "hypothesis": "Variant B increases order-page CTR" }'
```

**Response example:**

```json
{ "data": { "id": 3, "hypothesis": "Variant B increases order-page CTR" } }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | running | Experiment is currently running — stop it first |
| 400 | invalid_traffic | `variants[]` percentages don't sum to 100 |
| 400 | invalid_flags_flag_key | `flags_flag_key` does not match the flag-key pattern |
| 404 | not_found | No such experiment for this vendor |

### POST /experiments/{id}/start

Only one experiment may run per space at a time.

**Auth:** `experiments:write` scope, or dashboard JWT.

**Path parameters:** `id` (integer).

`data.assignment` is `flags` when Flags assignment is active for this experiment, otherwise
`legacy`; `data.flags_warnings` (string[]) is present when there is something to fix (see
`PUT /experiments/{id}`). Warnings never block the start. The activity log records `started`.

**Request example:**

```bash
curl -X POST https://cms.spoonity.com/api/v1/experiments/3/start \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "data": { "id": "3", "status": "running", "assignment": "legacy" } }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | already_running / completed / conflict | Bad state, or another experiment is already running for this space |
| 404 | not_found | No such experiment for this vendor |

### POST /experiments/{id}/stop

Stop a running experiment without declaring a winner. The activity log records `stopped`.

**Auth:** `experiments:write` scope, or dashboard JWT.

**Path parameters:** `id` (integer).

**Request example:**

```bash
curl -X POST https://cms.spoonity.com/api/v1/experiments/3/stop \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "data": { "id": "3", "status": "stopped" } }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | not_running | Experiment is not currently running |
| 404 | not_found | No such experiment for this vendor |

### POST /experiments/{id}/winner

Declare a winning variant; marks the experiment `completed`.

**Auth:** `experiments:write` scope, or dashboard JWT.

**Path parameters:** `id` (integer).

**Request body:**

| Name | Type | Required | Description |
|---|---|---|---|
| `winner` | string | Yes | Variant label (`a`, `b`, `c`, …) — must exist in the experiment. |

**Request example:**

```bash
curl -X POST https://cms.spoonity.com/api/v1/experiments/3/winner \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{ "winner": "b" }'
```

**Response example:**

```json
{ "data": { "id": "3", "status": "completed", "winner": "b" } }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | invalid_winner | `winner` missing or not a valid variant label |
| 404 | not_found | No such experiment for this vendor |

### DELETE /experiments/{id}

Cannot delete while running. Removes all impression/conversion data.

**Auth:** `experiments:write` scope, or dashboard JWT.

**Path parameters:** `id` (integer).

**Request example:**

```bash
curl -X DELETE https://cms.spoonity.com/api/v1/experiments/3 \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "success": true }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | running | Stop the experiment before deleting it |
| 404 | not_found | No such experiment for this vendor |

### POST /experiments/{id}/convert

Public endpoint. Client apps call this after a measurable user action (a CTA click, a purchase).
A repeat conversion for the same `(client_id, event_type)` is silently ignored by a unique index
and still answers `{ "recorded": true }`. A conversion sent without `client_id` is never
deduplicated.

**Auth:** None — public.

**Path parameters:** `id` (integer, experiment id).

**Request body:**

| Name | Type | Required | Description |
|---|---|---|---|
| `variant` | string | Yes | Variant label the client was shown. |
| `client_id` | string | No | |
| `event_type` | string | No | Default `cta_click`. |
| `space_slug`, `platform` | string | No | |

**Request example:**

```bash
curl -X POST https://cms.spoonity.com/api/v1/experiments/3/convert \
  -H "Content-Type: application/json" \
  -d '{ "variant": "b", "client_id": "device-abc123", "event_type": "cta_click" }'
```

**Response example:**

```json
{ "recorded": true }
```

If the experiment isn't running:

```json
{ "recorded": false, "reason": "experiment_not_running" }
```

`{ "recorded": false, "reason": "already_converted" }` appears only when the insert itself fails. The
variant label is validated only while the experiment is running.

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | invalid_variant | `variant` missing, not a string, or not a label on this experiment |
| 404 | not_found | No such experiment |

---

## Analytics

Aggregate statistics derived from CMS tables — no separate analytics store. All endpoints are
read-only (`analytics:read` scope covers every one; there is no `analytics:write`).

### GET /analytics/overview

KPI counts with period-over-period change, plus a content freshness score (0–100).

**Auth:** `analytics:read` scope, or dashboard JWT.

**Query parameters:** `range` — `7d` (default), `30d`, or `90d`.

**Request example:**

```bash
curl "https://cms.spoonity.com/api/v1/analytics/overview?range=30d" \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "total_spaces": 12, "published_spaces": 8, "draft_spaces": 3, "total_blocks": 41, "total_media": 20, "total_versions": 30, "activity_events": 55, "activity_change": 12, "new_spaces": 2, "spaces_change": 0, "publish_rate": 67, "freshness_score": 88, "range": "30d" }
```

**Errors:** none beyond auth.

### GET /analytics/activity-trends

Daily event counts by action.

**Auth:** `analytics:read` scope, or dashboard JWT.

**Query parameters:** `range` — `7d` (default), `30d`, `90d`.

**Request example:**

```bash
curl "https://cms.spoonity.com/api/v1/analytics/activity-trends?range=7d" \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "dates": ["2026-08-25", "2026-08-26"], "series": { "created": [1, 0], "published": [0, 1] }, "totals": [1, 1], "range": "7d" }
```

**Errors:** none beyond auth.

### GET /analytics/content-breakdown

Distributions across block types, platforms, workflow statuses and activity action types.

**Auth:** `analytics:read` scope, or dashboard JWT.

**Request example:**

```bash
curl https://cms.spoonity.com/api/v1/analytics/content-breakdown \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "block_types": [ { "block_type": "hero_banner", "cnt": 12 } ], "platforms": [ { "platform": "app", "cnt": 9 } ], "statuses": [ { "status": "published", "cnt": 8 } ], "action_types": [ { "action": "created", "cnt": 30 } ] }
```

**Errors:** none beyond auth.

### GET /analytics/top-spaces

Top 10 spaces ranked by recent activity, then block count.

**Auth:** `analytics:read` scope, or dashboard JWT.

**Query parameters:** `range` — default `30d`.

**Request example:**

```bash
curl https://cms.spoonity.com/api/v1/analytics/top-spaces \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "data": [ { "id": 42, "name": "Summer Promo", "status": "published", "block_count": 3, "version_count": 4, "recent_activity": 6 } ], "range": "30d" }
```

**Errors:** none beyond auth.

### GET /analytics/delivery-stats

Daily delivery **API fetches** (not user impressions — see content-performance for those), top-
served spaces, platform split and average response time.

**Auth:** `analytics:read` scope, or dashboard JWT.

**Query parameters:** `range` — default `30d`.

**Request example:**

```bash
curl https://cms.spoonity.com/api/v1/analytics/delivery-stats \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "dates": ["2026-08-01"], "impressions": [340], "response_ms": [42], "top_served": [ { "space_slug": "summer-promo", "impressions": 340 } ], "platforms": [ { "platform": "app", "cnt": 300 } ], "total_impressions": 340, "avg_response_ms": 42, "range": "30d" }
```

`response_ms` is the per-day average response time, index-aligned with `dates` (and `impressions`).
It is `null` — never `0` — on a day with no delivery events or no timing data, so a quiet day reads
as a gap rather than a real 0ms reading; `dates` is always ascending.

**Errors:** none beyond auth.

### GET /analytics/content-performance

Impression/click/conversion aggregates from `POST /track/{vendorSlug}` events.

**Auth:** `analytics:read` scope, or dashboard JWT.

**Query parameters:**

| Name | Type | Description |
|---|---|---|
| `days` | integer | Default `30`. Clamped into `1` to `365`; an out-of-range value is not an error. |
| `group_by` | string | `space` (default), `block`, `campaign`, or `day`. |

**Request example:**

```bash
curl "https://cms.spoonity.com/api/v1/analytics/content-performance?group_by=block&days=7" \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "group_by": "block", "days": 7, "data": [ { "block_id": 101, "impressions": 1200, "clicks": 90, "conversions": 12, "ctr": 0.075, "title": "Cold Brew Season", "block_type": "hero_banner" } ], "totals": { "impressions": 1200, "clicks": 90, "conversions": 12, "ctr": 0.075 } }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | Unrecognized `group_by` |

### GET /analytics/user-activity

Top 10 team members by event count, with per-action breakdown.

**Auth:** `analytics:read` scope, or dashboard JWT.

**Query parameters:** `range` — default `30d`.

**Request example:**

```bash
curl https://cms.spoonity.com/api/v1/analytics/user-activity \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "data": [ { "user_email": "editor@acme-cafe.com", "total": 22, "creates": 5, "updates": 15, "publishes": 2, "deletes": 0 } ], "range": "30d" }
```

**Errors:** none beyond auth.

### GET /analytics/heatmap

7×24 grid (day-of-week × hour) of activity-log event counts.

**Auth:** `analytics:read` scope, or dashboard JWT.

**Query parameters:** `range` — default `30d`.

**Request example:**

```bash
curl https://cms.spoonity.com/api/v1/analytics/heatmap \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "grid": [[0,0,0,1,2], [0,0,0,0,0]], "range": "30d" }
```

**Errors:** none beyond auth.

---

## Activity Log

### GET /activity

Audit trail of CMS content changes for the vendor. **Not scope-gated** — any authenticated
principal with vendor context can read it, regardless of API key scopes.

**Auth:** Any valid API key or dashboard JWT (no specific scope required).

**Query parameters:**

| Name | Type | Description |
|---|---|---|
| `page` | integer | Default `1`. |
| `limit` | integer | Default `50`, max `100`. |
| `entity_type` | string | `space, block, media, experiment, webhook, user`. |

**Request example:**

```bash
curl "https://cms.spoonity.com/api/v1/activity?entity_type=space&limit=10" \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{
  "data": [ { "id": 88, "vendor_id": 7, "user_email": "admin@acme-cafe.com", "action": "published", "entity_type": "space", "entity_id": 42, "entity_name": "Summer Promo", "details": { "version": 4 }, "created_at": "2026-08-31 12:00:00" } ],
  "pagination": { "page": 1, "limit": 10, "total": 1, "total_pages": 1 }
}
```

Experiment start/stop are logged as `started`/`stopped` (spoonity-cms #37); older rows that were
written as `published`/`unpublished` are mapped to those names on read for
`entity_type=experiment`. Space actions keep `published`/`unpublished`.

**Errors:** none beyond auth.

---

## Search

### GET /search

Server-side full-text search (SQL `LIKE`) across spaces, blocks and experiments, ranked spaces →
blocks → experiments. **Not scope-gated** — any authenticated principal with vendor context can
search, regardless of API key scopes.

**Auth:** Any valid API key or dashboard JWT (no specific scope required).

**Query parameters:**

| Name | Type | Required | Description |
|---|---|---|---|
| `q` | string | Yes | At least 2 characters. |
| `types` | string | No | Comma-separated `spaces,blocks,experiments`. Default all three. |
| `limit` | integer | No | Default `20`, max `50`. |

**Request example:**

```bash
curl "https://cms.spoonity.com/api/v1/search?q=cold+brew&types=spaces,blocks" \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "data": [ { "id": 42, "name": "Summer Promo", "result_type": "space", "block_count": 3 }, { "id": 101, "title": "Cold Brew Season", "result_type": "block", "space_name": "Summer Promo" } ], "query": "cold brew", "total": 2 }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | query_too_short | `q` missing or under 2 characters |

---

## Targeting Lookups

Feeds the dashboard's targeting pickers (space/block `region`, `store_ids`, `audience`) from the
vendor's own Spoonity loyalty account, so an editor sees "Flagship" and "Gold" instead of raw ids
and codes. Requires a Spoonity service credential (`SPOONITY_SERVICE_USERNAME`/
`SPOONITY_SERVICE_PASSWORD`, or `SPOONITY_SESSION_KEY`) to be configured — for a single-vendor
account this happens automatically after the next login; a multi-vendor deployment needs the
service credential set explicitly. `SPOONITY_PLATFORM_HOST_MAP` overrides the platform host for
vendors that live on a dedicated cluster rather than `api.spoonity.com`.

**Both endpoints always answer `200`.** "I cannot offer you a list right now" is a normal outcome
here, not a client error — no credential configured, the platform unreachable, or a tenancy check
that failed all fall back to the dashboard's free-text input rather than raising an error. The body
carries `available: false` plus a `reason` instead of an HTTP error status.

**Auth (both endpoints):** dashboard JWT, the legacy vendor-wide key, or a scoped key with `*` —
`spaces` is **not** in the mintable scope vocabulary (see [Authentication](#authentication)), so a
newly-minted scoped key cannot reach either route no matter which scopes it's given; only a
full-access key or a signed-in session can. Reachable by **every** role, `viewer` included — an
editor picking a targeting value needs the name whether or not they can save the space.

### GET /lookups

A status summary, so the dashboard can decide once whether to render pickers or free-text inputs,
without fetching all four lists up front.

**Request example:**

```bash
curl https://cms.spoonity.com/api/v1/lookups \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiJ9..."
```

**Response example:**

```json
{ "configured": true, "kinds": ["tiers", "segments", "stores", "regions"], "vendor_id": 7 }
```

**Errors:** none beyond auth.

### GET /lookups/{kind}

The option list for one lookup kind, in `items`, each already shaped for a picker: `{ value, label,
subtitle? }`. `value` is exactly what a space/block stores for that targeting field — tier
**names**, region **codes**, store/segment **ids as strings** — so it's also what the Content
Delivery API compares client-declared/resolved context against.

**Path parameters:**

| Name | Type | Description |
|---|---|---|
| `kind` | string | One of `tiers`, `segments`, `stores`, `regions`. |

**Request example:**

```bash
curl https://cms.spoonity.com/api/v1/lookups/tiers \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiJ9..."
```

**Response example:**

```json
{ "kind": "tiers", "available": true, "items": [ { "value": "gold", "label": "Gold" }, { "value": "silver", "label": "Silver" } ], "source": "spoonity", "stale": false }
```

Unavailable (still `200`):

```json
{ "kind": "tiers", "available": false, "items": [], "reason": "not_configured", "note": "Spoonity lookups are not available yet. A single-vendor account lights these up automatically after logging in again; otherwise set SPOONITY_SERVICE_USERNAME and SPOONITY_SERVICE_PASSWORD (or SPOONITY_SESSION_KEY) to enable them for every vendor." }
```

`reason` is one of `not_configured`, `auth_failed` (couldn't authenticate against the Spoonity
identity server), `tenant_mismatch` (the platform host answered for a different vendor — set
`SPOONITY_PLATFORM_HOST_MAP` for this vendor), or `upstream_error` (the platform didn't answer in
time). A fresh list is cached for 5 minutes and served with `stale: false`. `stale: true` means an
upstream call just failed and the last list fetched for this vendor and kind was served instead,
whatever its age.

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 404 | unknown_lookup | `kind` isn't one of the four values above (echoes `valid`) |

---

## Webhooks

Outbound event notifications. Deliveries are `POST`ed as `{ event, vendor_id, timestamp, data }`
with `X-Spoonity-Signature: sha256=<hmac>`, `X-Spoonity-Event` and `X-Spoonity-Delivery` headers. A
failed delivery is attempted at most 3 times in total (retries after 2s and 4s). Verify by
HMAC-SHA256'ing the raw body with the webhook's `secret`. Every error in this group is bare
`{ "error": "<code>" }` with no `message`, except URL rejections (`missing_url`, `invalid_url`) which
add a `message`. Events: `space.created`,
`space.submitted`, `space.approved`, `space.rejected`, `space.scheduled`, `space.published`,
`space.unpublished`, `space.deleted`, `space.updated`, `experiment.started`, `experiment.stopped`,
`experiment.completed`, `block.created`, `block.updated`, `block.deleted`,
`content.performance.daily` (an aggregated `{ days, spaces }` push after each hourly rollup, not
one delivery per event). **Write routes carry no role restriction** beyond `webhooks:write` scope.

### Webhook URL rules

Webhook URLs are vendor-supplied and the CMS calls them from inside its own network, so they are
checked at create/update and again at delivery (spoonity-cms #36, CM-12). A URL is **rejected** with
`400 { "error": "invalid_url", "message": "..." }` when it:

- is longer than 2048 characters or not a parseable URL;
- does not use `https://` (`http://` is accepted only on a development server);
- uses an IP literal, in any encoding (`http://169.254.169.254/`, `http://2852039166/`, `[::1]`);
- uses `localhost`, `metadata`, `metadata.google.internal`, any `*.localhost`, `*.internal`,
  `*.local`, `*.localdomain` or `*.home.arpa` name, or a single-label name (no dot);
- has a name that fails to resolve, or resolves to **any** private or reserved address
  (loopback, RFC 1918, link-local incl. the `169.254.169.254` metadata server, CGNAT, multicast,
  TEST-NETs, and IPv6 equivalents including mapped/NAT64/6to4/Teredo forms).

At delivery the connection is pinned to the address that was checked (defeating DNS rebinding) and
**redirects are never followed** — a `3xx` counts as a failed delivery. A blocked destination is not
retried. Stored URLs that predate this check and are now refused are skipped on fan-out (logged
server-side only), and `POST /webhooks/{id}/test` returns `400 invalid_url` for them; update the URL
to fix. `PUT` re-validates only when `url` is sent.

### GET /webhooks

List registered webhook endpoints for this vendor.

**Auth:** `webhooks:read` scope, or dashboard JWT.

**Request example:**

```bash
curl https://cms.spoonity.com/api/v1/webhooks \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "data": [ { "id": 4, "url": "https://acme-cafe.com/webhooks/cms", "events": ["space.published"], "is_active": true, "last_fired_at": "2026-08-30 10:00:00" } ] }
```

**Errors:** none beyond auth.

### POST /webhooks

Returns the signing `secret` once — never returned again on subsequent reads.

**Auth:** `webhooks:write` scope, or dashboard JWT.

**Request body:**

| Name | Type | Required | Description |
|---|---|---|---|
| `url` | string (URI) | Yes | |
| `events` | string[] | No | Defaults to every supported event when omitted. |

**Request example:**

```bash
curl -X POST https://cms.spoonity.com/api/v1/webhooks \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{ "url": "https://acme-cafe.com/webhooks/cms", "events": ["space.published", "space.unpublished"] }'
```

**Response example:**

```json
{ "data": { "id": 4, "url": "https://acme-cafe.com/webhooks/cms", "events": ["space.published", "space.unpublished"], "is_active": true, "secret": "3f9c1a...b02e" } }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | missing_url / invalid_url / invalid_events | Validation failure. `missing_url` and `invalid_url` carry a `message` (see [Webhook URL rules](#webhook-url-rules)); `invalid_events` echoes `invalid`/`valid` arrays |

### GET /webhooks/{id}

Returns the webhook (secret withheld) plus its last 50 delivery attempts — there is no separate
deliveries endpoint.

**Auth:** `webhooks:read` scope, or dashboard JWT.

**Path parameters:** `id` (integer).

**Request example:**

```bash
curl https://cms.spoonity.com/api/v1/webhooks/4 \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "data": { "id": 4, "url": "https://acme-cafe.com/webhooks/cms", "events": ["space.published"], "is_active": true }, "deliveries": [ { "id": 900, "status_code": 200, "created_at": "2026-08-30 10:00:00" } ] }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 404 | not_found | No such webhook for this vendor |

### PUT /webhooks/{id}

Update a webhook endpoint's URL, events, or active state.

**Auth:** `webhooks:write` scope, or dashboard JWT.

**Path parameters:** `id` (integer).

**Request body:** `url`, `events`, `is_active` — all optional.

**Request example:**

```bash
curl -X PUT https://cms.spoonity.com/api/v1/webhooks/4 \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{ "is_active": false }'
```

**Response example:**

```json
{ "data": { "id": 4, "is_active": false } }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | invalid_url | `url` fails the [Webhook URL rules](#webhook-url-rules); carries a `message` |
| 404 | not_found | No such webhook for this vendor |

### POST /webhooks/{id}/rotate-secret

Generate a new signing secret for a webhook endpoint, invalidating the old one.

**Auth:** `webhooks:write` scope, or dashboard JWT.

**Path parameters:** `id` (integer).

**Request example:**

```bash
curl -X POST https://cms.spoonity.com/api/v1/webhooks/4/rotate-secret \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "data": { "secret": "a1b2c3...f9e8" } }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 404 | not_found | No such webhook for this vendor |

### POST /webhooks/{id}/test

Fires a `space.published` event with `data: { test: true, message, webhook_id }` to **only** the
webhook in the path (spoonity-cms #36 — it used to fan out to every subscribed webhook), whether or
not that webhook is active or subscribed to `space.published`. A stored URL that no longer passes the
[Webhook URL rules](#webhook-url-rules) is refused before sending.

**Auth:** `webhooks:write` scope, or dashboard JWT.

**Path parameters:** `id` (integer).

**Request example:**

```bash
curl -X POST https://cms.spoonity.com/api/v1/webhooks/4/test \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "success": true, "message": "Test webhook queued for delivery" }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | invalid_url | The stored URL is no longer allowed; `message` ends `Update the URL before testing.` |
| 404 | not_found | No such webhook for this vendor |

### DELETE /webhooks/{id}

Also deletes its delivery history.

**Auth:** `webhooks:write` scope, or dashboard JWT.

**Path parameters:** `id` (integer).

**Request example:**

```bash
curl -X DELETE https://cms.spoonity.com/api/v1/webhooks/4 \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "success": true }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 404 | not_found | No such webhook for this vendor |

---

## Team (Users)

Per-vendor team members and their dashboard roles. Not scope-gated (no `requireScope` at all) —
gated purely by `requireRole('admin')` on the writes.

### GET /users

List this vendor's team members and their dashboard roles.

**Auth:** Any valid API key or dashboard JWT (no specific scope or role required).

**Request example:**

```bash
curl https://cms.spoonity.com/api/v1/users \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "data": [ { "id": 2, "email": "editor@acme-cafe.com", "role": "editor", "added_by": "admin@acme-cafe.com", "created_at": "2026-05-01 09:00:00" } ] }
```

**Errors:** none beyond auth.

### POST /users

Upserts a team member by email — this is also how an existing member's role is changed (there is
no `PUT /users/{id}`).

**Auth:** Dashboard JWT or API key — **admin** role required.

**Request body:**

| Name | Type | Required | Description |
|---|---|---|---|
| `email` | string | Yes | |
| `role` | string | Yes | `admin`, `editor`, or `viewer`. |

**Request example:**

```bash
curl -X POST https://cms.spoonity.com/api/v1/users \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{ "email": "newmember@acme-cafe.com", "role": "editor" }'
```

**Response example (new member, 201):**

```json
{ "data": { "id": 5, "email": "newmember@acme-cafe.com", "role": "editor" } }
```

Updating an existing member's role returns `200` with `{ "data": {...}, "updated": true }`.

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | missing_fields / invalid_role | |
| 403 | forbidden | Caller is not an admin |

### DELETE /users/{id}

Requires admin. A member may not remove themselves.

**Auth:** Dashboard JWT or API key — **admin** role required.

**Path parameters:** `id` (integer, `vendor_users` row id).

**Request example:**

```bash
curl -X DELETE https://cms.spoonity.com/api/v1/users/5 \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "success": true }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | self_removal | Cannot remove your own account |
| 403 | forbidden | Caller is not an admin |
| 404 | not_found | No such member for this vendor (bare `{ "error": "not_found" }`, no `message`) |

---

## Brand

One brand record per vendor — the palette, wordmark and artwork a wallet Pass Studio uses to render
a customer's loyalty pass. This is the CMS side of the Wallet pass brand: the CMS is the system of
record, and `wallet-api.spoonity.com` reads/writes it through these same routes rather than its own
storage.

### GET /brand

This vendor's brand record.

**Auth:** `vendor:read` scope, or dashboard JWT.

**Request example:**

```bash
curl https://cms.spoonity.com/api/v1/brand \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{
  "vendorId": "7",
  "company": "Acme Cafe Inc.",
  "name": "Acme Cafe",
  "colors": { "primary": "#38bdf8", "text": "#0f172a" },
  "palette": ["#38bdf8", "#0f172a", "#ffffff"],
  "logoUri": "https://media.spoonity.com/acme-logo.png",
  "iconUri": "https://media.spoonity.com/acme-icon.png",
  "heroUri": null,
  "sourceUrl": "https://acme-cafe.com",
  "updatedAt": "2026-08-01T09:00:00.000Z"
}
```

The **`404` is load-bearing**, not just tidy REST: a Pass Studio uses it to decide a vendor has
never been onboarded and opens its first-run brand-setup flow. A vendor that has never had a brand
written for it is a `404`, not an empty-but-present record.

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 404 | not_found | This vendor has no brand record yet |

### PUT /brand

Merge a partial patch into the vendor's brand record, creating it if none exists yet. Returns the
complete, post-merge brand either way.

**Merge semantics** — this is the whole point of the endpoint: a field **absent** from the body
keeps its previously stored value; a field **present and `null`** clears it; only a present,
non-null field overwrites. There is no way to "clear to empty string" — `null` is the only clear
signal. `vendorId` and `updatedAt` are not writable — the vendor always comes from the
authenticated session and the timestamp is server-set, so echoing a `GET` response straight back
into a `PUT` can never move a brand onto another tenant.

**Auth:** `vendor:write` scope, or dashboard JWT — **`denyRole('viewer')`, deliberately not
`requireRole('admin')`.** The Wallet Pass Studio authenticates as a Google-OIDC service identity,
which this API grants the `editor` role by default — an `admin`-only gate would 403 the one caller
this route exists for. A read-only human (`viewer`) is refused; a roleless API key and an editor
(human or service) can write it.

**Request body:** any subset of the following, each independently nullable to clear it:

| Name | Type | Description |
|---|---|---|
| `company` | string | |
| `name` | string | |
| `colors` | object | |
| `palette` | array | |
| `logoUri`, `iconUri`, `heroUri` | string | |
| `sourceUrl` | string | |

**Request example:**

```bash
curl -X PUT https://cms.spoonity.com/api/v1/brand \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiJ9..." \
  -H "Content-Type: application/json" \
  -d '{ "heroUri": "https://media.spoonity.com/acme-hero.png" }'
```

**Response example:** the complete brand, same shape as `GET /brand`.

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | Body isn't a JSON object, or a field's value is the wrong type (e.g. `colors` sent as a string) |
| 403 | forbidden | Caller is a viewer |

---

## Vendor Settings & API Keys

### GET /vendor/settings

Returns the vendor row (`id`, `spoonity_vendor_id`, `name`, `slug`, `logo_url`, `brand_color`,
`settings`) plus `base_url` — this service's own public origin, so a caller whose own origin
differs from the CMS's (e.g. the Prism shell) can still build a correct
`${base_url}/api/v1/content/:vendorSlug/:slug` link.

**Auth:** `vendor:read` scope, or dashboard JWT. (Reachable by a scoped API key, **not**
dashboard-session-only — see the note in Authentication above.)

**Request example:**

```bash
curl https://cms.spoonity.com/api/v1/vendor/settings \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "id": 7, "spoonity_vendor_id": "v_9001", "name": "Acme Cafe", "slug": "acme-cafe", "logo_url": null, "brand_color": "#38bdf8", "settings": { "auto_shorten_cta": false }, "base_url": "https://cms.spoonity.com" }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 404 | not_found | Vendor not found |

### PUT /vendor/settings

Update this vendor's account-level settings.

**Auth:** `vendor:write` scope, or dashboard JWT — **admin** role required.

**Request body:** `name`, `slug`, `logo_url`, `brand_color`, `settings`, all optional. `settings`
**replaces** the stored settings object as a whole rather than merging into it, so send every key
you want to keep (for example `auto_shorten_cta` and `default_fallback_space_slug`). Empty `name` or
`slug` values are ignored; `logo_url` and `brand_color` accept `null` or `""` to clear. `base_url`
is never persisted even if echoed back in a naive round-trip of the GET response.

**Request example:**

```bash
curl -X PUT https://cms.spoonity.com/api/v1/vendor/settings \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{ "settings": { "auto_shorten_cta": true } }'
```

**Response example:**

```json
{ "id": 7, "name": "Acme Cafe", "slug": "acme-cafe", "settings": { "auto_shorten_cta": true } }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 403 | forbidden | Caller is not an admin |
| 403 | insufficient_scope | Key lacks `vendor:write` |

### GET /vendor/api-key/status

Check whether the legacy vendor-wide API key exists, without exposing it.

**Auth:** `vendor:read` scope, or dashboard JWT. (Reachable by a scoped API key — see the note
above.)

**Request example:**

```bash
curl https://cms.spoonity.com/api/v1/vendor/api-key/status \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "exists": true, "hint": "ab12", "last_rotated": "2026-06-01 09:00:00" }
```

**Errors:** none beyond auth.

### POST /vendor/api-key/rotate

Generate a new legacy vendor-wide key; the old one stops working immediately.

**Auth:** Dashboard JWT session **only** (`requireJwtSession` blocks API keys and service tokens
outright) — **admin** role also required.

**Request example:**

```bash
curl -X POST https://cms.spoonity.com/api/v1/vendor/api-key/rotate \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiJ9..."
```

**Response example:**

```json
{ "api_key": "sck_a1b2c3d4e5f6...f6a1", "hint": "f6a1", "message": "Store this key securely. It will not be shown again." }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 403 | forbidden | Caller used an API key/service token, or is not an admin |

### GET /vendor/api-keys

List every scoped key ever issued for the vendor (including revoked), newest first. The secret is
never returned — only `key_hint` (last 4 characters).

**Auth:** Dashboard JWT session **only** — an `X-API-Key` request is rejected by
`requireJwtSession` regardless of its scopes.

**Request example:**

```bash
curl https://cms.spoonity.com/api/v1/vendor/api-keys \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiJ9..."
```

**Response example:**

```json
[ { "id": 12, "name": "CMS MCP server", "key_hint": "ab12", "scopes": ["content:read", "content:write"], "role": "editor", "is_active": true, "last_used_at": "2026-08-30 08:00:00", "revoked_at": null, "created_at": "2026-07-01 10:00:00", "created_by": "admin@acme-cafe.com" } ]
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 401 | unauthorized | Missing/invalid credentials |
| 403 | forbidden | An API key was used instead of a dashboard session |

### POST /vendor/api-keys

Mint a named, scoped key. Returns the secret **exactly once**. A vendor may hold at most 20 active
keys.

**Auth:** Dashboard JWT session **only**; minting a key that carries a `role` additionally requires
**admin**.

**Request body:**

| Name | Type | Required | Description |
|---|---|---|---|
| `name` | string (max 100) | Yes | |
| `scopes` | string[] | Yes | From the vocabulary in [Authentication](#2-scoped-api-keys). At least one. |
| `role` | string, nullable | No | `viewer`/`editor`/`admin`. Omit/`null`/`""` for a roleless key. Requires an admin session. |

**Request example:**

```bash
curl -X POST https://cms.spoonity.com/api/v1/vendor/api-keys \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiJ9..." \
  -H "Content-Type: application/json" \
  -d '{ "name": "Reporting job", "scopes": ["content:read", "analytics:read"] }'
```

**Response example:**

```json
{ "id": 13, "name": "Reporting job", "api_key": "sck_9f2c1a4b7e...ab12", "hint": "ab12", "scopes": ["content:read", "analytics:read"], "role": null, "message": "Store this key securely. It will not be shown again." }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | Missing/blank/over-long `name`; missing/empty/unrecognized `scopes` (echoes `valid_scopes`); unrecognized `role` (echoes `valid_roles`); or the 20-key limit is reached |
| 403 | forbidden | A non-admin session requested a `role`, or an API key was used instead of a dashboard session |

### DELETE /vendor/api-keys/{id}

Soft-revokes the key (`is_active: false`, `revoked_at` stamped); the row is kept for audit and
still appears in the list. Idempotent.

**Auth:** Dashboard JWT session **only**.

**Path parameters:** `id` (integer, key id).

**Request example:**

```bash
curl -X DELETE https://cms.spoonity.com/api/v1/vendor/api-keys/13 \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiJ9..."
```

**Response example:** `204 No Content` (empty body).

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | `id` is not a number |
| 403 | forbidden | An API key was used instead of a dashboard session |
| 404 | not_found | No such key for this vendor |

---

## Legacy Content Import

### POST /vendors/{vendorSlug}/import/legacy-content

One-time (per vendor, safely re-runnable) migration path for onboarding a vendor's existing content
— home banners, offers, FAQs, the points program, eGift artwork and similar — from an outgoing
platform's export format into the CMS's own spaces and blocks. Idempotent: re-running the same
import updates the same CMS space(s) rather than creating duplicates, and a space that was renamed
after import is still found on re-run and is never renamed back.

**Auth:** `content:write` scope, or dashboard JWT — non-viewer. `vendorSlug` must match the
authenticated vendor.

**Path parameters:**

| Name | Type | Description |
|---|---|---|
| `vendorSlug` | string | Must match the authenticated vendor. |

**Request body:**

| Name | Type | Required | Description |
|---|---|---|---|
| `groups` | object (`{ <group name>: LegacyExportRecord[] }`) | Yes | The export, grouped by legacy content type. Each record needs at least a numeric `home_id`; the rest of the shape is intentionally permissive — it mirrors whatever the outgoing export produced. |
| `merchant_id` | string or number | No | Recorded on the activity-log entry when not a dry run. |
| `dry_run` | boolean | No | **Default `true`.** Only an explicit `false` writes anything — matches the companion CLI's dry-run-unless-`--apply` default. A dry run returns the same report shape, with nothing persisted. |
| `options.space_prefix` | string | No | Prepended to every space slug this import would create. |
| `options.publish` | boolean | No | Opt-in: publish each written/updated space immediately instead of leaving it in its current workflow status. |

**Request example:**

```bash
curl -X POST https://cms.spoonity.com/api/v1/vendors/acme-cafe/import/legacy-content \
  -H "X-API-Key: sck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{ "groups": { "faqs": [ { "home_id": 501, "primary_content": "Do you offer refunds?", "secondary_content": "Yes, within 14 days." } ] }, "dry_run": true }'
```

**Response example:**

```json
{
  "dry_run": true,
  "spaces": [
    {
      "slug": "app-faqs",
      "group": "faqs",
      "action": "reused",
      "unknown_group": false,
      "blocks": [ { "block_type": "faq", "action": "updated", "home_ids": [501], "warnings": [] } ],
      "published": false,
      "would_publish": false
    }
  ],
  "media": { "uploaded": 0, "reused": 0, "failed": [] },
  "skipped_items": []
}
```

An item that the legacy system itself would have skipped (an empty title or image, matching the
outgoing platform's own display rule) is reported in `skipped_items`, not silently dropped without a
trace. A group this importer has no specific mapping for still imports — as an opaque
`custom_json` block — and is flagged with `unknown_group: true` so an operator notices.

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | `groups` missing/malformed, or an item is missing its numeric `home_id` |
| 403 | forbidden | Caller is a viewer, or `vendorSlug` doesn't match the authenticated vendor |
| 500 | import_failed | The import failed unexpectedly (partial writes are possible on a mid-import failure; safe to re-run) |

---

## Vendor Authentication (dashboard login flow)

These are how a **human dashboard user** obtains the JWT used above — not something a server
integration calls routinely.

### POST /auth/login

Authenticate against the Spoonity Identity Server. A single-vendor user gets a token immediately;
a multi-vendor user gets a short-lived `selection_token` for `/auth/select-vendor`. Rate-limited to
10 requests/min/IP.

**Auth:** None.

**Request body:**

| Name | Type | Required |
|---|---|---|
| `email` | string | Yes |
| `password` | string | Yes |

**Request example:**

```bash
curl -X POST https://cms.spoonity.com/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{ "email": "admin@acme-cafe.com", "password": "REDACTED" }'
```

**Response example (single vendor):**

```json
{ "success": true, "requires_vendor_selection": false, "token": "eyJhbGciOiJIUzI1NiJ9...", "vendor": { "id": 7, "spoonity_vendor_id": "v_9001", "name": "Acme Cafe", "slug": "acme-cafe" }, "user": { "email": "admin@acme-cafe.com" }, "identities": [ { "id": "v_9001", "name": "Acme Cafe" } ] }
```

**Response example (multi-vendor):**

```json
{ "success": true, "requires_vendor_selection": true, "selection_token": "eyJhbGciOiJIUzI1NiJ9...", "identities": [ { "id": "v_9001", "name": "Acme Cafe" }, { "id": "v_9002", "name": "Acme Bakery" } ] }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | `email`/`password` missing |
| 401 | unauthorized | Invalid credentials |
| 403 | forbidden | Email domain not allowlisted, the identity server would not list the account's vendors, the account is linked to no vendors, or the single vendor's scoped session was refused |
| 500 | internal | The identity server could not be reached |

### POST /auth/select-vendor

Second leg of a multi-vendor login. Send the `selection_token` from `/auth/login` with the chosen
`vendor_id` (an `email`+`password` fallback is supported for legacy clients). Rate-limited to 10
requests/min/IP.

**Auth:** None (the `selection_token` itself is the credential).

**Request body:**

| Name | Type | Required | Description |
|---|---|---|---|
| `vendor_id` | string | Yes | The Spoonity vendor id. A CMS slug is not accepted. |
| `selection_token` | string | No\* | \*Or `email`+`password`. |
| `email`, `password` | string | No | Legacy alternative. |
| `vendor_name` | string | No | Used when auto-provisioning a new vendor. |

**Request example:**

```bash
curl -X POST https://cms.spoonity.com/api/v1/auth/select-vendor \
  -H "Content-Type: application/json" \
  -d '{ "selection_token": "eyJhbGciOiJIUzI1NiJ9...", "vendor_id": "v_9002" }'
```

**Response example:**

```json
{ "token": "eyJhbGciOiJIUzI1NiJ9...", "vendor": { "id": 8, "spoonity_vendor_id": "v_9002", "name": "Acme Bakery", "slug": "acme-bakery", "logo_url": null, "brand_color": null }, "user": { "email": "admin@acme-cafe.com", "id": "admin@acme-cafe.com", "role": "admin" } }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | `vendor_id` missing, or neither `selection_token` nor credentials supplied |
| 401 | unauthorized | The `selection_token` is invalid or expired |
| 403 | forbidden | Email domain not allowlisted, the vendor isn't one of the caller's identities, or (legacy `email`+`password` path) the identity server refused the credentials for that vendor |
| 500 | internal | The identity server could not be reached |

### POST /auth/switch-vendor

Re-issue a JWT scoped to another vendor already authorized at login (`allowedVendors` on the
current token) — no credentials needed. Auto-provisions the vendor's CMS row on first switch.

**Auth:** Dashboard JWT. The route runs `requireAuth` only, so an API key or service token is
authenticated too, but it carries no `allowedVendors` and gets the `403`.

**Request body:**

| Name | Type | Required |
|---|---|---|
| `vendor_id` | string | Yes |
| `vendor_name` | string | No |

**Request example:**

```bash
curl -X POST https://cms.spoonity.com/api/v1/auth/switch-vendor \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiJ9..." \
  -H "Content-Type: application/json" \
  -d '{ "vendor_id": "v_9002" }'
```

**Response example:**

```json
{ "token": "eyJhbGciOiJIUzI1NiJ9...", "vendor": { "id": 8, "spoonity_vendor_id": "v_9002", "name": "Acme Bakery", "slug": "acme-bakery", "logo_url": null, "brand_color": null }, "user": { "email": "admin@acme-cafe.com", "id": "admin@acme-cafe.com", "role": "admin" } }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | `vendor_id` missing |
| 403 | forbidden | Vendor is not in the token's `allowedVendors` |
| 404 | not_found | Vendor could not be resolved |

### GET /auth/me

Current user + vendor info from the presented credential.

**Auth:** Dashboard JWT, API key or service token. Not scope-gated.

**Request example:**

```bash
curl https://cms.spoonity.com/api/v1/auth/me \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiJ9..."
```

**Response example:**

```json
{ "user": { "email": "admin@acme-cafe.com", "id": "admin@acme-cafe.com" }, "vendor": { "id": 7, "spoonity_vendor_id": "v_9001", "name": "Acme Cafe", "slug": "acme-cafe", "logo_url": null, "brand_color": "#38bdf8" } }
```

**Errors:** none beyond auth.

### Development-only: POST /auth/dev-login

The route source also defines `POST /auth/dev-login`, a credential-free login that auto-provisions
a demo vendor. It is gated on `config.isDev` and returns a plain `404 not_found` whenever the
service is not running in development mode — **it is never reachable in production** and is not
part of the public API surface (the upstream `openapi.yaml` deliberately excludes it too). It is
documented here only so its existence is not a surprise when reading route source.

---

## Health and discovery

These routes sit outside `/api/v1`, so they are not in the OpenAPI spec. They are public, need no
credentials, and are not rate limited.

### GET /health

Liveness and readiness in one document. The deploy workflow gates on this returning `200`.

**Auth:** None.

**Request example:**

```bash
curl https://cms.spoonity.com/health
```

**Response example:**

```json
{ "status": "healthy", "service": "spoonity-cms", "timestamp": "2026-09-30T10:40:33.607Z", "uptime_seconds": 140742, "version": "1.2.0", "checks": { "database": "ok" } }
```

`status` is `healthy` (`200`), `starting` (`503`: the process is listening but has never reached
the database; it retries on its own, and the body may add a `detail` string) or `degraded` (`503`:
the database was reachable and is not any more; delivery serves last-good content and tracking
drops events).

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 503 | (status `starting` or `degraded`) | The database is not reachable. The body has the same shape as the `200`. |

### GET /docs/openapi.yaml

The CMS repository's own OpenAPI file, served as-is. It lags the route source: it lacks 15 of the
operations documented here (the item-level translation routes, app config, brand, lookups, the
Links helper routes and the legacy import). Prefer the maintained copy at
[openapi/cms.yaml](openapi/cms.yaml).

**Auth:** None.

```bash
curl https://cms.spoonity.com/docs/openapi.yaml
```

### GET /docs/guides

HTML index of the CMS developer guides; `GET /docs/guides/{slug}` renders one guide, and an unknown
slug is an HTML `404`.

**Auth:** None.

```bash
curl https://cms.spoonity.com/docs/guides
```
