# Prism BFF API

**This is not a public integration surface.** Every route on this page lives
on Prism's own backend-for-frontend (`prism.spoonity.com`) and is called by
Prism's own single-page app, from the same origin. Apart from the sign-in
handshake, the health probe, the PostHog relay and this documentation site,
every route requires a signed-in **Prism operator session cookie**
(`prism_session`, HttpOnly, Secure, `SameSite=Lax`) and is scoped to that
session's active vendor. The one exception is `POST /api/flags/sync/segment`,
which also accepts a Google-signed ID token from Cloud Scheduler. None of it
is reachable with a vendor API key. If you are looking for a self-serve
integration API, see [`cms.md`](./cms.md), [`links.md`](./links.md), or
[`wallet.md`](./wallet.md) instead.

This page exists for two audiences: someone trying to understand what the
Prism dashboard itself does when an operator clicks something, and anyone
working on Prism's backend. The request and response shapes below are what
ships today; they are not a contract anyone outside this repository should
build against.

## Conventions specific to this page

- **Base URL:** same origin as the dashboard, `https://prism.spoonity.com`.
  Every path below is relative to that.
- **Session cookie:** `prism_session`, attached automatically by the
  browser on every same-origin request. It is never a header value a client
  sets itself, and it cannot be replaced with a static key.
- **The session guard.** Every session-authenticated route runs the same
  check first. No cookie, or one that is expired or tampered with, answers
  `401 {"error": "unauthorized", "detail": "Not signed in"}`. A session whose
  email domain has since been removed from the allowlist answers
  `403 {"error": "forbidden", "detail": "Access to Prism is restricted to Spoonity team accounts."}`.
  A session that has been logged out or whose server-side record was deleted
  answers `401` with `"error": "unauthorized"` and a "session has ended"
  detail. The cookie is cleared in all three cases. Revocation is checked
  against the session store with a cache of up to 30 seconds.
- **Vendor scoping:** wherever a route below reads or writes "the active
  vendor," that is `session.activeVendorId`, the vendor the operator most
  recently selected or switched to. Only the sign-in routes accept a vendor
  id to switch to. `POST /api/flags/sync/segment` takes a `vendorId` in its
  body, and on the operator path it must equal the active vendor. No other
  route accepts a vendor id from a query string, a header, or a body.
- **Roles:** `admin`, `editor`, `viewer`, most-privileged first, resolved
  per (email, vendor) pair at sign-in and switch time from Spoonity
  Identity's own role for that membership. A session can also carry no role
  at all when Identity sent none. A route that gates on role says so
  explicitly; every other route is open to any signed-in session at the
  active vendor.
- **Error envelopes.** There are two:
  - BFF-local routes (`/auth/*`, the saved objects, audit, digest, welcome,
    feedback, product updates) answer `{"error": "<code>", "detail": "<human string>"}`.
    Routes whose failures the SPA needs to tell apart add a
    machine-readable `code` beside those two.
  - The product proxy (`/api/<product>/*`), the ordering menu reads, the
    Flags routes and the PostHog relay answer
    `{"error": "<class>", "code": "<machine code>", "message": "<human string>", "detail": "<optional>"}`.
- **Rate limits:** the credential routes (sign-in, second-factor
  verification, the Apex and ordering connects) share a limit of 10
  requests/minute/IP. A route that is rate-limited says so.
- **Caching:** every response under `/auth` carries `Cache-Control: no-store`.

## What is deliberately not documented here

- **The product APIs behind the proxy.** The proxy itself, its targets and
  its rules are documented below in
  [The product proxy](#the-product-proxy-apiproductpath); what each upstream
  accepts is on that service's own page, for example
  [`insights.md`](./insights.md), [`cms.md`](./cms.md),
  [`links.md`](./links.md) and [`wallet.md`](./wallet.md).
- **Schedules, alerts, and the `/api/ask*` assistant endpoints.** They
  exist in the ported data model or the frontend's own contract types, but
  have no mounted route on this backend and 404 if called. See
  [`insights.md`](./insights.md#what-is-deliberately-not-documented-here)
  for the same note from the other side.
- **The `studio.spoonity.com` legacy-host redirect.** When a request's host
  is listed in `LEGACY_STUDIO_HOSTS`, old Pass Studio paths answer a `302`
  to the pass builder on the same host. It is a routing rule, not an API.

---

## Health and documentation

### GET /health

Cloud Run's readiness probe. Public: no session, no rate limit, and it
answers before the SPA build exists.

**Auth:** none.

**Params:** none.

**Request example:**

```bash
curl -sS 'https://prism.spoonity.com/health'
```

**Response example** (`200`):

```json
{ "status": "ok", "service": "prism-bff", "uptime": 113.43, "version": "95adca5d52fe962486784d79303ec73da4cb1e0d" }
```

`version` is the git commit the image was built from, or `"dev"` when the
image was built without one. `uptime` is the process uptime in seconds.

**Errors:** none.

---

### GET /docs, /docs/:slug, /docs/:slug.md, /docs/openapi/:slug.yaml, /llms.txt

This documentation site. Public: no session, no cookie read, and every
response is identical for every caller. It serves a fixed allowlist of pages
and specs; the site's own navigation and [`/llms.txt`](/llms.txt) (also at
[`/docs/llms.txt`](/docs/llms.txt)) list exactly what is on it.
`/docs/<slug>` is HTML, `/docs/<slug>.md` the raw Markdown, and
`/docs/openapi/<slug>.yaml` an OpenAPI 3.1 spec.

**Auth:** none.

**Request example:**

```bash
curl -sS 'https://prism.spoonity.com/docs/prism.md'
```

**Response:** `200` with `text/html`, `text/markdown`, `application/yaml` or
`text/plain`. A listed page whose file is missing is served as a labelled
placeholder with `200` and the header `X-Prism-Docs-Placeholder: 1`.

**Errors:** `404` (an HTML "No such page" document listing every page) for
any slug that is not on the allowlist.

---

## Authentication & session (`/auth/*`)

The handshake with Spoonity Identity, ending in Prism's own signed session
cookie. Everything under `/auth` answers with `Cache-Control: no-store`, and
everything under `/auth` is exempt from the vendor-scoping rule above by
definition: establishing the session **is** how the active vendor gets set.

**Who can sign in.** Before Identity is ever contacted, the email must pass
the deployment's allowed-domain check (`ALLOWED_EMAIL_DOMAINS`, default
`spoonity.com`). The check is repeated on every session-authenticated request,
so removing a domain ends every live session on its next call. A refused
address gets `403 {"error": "forbidden", "detail": "Access to Prism is
restricted to Spoonity team accounts."}`.

**The session cookie.** `prism_session`, `HttpOnly`, `Secure`,
`SameSite=Lax`, `Path=/`, valid for 24 hours. The server also keeps a
membership record per session; a request whose record has been deleted (for
example after `POST /auth/logout` elsewhere) gets `401` with a detail saying
the session has ended, and the cookie is cleared. Other instances notice a
logout within about 30 seconds.

**Rate limits.** Every route that sees a password or a one-time code is
limited to 10 requests per minute per IP. Over the limit the answer is
`429 {"error": "rate_limited", "detail": "Too many attempts. Try again in a minute."}`
with standard `RateLimit-*` headers.

**The session view.** `POST /auth/login`, `POST /auth/select-vendor`,
`POST /auth/switch-vendor`, `GET /auth/me` and every MFA route that completes
a sign-in return the same session object:

| Field | Type | Notes |
|---|---|---|
| `email` | string | the signed-in operator |
| `allowedVendors` | `{id, name, role?}[]` | every vendor this account can switch to |
| `activeVendorId` | number | the vendor every `/api/*` call is scoped to |
| `exp` | number | Unix seconds when the session expires |
| `role` | `"admin"` \| `"editor"` \| `"viewer"` | role at the active vendor; absent if none resolved |
| `config.walletsBaseUrl` | string | `https://wallets.spoonity.com` unless the deploy overrides it |
| `config.posthogKey` | string | the public PostHog project token; absent when analytics is off |
| `mfa.verified` | boolean | `true` when the session cleared a second factor (a remembered browser counts) |
| `mfa.methods` | string[] | how it did so: any of `totp`, `passkey`, `sms`, `email`, `recovery`, `trusted_device` |
| `staff` | boolean | the email's domain is a Spoonity staff domain; cosmetic, not an authorization check |

### POST /auth/login

Step one of the handshake: verify the password against Spoonity Identity,
then either issue a session, ask for a vendor, or ask for a second factor.

**Auth:** none (this is what creates one). Rate-limited: 10/min/IP.

**Body:**

| Field | Type | Required | Notes |
|---|---|---|---|
| `email` | string | yes | must pass the allowed-domain check before Identity is contacted |
| `password` | string | yes | used for this request only; never stored or logged |

**Request example:**

```bash
curl -sS -c cookies.txt 'https://prism.spoonity.com/auth/login' \
  -H 'Content-Type: application/json' \
  -d '{ "email": "ops@spoonity.com", "password": "<password>" }'
```

**Response example: signed in** (`200`, sets `Set-Cookie: prism_session=...`).
Returned for a single-vendor account when no second factor is needed:

```json
{
  "status": "ok",
  "user": {
    "email": "ops@spoonity.com",
    "allowedVendors": [{ "id": 123456, "name": "Example Merchant", "role": "admin" }],
    "activeVendorId": 123456,
    "exp": 1798761600,
    "role": "admin",
    "config": { "walletsBaseUrl": "https://wallets.spoonity.com" },
    "mfa": { "verified": false, "methods": [] },
    "staff": true
  },
  "vendors": [{ "id": 123456, "name": "Example Merchant", "role": "admin" }]
}
```

**Response example: several vendors** (`200`, no cookie yet). Finish with
`POST /auth/select-vendor`:

```json
{
  "status": "requires_vendor_selection",
  "selection_token": "<opaque, 15-minute token>",
  "vendors": [
    { "id": 123456, "name": "Example Merchant", "role": "admin" },
    { "id": 789012, "name": "Other Merchant", "role": "viewer" }
  ]
}
```

**Response example: second factor needed** (`200`, no cookie yet). Returned
when the account has an enrolled factor usable at this vendor and the browser
is not remembered. Finish with one of the `/auth/mfa` verification routes
below, passing `mfa_token`:

```json
{
  "status": "requires_mfa",
  "mfa_token": "<opaque, 10-minute token>",
  "vendor": { "id": 123456, "name": "Example Merchant" },
  "methods": [
    { "type": "passkey" },
    { "type": "totp" },
    { "type": "email", "destinationMasked": "o•••s@spoonity.com" },
    { "type": "recovery" }
  ],
  "preferred": "passkey",
  "trustedDeviceAllowed": true
}
```

**Response example: enrollment needed** (`200`, no cookie yet). Returned
when the vendor's policy requires a second factor and the account has none
that qualifies. Finish with one of the `/auth/mfa/enroll/*` routes, passing
`mfa_token`:

```json
{
  "status": "requires_mfa_enrollment",
  "mfa_token": "<opaque, 10-minute token>",
  "vendor": { "id": 123456, "name": "Example Merchant" },
  "policy": { "minimumStrength": "any" },
  "capabilities": { "sms": true, "email": true, "passkeys": true }
}
```

**Errors:**

| Status | Body | Meaning |
|---|---|---|
| `400` | `{"error": "bad_request", "detail": "email and password are required"}` | missing fields |
| `403` | `{"error": "forbidden", "detail": "Access to Prism is restricted to Spoonity team accounts."}` | email not on the allowed-domain list |
| `403` | `{"error": "forbidden", "detail": "Your account is not linked to any vendors"}` | the account has no vendors |
| `401` | `{"error": "unauthorized", "detail": "Invalid email or password"}` | bad credentials |
| `502` | `{"error": "upstream", "detail": "Authentication service unavailable"}` | Spoonity Identity unreachable |
| `429` | `{"error": "rate_limited", "detail": "Too many attempts. Try again in a minute."}` | more than 10 attempts per minute from this IP |
| `503` | `{"error": "unavailable", "detail": "Session service temporarily unavailable"}` | the session or MFA store could not be read or written |

---

### POST /auth/select-vendor

Step two, for a multi-vendor account: finish the login using the
15-minute selection token instead of a password. The chosen vendor's MFA
policy then applies, so this can answer any of the `ok`, `requires_mfa` or
`requires_mfa_enrollment` shapes shown for `POST /auth/login`.

**Auth:** none directly; authorized by possessing a valid, unexpired
`selection_token` from `POST /auth/login`. Rate-limited: 10/min/IP.

**Body:**

| Field | Type | Required |
|---|---|---|
| `selection_token` | string | yes |
| `vendor_id` (or `vendorId`) | number or numeric string | yes |

**Request example:**

```bash
curl -sS -c cookies.txt 'https://prism.spoonity.com/auth/select-vendor' \
  -H 'Content-Type: application/json' \
  -d '{ "selection_token": "<token from /auth/login>", "vendor_id": 123456 }'
```

**Response example** (`200`, sets `Set-Cookie: prism_session=...` when
`status` is `ok`): same shapes as `POST /auth/login`.

**Errors:**

| Status | Body | Meaning |
|---|---|---|
| `400` | `{"error": "bad_request", "detail": "selection_token and vendor_id are required"}` | missing or malformed fields |
| `401` | `{"error": "unauthorized", "detail": "..."}` | token expired or invalid; the detail asks the operator to sign in again |
| `403` | `{"error": "forbidden", "detail": "Access to Prism is restricted to Spoonity team accounts."}` | email removed from the allowlist since login |
| `403` | `{"error": "forbidden", "detail": "You do not have access to this vendor"}` | the vendor is not in the token's list |
| `429` | `{"error": "rate_limited", ...}` | rate limit |
| `503` | `{"error": "unavailable", "detail": "Session service temporarily unavailable"}` | store unreachable |

---

### POST /auth/switch-vendor

Re-scope the current session to another vendor the operator already has
access to. Same session id, refreshed expiry, and the active role is
recomputed for the new vendor. The session's MFA state, Loyalty credentials,
connected Apex account and ordering credentials carry over.

**Auth:** Prism session cookie. If the session never cleared a second factor
and the target vendor's policy requires one, the switch is refused with
`code: "mfa_required"`; the client signs out and the next login gates
properly.

**Body:**

| Field | Type | Required |
|---|---|---|
| `vendorId` (or `vendor_id`) | number or numeric string | yes |

**Request example:**

```bash
curl -sS -b cookies.txt -c cookies.txt 'https://prism.spoonity.com/auth/switch-vendor' \
  -H 'Content-Type: application/json' \
  -d '{ "vendorId": 789012 }'
```

**Response example** (`200`, sets a refreshed cookie):

```json
{ "status": "ok", "user": { "email": "ops@spoonity.com", "activeVendorId": 789012, "role": "viewer", "...": "the session view" } }
```

Unlike login, there is no top-level `vendors` field.

**Errors:**

| Status | Body | Meaning |
|---|---|---|
| `400` | `{"error": "bad_request", "detail": "vendorId is required"}` | missing or malformed vendor id |
| `401` | `{"error": "unauthorized", "detail": "Not signed in"}` | no valid cookie |
| `401` | `{"error": "unauthorized", "detail": "..."}` | the membership record is gone; the cookie is cleared |
| `403` | `{"error": "forbidden", "detail": "..."}` | vendor not in this account's membership list; the detail asks the operator to sign in again |
| `403` | `{"error": "forbidden", "code": "mfa_required", "detail": "..."}` | the target vendor requires a second factor this session did not clear |
| `503` | `{"error": "unavailable", "detail": "Session service temporarily unavailable"}` | store unreachable |

---

### POST /auth/identity-credential

Mint a vendor-scoped Spoonity Identity token for the **active** vendor
mid-session, from a password the operator has just re-typed. This is what
the Loyalty, Customers, Communication and Corporate sections ask for when
the proxy answers `403 identity_reauth_required`: login mints these tokens
only up to a cap, and they expire after a few hours. The token is written
to the server-side session record and is never returned.

**Auth:** Prism session cookie. Rate-limited: 10/min/IP. The vendor is always
the session's active vendor; there is no vendor field.

**Body:**

| Field | Type | Required |
|---|---|---|
| `password` | string | yes |

**Request example:**

```bash
curl -sS -b cookies.txt 'https://prism.spoonity.com/auth/identity-credential' \
  -H 'Content-Type: application/json' \
  -d '{ "password": "<password>" }'
```

**Response example** (`200`):

```json
{ "status": "ok", "vendorId": 123456, "expiresAt": 1798761600 }
```

`expiresAt` is the new token's expiry in Unix seconds.

**Errors:**

| Status | Body | Meaning |
|---|---|---|
| `400` | `{"error": "bad_request", "detail": "password is required"}` | missing password |
| `401` | `{"error": "unauthorized", "detail": "..."}` | no session, or its membership record is gone |
| `403` | `{"error": "forbidden", "code": "password_invalid", "detail": "That password is not correct"}` | wrong password (a `403`, not a `401`, so the console does not sign out) |
| `403` | `{"error": "forbidden", "detail": "..."}` | the active vendor is no longer in the membership record |
| `502` | `{"error": "upstream", "detail": "Authentication service unavailable"}` | Identity unreachable |
| `429` / `503` | as above | rate limit; store unreachable |

---

### GET /auth/me

The current session as the server sees it, including the full vendor
membership list for the vendor switcher.

**Auth:** Prism session cookie.

**Params:** none.

**Request example:**

```bash
curl -sS -b cookies.txt 'https://prism.spoonity.com/auth/me'
```

**Response example** (`200`): the session view on its own, not wrapped in
`user`:

```json
{
  "email": "ops@spoonity.com",
  "allowedVendors": [
    { "id": 123456, "name": "Example Merchant", "role": "admin" },
    { "id": 789012, "name": "Other Merchant", "role": "viewer" }
  ],
  "activeVendorId": 123456,
  "exp": 1798761600,
  "role": "admin",
  "config": { "walletsBaseUrl": "https://wallets.spoonity.com" },
  "mfa": { "verified": true, "methods": ["passkey"] },
  "staff": true
}
```

**Errors:**

| Status | Body | Meaning |
|---|---|---|
| `401` | `{"error": "unauthorized", "detail": "Not signed in"}` | no cookie, or an invalid one |
| `401` | `{"error": "unauthorized", "detail": "..."}` | the membership record behind the cookie is gone (the cookie is cleared) |
| `403` | `{"error": "forbidden", "detail": "Access to Prism is restricted to Spoonity team accounts."}` | email removed from the allowlist (the cookie is cleared) |
| `503` | `{"error": "unavailable", "detail": "Session service temporarily unavailable"}` | session store unreachable (the cookie is left alone, since the server does not know) |

---

### POST /auth/logout

End the session: clears the cookie and deletes the server-side membership
record, so a copy of the cookie stops working everywhere, not just in the
browser that called this.

**Auth:** none required (safe to call with no session).

**Params:** none.

**Request example:**

```bash
curl -sS -b cookies.txt -X POST 'https://prism.spoonity.com/auth/logout'
```

**Response:** `204 No Content`, always (even with no session to end).

**Errors:** none. A failure to delete the server-side record is logged and
does not change the response; the cookie is cleared and the session is
revoked on the answering instance either way.

---

## Multi-factor authentication (`/auth/mfa/*`)

Second factors for Prism operators: TOTP authenticator apps, passkeys
(WebAuthn), SMS codes, email codes (with a magic link), and one-time recovery
codes. The routes fall into three groups:

- **Verification** completes a login that answered `requires_mfa`.
- **Enrollment** adds a factor, either during a login that answered
  `requires_mfa_enrollment` or from a signed-in session (Settings, Security).
- **Management** reads and changes the signed-in operator's own factors,
  remembered browsers, and the active vendor's policy.

**Two credentials.** A route accepts either the `prism_session` cookie or an
`mfa_token` field in the JSON body (the token from `requires_mfa` or
`requires_mfa_enrollment`, valid for 10 minutes and single use). The email,
vendor and role always come from that credential, never from the body. The
verification routes accept only an `mfa_token` issued for verification; the
enrollment routes accept a session or an `mfa_token` issued for enrollment,
and the session wins when both are sent. The management routes accept only
a session.

**Completing a login.** A verification or login-mode enrollment that
succeeds sets `prism_session` and answers
`{"status": "ok", "user": <session view>, "vendors": [...]}`, the same shape
as `POST /auth/login`. With `"remember_device": true` in the body and a vendor
policy that allows it, it also sets a `prism_mfa_trust` cookie
(`Path=/auth`, 30 days) so the next login from that browser skips the second
factor.

**Error envelope.** MFA routes add a machine-readable `code` to the usual
envelope: `{"error": "<status name>", "code": "<code>", "detail": "<human string>"}`.
Common to most routes:

| Status | Body | Meaning |
|---|---|---|
| `401` | `{"error": "unauthorized", "code": "unauthorized", "detail": "Sign in again to continue"}` | no `mfa_token` and no session |
| `401` | `{"error": "unauthorized", "code": "unauthorized", "detail": "Not signed in"}` | a session-only route called without a session |
| `401` | `{"error": "unauthorized", "code": "mfa_token_invalid", "detail": "..."}` | the `mfa_token` is expired, invalid, or already used |
| `403` | `{"error": "forbidden", "detail": "Access to Prism is restricted to Spoonity team accounts."}` | email removed from the allowlist |
| `423` | `{"error": "locked", "code": "locked", "detail": "Too many incorrect codes. Try again shortly.", "retry_after": 840}` | 10 consecutive failures lock the account for 15 minutes; `retry_after` is seconds |
| `429` | `{"error": "rate_limited", "detail": "Too many attempts. Try again in a minute."}` | 10/min/IP (120/min/IP on `POST /auth/mfa/status`) |
| `503` | `{"error": "unavailable", "detail": "Session service temporarily unavailable"}` | a store could not be read or written |

### POST /auth/mfa/challenge/:method

Send a one-time code to the account's already-enrolled phone (`sms`) or login
email (`email`). The destination always comes from the account. An email
challenge also carries a magic link.

**Auth:** `mfa_token` (verification purpose). Rate-limited: 10/min/IP.

**Path params:** `method`: `sms` or `email`.

**Body:**

| Field | Type | Required | Notes |
|---|---|---|---|
| `mfa_token` | string | yes | from `requires_mfa` |
| `locale` | string | no | `es...` sends Spanish; anything else English |

**Request example:**

```bash
curl -sS 'https://prism.spoonity.com/auth/mfa/challenge/email' \
  -H 'Content-Type: application/json' \
  -d '{ "mfa_token": "<mfa_token>" }'
```

**Response example** (`200`):

```json
{
  "challenge_id": "9b2f4c1e0a7d4e5f8c3b6a1d2e4f7a90",
  "destination_masked": "o•••s@spoonity.com",
  "expires_in": 600,
  "resend_after": 30,
  "magic_link": true
}
```

**Errors:**

| Status | Body | Meaning |
|---|---|---|
| `400` | `{"error": "bad_request", "code": "unknown_method", "detail": "Unknown verification method"}` | `method` is not `sms` or `email` |
| `400` | `{"error": "bad_request", "code": "enrollment_required", "detail": "Set up two-factor authentication to continue"}` | the token was issued for enrollment |
| `400` | `{"error": "bad_request", "code": "method_unavailable", "detail": "That verification method is not available on this account"}` | not enrolled, not deliverable on this deploy, or too weak for the vendor's policy |
| `502` | `{"error": "upstream", "code": "delivery_failed", "detail": "We could not send your code right now. Try another method."}` | SMS or email delivery failed |
| `401` / `403` / `423` / `429` / `503` | see the common table | |

---

### POST /auth/mfa/verify/:method

Check a code and complete the login.

**Auth:** `mfa_token` (verification purpose). Rate-limited: 10/min/IP.

**Path params:** `method`: `totp`, `sms`, `email` or `recovery`.

**Body:**

| Field | Type | Required | Notes |
|---|---|---|---|
| `mfa_token` | string | yes | |
| `code` | string | yes | the 6-digit code, or a recovery code |
| `challenge_id` | string | for `sms` and `email` | from `POST /auth/mfa/challenge/:method` |
| `remember_device` | boolean | no | `true` to remember this browser for 30 days |

**Request example:**

```bash
curl -sS -c cookies.txt 'https://prism.spoonity.com/auth/mfa/verify/totp' \
  -H 'Content-Type: application/json' \
  -d '{ "mfa_token": "<mfa_token>", "code": "123456", "remember_device": true }'
```

**Response example** (`200`, sets `prism_session`):
`{"status": "ok", "user": {...}, "vendors": [...]}`.

**Errors:**

| Status | Body | Meaning |
|---|---|---|
| `400` | `{"error": "bad_request", "code": "unknown_method", ...}` | unknown `method` |
| `400` | `{"error": "bad_request", "code": "enrollment_required", ...}` | the token was issued for enrollment |
| `400` | `{"error": "bad_request", "code": "code_invalid", "detail": "Enter the code to continue"}` | no `code` |
| `400` | `{"error": "bad_request", "code": "code_invalid", "detail": "Request a code first"}` | `sms`/`email` without `challenge_id` |
| `400` | `{"error": "bad_request", "code": "method_unavailable", "detail": "That verification method is not available for this vendor"}` | method too weak for the vendor's policy |
| `400` | `{"error": "bad_request", "code": "code_invalid", "detail": "That code is not correct"}` | wrong code; `sms`/`email` also carry `attempts_remaining` |
| `410` | `{"error": "gone", "code": "challenge_expired" or "challenge_exhausted", "detail": "..."}` | the challenge expired (10 minutes) or used its 5 attempts; request a new one |
| `401` / `403` / `423` / `429` / `503` | see the common table | |

---

### POST /auth/mfa/passkey/options

Start a passkey sign-in: returns WebAuthn assertion options for the
account's registered passkeys.

**Auth:** `mfa_token` (verification purpose). Rate-limited: 10/min/IP.

**Body:** `{ "mfa_token": "<mfa_token>" }`.

**Request example:**

```bash
curl -sS 'https://prism.spoonity.com/auth/mfa/passkey/options' \
  -H 'Content-Type: application/json' \
  -d '{ "mfa_token": "<mfa_token>" }'
```

**Response example** (`200`):

```json
{ "challenge_id": "4e1a7c9d2b3f4a5e8d6c1b0a9f2e3d47", "options": { "challenge": "<base64url>", "allowCredentials": [ "..." ], "userVerification": "preferred" } }
```

`options` is a standard `PublicKeyCredentialRequestOptionsJSON` for
`navigator.credentials.get()`. The challenge is valid for 5 minutes.

**Errors:**

| Status | Body | Meaning |
|---|---|---|
| `400` | `{"error": "bad_request", "code": "enrollment_required", ...}` | the token was issued for enrollment |
| `400` | `{"error": "bad_request", "code": "method_unavailable", "detail": "No passkeys are registered on this account"}` | no passkeys |
| `401` / `403` / `423` / `429` / `503` | see the common table | |

---

### POST /auth/mfa/passkey/verify

Verify a passkey assertion and complete the login. Accepted even while the
account is locked, and a success clears the lock.

**Auth:** `mfa_token` (verification purpose). Rate-limited: 10/min/IP.

**Body:**

| Field | Type | Required | Notes |
|---|---|---|---|
| `mfa_token` | string | yes | |
| `challenge_id` | string | yes | from `POST /auth/mfa/passkey/options` |
| `credential` | object | yes | the `AuthenticationResponseJSON` from `navigator.credentials.get()` |
| `remember_device` | boolean | no | |

**Request example:**

```bash
curl -sS -c cookies.txt 'https://prism.spoonity.com/auth/mfa/passkey/verify' \
  -H 'Content-Type: application/json' \
  -d '{ "mfa_token": "<mfa_token>", "challenge_id": "4e1a7c9d2b3f4a5e8d6c1b0a9f2e3d47", "credential": { "id": "...", "response": { "...": "..." } } }'
```

**Response example** (`200`, sets `prism_session`):
`{"status": "ok", "user": {...}, "vendors": [...]}`.

**Errors:**

| Status | Body | Meaning |
|---|---|---|
| `400` | `{"error": "bad_request", "code": "enrollment_required", ...}` | the token was issued for enrollment |
| `400` | `{"error": "bad_request", "code": "passkey_invalid", "detail": "That passkey could not be verified"}` | unknown challenge or credential, or the assertion failed |
| `401` / `403` / `429` / `503` | see the common table | |

---

### POST /auth/mfa/status

The poll behind the email magic link. The tab that requested an email
challenge calls this every few seconds; once the link has been opened (on
any device), this call completes the login in the waiting tab.

**Auth:** `mfa_token`. Rate-limited: 120/min/IP.

**Body:**

| Field | Type | Required |
|---|---|---|
| `mfa_token` | string | yes |
| `challenge_id` | string | yes |
| `remember_device` | boolean | no |

**Request example:**

```bash
curl -sS -c cookies.txt 'https://prism.spoonity.com/auth/mfa/status' \
  -H 'Content-Type: application/json' \
  -d '{ "mfa_token": "<mfa_token>", "challenge_id": "9b2f4c1e0a7d4e5f8c3b6a1d2e4f7a90" }'
```

**Response example** (`200`): `{"state": "pending"}` while waiting,
`{"state": "expired"}` for an unknown, expired or foreign challenge, and
`{"status": "ok", "user": {...}, "vendors": [...]}` (with `prism_session` set)
once approved.

**Errors:**

| Status | Body | Meaning |
|---|---|---|
| `400` | `{"error": "bad_request", "code": "bad_request", "detail": "challenge_id is required"}` | missing `challenge_id` |
| `401` / `403` / `429` / `503` | see the common table | |

---

### GET /auth/mfa/magic/:token

The link in the email. A browser navigation, not an API call: it answers an
HTML page (English or Spanish from `Accept-Language`), marks the challenge
approved, and sets no cookie. The session is issued to the tab polling
`POST /auth/mfa/status`, not to this page. Valid for 15 minutes.

**Auth:** none; possession of the link. Rate-limited: 10/min/IP.

**Path params:** `token`: the opaque value in the emailed link.

**Request example:**

```bash
curl -sS 'https://prism.spoonity.com/auth/mfa/magic/<token>'
```

**Response:** `200 text/html` confirming the sign-in was approved.

**Errors:** `410 text/html` for an invalid, expired or used link;
`503 text/html` if the store could not be reached.

---

### POST /auth/mfa/enroll/totp/start

Generate a new authenticator-app secret. It stays pending until confirmed;
a second start replaces it.

**Auth:** Prism session cookie, or an `mfa_token` from
`requires_mfa_enrollment`. Rate-limited: 10/min/IP.

**Body:** `{}` with a session, or `{ "mfa_token": "<mfa_token>" }`.

**Request example:**

```bash
curl -sS -b cookies.txt -X POST 'https://prism.spoonity.com/auth/mfa/enroll/totp/start' \
  -H 'Content-Type: application/json' -d '{}'
```

**Response example** (`200`):

```json
{
  "secret": "JBSWY3DPEHPK3PXP",
  "otpauth_uri": "otpauth://totp/Spoonity%20Prism:ops%40spoonity.com?secret=JBSWY3DPEHPK3PXP&issuer=Spoonity%20Prism",
  "issuer": "Spoonity Prism",
  "account": "ops@spoonity.com"
}
```

**Errors:**

| Status | Body | Meaning |
|---|---|---|
| `400` | `{"error": "bad_request", "code": "verification_required", "detail": "Verify your existing second factor to continue"}` | an `mfa_token` issued for verification, not enrollment |
| `401` / `403` / `423` / `429` / `503` | see the common table | |

---

### POST /auth/mfa/enroll/totp/confirm

Confirm the pending secret with a code from the app. The account's first
factor also generates 10 recovery codes, returned once.

**Auth:** session or enrollment `mfa_token`. Rate-limited: 10/min/IP.

**Body:**

| Field | Type | Required | Notes |
|---|---|---|---|
| `code` | string | yes | 6-digit code |
| `mfa_token` | string | without a session | |
| `remember_device` | boolean | no | login mode only |

**Request example:**

```bash
curl -sS -b cookies.txt 'https://prism.spoonity.com/auth/mfa/enroll/totp/confirm' \
  -H 'Content-Type: application/json' -d '{ "code": "123456" }'
```

**Response example** (`200`, session mode):

```json
{ "status": "enrolled", "recovery_codes": ["k7m2p-x9qa4", "..."] }
```

`recovery_codes` is present only when this was the account's first factor.
In login mode the answer is `{"status": "ok", "user": {...}, "vendors": [...]}`
plus `recovery_codes`, and `prism_session` is set.

**Errors:**

| Status | Body | Meaning |
|---|---|---|
| `400` | `{"error": "bad_request", "code": "no_pending_enrollment", "detail": "Start setting up your authenticator app again"}` | no pending secret |
| `400` | `{"error": "bad_request", "code": "code_invalid", "detail": "That code is not correct"}` | wrong code |
| `400` | `{"error": "bad_request", "code": "verification_required", ...}` | wrong token purpose |
| `401` / `403` / `423` / `429` / `503` | see the common table | |

---

### POST /auth/mfa/enroll/passkey/options

Start registering a passkey: returns WebAuthn creation options.

**Auth:** session or enrollment `mfa_token`. Rate-limited: 10/min/IP.

**Body:** `{}` with a session, or `{ "mfa_token": "<mfa_token>" }`.

**Request example:**

```bash
curl -sS -b cookies.txt -X POST 'https://prism.spoonity.com/auth/mfa/enroll/passkey/options' \
  -H 'Content-Type: application/json' -d '{}'
```

**Response example** (`200`):

```json
{ "challenge_id": "7d3e2a1b9c8f4e6d5a0b1c2d3e4f5a61", "options": { "challenge": "<base64url>", "rp": { "...": "..." }, "user": { "...": "..." } } }
```

`options` is a standard `PublicKeyCredentialCreationOptionsJSON` for
`navigator.credentials.create()`, excluding passkeys already registered.

**Errors:** `400 verification_required` (wrong token purpose); see the
common table for the rest.

---

### POST /auth/mfa/enroll/passkey/verify

Finish registering a passkey.

**Auth:** session or enrollment `mfa_token`. Rate-limited: 10/min/IP.

**Body:**

| Field | Type | Required | Notes |
|---|---|---|---|
| `challenge_id` | string | yes | from the options call |
| `credential` | object | yes | the `RegistrationResponseJSON` from `navigator.credentials.create()` |
| `nickname` | string | no | display label, trimmed to 60 characters |
| `mfa_token` | string | without a session | |
| `remember_device` | boolean | no | login mode only |

**Request example:**

```bash
curl -sS -b cookies.txt 'https://prism.spoonity.com/auth/mfa/enroll/passkey/verify' \
  -H 'Content-Type: application/json' \
  -d '{ "challenge_id": "7d3e2a1b9c8f4e6d5a0b1c2d3e4f5a61", "credential": { "id": "...", "response": { "...": "..." } }, "nickname": "MacBook" }'
```

**Response example** (`200`, session mode):

```json
{
  "status": "enrolled",
  "passkey": { "id": "f3a91c0e5b7d4e2a9c8b6d1e0f4a2c55", "nickname": "MacBook", "createdAt": "2026-09-30T14:02:11.483Z" }
}
```

`recovery_codes` is added when this was the account's first factor. Login
mode answers the completion shape plus `passkey` (and `recovery_codes`).

**Errors:**

| Status | Body | Meaning |
|---|---|---|
| `400` | `{"error": "bad_request", "code": "passkey_invalid", "detail": "That passkey could not be registered"}` | unknown challenge, or the attestation failed |
| `409` | `{"error": "conflict", "code": "passkey_exists", "detail": "That passkey is already registered on this account"}` | duplicate credential |
| `400` | `{"error": "bad_request", "code": "verification_required", ...}` | wrong token purpose |
| `401` / `403` / `423` / `429` / `503` | see the common table | |

---

### POST /auth/mfa/enroll/sms/start

Send a code to a phone number the operator wants to enroll.

**Auth:** session or enrollment `mfa_token`. Rate-limited: 10/min/IP.

**Body:**

| Field | Type | Required | Notes |
|---|---|---|---|
| `phone` | string | yes | E.164, for example `+14165550123` |
| `locale` | string | no | `es...` for Spanish |
| `mfa_token` | string | without a session | |

**Request example:**

```bash
curl -sS -b cookies.txt 'https://prism.spoonity.com/auth/mfa/enroll/sms/start' \
  -H 'Content-Type: application/json' -d '{ "phone": "+14165550123" }'
```

**Response example** (`200`):

```json
{ "challenge_id": "2c8e1f4a7b3d4c9e6f0a1b2c3d4e5f72", "destination_masked": "+1•••0123", "expires_in": 600, "resend_after": 30 }
```

**Errors:**

| Status | Body | Meaning |
|---|---|---|
| `400` | `{"error": "bad_request", "code": "method_unavailable", "detail": "That verification method is not available on this deployment"}` | SMS delivery is not configured |
| `400` | `{"error": "bad_request", "code": "phone_invalid", "detail": "Enter your number in international format, e.g. +14165550123"}` | not E.164 |
| `502` | `{"error": "upstream", "code": "delivery_failed", "detail": "We could not send your code right now. Try again in a moment."}` | delivery failed |
| `400` | `{"error": "bad_request", "code": "verification_required", ...}` | wrong token purpose |
| `401` / `403` / `423` / `429` / `503` | see the common table | |

---

### POST /auth/mfa/enroll/sms/confirm

Confirm the phone with the code sent to it.

**Auth:** session or enrollment `mfa_token`. Rate-limited: 10/min/IP.

**Body:**

| Field | Type | Required | Notes |
|---|---|---|---|
| `challenge_id` | string | yes | from the start call |
| `code` | string | yes | |
| `mfa_token` | string | without a session | |
| `remember_device` | boolean | no | login mode only |

**Request example:**

```bash
curl -sS -b cookies.txt 'https://prism.spoonity.com/auth/mfa/enroll/sms/confirm' \
  -H 'Content-Type: application/json' -d '{ "challenge_id": "2c8e1f4a7b3d4c9e6f0a1b2c3d4e5f72", "code": "123456" }'
```

**Response example** (`200`, session mode): `{"status": "enrolled"}`, plus
`recovery_codes` for a first factor. Login mode answers the completion
shape.

**Errors:**

| Status | Body | Meaning |
|---|---|---|
| `400` | `{"error": "bad_request", "code": "code_invalid", "detail": "Enter the code we sent you"}` | missing `challenge_id` or `code` |
| `400` | `{"error": "bad_request", "code": "code_invalid", "detail": "That code is not correct", "attempts_remaining": 4}` | wrong code |
| `410` | `{"error": "gone", "code": "challenge_expired" or "challenge_exhausted", "detail": "..."}` | request a new code |
| `400` | `{"error": "bad_request", "code": "verification_required", ...}` | wrong token purpose |
| `401` / `403` / `423` / `429` / `503` | see the common table | |

---

### POST /auth/mfa/enroll/email/start

Send a code to the operator's own login email. There is no address field:
email enrollment always targets the login address.

**Auth:** session or enrollment `mfa_token`. Rate-limited: 10/min/IP.

**Body:** `{}` with a session (optional `locale`), or
`{ "mfa_token": "<mfa_token>" }`.

**Request example:**

```bash
curl -sS -b cookies.txt -X POST 'https://prism.spoonity.com/auth/mfa/enroll/email/start' \
  -H 'Content-Type: application/json' -d '{}'
```

**Response example** (`200`): same shape as `POST /auth/mfa/enroll/sms/start`.

**Errors:** `400 method_unavailable` (email delivery not configured),
`502 delivery_failed`, `400 verification_required`; see the common table
for the rest.

---

### POST /auth/mfa/enroll/email/confirm

Confirm email as a factor with the code sent to it.

**Auth:** session or enrollment `mfa_token`. Rate-limited: 10/min/IP.

**Body:** same fields as `POST /auth/mfa/enroll/sms/confirm`.

**Request example:**

```bash
curl -sS -b cookies.txt 'https://prism.spoonity.com/auth/mfa/enroll/email/confirm' \
  -H 'Content-Type: application/json' -d '{ "challenge_id": "6a0f3e2d1c9b4a8e7d6c5b4a3f2e1d83", "code": "123456" }'
```

**Response example** (`200`, session mode): `{"status": "enrolled"}`, plus
`recovery_codes` for a first factor.

**Errors:** same as `POST /auth/mfa/enroll/sms/confirm`.

---

### GET /auth/mfa/me

Everything the Security settings page shows: enrolled factors, recovery-code
count, remembered browsers, and the active vendor's policy.

**Auth:** Prism session cookie.

**Request example:**

```bash
curl -sS -b cookies.txt 'https://prism.spoonity.com/auth/mfa/me'
```

**Response example** (`200`):

```json
{
  "enrolled": true,
  "factors": {
    "totp": { "enrolledAt": "2026-09-01T10:00:00.000Z" },
    "passkeys": [
      { "id": "f3a91c0e5b7d4e2a9c8b6d1e0f4a2c55", "nickname": "MacBook", "createdAt": "2026-09-01T10:05:00.000Z", "lastUsedAt": null, "backedUp": true }
    ],
    "sms": null,
    "email": { "enabled": false, "destinationMasked": "o•••s@spoonity.com" }
  },
  "recoveryCodes": { "remaining": 10, "generatedAt": "2026-09-01T10:00:00.000Z" },
  "trustedDevices": [
    { "id": "b7e20d9c4a1f4e3b8d5c6a7e9f0b1c26", "label": "Chrome on macOS", "createdAt": "2026-09-01T10:00:00.000Z", "lastUsedAt": "2026-09-29T08:00:00.000Z", "expiresAt": "2026-10-01T10:00:00.000Z", "current": true }
  ],
  "policy": { "required": false, "minimumStrength": "any", "allowTrustedDevices": true, "canEdit": true },
  "capabilities": { "sms": true, "email": true, "passkeys": true },
  "session": { "amr": ["pwd", "passkey"], "mfaVerified": true }
}
```

`policy.canEdit` is `true` for an `admin` at the active vendor.

**Errors:** `401` (no session), `503`; see the common table.

---

### DELETE /auth/mfa/factors/:method

Remove a factor. Always password-confirmed. Removing the last factor is
refused when the active vendor requires MFA; otherwise it also discards the
recovery codes and every remembered browser.

**Auth:** Prism session cookie, plus the password. Rate-limited: 10/min/IP.

**Path params:** `method`: `totp`, `sms` or `email` (passkeys use
`DELETE /auth/mfa/passkeys/:id`).

**Body:** `{ "password": "<password>" }`.

**Request example:**

```bash
curl -sS -b cookies.txt -X DELETE 'https://prism.spoonity.com/auth/mfa/factors/sms' \
  -H 'Content-Type: application/json' -d '{ "password": "<password>" }'
```

**Response:** `204 No Content`.

**Errors:**

| Status | Body | Meaning |
|---|---|---|
| `400` | `{"error": "bad_request", "code": "unknown_method", ...}` | unknown `method` |
| `401` | `{"error": "unauthorized", "code": "password_invalid", "detail": "That password is not correct"}` | wrong or missing password |
| `409` | `{"error": "conflict", "code": "policy_requires_mfa", "detail": "..."}` | last factor, and the vendor requires MFA |
| `502` | `{"error": "upstream", "detail": "Authentication service unavailable"}` | Identity unreachable |
| `401` / `429` / `503` | see the common table | |

---

### PATCH /auth/mfa/passkeys/:id

Rename a passkey.

**Auth:** Prism session cookie.

**Path params:** `id`: the passkey id from `GET /auth/mfa/me`.

**Body:** `{ "nickname": "<name>" }` (trimmed to 60 characters).

**Request example:**

```bash
curl -sS -b cookies.txt -X PATCH 'https://prism.spoonity.com/auth/mfa/passkeys/f3a91c0e5b7d4e2a9c8b6d1e0f4a2c55' \
  -H 'Content-Type: application/json' -d '{ "nickname": "Work laptop" }'
```

**Response example** (`200`):

```json
{ "passkey": { "id": "f3a91c0e5b7d4e2a9c8b6d1e0f4a2c55", "nickname": "Work laptop", "createdAt": "2026-09-01T10:05:00.000Z" } }
```

**Errors:** `400 {"error": "bad_request", "code": "bad_request", "detail": "A name is required"}`;
`404 {"error": "not_found", "code": "not_found", "detail": "No such passkey"}`;
`401` / `503` as in the common table.

---

### DELETE /auth/mfa/passkeys/:id

Remove a passkey. Password-confirmed, with the same last-factor rule as
`DELETE /auth/mfa/factors/:method`.

**Auth:** Prism session cookie, plus the password. Rate-limited: 10/min/IP.

**Path params:** `id`.

**Body:** `{ "password": "<password>" }`.

**Request example:**

```bash
curl -sS -b cookies.txt -X DELETE 'https://prism.spoonity.com/auth/mfa/passkeys/f3a91c0e5b7d4e2a9c8b6d1e0f4a2c55' \
  -H 'Content-Type: application/json' -d '{ "password": "<password>" }'
```

**Response:** `204 No Content`.

**Errors:** `401 password_invalid`; `404 not_found` ("No such passkey");
`409 policy_requires_mfa`; `502 upstream`; see the common table for the
rest.

---

### POST /auth/mfa/recovery-codes

Generate a fresh set of 10 recovery codes. The previous set stops working
immediately. Password-confirmed.

**Auth:** Prism session cookie, plus the password. Rate-limited: 10/min/IP.

**Body:** `{ "password": "<password>" }`.

**Request example:**

```bash
curl -sS -b cookies.txt 'https://prism.spoonity.com/auth/mfa/recovery-codes' \
  -H 'Content-Type: application/json' -d '{ "password": "<password>" }'
```

**Response example** (`200`):

```json
{ "codes": ["k7m2p-x9qa4", "..."] }
```

Shown once; only hashes are stored.

**Errors:** `401 password_invalid`; `502 upstream`; see the common table.

---

### GET /auth/mfa/trusted-devices

List the browsers remembered for this operator.

**Auth:** Prism session cookie.

**Request example:**

```bash
curl -sS -b cookies.txt 'https://prism.spoonity.com/auth/mfa/trusted-devices'
```

**Response example** (`200`):

```json
{
  "devices": [
    { "id": "b7e20d9c4a1f4e3b8d5c6a7e9f0b1c26", "label": "Chrome on macOS", "createdAt": "2026-09-01T10:00:00.000Z", "lastUsedAt": "2026-09-29T08:00:00.000Z", "expiresAt": "2026-10-01T10:00:00.000Z", "current": true }
  ]
}
```

`current` marks the browser making the call.

**Errors:** `401`, `503`; see the common table.

---

### DELETE /auth/mfa/trusted-devices/:id

Forget one remembered browser. No password needed.

**Auth:** Prism session cookie. Only the operator's own devices are visible.

**Path params:** `id`.

**Request example:**

```bash
curl -sS -b cookies.txt -X DELETE 'https://prism.spoonity.com/auth/mfa/trusted-devices/b7e20d9c4a1f4e3b8d5c6a7e9f0b1c26'
```

**Response:** `204 No Content`. If it was the calling browser, its
`prism_mfa_trust` cookie is cleared too.

**Errors:** `404 {"error": "not_found", "code": "not_found", "detail": "No such device"}`
(missing or another operator's); `401` / `503` as in the common table.

---

### DELETE /auth/mfa/trusted-devices

Forget every remembered browser for this operator.

**Auth:** Prism session cookie.

**Request example:**

```bash
curl -sS -b cookies.txt -X DELETE 'https://prism.spoonity.com/auth/mfa/trusted-devices'
```

**Response:** `204 No Content`; the calling browser's trust cookie is
cleared.

**Errors:** `401`, `503`; see the common table.

---

### GET /auth/mfa/policy

The active vendor's MFA policy.

**Auth:** Prism session cookie. Any role.

**Request example:**

```bash
curl -sS -b cookies.txt 'https://prism.spoonity.com/auth/mfa/policy'
```

**Response example** (`200`):

```json
{ "required": false, "minimumStrength": "any", "allowTrustedDevices": true }
```

A vendor that has never set one gets this default. A stored policy also
carries `updatedAt` and `updatedBy`.

**Errors:** `401`, `503`; see the common table.

---

### PUT /auth/mfa/policy

Set the active vendor's MFA policy.

**Auth:** Prism session cookie, `admin` at the active vendor. An admin must
have a factor enrolled before setting `required: true`.

**Body:**

| Field | Type | Required | Notes |
|---|---|---|---|
| `required` | boolean | no | only `true` turns it on; anything else is `false` |
| `minimumStrength` | `"any"` \| `"strong"` | no | `strong` accepts only TOTP, passkeys and recovery codes; anything else is `any` |
| `allowTrustedDevices` | boolean | no | defaults to `true`; only `false` turns it off |

The whole policy is replaced: an omitted field takes its default.

**Request example:**

```bash
curl -sS -b cookies.txt -X PUT 'https://prism.spoonity.com/auth/mfa/policy' \
  -H 'Content-Type: application/json' \
  -d '{ "required": true, "minimumStrength": "strong", "allowTrustedDevices": true }'
```

**Response example** (`200`):

```json
{ "required": true, "minimumStrength": "strong", "allowTrustedDevices": true, "updatedAt": "2026-09-30T14:02:11.483Z", "updatedBy": "ops@spoonity.com" }
```

**Errors:**

| Status | Body | Meaning |
|---|---|---|
| `403` | `{"error": "forbidden", "detail": "Only administrators can change this setting"}` | not an admin |
| `409` | `{"error": "conflict", "code": "enroll_first", "detail": "Set up your own second factor before requiring it for this vendor"}` | turning on `required` without a factor of your own |
| `401` / `503` | see the common table | |

---

## Apex connection (`/auth/apex/*`)

Connects an operator's own Apex marketing-automation account to their live
Prism session, so the `apex` proxy target (`/api/apex/*`) has a credential to
forward. Apex authenticates an Apex account, not a Spoonity one, so this is a
separate step after sign-in. The Apex password is used for one call and never
stored, logged or echoed; the Apex tokens are kept on the server-side session
record only and never appear in a response body or cookie.

Every route below sits under `/auth`, so every response carries
`Cache-Control: no-store`. A wrong Apex password is a `403`, never a `401`,
because the SPA ends the whole Prism session on any `401`. The only `401` on
these routes means the Prism session itself is gone: either no cookie
(`{"error": "unauthorized", "detail": "Not signed in"}`) or a session whose
server-side record has been deleted (the same session-expired `401` that
`GET /auth/me` answers, which also clears the cookie).

### POST /auth/apex/connect

Sign in to Apex with an Apex email and password and attach the resulting
credential to this session. Prism then tries to pick the Apex workspace for
the active vendor automatically (a workspace whose `spoonity.vendor_id`
matches). If it cannot, the connect still succeeds with `workspace: null` and
the operator picks one with `POST /auth/apex/workspace`. Reconnecting with the
same Apex email keeps the remembered per-vendor workspaces; a different email
starts with none.

**Auth:** Prism session cookie. Rate-limited: 10 requests/minute/IP (counted
before the session check).

**Body:**

| Field | Type | Required | Notes |
|---|---|---|---|
| `email` | string | yes | the Apex account's email |
| `password` | string | yes | the Apex account's password |

**Request example:**

```bash
curl -sS -b cookies.txt 'https://prism.spoonity.com/auth/apex/connect' \
  -H 'Content-Type: application/json' \
  -d '{ "email": "ops@example.com", "password": "<apex password>" }'
```

**Response example** (`200`):

```json
{
  "status": "ok",
  "email": "ops@example.com",
  "workspace": { "id": "ws_42", "name": "Example Merchant" }
}
```

`workspace` is `null` when no workspace could be resolved for the active
vendor. `workspace.name` can be `null` when the id is known but the name could
not be read.

**Errors:**

| Status | Body | Meaning |
|---|---|---|
| `400` | `{"error": "bad_request", "detail": "email and password are required"}` | a field is missing or empty; Apex is not called |
| `401` | `{"error": "unauthorized", "detail": "Not signed in"}` | no Prism session |
| `403` | `{"error": "forbidden", "code": "password_invalid", "detail": "That Apex email or password is not correct"}` | Apex refused the credentials |
| `429` | `{"error": "rate_limited", "detail": "Too many attempts. Try again in a minute."}` | more than 10 attempts/minute from this IP |
| `502` | `{"error": "upstream", "detail": "The Apex service is unavailable"}` | Apex could not be reached |
| `503` | `{"error": "unavailable", "detail": "Session service temporarily unavailable"}` | the session store could not be read or written |

On success an `auth.apex_connect` audit event is recorded under the active
vendor (section `auth`).

---

### POST /auth/apex/disconnect

Drop the Apex credential from this session. Because the session record is the
only place the credential lives, this is the revocation.

**Auth:** Prism session cookie.

**Params:** none.

**Request example:**

```bash
curl -sS -b cookies.txt -X POST 'https://prism.spoonity.com/auth/apex/disconnect'
```

**Response example** (`200`):

```json
{ "status": "ok" }
```

The same answer is returned when nothing was connected; in that case nothing
is written and no audit event is recorded. When a credential really is
dropped, an `auth.apex_disconnect` audit event is recorded.

**Errors:** `401` (no session, or session record gone); `503` (session store
unavailable).

---

### GET /auth/apex/status

Whether an Apex account is connected to this session, which one, and which
workspace (if any) is remembered for the active vendor. Makes no token
refresh.

**Auth:** Prism session cookie.

**Params:** none.

**Request example:**

```bash
curl -sS -b cookies.txt 'https://prism.spoonity.com/auth/apex/status'
```

**Response example** (`200`, connected):

```json
{
  "connected": true,
  "email": "ops@example.com",
  "workspace": { "id": "ws_42", "name": "Example Merchant" }
}
```

Not connected: `{"connected": false}`. `workspace` is `null` when no workspace
is remembered for the active vendor, and `workspace.name` is `null` when Apex
could not be asked for the name.

**Errors:** `401` (no session, or session record gone); `503` (session store
unavailable).

---

### GET /auth/apex/workspaces

Every Apex workspace the connected account is an active member of, for the
workspace picker.

**Auth:** Prism session cookie. Requires a connected Apex account.

**Params:** none.

**Request example:**

```bash
curl -sS -b cookies.txt 'https://prism.spoonity.com/auth/apex/workspaces'
```

**Response example** (`200`):

```json
{ "workspaces": [{ "id": "ws_42", "name": "Example Merchant" }] }
```

**Errors:**

| Status | Body | Meaning |
|---|---|---|
| `401` | as above | no session, or session record gone |
| `403` | `{"error": "forbidden", "code": "apex_connect_required", "detail": "Connect an Apex account to continue"}` | no Apex account connected to this session |
| `502` | `{"error": "upstream", "detail": "The Apex service is unavailable"}` | the list could not be produced |
| `503` | `{"error": "unavailable", "detail": "Session service temporarily unavailable"}` | session store unavailable |

---

### POST /auth/apex/workspace

Choose the Apex workspace to use for the active vendor. Membership is checked
against the account's workspace list, or, when no list can be produced yet,
by probing the chosen workspace directly. An id the account is not a member of
is refused.

**Auth:** Prism session cookie. Requires a connected Apex account.

**Body:**

| Field | Type | Required |
|---|---|---|
| `workspaceId` | string | yes |

**Request example:**

```bash
curl -sS -b cookies.txt 'https://prism.spoonity.com/auth/apex/workspace' \
  -H 'Content-Type: application/json' \
  -d '{ "workspaceId": "ws_42" }'
```

**Response example** (`200`):

```json
{ "status": "ok", "workspace": { "id": "ws_42", "name": "Example Merchant" } }
```

`workspace.name` is `null` when membership was confirmed by probing rather than
from the list.

**Errors:**

| Status | Body | Meaning |
|---|---|---|
| `400` | `{"error": "bad_request", "detail": "workspaceId is required"}` | missing or empty `workspaceId` |
| `401` | as above | no session, or session record gone |
| `403` | `{"error": "forbidden", "code": "apex_connect_required", "detail": "Connect an Apex account to continue"}` | no Apex account connected |
| `403` | `{"error": "forbidden", "code": "apex_workspace_invalid", "detail": "That workspace is not one this Apex account can use"}` | not a member of that workspace |
| `502` | `{"error": "upstream", "detail": "The Apex service is unavailable"}` | membership could not be checked |
| `503` | `{"error": "unavailable", "detail": "Session service temporarily unavailable"}` | session store unavailable |

On success an `auth.apex_workspace_select` audit event is recorded with the
workspace id as its entity.

---

### GET /auth/apex/editor-config

The Apex email editor's (Topol's) boot config — an API key and a user id, or
`null` when Topol is not configured on this deployment. Fetched only when an
operator opens the node email editor or the standalone template editor (the
apex-canvas port, plan `apex-canvas-port-plan.md` AC16); it is deliberately
**not** part of `GET /auth/me`, which every page load reads, because the key
should reach the browser only when an editor is actually about to open.

Topol's security model is a public key restricted by a domain allow-list in
the Topol dashboard, the same way upstream Apex exposes it to its own
dashboard — this endpoint is a narrower, conscious version of that exposure:
editor role or above, fetched on demand, `no-store`.

**Auth:** Prism session cookie, editor role or above at the active vendor.

**Params:** none.

**Request example:**

```bash
curl -sS -b cookies.txt 'https://prism.spoonity.com/auth/apex/editor-config'
```

**Response example** (`200`, Topol configured):

```json
{ "topol": { "apiKey": "pub_...", "userId": "ws_42" } }
```

`userId` **is the Apex workspace id** for the active vendor — the same value
upstream passes as Topol's `authorize.userId` — so Topol's per-user storage
(saved blocks, uploaded images) is shared between the Apex dashboard and
Prism.

**Response example** (`200`, Topol not configured on this deployment):

```json
{ "topol": null }
```

A missing `TOPOL_API_KEY` is **not an error**: the section renders "Email
editor isn't set up for this deployment" plus "Open in Apex", and this is
answered before the session record is even read, so no deploy can fail for
lack of the secret.

**Errors:**

| Status | Body | Meaning |
|---|---|---|
| `401` | as above | no session, or session record gone |
| `403` | `{"error": "forbidden", "code": "role_insufficient", "detail": "the Apex email editor needs editor or admin; the session's role here is viewer"}` | the session's role at the active vendor is below `editor` (checked **before** `topol: null` would otherwise apply, so a viewer learns nothing about whether Topol is configured) |
| `403` | `{"error": "forbidden", "code": "apex_connect_required", "detail": "no Apex account is connected to this session"}` | Topol is configured but no Apex account is connected |
| `403` | `{"error": "forbidden", "code": "apex_workspace_required", "detail": "no Apex workspace is set for vendor <id>"}` | Topol is configured and an Apex account is connected, but no workspace is resolved for the active vendor |
| `503` | `{"error": "unavailable", "detail": "Session service temporarily unavailable"}` | session store unavailable |

No audit event: this is a read of configuration, not a credential action.

---

## Ordering site and connection (`/auth/ordering/*`)

Two related things share this prefix. The **site** is per vendor and
permanent: which Spoonity Order brand deployment (an `https://` origin plus its
Firebase web API key and project id) the Ordering section talks to for this
merchant. Only Prism admins manage it. The **credential** is per session and
per vendor and lasts at most one hour: a Firebase ID token for that site,
obtained by the operator entering their Spoonity password (and, when the brand
requires it, a second-factor code). The credential is what the `ordering` proxy
target (`/api/ordering/*`) and `/api/ordering-menus/*` forward.

As with Apex, the password is used for one call and never stored; tokens and
second-factor tickets stay on the server-side session record and never appear
in a response. Every credential failure is a `403` with a `code`, never a
`401`. All responses carry `Cache-Control: no-store`. Times (`loginAt`,
`expiresAt`, `registeredAt`) are Unix **milliseconds**.

Common errors on every route below: `401 {"error": "unauthorized", "detail": "Not signed in"}`
with no session; the session-expired `401` (see `GET /auth/me`) when the
session record is gone; `503 {"error": "unavailable", "detail": "Session service temporarily unavailable"}`
when the session store or the site registry cannot be read or written. The
admin-only routes also answer
`403 {"error": "forbidden", "code": "admin_required", "detail": "Only a Prism admin can manage the ordering site for this merchant"}`
to any role other than `admin` at the active vendor.

### POST /auth/ordering/sites/probe

Check that an origin is a Spoonity Order deployment that serves the active
vendor, and try to read its Firebase config out of its public bundle. The
vendor check uses the site's own `/api/proxy/health`, which lists the Spoonity
vendor ids it serves. The Firebase sniff is best effort: `detected` may be
empty, and the admin can type the values instead. Nothing is stored.

**Auth:** Prism session cookie, `admin` at the active vendor.

**Body:**

| Field | Type | Required | Notes |
|---|---|---|---|
| `origin` | string | yes | an `https://` origin with no path, query, fragment or credentials |

**Request example:**

```bash
curl -sS -b cookies.txt 'https://prism.spoonity.com/auth/ordering/sites/probe' \
  -H 'Content-Type: application/json' \
  -d '{ "origin": "https://order.example.com" }'
```

**Response example** (`200`):

```json
{
  "origin": "https://order.example.com",
  "build": { "sha": "3f9c1e2", "release": "2026.09.1" },
  "spoonityVendors": ["123456"],
  "detected": { "firebaseApiKey": "AIza...", "firebaseProjectId": "example-order" }
}
```

`build` is passed through from the site's health response and is opaque to
Prism. `spoonityVendors` are strings.

**Errors:**

| Status | Body | Meaning |
|---|---|---|
| `400` | `{"error": "bad_request", "detail": "origin must be an https:// URL with no path"}` | missing or malformed origin; nothing is called |
| `400` | `{"error": "bad_request", "code": "site_unreachable", "detail": "<origin> did not answer /api/proxy/health"}` | the origin did not answer |
| `400` | `{"error": "bad_request", "code": "site_not_for_vendor", "detail": "<origin> does not list vendor <id> among the merchants it serves"}` | the site does not serve the active vendor |
| `403` | `admin_required` | not an admin |

---

### GET /auth/ordering/site

The full registry row for the active vendor, including the Firebase API key.
This is the only route that returns the key.

**Auth:** Prism session cookie, `admin` at the active vendor.

**Params:** none.

**Request example:**

```bash
curl -sS -b cookies.txt 'https://prism.spoonity.com/auth/ordering/site'
```

**Response example** (`200`):

```json
{
  "site": {
    "vendorId": 123456,
    "origin": "https://order.example.com",
    "firebaseApiKey": "AIza...",
    "firebaseProjectId": "example-order",
    "registeredBy": "ops@example.com",
    "registeredAt": 1790000000000
  }
}
```

**Errors:**

| Status | Body | Meaning |
|---|---|---|
| `403` | `{"error": "forbidden", "code": "ordering_site_unregistered", "detail": "no ordering site is registered for vendor <id>"}` | nothing registered |
| `403` | `admin_required` | not an admin |

---

### PUT /auth/ordering/site

Register, or re-register, the ordering site for the active vendor. The origin
is not re-probed here; only its shape and the two Firebase fields are checked.

**Auth:** Prism session cookie, `admin` at the active vendor.

**Body:**

| Field | Type | Required | Notes |
|---|---|---|---|
| `origin` | string | yes | `https://` origin, no path |
| `firebaseApiKey` | string | yes | non-empty after trimming |
| `firebaseProjectId` | string | yes | non-empty after trimming |

**Request example:**

```bash
curl -sS -b cookies.txt -X PUT 'https://prism.spoonity.com/auth/ordering/site' \
  -H 'Content-Type: application/json' \
  -d '{ "origin": "https://order.example.com", "firebaseApiKey": "AIza...", "firebaseProjectId": "example-order" }'
```

**Response example** (`200`):

```json
{ "status": "ok", "site": { "vendorId": 123456, "origin": "https://order.example.com", "firebaseApiKey": "AIza...", "firebaseProjectId": "example-order", "registeredBy": "ops@example.com", "registeredAt": 1790000000000 } }
```

**Errors:**

| Status | Body | Meaning |
|---|---|---|
| `400` | `{"error": "bad_request", "detail": "origin must be an https:// URL with no path"}` | malformed origin |
| `400` | `{"error": "bad_request", "detail": "firebaseApiKey and firebaseProjectId are required"}` | a Firebase field is missing |
| `403` | `admin_required` | not an admin |

Records an `ordering_site.register` audit event (section `ordering`).

---

### DELETE /auth/ordering/site

Remove the active vendor's ordering site, and drop this session's ordering
credential for that vendor (other sessions' credentials stop working on their
next call).

**Auth:** Prism session cookie, `admin` at the active vendor.

**Params:** none.

**Request example:**

```bash
curl -sS -b cookies.txt -X DELETE 'https://prism.spoonity.com/auth/ordering/site'
```

**Response example** (`200`):

```json
{ "status": "ok" }
```

The same answer is returned when nothing was registered, with nothing written
and no audit event. Otherwise an `ordering_site.delete` audit event is
recorded.

**Errors:** `403 admin_required`; the common `401` and `503` answers.

---

### GET /auth/ordering/status

Whether a site is registered for the active vendor, and whether this session
holds a live credential for it. Makes no upstream call and never returns the
API key, so it is safe to poll. A credential past its one-hour limit reports
`connected: false`.

**Auth:** Prism session cookie (any role).

**Params:** none.

**Request example:**

```bash
curl -sS -b cookies.txt 'https://prism.spoonity.com/auth/ordering/status'
```

**Response example** (`200`, registered and connected):

```json
{
  "registered": true,
  "site": { "origin": "https://order.example.com", "firebaseProjectId": "example-order" },
  "connected": true,
  "loginAt": 1790000000000,
  "expiresAt": 1790003600000
}
```

Not registered: `{"registered": false, "connected": false}`. `loginAt` and
`expiresAt` appear only when `connected` is `true`.

**Errors:** the common `401` and `503` answers.

---

### POST /auth/ordering/connect

Obtain an ordering credential for the active vendor's registered site. The body
is exactly one of `{password}` or `{code}`. Step one sends the operator's
Spoonity password (the username is always the session's own email) to the
brand's `/api/admin/login`. If the brand requires a second factor and the
account is enrolled, the answer is `403 ordering_mfa_required`; the
second-factor ticket is kept server-side for just under five minutes, and step
two sends `{code}` (a 6-digit authenticator code or a backup code). A wrong
code keeps the ticket; an expired or exhausted one is dropped and the operator
starts again with the password.

**Auth:** Prism session cookie (any role). Rate-limited: 10 requests/minute/IP,
counting code attempts too.

**Body:**

| Field | Type | Required | Notes |
|---|---|---|---|
| `password` | string | one of | the operator's Spoonity password |
| `code` | string | one of | second-factor code; whitespace is removed; at most 32 characters |

**Request example:**

```bash
curl -sS -b cookies.txt 'https://prism.spoonity.com/auth/ordering/connect' \
  -H 'Content-Type: application/json' \
  -d '{ "password": "<spoonity password>" }'
```

**Response example** (`200`):

```json
{ "status": "ok", "expiresAt": 1790003600000 }
```

`expiresAt` is the credential's login time plus one hour. On success an
`auth.ordering_connect` audit event is recorded (section `auth`).

**Errors:** every `403` has `"error": "forbidden"` plus the `code` and `detail`
below.

| Status | `code` | Meaning |
|---|---|---|
| `400` | none; `detail` `"send either password or code"` | both or neither sent |
| `400` | none; `detail` `"that code is too long"` | code longer than 32 characters |
| `403` | `ordering_site_unregistered` | no site registered for the active vendor |
| `403` | `password_invalid` | the brand refused the Spoonity password |
| `403` | `ordering_not_authorized` | the account lacks the `root` scope at this brand |
| `403` | `ordering_captcha_required` | the brand requires a captcha; sign in once at `<origin>/admin` |
| `403` | `ordering_mfa_required` | password accepted; send `{code}` next |
| `403` | `ordering_mfa_enroll_required` | the brand requires a second factor the account has not set up; the body also carries `adminUrl` (`<origin>/admin`) |
| `403` | `ordering_mfa_invalid_code` | wrong code; may carry `attemptsRemaining` |
| `403` | `ordering_mfa_clock_skew` | code for the wrong time; may carry `skewSeconds` |
| `403` | `ordering_mfa_code_used` | code already used |
| `403` | `ordering_mfa_locked` | authenticator codes locked for 30 minutes; may carry `lockedUntil` |
| `403` | `ordering_mfa_ticket_expired` | no pending ticket, or it expired; start again with the password |
| `403` | `ordering_mfa_too_many_attempts` | too many codes for this sign-in; start again |
| `403` | `ordering_site_misconfigured` | Firebase refused the token; the registered API key or project id is wrong |
| `429` | none; `{"error": "rate_limited", ...}` | Prism's 10/minute limit, or the brand's own sign-in or code rate limit passed through |
| `502` | none; `{"error": "upstream", "detail": "The ordering site is unavailable"}` or `"Firebase is unavailable"` | the brand backend or Firebase could not be reached |

---

### POST /auth/ordering/disconnect

Drop this session's ordering credential for the active vendor only.
Credentials for other vendors on the same session are kept.

**Auth:** Prism session cookie.

**Params:** none.

**Request example:**

```bash
curl -sS -b cookies.txt -X POST 'https://prism.spoonity.com/auth/ordering/disconnect'
```

**Response example** (`200`):

```json
{ "status": "ok" }
```

Also returned when nothing was connected (nothing written, no audit event).
Otherwise an `auth.ordering_disconnect` audit event is recorded.

**Errors:** the common `401` and `503` answers.

---

## Analytics relay (`/ingest/*`)

Prism's own product analytics (PostHog: pageviews, autocapture, masked
session replay) never leave the dashboard's origin from the browser. The
SPA's `posthog-js` is configured with `api_host: '/ingest'`, and the BFF
relays that namespace to PostHog Cloud so its Content-Security-Policy can
keep `connect-src 'self'`:

| Path | Relayed to |
| --- | --- |
| `ALL /ingest/static/*` | `POSTHOG_ASSETS_HOST` (default `https://us-assets.i.posthog.com`) `/static/*` |
| `ALL /ingest/*` | `POSTHOG_HOST` (default `https://us.i.posthog.com`) `/*` |

Method, query string, body and headers pass through unchanged; the
upstream's status, headers and body come back unchanged (minus hop-by-hop
headers and any `Set-Cookie`), tagged `X-Prism-Upstream: posthog`. The
`Cookie` and `Authorization` headers are **dropped** before the request
leaves, and the caller's IP is sent as `X-Forwarded-For`. There is no OIDC
token, no `X-Spoonity-*` header and **no session requirement**: the PostHog
project token is a public write-only value the SDK puts in the body itself,
and the anonymous sign-in page is instrumented too.

**Only mounted when `POSTHOG_API_KEY` is set on the service.** Without it
`/ingest/*` answers `404` and the SPA never initialises the SDK: the served
shell carries no `<meta name="posthog-key">`, and the session view's
`config` has no `posthogKey`. Rate-limited to 1200 requests/minute/IP.
Errors use `{"error", "code", "message"}`: a path containing `..` is
`400` with `code: path_traversal`, and an unreachable or timed-out upstream
(30 seconds to response headers) is `502` with
`code: upstream_unreachable | upstream_timeout`.

Nothing on this route is an integration surface: it exists for the
dashboard's own bundle and is documented here only so a `/ingest/e/` POST in
Prism's access logs is recognisable.

---

## Audit log (`/api/audit`)

The read side of Prism's operator activity trail. There is no write
endpoint: every audited mutation, whether it went through the product proxy
or one of Prism's own local routes, is recorded automatically as it
happens, and this is the only way to read it back.

### GET /api/audit

List audit events for the caller's active vendor, newest first.

**Auth:** Prism session cookie. Always scoped to `session.activeVendorId`;
a `?vendorId=` query parameter, if sent, is silently ignored (a deliberate
security property). `section=auth` additionally requires `role === 'admin'`,
and a non-admin caller with no `section` filter never sees `auth`-section
events in the unfiltered feed.

**Query params:**

| Name | Type | Required | Notes |
|---|---|---|---|
| `section` | one of `cms`, `links`, `wallet`, `insights`, `auth`, `feedback`, `loyalty`, `reporting`, `comms`, `marketing`, `corporate`, `apex`, `ordering`, `flags`, `promotions` | no | `auth` is admin-only (`403` otherwise) |
| `actor` | string (email) | no | exact match on the recording actor's email; must be non-empty when sent |
| `limit` | integer | no | default 30, clamped to 1 to 50 (an out-of-range value is clamped, never a `400`) |
| `cursor` | opaque string | no | from a previous response's `nextCursor`, for the next page |

Each parameter may be sent at most once.

**Request example:**

```bash
curl -sS -b cookies.txt \
  'https://prism.spoonity.com/api/audit?section=cms&limit=20'
```

**Response example** (`200`):

```json
{
  "events": [
    {
      "id": "3f9c1e2a",
      "ts": "2026-08-30T14:02:11.483Z",
      "expireAt": "2027-10-04T14:02:11.483Z",
      "vendorId": "123456",
      "email": "ops@example.com",
      "role": "editor",
      "source": "proxy",
      "section": "cms",
      "action": "space.publish",
      "entityType": "space",
      "entityId": "5821",
      "method": "POST",
      "path": "/spaces/:id/publish",
      "status": 200,
      "requestId": "b6b9e3a0-1e2d-4c9b-9a5a-1a2b3c4d5e6f"
    }
  ],
  "nextCursor": "eyJ0cyI6IjIwMjYtMDgtMzBUMTQ6MDA6MDAuMDAwWiIsImlkIjoiYWJjMTIzIn0"
}
```

`nextCursor` is `null` once there is no further page.

#### The audit event shape

Every event recorded anywhere in Prism, proxied or BFF-local, has this same
15-field shape (`apps/bff/src/audit/types.ts`):

```ts
interface AuditEvent {
  id: string;               // store-assigned document id
  ts: string;               // ISO-8601, stamped when the event was recorded
  expireAt: Date;           // ts + 400 days, a retention TTL (an ISO string on the wire)
  vendorId: string;         // the vendor the action happened under, always as a string
  email: string;            // the operator who performed the action
  role: string | null;      // that operator's role at that vendor, if known
  source: "proxy" | "local"; // captured by the reverse-proxy hook, or an explicit local recorder call
  section: AuditSection;    // one of the `section` values listed above
  action: string;           // e.g. "space.publish", "insights_tile.create", "auth.session_start"
  entityType: string;       // e.g. "space", "insights_tile"
  entityId: string | null;  // parsed from the URL PATH only, never from a request or response body
  method: string;           // the HTTP method of the recorded request
  path: string;             // a TEMPLATED pattern, e.g. "/spaces/:id/publish", never the raw path or a query string
  status: number;           // the response status the recorded request actually got
  requestId: string;        // minted fresh by the recorder, unrelated to any upstream request id
}
```

No request or response body is ever read, buffered, or stored by the audit
system; `entityId` comes from the URL path alone. Every `POST` under
`/api/insights/*` (the proxied Insights surface) is **default-denied** from
this log except its two CSV export routes (`query.export`, `tile.export`).
See [`insights.md`'s POST-is-a-read callout](./insights.md#the-trap-every-endpoint-here-that-answers-to-post-is-a-read)
for why the rest of that surface, despite being `POST`, is never recorded
here: it is reads, not writes.

**Errors:**

| Status | Body | Meaning |
|---|---|---|
| `401` | `{"error": "unauthorized", "detail": "Not signed in"}` | no session |
| `400` | `{"error": "bad_request", "detail": "'section' must be one of: ..."}` | unknown `section` |
| `400` | `{"error": "bad_request", "detail": "'<name>' must be a single value"}` | a query param sent more than once (for `actor`: `"'actor' must be a single, non-empty value"`) |
| `400` | `{"error": "bad_request", "detail": "'cursor' is not a valid page token"}` | an invalid `cursor` |
| `403` | `{"error": "forbidden", "detail": "Only admins can view auth events"}` | `section=auth` from a non-admin |
| `500` | `{"error": "internal_error", "detail": "Could not load audit events"}` | store read failed |

---

## Saved tiles (`/api/tiles`)

An operator's own saved Explore queries: a `QuerySpec` (see
[`insights.md`](./insights.md#post-query)) plus a chart config, persisted so
it can be reused, shared at `vendor` visibility, or placed on a personal
dashboard. These records are the same Firestore documents the standalone
Insights app reads.

Rules shared by every saved-object family on this page (tiles, dashboards,
goals):

- A record id belonging to another vendor is always `404`, never `403`, so
  cross-vendor existence is never leaked.
- A same-vendor record owned by someone else is readable when its
  visibility is `vendor`, but not writable (`403` on PATCH, PUT and DELETE by
  a non-owner).
- Ids are server-assigned UUIDs; `vendorId`, `ownerEmail` and the
  timestamps are stamped from the session and cannot be set by the client.
- Bodies are JSON, limited to 1 MB.
- Each vendor may hold at most 1000 records of one kind; a create past that
  answers `429 {"error": "too_many_records", "detail": "..."}`.
- An unexpected store failure answers
  `500 {"error": "internal", "detail": "Internal server error"}`.

### GET /api/tiles

List every tile visible to the caller at their active vendor (their own
private tiles, plus every `vendor`-visibility tile at that vendor).

**Auth:** Prism session cookie.

**Params:** none.

**Request example:**

```bash
curl -sS -b cookies.txt 'https://prism.spoonity.com/api/tiles'
```

**Response example** (`200`):

```json
[
  {
    "id": "8f2a6c1e-3b7d-4e0a-9c55-2d1f0e7b4a90",
    "vendorId": "123456",
    "ownerEmail": "ops@example.com",
    "name": "Net sales by location",
    "visibility": "private",
    "createdAt": "2026-07-01T09:00:00.000Z",
    "updatedAt": "2026-07-01T09:00:00.000Z",
    "spec": { "view": "sales", "fields": ["location", "net_sales"], "filters": [], "sorts": [], "params": {} },
    "viz": { "kind": "bar" }
  }
]
```

**Errors:** `401` (session guard); `500 internal` on a store failure.

---

### POST /api/tiles

Create a tile owned by the caller.

**Auth:** Prism session cookie.

**Body:**

| Field | Type | Required | Notes |
|---|---|---|---|
| `name` | string | yes | non-empty after trimming |
| `visibility` | `"private"` or `"vendor"` | no | defaults to `"private"` |
| `spec` | `QuerySpec` object | no | defaults to an empty query; see [`insights.md`](./insights.md#post-query) for the shape |
| `viz` | object | no | defaults to `{}`; `viz.kind`, if present, must be one of `stat`, `trend`, `bar`, `pie`, `funnel`, `pyramid`, `table` |

**Request example:**

```bash
curl -sS -b cookies.txt 'https://prism.spoonity.com/api/tiles' \
  -H 'Content-Type: application/json' \
  -d '{
        "name": "Net sales by location",
        "visibility": "private",
        "viz": { "kind": "bar" },
        "spec": { "view": "sales", "fields": ["location", "net_sales"], "filters": [], "sorts": [], "params": {} }
      }'
```

**Response example** (`201`): the created tile record, same shape as one
entry from `GET /api/tiles`. Records an `insights_tile.create` audit event.

**Errors:**

| Status | Body | Meaning |
|---|---|---|
| `400` | `{"error": "bad_request", "detail": "'name' is required and must be a non-empty string"}` (or the detail naming the bad field) | validation failure |
| `429` | `{"error": "too_many_records", "detail": "..."}` | this vendor already holds 1000 saved tiles |
| `401` / `500` | as above | |

---

### GET /api/tiles/:id

Fetch one tile.

**Auth:** Prism session cookie.

**Path params:** `id`, the tile's id.

**Request example:**

```bash
curl -sS -b cookies.txt 'https://prism.spoonity.com/api/tiles/8f2a6c1e-3b7d-4e0a-9c55-2d1f0e7b4a90'
```

**Response example** (`200`): one tile record, same shape as above.

**Errors:** `404 {"error": "not_found", "detail": "Tile not found"}` for a
missing id **or** one not visible to the caller (deliberately
indistinguishable); `401` / `500` as above.

---

### PATCH /api/tiles/:id

Owner-only partial update. Any subset of `name`, `visibility`, `spec`,
`viz` may be sent; an absent field is left untouched.

**Auth:** Prism session cookie. Only the tile's own `ownerEmail` may write.

**Path params:** `id`.

**Body:** same fields as `POST /api/tiles`, all optional.

**Request example:**

```bash
curl -sS -b cookies.txt -X PATCH 'https://prism.spoonity.com/api/tiles/8f2a6c1e-3b7d-4e0a-9c55-2d1f0e7b4a90' \
  -H 'Content-Type: application/json' \
  -d '{ "visibility": "vendor" }'
```

**Response example** (`200`): the updated tile record. Records an
`insights_tile.update` audit event.

**Errors:**

| Status | Body | Meaning |
|---|---|---|
| `400` | `{"error": "bad_request", "detail": "..."}` | validation failure |
| `403` | `{"error": "forbidden", "detail": "Only the owner can update this tile"}` | visible at this vendor, owned by someone else |
| `404` | `{"error": "not_found", "detail": "Tile not found"}` | missing or not visible |
| `401` / `500` | as above | |

---

### DELETE /api/tiles/:id

Owner-only remove.

**Auth:** Prism session cookie. Owner-only, same as PATCH.

**Path params:** `id`.

**Request example:**

```bash
curl -sS -b cookies.txt -X DELETE 'https://prism.spoonity.com/api/tiles/8f2a6c1e-3b7d-4e0a-9c55-2d1f0e7b4a90'
```

**Response example** (`200`):

```json
{ "ok": true }
```

Records an `insights_tile.delete` audit event.

**Errors:** `403 {"error": "forbidden", "detail": "Only the owner can delete this tile"}`;
`404 not_found`; `401` / `500` as above.

---

## Saved dashboards (`/api/dashboards`)

An operator's own arrangement of saved tiles into a personal dashboard.
**Not** to be confused with `GET /api/insights/dashboards`, the curated,
entitled dashboard list served by the Insights proxy
([`insights.md`](./insights.md#get-dashboards)). They differ by one path
segment and return completely different shapes. Same visibility, ownership
and 404-versus-403 model as saved tiles.

### GET /api/dashboards

List dashboards visible to the caller at their active vendor.

**Auth:** Prism session cookie.

**Params:** none.

**Request example:**

```bash
curl -sS -b cookies.txt 'https://prism.spoonity.com/api/dashboards'
```

**Response example** (`200`):

```json
[
  {
    "id": "4a11d0b2-7c3e-4f19-8e2a-6b5c9d0e1f23",
    "vendorId": "123456",
    "ownerEmail": "ops@example.com",
    "name": "My morning check",
    "visibility": "private",
    "createdAt": "2026-07-01T09:00:00.000Z",
    "updatedAt": "2026-07-01T09:00:00.000Z",
    "filters": {}
  }
]
```

**Errors:** `401` / `500` as above.

---

### POST /api/dashboards

Create a dashboard owned by the caller.

**Auth:** Prism session cookie.

**Body:**

| Field | Type | Required | Notes |
|---|---|---|---|
| `name` | string | yes | non-empty after trimming |
| `visibility` | `"private"` or `"vendor"` | no | defaults to `"private"` |
| `filters` | object mapping filter names to string values | no | dashboard-level filter defaults; every value must be a string |

**Request example:**

```bash
curl -sS -b cookies.txt 'https://prism.spoonity.com/api/dashboards' \
  -H 'Content-Type: application/json' \
  -d '{ "name": "My morning check", "visibility": "private" }'
```

**Response example** (`201`): the created dashboard record. Records an
`insights_dashboard.create` audit event.

**Errors:** `400 bad_request` (validation, with the bad field named);
`429 too_many_records` (per-vendor cap); `401` / `500` as above.

---

### GET /api/dashboards/:id

Fetch one dashboard record (not its tile placements; see
`GET /api/dashboards/:id/tiles` below).

**Auth:** Prism session cookie.

**Path params:** `id`.

**Request example:**

```bash
curl -sS -b cookies.txt 'https://prism.spoonity.com/api/dashboards/4a11d0b2-7c3e-4f19-8e2a-6b5c9d0e1f23'
```

**Response example** (`200`): one dashboard record, same shape as above.

**Errors:** `404 {"error": "not_found", "detail": "Dashboard not found"}`
(missing or not visible); `401` / `500`.

---

### PATCH /api/dashboards/:id

Owner-only partial update of `name`, `visibility`, and/or `filters`.

**Auth:** Prism session cookie, owner-only.

**Path params:** `id`.

**Body:** same fields as `POST /api/dashboards`, all optional.

**Request example:**

```bash
curl -sS -b cookies.txt -X PATCH 'https://prism.spoonity.com/api/dashboards/4a11d0b2-7c3e-4f19-8e2a-6b5c9d0e1f23' \
  -H 'Content-Type: application/json' \
  -d '{ "name": "Morning standup numbers" }'
```

**Response example** (`200`): the updated dashboard record. Records an
`insights_dashboard.update` audit event.

**Errors:** `400 bad_request`;
`403 {"error": "forbidden", "detail": "Only the owner can update this dashboard"}`;
`404 not_found`; `401` / `500`.

---

### DELETE /api/dashboards/:id

Owner-only remove. Cascades: the dashboard's tile placements are removed
with it, and this route records exactly one audit event
(`insights_dashboard.delete`) for the dashboard, not one per placement.

**Auth:** Prism session cookie, owner-only.

**Path params:** `id`.

**Request example:**

```bash
curl -sS -b cookies.txt -X DELETE 'https://prism.spoonity.com/api/dashboards/4a11d0b2-7c3e-4f19-8e2a-6b5c9d0e1f23'
```

**Response example** (`200`):

```json
{ "ok": true }
```

**Errors:** `403 forbidden` (non-owner) / `404 not_found`; `401` / `500`.

---

### GET /api/dashboards/:id/tiles

The dashboard's tile placement list: which saved tiles appear, in what
order, at what grid span.

**Auth:** Prism session cookie. Any caller who can see the dashboard (the
owner, or any member of the vendor when it is `vendor`-visible) may read
this.

**Path params:** `id`.

**Request example:**

```bash
curl -sS -b cookies.txt 'https://prism.spoonity.com/api/dashboards/4a11d0b2-7c3e-4f19-8e2a-6b5c9d0e1f23/tiles'
```

**Response example** (`200`):

```json
[
  {
    "id": "c7e1a9d4-2b6f-4a38-9d1c-5e0f7a2b8c61",
    "dashboardId": "4a11d0b2-7c3e-4f19-8e2a-6b5c9d0e1f23",
    "savedTileId": "8f2a6c1e-3b7d-4e0a-9c55-2d1f0e7b4a90",
    "position": 0,
    "span": 6
  }
]
```

**Errors:** `404 {"error": "not_found", "detail": "Dashboard not found"}`
(missing or not visible); `401` / `500`.

---

### PUT /api/dashboards/:id/tiles

Replace the dashboard's entire tile placement list. Owner-only. A partial
update is not supported: this always replaces the whole list, `position` is
assigned from array order, and every placement gets a fresh id.

**Auth:** Prism session cookie, owner-only.

**Path params:** `id`.

**Body:** a JSON array of placements.

| Field | Type | Required | Notes |
|---|---|---|---|
| `tileId` | string | yes | non-empty; stored as `savedTileId` |
| `span` | integer | no | 1 to 12; defaults to 1 |

**Request example:**

```bash
curl -sS -b cookies.txt -X PUT 'https://prism.spoonity.com/api/dashboards/4a11d0b2-7c3e-4f19-8e2a-6b5c9d0e1f23/tiles' \
  -H 'Content-Type: application/json' \
  -d '[{ "tileId": "8f2a6c1e-3b7d-4e0a-9c55-2d1f0e7b4a90", "span": 6 }]'
```

**Response example** (`200`): the new placement list, same shape as
`GET /api/dashboards/:id/tiles`. Records an
`insights_dashboard.set_placements` audit event.

**Errors:**

| Status | Body | Meaning |
|---|---|---|
| `400` | `{"error": "bad_request", "detail": "body must be a JSON array of placements"}` (or a per-index detail such as `"placements[0].span must be an integer between 1 and 12"`) | malformed body |
| `403` | `{"error": "forbidden", "detail": "Only the owner can update this dashboard"}` | non-owner |
| `404` | `{"error": "not_found", "detail": "Dashboard not found"}` | dashboard missing or not visible |
| `401` / `500` | as above | |

---

## Goals (`/api/goals`)

A target on a saved tile's measure over the current calendar month,
quarter, or year, with optional attainment email. This is the one
saved-object family with a read that makes a live upstream call
(`GET /api/goals/:id/progress`), because computing progress means running
the goal's own tile spec for the current period.

### GET /api/goals

List goals visible to the caller at their active vendor.

**Auth:** Prism session cookie.

**Params:** none.

**Request example:**

```bash
curl -sS -b cookies.txt 'https://prism.spoonity.com/api/goals'
```

**Response example** (`200`):

```json
[
  {
    "id": "2c90e4b1-6a7d-4c2f-8b3e-9d0a1f5e7c42",
    "vendorId": "123456",
    "ownerEmail": "ops@example.com",
    "name": "Q3 net sales",
    "savedTileId": "8f2a6c1e-3b7d-4e0a-9c55-2d1f0e7b4a90",
    "field": "net_sales",
    "aggregate": "sum",
    "target": 500000,
    "direction": "at_least",
    "period": "quarter",
    "recipients": ["ops@example.com"],
    "notifyOnAttain": true,
    "enabled": true,
    "attainedNotifiedAt": null,
    "createdAt": "2026-07-01T09:00:00.000Z",
    "updatedAt": "2026-07-01T09:00:00.000Z"
  }
]
```

**Errors:** `401` / `500`.

---

### POST /api/goals

Create a goal owned by the caller. `savedTileId` must resolve to a tile the
caller can see, so a goal can never be pointed at another vendor's tile.

**Auth:** Prism session cookie.

**Body:**

| Field | Type | Required | Notes |
|---|---|---|---|
| `name` | string | yes | non-empty |
| `savedTileId` | string | yes | must be a saved tile visible to the caller |
| `field` | string | yes | the tile result's measure to reduce |
| `aggregate` | `"sum"` or `"first_row"` | yes | |
| `target` | number | yes | finite |
| `direction` | `"at_least"` or `"at_most"` | yes | |
| `period` | `"month"`, `"quarter"` or `"year"` | yes | |
| `recipients` | string[] | yes | 1 to 10 valid email addresses; lowercased and deduplicated. Omitting it, or sending `[]`, is a `400` |
| `notifyOnAttain` | boolean | no | defaults `false` |
| `enabled` | boolean | no | defaults `true` |

**Request example:**

```bash
curl -sS -b cookies.txt 'https://prism.spoonity.com/api/goals' \
  -H 'Content-Type: application/json' \
  -d '{
        "name": "Q3 net sales",
        "savedTileId": "8f2a6c1e-3b7d-4e0a-9c55-2d1f0e7b4a90",
        "field": "net_sales",
        "aggregate": "sum",
        "target": 500000,
        "direction": "at_least",
        "period": "quarter",
        "recipients": ["ops@example.com"],
        "notifyOnAttain": true
      }'
```

**Response example** (`201`): the created goal record. Records an
`insights_goal.create` audit event.

**Errors:**

| Status | Body | Meaning |
|---|---|---|
| `400` | `{"error": "bad_request", "detail": "..."}` | a field failing its rule (named in `detail`) |
| `400` | `{"error": "bad_request", "detail": "'recipients' must be a non-empty array of address strings"}` | `recipients` missing or empty; other recipient details name invalid addresses or the 10-address cap |
| `400` | `{"error": "bad_request", "detail": "'savedTileId' does not refer to a saved tile visible to you"}` | tile missing or not visible |
| `429` | `{"error": "too_many_records", "detail": "..."}` | per-vendor cap |
| `401` / `500` | as above | |

---

### GET /api/goals/:id

Fetch one goal record.

**Auth:** Prism session cookie.

**Path params:** `id`.

**Request example:**

```bash
curl -sS -b cookies.txt 'https://prism.spoonity.com/api/goals/2c90e4b1-6a7d-4c2f-8b3e-9d0a1f5e7c42'
```

**Response example** (`200`): one goal record, same shape as above.

**Errors:** `404 {"error": "not_found", "detail": "Goal not found"}`;
`401` / `500`.

---

### PATCH /api/goals/:id

Owner-only partial update. Any of the create fields may be sent;
`recipients` is re-validated when present (so it can be replaced but not
emptied), and a new `savedTileId` must again be a tile visible to the
caller.

**Auth:** Prism session cookie, owner-only.

**Path params:** `id`.

**Body:** same fields as `POST /api/goals`, all optional.

**Request example:**

```bash
curl -sS -b cookies.txt -X PATCH 'https://prism.spoonity.com/api/goals/2c90e4b1-6a7d-4c2f-8b3e-9d0a1f5e7c42' \
  -H 'Content-Type: application/json' \
  -d '{ "target": 550000 }'
```

**Response example** (`200`): the updated goal record. Records an
`insights_goal.update` audit event.

**Errors:** `400 bad_request`;
`403 {"error": "forbidden", "detail": "Only the owner can update this goal"}`;
`404 not_found`; `401` / `500`.

---

### DELETE /api/goals/:id

Owner-only remove.

**Auth:** Prism session cookie, owner-only.

**Path params:** `id`.

**Request example:**

```bash
curl -sS -b cookies.txt -X DELETE 'https://prism.spoonity.com/api/goals/2c90e4b1-6a7d-4c2f-8b3e-9d0a1f5e7c42'
```

**Response example** (`200`):

```json
{ "ok": true }
```

Records an `insights_goal.delete` audit event.

**Errors:** `403 forbidden`; `404 not_found`; `401` / `500`.

---

### GET /api/goals/:id/progress

Run the goal's tile spec for the **current** calendar period (overriding
the tile's own saved period) and reduce the goal's field against it. The
only saved-object route that makes a live call to the Insights API on the
caller's behalf.

**Auth:** Prism session cookie.

**Path params:** `id`.

**Request example:**

```bash
curl -sS -b cookies.txt 'https://prism.spoonity.com/api/goals/2c90e4b1-6a7d-4c2f-8b3e-9d0a1f5e7c42/progress'
```

**Response example** (`200`):

```json
{
  "current": 312500,
  "target": 500000,
  "pct": 62.5,
  "period": "quarter",
  "periodKey": "2026-Q3",
  "onPace": true,
  "direction": "at_least"
}
```

`current`, `pct`, and `onPace` are `null` when the tile result carried no
usable value for the goal's field. `pct` is also `null` when `target` is
`0`. `onPace` compares `current` with the target prorated by how much of the
period has elapsed.

**Errors:**

| Status | Body | Meaning |
|---|---|---|
| `404` | `{"error": "not_found", "detail": "Goal not found"}` | missing or not visible |
| `400` | `{"error": "bad_request", "detail": "the goal's saved tile no longer exists or is not visible to you"}` | the goal's tile was since deleted or made private by someone else |
| `502` | `{"error": "upstream", "detail": "Insights API authentication failed"}`, `{"error": "upstream", "detail": "Insights API is unreachable"}` or `{"error": "upstream", "detail": "Insights API query failed"}` | the live upstream call failed |
| `401` / `500` | as above | |

---

## Digest preference (`/api/digest`)

The operator's own opt-in to the weekly performance-digest email: one
record per (vendor, email), upsert semantics. Prism only writes the
preference; a separate scheduled job reads the same record and sends the
mail.

### GET /api/digest

The caller's own digest preference at their active vendor.

**Auth:** Prism session cookie.

**Params:** none.

**Request example:**

```bash
curl -sS -b cookies.txt 'https://prism.spoonity.com/api/digest'
```

**Response example** (`200`, set):

```json
{
  "id": "5d3b9a70-1c2e-4f8a-b6d4-0e9f7a1c3b25",
  "vendorId": "123456",
  "email": "ops@example.com",
  "enabled": true,
  "createdAt": "2026-07-01T09:00:00.000Z",
  "updatedAt": "2026-07-01T09:00:00.000Z"
}
```

`null` (still `200`) when the caller has never set a preference, which the
UI treats as disabled.

**Errors:** `401` / `500`.

---

### PUT /api/digest

Upsert the caller's own preference. The email is always the session's own;
there is no way to set another address's preference through this route.

**Auth:** Prism session cookie.

**Body:**

| Field | Type | Required |
|---|---|---|
| `enabled` | boolean | yes |

**Request example:**

```bash
curl -sS -b cookies.txt -X PUT 'https://prism.spoonity.com/api/digest' \
  -H 'Content-Type: application/json' \
  -d '{ "enabled": true }'
```

**Response example** (`200`): the stored record, same shape as
`GET /api/digest`'s non-null case. Records an `insights_digest.update`
audit event.

**Errors:**

| Status | Body | Meaning |
|---|---|---|
| `400` | `{"error": "bad_request", "detail": "'enabled' is required and must be a boolean"}` | missing or wrong type |
| `401` / `500` | as above | |

---

## Welcome page (`/api/welcome`)

The operator's own customized set of tiles on the Insights welcome page:
one record per (vendor, email), upsert semantics, structurally the same as
the digest preference. Tiles are references to tiles on the curated
dashboards (`dashboardId` plus `tileKey`), not new queries, so only their
shape is validated.

### GET /api/welcome

The caller's own welcome-page configuration at their active vendor.

**Auth:** Prism session cookie.

**Params:** none.

**Request example:**

```bash
curl -sS -b cookies.txt 'https://prism.spoonity.com/api/welcome'
```

**Response example** (`200`, set):

```json
{
  "id": "9b1e4c7a-0d2f-4e63-a8b5-7c6d1e2f3a40",
  "vendorId": "123456",
  "email": "ops@example.com",
  "tiles": [{ "dashboardId": "sales", "tileKey": "net_sales", "span": 4 }],
  "createdAt": "2026-07-01T09:00:00.000Z",
  "updatedAt": "2026-07-01T09:00:00.000Z"
}
```

`null` (still `200`) when the caller has never saved one; the SPA then shows
its default tile set. A saved empty `tiles` list is a real choice and is not
`null`.

**Errors:** `401` / `500`.

---

### PUT /api/welcome

Upsert the caller's own welcome-page tile set.

**Auth:** Prism session cookie.

**Body:**

| Field | Type | Required | Notes |
|---|---|---|---|
| `tiles` | array | yes | at most 60 entries; may be empty |
| `tiles[].dashboardId` | string | yes | non-empty |
| `tiles[].tileKey` | string | yes | non-empty |
| `tiles[].span` | integer | no | 1 to 12; defaults to 4 |

**Request example:**

```bash
curl -sS -b cookies.txt -X PUT 'https://prism.spoonity.com/api/welcome' \
  -H 'Content-Type: application/json' \
  -d '{ "tiles": [{ "dashboardId": "sales", "tileKey": "net_sales", "span": 4 }] }'
```

**Response example** (`200`): the stored record, same shape as
`GET /api/welcome`'s non-null case. Records an `insights_welcome.update`
audit event.

**Errors:**

| Status | Body | Meaning |
|---|---|---|
| `400` | `{"error": "bad_request", "detail": "'tiles' is required and must be an array"}` (or a per-index detail such as `"tiles[0].tileKey is required and must be a non-empty string"`) | malformed body, or more than 60 tiles |
| `401` / `500` | as above | |

---

## Feedback (`/api/feedback`)

A same-origin front for the in-product feedback widget, relayed to Spoonity's
feedback intake service. It never forwards the caller's own credentials:
the operator's identity is rebuilt server-side from the session and stamped
onto the payload instead, so a browser cannot file a ticket under a spoofed
email or vendor.

### POST /api/feedback

Submit one feedback report, optionally with a screenshot.

**Auth:** Prism session cookie.

**Body:** `multipart/form-data`, capped at 4 MiB (4194304 bytes) in total.

| Part | Type | Required | Notes |
|---|---|---|---|
| `payload` | JSON string | yes | a JSON object with at least `tool` (a Prism section id) and `feedback` (the text); `tenant.name` is a display-only label, kept as sent |
| `screenshot` | file | no | forwarded as-is when present |

`user` and `tenant.id` inside `payload` are ignored if sent; they are always
rebuilt from the session (email, role and active vendor). A `tool` the intake
does not know (anything but `cms`, `links`, `insights`, `wallet`, `wallets`,
`pass-studio`) is filed under `cms` with the original section id prefixed to
the text as `[prism: <tool>]`.

**Request example:**

```bash
curl -sS -b cookies.txt 'https://prism.spoonity.com/api/feedback' \
  -F 'payload={"tool":"insights","feedback":"The Explore export button is hard to find."}' \
  -F 'screenshot=@screenshot.png;type=image/png'
```

**Response example** (the intake's own status, normally `201`, and body,
relayed verbatim):

```json
{ "key": "PA-4821", "url": "https://spoonity.atlassian.net/browse/PA-4821" }
```

The body can also carry a `warning` (for example `screenshot_not_attached`).
Records a `feedback.submit` audit event (section `feedback`).

**Errors:**

| Status | Body | Meaning |
|---|---|---|
| `401` | `{"error": "unauthorized", "detail": "Not signed in"}` | no session (session guard) |
| `400` | `{"error": "bad_request", "detail": "Feedback must be sent as multipart/form-data."}` | wrong content type |
| `400` | `{"error": "bad_request", "detail": "'payload' part is required and must be a JSON string."}` or `"'payload' part must be a JSON object."` | missing or invalid `payload` part; also `"Feedback body was not valid multipart/form-data."` |
| `413` | `{"error": "payload_too_large", "detail": "Feedback submissions are limited to 4194304 bytes."}` | over the 4 MiB cap |
| `502` | `{"error": "bad_gateway", "detail": "The feedback service is unavailable."}`, `"feedback upstream (leon-intake) returned <status>"` or `"The feedback service returned an invalid response."` | the intake is unreachable (30-second timeout), refused the request, or answered with a body that is not JSON |

---

### POST /api/feedback/evaluate

Ask the intake for a quick verdict on a feedback draft while the operator is
still typing, so the widget can suggest improvements before submitting.
Advisory only: every failure is a silent `204`, never an error the widget
has to show.

**Auth:** Prism session cookie.

**Body:** JSON, limited to 64 KB.

| Field | Type | Required | Notes |
|---|---|---|---|
| `tool` | string | yes | a Prism section id, mapped the same way as `POST /api/feedback` |
| `feedback` | string | no | the draft text; fewer than 12 characters after trimming answers `204` without calling the intake |
| `route` | string | no | the SPA route the draft was written on |

The session's email is added server-side.

**Request example:**

```bash
curl -sS -b cookies.txt 'https://prism.spoonity.com/api/feedback/evaluate' \
  -H 'Content-Type: application/json' \
  -d '{ "tool": "insights", "feedback": "Export should remember my columns.", "route": "/insights/explore" }'
```

**Response example** (`200`, the intake's verdict relayed verbatim):

```json
{ "verdict": "good", "sentence": "Removes a step." }
```

`204 No Content` when the draft is too short, or the intake is unreachable
(8-second timeout), answers non-2xx, or answers with anything that is not a
JSON object.

**Errors:**

| Status | Body | Meaning |
|---|---|---|
| `401` | `{"error": "unauthorized", "detail": "Not signed in"}` | no session (session guard) |
| `400` | `{"error": "bad_request", "detail": "'tool' is required and must be a string."}` | missing `tool`; a body that is not a JSON object is `"A JSON object body is required."` |

---

## Product updates (`/api/product-updates`)

A same-origin front for the "what's new" feed: the release-notes widget
shown in the shell and in individual sections. The feed is public
marketing copy, not user data, but the shell ships with
`connect-src 'self'`, so a direct cross-origin fetch from the browser would
be blocked. This route relays the one path the widgets need.

### GET /api/product-updates

Fetch the update feed for one product slug.

**Auth:** Prism session cookie.

**Query params:**

| Name | Type | Required | Notes |
|---|---|---|---|
| `product` | string | yes | One of `cms`, `links`, `insights`, `wallets`, `pass-studio`, validated here so an unknown slug never reaches the upstream. There is no `prism` member and no union across products in one call; a caller wanting more than one slug calls this once per slug. |

**Request example:**

```bash
curl -sS -b cookies.txt \
  'https://prism.spoonity.com/api/product-updates?product=wallets'
```

**Response example** (`200`, relayed verbatim from the feed):

```json
{
  "updates": [
    {
      "id": 3,
      "title": "See what's new without leaving the dashboard",
      "body": "This announcement panel is new! We'll use it to let you know about features and fixes as they ship.",
      "products": ["cms", "links", "insights", "wallets", "pass-studio"],
      "publishedAt": "2026-08-20T00:00:00.000Z"
    }
  ]
}
```

**Errors:**

| Status | Body | Meaning |
|---|---|---|
| `401` | `{"error": "unauthorized", "detail": "Not signed in"}` | no session |
| `400` | `{"error": "bad_request", "detail": "'product' must be one of: cms, links, insights, wallets, pass-studio"}` | `product` missing or outside the known list; never forwarded upstream |
| `502` | `{"error": "bad_gateway", "detail": "The updates service is unavailable."}`, `"updates upstream (leon-intake) returned <status>"` or `"The updates service returned an invalid response."` | upstream unreachable or timed out (10 seconds); upstream answered non-2xx; upstream body did not parse as JSON |

---

## Ordering menus (`/api/ordering-menus/*`)

The two things the Spoonity Order admin panel reads directly from the brand's
Firestore rather than through an API route: the saved menu draft and the menu
audit history. Prism reads them server-side over Firestore REST with the
operator's own ordering credential (from `POST /auth/ordering/connect`), so the
brand's Firestore rules apply exactly as they do in the panel. Both routes are
scoped to the active vendor.

Errors on these routes use the proxy's envelope,
`{"error", "code", "message", "detail"}`, and resolve the credential the same
way the `ordering` proxy target does:

| Status | `code` | Meaning |
|---|---|---|
| `401` | none; `{"error": "unauthorized", "detail": "Not signed in"}` | no session |
| `403` | `ordering_site_unregistered` | no ordering site registered for the active vendor |
| `403` | `ordering_connect_required` | no ordering credential on this session for the active vendor |
| `403` | `ordering_reconnect_required` | the credential is past its hour, could not be refreshed, or Firestore rejected it (the credential is then dropped) |
| `403` | `ordering_upstream_unauthorized` | the brand's Firestore rules refused this operator for this vendor (the credential is kept) |
| `502` | `upstream_error` (`"error": "bad_gateway"`, `"detail": "Firestore could not be read"`) | Firestore failed |
| `503` | `session_store_unavailable` | session store or site registry unavailable |

### GET /api/ordering-menus/draft

The active vendor's saved menu draft (`menus_draft/<vendor>`), decoded to plain
JSON.

**Auth:** Prism session cookie and a connected ordering credential.

**Params:** none.

**Request example:**

```bash
curl -sS -b cookies.txt 'https://prism.spoonity.com/api/ordering-menus/draft'
```

**Response example** (`200`):

```json
{
  "exists": true,
  "menus": [{ "id": "breakfast", "name": "Breakfast" }],
  "storeAssignments": { "store-1": "breakfast" },
  "defaultMenuId": "breakfast",
  "defaultTax": { "rate": 0.13, "inclusive": false },
  "modifierLibrary": [],
  "updatedAt": "2026-09-20T14:02:11.483Z"
}
```

A brand that has never saved a draft answers `200 {"exists": false}`, not a
`404`. Missing fields default to `[]`, `{}` or `null`. `updatedAt` is an
ISO-8601 string.

**Errors:** see the table above.

---

### GET /api/ordering-menus/audit

The active vendor's menu audit history (`menu_audit/<vendor>/entries`), newest
first by the entry's `at` timestamp.

**Auth:** Prism session cookie and a connected ordering credential.

**Query params:**

| Name | Type | Required | Notes |
|---|---|---|---|
| `limit` | integer | no | default 50, capped at 200; a non-numeric or non-positive value falls back to 50 |

**Request example:**

```bash
curl -sS -b cookies.txt 'https://prism.spoonity.com/api/ordering-menus/audit?limit=20'
```

**Response example** (`200`):

```json
{
  "entries": [
    {
      "id": "a1b2c3",
      "action": "publish",
      "by": "ops@example.com",
      "at": "2026-09-20T14:02:11.483Z",
      "hasSnapshot": true
    }
  ]
}
```

Each entry carries its document id, every field the writer stored, and
`hasSnapshot` in place of the (large) `publishedSnapshot` field, which is never
returned. A vendor with no history answers `{"entries": []}`.

**Errors:** see the table above.

---

## Flags sync and provisioning (`/api/flags/*`)

Two BFF-local routes inside the `flags` proxy namespace. They are served by
Prism itself (mounted ahead of the proxy) because each composes its upstream
calls from the session instead of relaying the browser's request. Both call
Flags (`flags.spoonity.com`) with Prism's own Google ID token, send
`X-Spoonity-Vendor`, `X-Spoonity-User` and `X-Spoonity-Role`, and carry
`Cache-Control: no-store`. Errors use `{"error", "code", "message", "detail"}`
(`detail` optional); a body that is not valid JSON is
`400 {"error": "bad_request", "code": "invalid_request", "message": "The request body is not valid JSON."}`.

### POST /api/flags/sync/segment

Replace a Flags segment's membership with the members of a Customers
(reporting) segment. Each member is keyed by their loyalty member id; rows
without a positive integer id are skipped. The Flags segment must already
exist. The first write replaces the membership and later writes add, in chunks
of 5,000 keys; the replace is not atomic across chunks, so a failure part-way
leaves a partial list until the next run (and the error says so).

**Auth:** one of two callers.

1. **An operator** with a Prism session cookie. The role at the active vendor
   must be `editor` or `admin`, `vendorId` in the body must equal the active
   vendor, and reporting is read with the operator's own vendor-scoped
   Spoonity Identity token held on the session record.
2. **Cloud Scheduler**, with no session cookie and
   `Authorization: Bearer <Google ID token>`. The token must verify with an
   audience of Prism's public origin (or `FLAGS_SYNC_AUDIENCE`), and its email
   must be in `FLAGS_SYNC_INVOKERS` (default: Prism's own service account).
   Reporting is then read with a dedicated Spoonity sync account configured on
   the service; Flags is called with role `editor`.

When a request carries a `prism_session` cookie it is always treated as the
operator path.

**Body:**

| Field | Type | Required | Notes |
|---|---|---|---|
| `vendorId` | integer | yes | positive; must be the active vendor on the operator path |
| `environment` | string | yes | Flags environment key, matching `^[a-z0-9][a-z0-9_-]{0,63}$` (e.g. `production`) |
| `reportingSegmentId` | integer | yes | positive; the Customers segment id |
| `flagsSegmentName` | string | yes | matching `^[a-z0-9][a-z0-9_-]{0,63}$` |

Any other field is rejected. The body is limited to 16 KB.

**Request example:**

```bash
curl -sS -b cookies.txt 'https://prism.spoonity.com/api/flags/sync/segment' \
  -H 'Content-Type: application/json' \
  -d '{ "vendorId": 123456, "environment": "production", "reportingSegmentId": 790, "flagsSegmentName": "gold-members" }'
```

**Response example** (`200`):

```json
{
  "vendorId": 123456,
  "environment": "production",
  "reportingSegmentId": 790,
  "flagsSegmentName": "gold-members",
  "members": 1842,
  "chunks": 1,
  "mode": "replace",
  "added": null,
  "removed": null,
  "segment": { "name": "gold-members" }
}
```

`segment` is the Flags service's response to the last write, passed through.
`mode` is `replace` when the whole membership fits in one request (about
15,000 member ids or more): one atomic write, `added`/`removed` `null`. A
larger segment is written as a `diff` against the keys the Flags segment
holds: only the members who joined or left are sent (`added`, `removed`,
`chunks` = the number of writes, `0` when nothing changed), so a member in
both lists is never removed, even for a moment.
On success a `flag_segment.sync` audit event is recorded (section `flags`).

**Errors:**

| Status | `code` | Meaning |
|---|---|---|
| `400` | `invalid_request` | body not JSON, not an object, an unknown field, or a field failing its rule (named in `detail`) |
| `400` | `vendor_mismatch` | operator path: `vendorId` is not the active vendor |
| `401` | none; `{"error": "unauthorized", "detail": "Not signed in"}` | operator path with no session |
| `401` | `invalid_token` | scheduler path: the ID token failed verification |
| `403` | `flags_role_required` | operator path: role is not `editor` or `admin` |
| `403` | `sync_invoker_not_allowed` | scheduler path: caller not in `FLAGS_SYNC_INVOKERS` |
| `403` | `identity_reauth_required` / `identity_token_expired` / `identity_upstream_unauthorized` | the Identity token for reporting is missing, expired, or rejected; sign in again |
| `404` | `flags_segment_not_found` | the Flags segment does not exist |
| `404` | `reporting_segment_not_found` | the Customers segment does not exist |
| `413` | `segment_too_large` | more than 500,000 members, or more than 2,000 reporting pages |
| `502` | `upstream_unreachable`, `upstream_auth_failed`, `upstream_unconfigured`, `bad_gateway`, `sync_identity_failed` | an upstream could not be reached, Prism could not mint its token, or the scheduled sync account was refused |
| `503` | `session_store_unavailable` | operator path: session store unavailable |
| `503` | `sync_identity_unconfigured` | scheduler path: no sync account is configured |

A non-2xx answer from reporting or Flags that is not covered above is passed
through with its status and `reporting_rejected`, `flags_rejected`, or the
Flags error code.

---

### Linked audiences: /api/flags/links

A **linked audience** is a Flags segment that Prism keeps equal to a
Customers segment: it is synced when it is linked, again on demand, and again
by a scheduled refresh. The link is Prism's own record; the Flags service only
sees the same segment writes as `POST /api/flags/sync/segment` makes, with the
same `mode` rules. Every route acts on the **active vendor**; no body or path
names a vendor.

**Auth:** Prism session cookie. `GET` needs any role at the active vendor;
every write needs `editor` or `admin`. The refresh route is for Cloud
Scheduler only (below).

A link, as every route returns it:

```json
{
  "vendorId": 123456,
  "environment": "production",
  "flagsSegmentName": "gold-members-790",
  "reportingSegmentId": 790,
  "reportingSegmentName": "Gold members",
  "createdBy": "ops@example.com",
  "createdAt": 1791334043000,
  "lastSync": { "at": 1791335843000, "ok": true, "by": "ops@example.com", "members": 1842, "added": null, "removed": null }
}
```

Times are Unix milliseconds. A failed sync records `ok: false` with `code`
and `message` instead of the counts.

#### GET /api/flags/links

Query `environment` (optional, an environment key) filters to one
environment. Answers `200 { "items": [link, …] }`, sorted by
`flagsSegmentName`.

#### POST /api/flags/links

| Field | Type | Required | Notes |
|---|---|---|---|
| `environment` | string | yes | Flags environment key |
| `flagsSegmentName` | string | yes | matching `^[a-z0-9][a-z0-9_-]{0,63}$` |
| `reportingSegmentId` | integer | yes | positive; the Customers segment id |
| `reportingSegmentName` | string | no | up to 200 characters; a label shown with the link |
| `createSegment` | boolean | no | `true` creates the Flags segment first; `false` (default) links an existing one |

Any other field is rejected. The body is limited to 16 KB. The first sync
runs with the operator's own Identity token **before** the link is stored, so
a pair that cannot sync is never saved (a segment created by `createSegment`
stays, empty). Linking an audience that is already linked replaces its link.

```bash
curl -sS -b cookies.txt 'https://prism.spoonity.com/api/flags/links' \
  -H 'Content-Type: application/json' \
  -d '{ "environment": "production", "flagsSegmentName": "gold-members-790", "reportingSegmentId": 790, "reportingSegmentName": "Gold members", "createSegment": true }'
```

Answers `201 { "link": link, "sync": <the sync result> }` and records a
`flag_segment.link` audit event.

#### POST /api/flags/links/{environment}/{name}/sync

Sync a linked audience now, with the operator's Identity token. Answers
`200 { "link": link, "sync": <the sync result> }`, records the outcome on the
link (failures too) and a `flag_segment.sync` audit event on success.

#### DELETE /api/flags/links/{environment}/{name}

Unlink. The Flags segment and its keys stay as they are. Answers `204` and
records a `flag_segment.unlink` audit event.

#### POST /api/flags/links/refresh

Re-sync every link of every vendor, never-synced first and then the stalest,
for at most `FLAGS_LINK_REFRESH_BUDGET_MS` (default 240 s); links left over
are counted as `deferred` and run first next time. Cloud Scheduler only:
`Authorization: Bearer <Google ID token>` checked exactly as the scheduler
path of `POST /api/flags/sync/segment`, with reporting read as the sync
account (`FLAGS_SYNC_IDENTITY_EMAIL`). Each link's outcome is recorded on it;
a link whose Flags segment no longer exists is removed. A `flag_segment.sync`
audit event is recorded per link whose membership may have changed.

```json
{ "total": 3, "synced": 2, "failed": 1, "deferred": 0, "results": [ { "vendorId": 123456, "environment": "production", "flagsSegmentName": "gold-members-790", "ok": true, "members": 1842 } ] }
```

**Errors** (all routes, in addition to the sync route's table above):

| Status | `code` | Meaning |
|---|---|---|
| `404` | `link_not_found` | sync now / unlink: the audience is not linked |
| `409` | `flags_segment_exists` | `createSegment: true` and a Flags segment with that name exists |
| `503` | `link_store_unavailable` | the link store could not be read or written |

---

### POST /api/flags/provision

Turn Flags on for the active vendor: create its Flags workspace and whichever
of the `production` and `staging` environments are missing. Idempotent: an
existing workspace or environment is not an error, and a second run creates
nothing. The workspace's `vendorId` always comes from the session, never from
the body.

**Auth:** Prism session cookie, `admin` at the active vendor.

**Body:**

| Field | Type | Required | Notes |
|---|---|---|---|
| `name` | string | no | workspace display name, 1 to 120 characters after trimming; defaults to `Vendor <id>` |

The body is limited to 4 KB.

**Request example:**

```bash
curl -sS -b cookies.txt 'https://prism.spoonity.com/api/flags/provision' \
  -H 'Content-Type: application/json' \
  -d '{ "name": "Example Merchant" }'
```

**Response example** (`200`):

```json
{
  "workspace": { "vendorId": "123456", "name": "Example Merchant" },
  "environments": [
    { "key": "production", "name": "Production", "production": true },
    { "key": "staging", "name": "Staging", "production": false }
  ],
  "created": { "workspace": true, "environments": ["production", "staging"] }
}
```

`workspace` and each environment are the Flags service's own records, passed
through. A `flags_workspace.provision` audit event is recorded only when
something was created.

**Errors:**

| Status | `code` | Meaning |
|---|---|---|
| `400` | `invalid_request` | body not JSON, or `name` is not a string of 1 to 120 characters |
| `401` | none; `{"error": "unauthorized", "detail": "Not signed in"}` | no session |
| `403` | `flags_role_required` | role at the active vendor is not `admin` |
| `403` | `flags_forbidden` | the Flags service refused a step |
| `502` | `upstream_unreachable`, `upstream_auth_failed`, `upstream_unconfigured`, or the Flags error code | Flags could not be reached or a step failed; `detail` names the step |

---

### POST /api/flags/import-app-config

Import the active vendor's app switches from its CMS app-config into Flags
(design note `docs/design/cms-to-flags.md`). Reads the vendor's CMS slug
(`GET /vendor/settings` on the CMS) and its published
`GET /app-config/:slug`, then for `production` (and `staging` when present)
creates the `qa-testers` segment and one `on`/`off` flag per switch with a
default rule of 100 % `on` when the CMS value is `true`, else 100 % `off`.
`qa_feedback` also gets tester rules from `qa_feedback.testers` (absent:
`@spoonity.com`). A CMS `404` is not an error: every switch is treated as
absent. Existing flags and definitions are left alone unless `overwrite`.

**Auth:** Prism session cookie, `editor` or `admin` at the active vendor. The
Flags workspace must already exist.

**Body:**

| Field | Type | Required | Notes |
|---|---|---|---|
| `dryRun` | boolean | no | default `true`: answer the plan, write nothing |
| `overwrite` | boolean | no | default `false`: also rewrite existing flags and definitions |

**Request example:**

```bash
curl -sS -b cookies.txt 'https://prism.spoonity.com/api/flags/import-app-config' \
  -H 'Content-Type: application/json' \
  -d '{ "dryRun": false }'
```

**Response example** (`200`, abridged):

```json
{
  "dryRun": false,
  "overwrite": false,
  "vendorId": "123456",
  "cms": { "slug": "vendor-123456", "status": "found" },
  "environments": ["production", "staging"],
  "segments": [{ "environment": "production", "name": "qa-testers", "outcome": "created" }],
  "flags": [
    {
      "key": "wallet",
      "source": "feature_flags.wallet",
      "cms": true,
      "treatment": "on",
      "outcome": "created",
      "definitions": { "production": { "outcome": "created", "defaultRule": "on 100%", "rules": 0 } }
    }
  ],
  "testers": { "domains": ["@spoonity.com"], "emails": [], "source": "default" },
  "warnings": [],
  "changed": 40
}
```

Outcomes are `created`, `overwritten` or `exists`, and `would-create` /
`would-overwrite` on a dry run. A `flags_app_config.import` audit event is
recorded only when an apply changed something.

**Errors:**

| Status | `code` | Meaning |
|---|---|---|
| `400` | `invalid_request` | body not JSON, or `dryRun` / `overwrite` not a boolean |
| `401` | `no_session` | no session |
| `403` | `flags_role_required` | role at the active vendor is not `editor` or `admin` |
| `403` | `flags_forbidden` | an upstream refused a step |
| `409` | `flags_not_provisioned` | no Flags workspace, or neither `production` nor `staging` |
| `502` | `upstream_unreachable`, `upstream_auth_failed`, `upstream_unconfigured`, or the upstream error code | the CMS or Flags could not be reached or a step failed; `detail` names the step |

---

## The product proxy (`/api/<product>/<path>`)

Prism owns almost no data of its own. Every product API stays where it is,
and the SPA reaches each one through the BFF at
`/api/<product>/<path>`, which forwards to `<upstream base>/<path>` with
the query string unchanged. The browser never holds a credential for any
upstream. What each upstream accepts is that service's own contract, on its
own page where one is published; this section documents only what the
proxy itself does.

**Auth:** Prism session cookie on every target. The credential the upstream
sees depends on the target (below), never on anything the browser sent.

**Request example:**

```bash
curl -sS -b cookies.txt 'https://prism.spoonity.com/api/links/links?limit=20'
```

**Response:** the upstream's status, headers and body, streamed through
unbuffered and uncompressed by the BFF, plus `X-Prism-Upstream: <target id>`.
Any `Set-Cookie` from the upstream is dropped. A `text/event-stream`
response (the Links click stream) is flushed frame by frame with
`Cache-Control: no-cache, no-transform`.

### Targets

| Target (`/api/<id>`) | Upstream | Credential mode | Notes |
|---|---|---|---|
| `links` | Spoonity Links, `https://links.spoonity.com/api/v1` | OIDC service identity | see [`links.md`](./links.md) |
| `cms` | Spoonity CMS, `https://cms.spoonity.com/api/v1` | OIDC service identity | see [`cms.md`](./cms.md) |
| `insights` | the Insights API (a Cloud Run service with no public custom domain), under its `/insights` prefix | OIDC service identity | see [`insights.md`](./insights.md) |
| `wallet` | Spoonity Wallet, `https://wallet-api.spoonity.com` | OIDC service identity | see [`wallet.md`](./wallet.md) |
| `auth-engine` | Spoonity Auth, `https://auth.spoonity.com` (the SPA calls its `/admin/v1/...` API) | OIDC service identity | see [`auth.md`](./auth.md) |
| `loyalty` | loyalty-api, `https://api.spoonity.com` | identity-jwt | Loyalty section |
| `reporting` | `https://reporting.spoonity.com` | identity-jwt | segments and campaign stats |
| `comms` | `https://comms.spoonity.com` | identity-jwt | campaign send and schedule |
| `marketing` | `https://marketing.spoonity.com` | identity-jwt | notifications |
| `identity` | Spoonity Identity, `https://identity.spoonity.com` | identity-jwt | closed: only `/billing/*`, `/identities/*` (except `/identities/<id>/credentials`) and `/scopes*` |
| `apex` | Apex, `https://api.getapex.app/api` | the operator's connected Apex account | closed: only `/analytics`, `/journeys`, `/campaigns`, `/customers`, `/tags`, `/properties`, `/email-templates`, `/domains`, `/configurations`, `/workspaces`; see [Apex connection](#apex-connection-authapex) |
| `ordering` | the active vendor's registered Spoonity Order site (one deployment per brand, no fixed base) | the operator's connected ordering credential | closed: `/admin/*` (except `/admin/login` and `/admin/cashier-login`), `/cashier/*` and a fixed list of public reads; see [Ordering site and connection](#ordering-site-and-connection-authordering) |
| `flags` | Spoonity Flags admin API, `https://flags.spoonity.com/admin/v1` | OIDC service identity | request guard, below |
| `promotions` | Spoonity Offers admin API (`offers.spoonity.com`), under its `/v1/admin` prefix | OIDC service identity | request guard, below; see [`offers.md`](./offers.md) |

Every base is overridable per deployment through an environment variable
(`LINKS_API_URL`, `CMS_API_URL` and so on); the hostnames above are the
defaults or the public names of the defaults.

### Credential modes

- **OIDC service identity.** The BFF mints a Google-signed ID token for the
  upstream's origin as Prism's own service account and sends it as
  `Authorization: Bearer <token>`. The token says "Prism"; the operator is
  identified by the headers below.
- **identity-jwt.** The operator's own vendor-scoped Spoonity Identity JWT,
  minted at sign-in and held on the server-side session record, picked for
  the active vendor. No ID token is minted.
- **Apex.** The operator's own Apex access token from
  `POST /auth/apex/connect`, plus `X-Auth-Provider: credentials` and
  `X-Auth-Workspace: <the workspace chosen for the active vendor>`. It is
  refreshed in place shortly before it expires.
- **Ordering.** A Firebase ID token for the active vendor's brand site, from
  `POST /auth/ordering/connect`, capped at one hour. The upstream base is the
  site registered for the active vendor. A `POST` under `/admin/*` or
  `/cashier/*` must carry a JSON body whose `vendor` is the active vendor;
  that body is read (up to 2 MB) and checked before it is forwarded.

### Headers the proxy sets

On every target, the inbound `Cookie` and `Authorization` headers, every
inbound `X-Spoonity-*` header, hop-by-hop headers and the
`Forwarded` / `X-Forwarded-*` / `Via` / trace family are dropped. Then:

| Header | Value |
|---|---|
| `Authorization` | `Bearer <credential>` for the target's mode |
| `X-Spoonity-Vendor` | the session's active vendor id |
| `X-Spoonity-User` | the session's email |
| `X-Spoonity-Role` | the session's role at the active vendor; **omitted**, never defaulted, when the session has none |

### Request guards

`flags` and `promotions` check each request before any credential is
minted:

- **flags.** Only `GET /me`, `GET /config`, `/workspaces/<active vendor>/...`
  and `/environments/<active vendor>:<env>/...` are proxied. Any other
  workspace or environment is `403 flags_vendor_scope`; the cross-workspace
  list (`/workspaces`) is refused too. Any other path is
  `404 path_not_proxied`. The operator's role must meet what the route
  needs (reads: `viewer`; most writes: `editor`; workspace and environment
  administration and environment keys: `admin`), or the answer is
  `403 flags_role_required`.
- **promotions.** Every method other than `GET`, `HEAD` and `OPTIONS` needs
  `editor` or `admin`, except `POST /promotions/simulate` (a dry run), or the
  answer is `403 promotions_role_required`.

### Errors

Every proxy error uses `{"error", "code", "message", "detail"}` (`detail`
optional). Checks run in this order: session, path, allowlist, guard,
credential, upstream.

| Status | `code` | Meaning |
|---|---|---|
| `401` | none (the session guard's `{"error", "detail"}`) or `no_session` | no, expired or revoked session |
| `400` | `path_traversal`, `bad_path` | a `..` segment or an unparseable path |
| `404` | `path_not_proxied` | a closed target (`identity`, `apex`, `ordering`, `flags`) does not proxy this path; no credential is read |
| `403` | `flags_vendor_scope`, `flags_role_required`, `promotions_role_required` | a request guard refused the call |
| `403` | `identity_reauth_required`, `identity_token_expired`, `identity_upstream_unauthorized` | identity-jwt targets: no token held for the active vendor, the token has expired, or the upstream answered `401` |
| `403` | `apex_connect_required`, `apex_workspace_required`, `apex_upstream_unauthorized` | `apex`: no account connected, no workspace chosen for this vendor, or Apex refused the token or its refresh |
| `403` | `ordering_site_unregistered`, `ordering_connect_required`, `ordering_reconnect_required`, `ordering_upstream_unauthorized` | `ordering`: no site registered, no credential, the credential is finished (it is then dropped), or a single refused call |
| `400` / `413` | `vendor_mismatch`, `bad_body` / `body_too_large` | `ordering` guarded `POST`: the body names another vendor, cannot be read, or is over 2 MB |
| `503` | `session_store_unavailable` | the session record a non-OIDC target needs could not be read |
| `502` | `upstream_error` | the upstream answered `5xx` |
| `502` | `upstream_unreachable`, `upstream_timeout` | the upstream could not be reached, or sent no response headers within 30 seconds (`UPSTREAM_TIMEOUT_MS`) |
| `502` | `upstream_auth`, `upstream_unconfigured` | the BFF could not mint an ID token, or has no base for the request |

For OIDC targets, an upstream `401` or `403` passes through unchanged, so
the shell can sign the operator out or show "no access". For every other
mode an upstream `401` becomes one of the `403` codes above, because the
SPA ends the whole console session on any `401` and one section's expired
credential must not sign the operator out of everything. Any other `4xx`
passes through unchanged. A `502` never means the BFF itself failed; a `500`
from the proxy would be a bug in the proxy.

Successful (`2xx`) mutating calls through the proxy are recorded in the
[audit log](#audit-log-apiaudit), with a templated path and never a body.
