# Spoonity Links API

Spoonity Links is Spoonity's multi-tenant short-link, deep-linking, QR code, and
click-analytics platform for QSR brands. Two audiences use it: **vendor
integrators** (marketing/engineering teams at a brand) who create and manage
short links, deep-link configs, webhooks, and branded QR codes through the
management API; and **end-user-facing surfaces** (browsers, installed mobile
apps, and social/messaging bots) that resolve a short code into a redirect,
an app deep link, or a link-in-bio / loyalty sign-up page. That second,
unauthenticated surface is the one most integrations actually touch first: a
QR code on a menu, a link in a receipt or SMS, or a bio-page link is a
`https://links.spoonity.com/<code>`-shaped URL, not an API call.

**Base URL (management API):** `https://links.spoonity.com/api/v1`
**Base URL (short-link surface):** `https://links.spoonity.com` (bare root, no
`/api/v1` prefix; this is `DEFAULT_SHORT_DOMAIN`, overridable per vendor
either with a connected custom domain, or with the shared host, via
`PUT /vendor/domain`)

**The shared short-link host.** A vendor is not limited to
`links.spoonity.com` or a custom domain of its own: `PUT /vendor/domain` with
`{"mode": "shared"}` (or the one-call `POST /vendor/enroll`) moves it onto
`https://x.spnty.co/<slug>/<code>` instead: one shared, multi-tenant host,
scoped per vendor by the path's leading `<slug>` segment, with no DNS record
or certificate to wait for. It is the recommended setup for a new vendor, but
it is not automatic: unless the service flag
`SHARED_HOST_DEFAULT_FOR_NEW_VENDORS` is on (it defaults to off), a newly
provisioned vendor starts in mode `none` (`links.spoonity.com/<code>`) until
something calls `PUT /vendor/domain` or `POST /vendor/enroll`. The shared host itself
serves only `/<slug>/<code>` paths, `/.well-known/*` and `/health`; every other
path on it (the API, `/docs`, `/bio`, a bare `/<code>`) answers `404`.
See [Short-link domain](#short-link-domain) below.

An earlier draft of these docs pointed integrators at `l.spnty.co` as the short
domain. That domain is **not available to this service**: its DNS points at
AWS SES's click-tracking for Spoonity's outbound email, and repointing it
would break that. `links.spoonity.com` is the real, current default.

## Authentication

The management API (everything under `/api/v1`, except the public endpoints
called out in each section below) accepts four credential types. A request
with an `Authorization: Bearer` header is tried as a dashboard JWT first and
then as a Google OIDC token; otherwise an `X-API-Key` header is tried as a
platform key first and then as a merchant key; otherwise a `?token=` query
parameter is tried as a dashboard JWT (for `EventSource`, which cannot set
headers).

1. **`Authorization: Bearer <JWT>`**: a dashboard session, issued by
   `POST /auth/login` (then `/auth/select-vendor` when the account has more
   than one authorized vendor) or `/auth/switch-vendor`. Sessions last 24 hours
   by default (`JWT_EXPIRES_IN`) and must belong to an allowed email domain on
   every request. Used by the Links dashboard UI; not something a
   server-to-server integration should use.
2. **`X-API-Key: <key>`**: a static merchant key, checked in two tiers:
   - **Scoped key** (`slk_<64 hex chars>`), created via
     `POST /vendor/api-keys`. Carries a `scopes` array drawn from a fixed
     vocabulary (below) and belongs to exactly one vendor. Its last-used time
     is recorded on each call.
   - **Legacy vendor-wide key** (also `slk_<64 hex chars>`), one per vendor,
     rotated via `POST /vendor/api-key/rotate`. Grants unrestricted access
     (`scopes: ['*']`) to every endpoint for that vendor, and there is no way
     to narrow it. Prefer a scoped key for anything new.
3. **Google-signed OIDC ID token** (`Authorization: Bearer <google-id-token>`):
   service-to-service auth for a server-side allowlist of trusted Google Cloud
   service accounts (`TRUSTED_SERVICE_ACCOUNTS`; for example, the Spoonity CMS
   or Prism's BFF calling Links). The token's audience must be the Links base
   URL and its email must be verified. Requires
   `X-Spoonity-Vendor: <spoonity_vendor_id>` on every request, plus an optional
   `X-Spoonity-Vendor-Name` used when that vendor is auto-provisioned on first
   sight. Full access, but never key management. This is **not something a
   normal integrator configures**; it exists for Spoonity's own services.
4. **Platform API key** (`X-API-Key: slp_<secret>` plus
   `X-Spoonity-Vendor: <spoonity_vendor_id>`): one shared secret per
   first-party **service** rather than per merchant (`loyalty-api`, the native
   release workflow), treated exactly like the OIDC path above: the vendor
   comes from `X-Spoonity-Vendor` (auto-provisioned on first sight), access is
   full, keys cannot be minted or revoked with it, and `platform:<label>`
   appears in the audit trail in place of a person. Configured via
   `PLATFORM_API_KEYS` (`label:secret` pairs, every secret starting `slp_`) on
   the Links service. A platform key sent without `X-Spoonity-Vendor` gets
   `401`. Also **not something a normal integrator configures**; Prism does not
   manage these keys.

**Maintenance switch.** When the service runs with `LOGIN_DISABLED=1`, every
human credential (dashboard JWTs, `slk_` keys, `?token=`) and the login
endpoints answer `503 {"error": "maintenance"}`. OIDC service tokens and
platform keys keep working, and so do the public redirect surfaces.

### Scopes (area-based)

Links scopes an API key by **area**: each router checks one area, and the
required scope is `<area>:read` for `GET`/`HEAD` and `<area>:write` for every
other method. A `:write` scope implies its matching `:read`. There is no
admin/editor/viewer role system on top: a key either has the scope or it does
not. Dashboard JWTs, OIDC service tokens, platform keys and the legacy key
carry no scope list (or `*`), so they pass every scope check.

| Area | Gates |
|---|---|
| `links` | `/links/*`, `/qr/*` |
| `analytics` | `/analytics/*` |
| `deeplinks` | `/deeplinks/*` (except the public `/deeplinks/match/{vendor_id}`) |
| `webhooks` | `/webhooks/*` |
| `bio` | `/api/v1/bio` (management; the public `/bio/{slug}` render needs no auth) |
| `vendor` | `/vendor/settings`, `/vendor/domain`, `/vendor/enroll`, `/vendor/api-key/*`, `/vendor/usage`, `/vendor/locations` |
| `*` | Full access. Carried by the legacy vendor-wide key, and also mintable on a named key through `POST /vendor/api-keys` |

`/auth/me` and `/auth/switch-vendor` need a credential but no scope.

Valid scope values for `POST /vendor/api-keys`: `links:read`, `links:write`,
`analytics:read`, `webhooks:read`, `webhooks:write`, `bio:read`, `bio:write`,
`deeplinks:read`, `deeplinks:write`, `vendor:read`, `vendor:write`, `*`.

Managing named keys (`/vendor/api-keys`) always requires a dashboard JWT
session: an `slk_` key, an OIDC token or a platform key gets
`403 forbidden` there. `POST /vendor/api-key/rotate` mints a new legacy,
full-access (`scopes: ['*']`) key, so it is gated the same way, via
`requireFullAccessCredential`: a dashboard session, or an `slk_` key that
already has `*`, may call it; any other `slk_` key — including one holding
`vendor:write` — and service identities (Google OIDC, platform keys) get
`403 forbidden`. `vendor:write` alone is no longer enough to rotate the
legacy key.

### Error bodies

Most errors are `{"error": "<code>", "message": "<text>"}` with a short code
such as `bad_request`, `unauthorized`, `forbidden`, `insufficient_scope`,
`not_found`, `validation` or `rate_limit`. Two exceptions matter to a client
that switches on `error`:

- Errors raised inside the link service (create, update, delete, duplicate,
  bulk create, deep-link config, webhook URL validation, bio link
  validation) come back with the literal string `"AppError"` in `error`, and
  only the HTTP status and `message` distinguish them. For example, a taken
  custom code is `409 {"error": "AppError", "message": "The code \"fall-menu\" is already in use."}`.
- An unhandled failure is `500 {"error": "internal_error", "message": "An unexpected error occurred"}`,
  while route-level failures use `{"error": "internal", ...}`.

A request with no vendor on its credential gets
`403 {"error": "forbidden", "message": "No vendor context. Authentication required."}`.

---

## Public Redirect & Resolution API

**This is the surface an integration touches most often:** the destination
of every QR code, printed short link, or shared URL Spoonity Links generates.
All of it is unauthenticated and served from the short-link hosts, not
`/api/v1`. The same handlers answer on three path shapes, and a code resolves
the same way on each:

| Shape | Host |
|---|---|
| `/{code}` | `https://links.spoonity.com`, or the vendor's own custom domain |
| `/{slug}/{code}` | the shared host `https://x.spnty.co` (also answered on `links.spoonity.com`). The slug must be the link's own vendor's current slug or one of its previous slugs, otherwise `404` |
| `/l/{code}` | a deprecated per-merchant host such as `brand.spnty.co` |

Every endpoint below also exists under the `/{slug}` and `/l` prefixes
(`/{slug}/{code}/preview`, `/l/{code}/qr`, and so on). Codes are globally
unique, so resolution never depends on which host was used, apart from the
slug check on the shared host.

### GET /auth/magic?t=

Land auth-engine magic links on the engine landing page. This is the fallback
when a magic link is clicked in an environment where the app isn't installed,
a browser is used, or mail scanners intercept the click. Native apps already
parse `/auth/magic?t=` on this host through Universal Links / App Links and
route it directly to the app (no HTTP request needed).

**Auth:** None.

**Query parameters:**

| Name | Type | Description |
|---|---|---|
| `t` | string | The authentication token (also accepted as `token=`) |

**Path variations:**

- `GET /auth/magic?t=<token>` — query parameter form
- `GET /auth/magic?token=<token>` — alternative query parameter
- `GET /auth/magic/<token>` — path parameter form

**Request example:**

```bash
curl -i "https://links.spoonity.com/auth/magic?t=aBcD1234_-XyZ5678"
```

**Response example:**

```
HTTP/1.1 302 Found
Location: https://auth.spoonity.com/v1/magic/aBcD1234_-XyZ5678
Cache-Control: no-store
Referrer-Policy: no-referrer
```

The token is redirected to the auth engine's landing page (`${AUTH_ENGINE_URL}/v1/magic/<token>`, default `https://auth.spoonity.com`). The engine page only peeks at the token and never shows the code.

Token pattern: `[A-Za-z0-9_-]{10,200}`. Invalid tokens return `404`.

**Headers:**

- `Cache-Control: no-store` — prevent caching
- `Referrer-Policy: no-referrer` — prevent leaking the token in referrer headers

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 404 | not_found | Token format invalid or too short/long |

### GET /{slug}/auth/magic?t=

Same as `/auth/magic?t=` but scoped to a brand's enrollment slug on the shared
host (`https://x.spnty.co`). The slug isn't validated against any vendor —
the landing page never consumes the token — so this doesn't clash with the
short-code routes.

**Auth:** None.

**Path parameters:**

| Name | Type | Description |
|---|---|---|
| `slug` | string | The vendor's enrollment slug (e.g. `pollo-campero`) |

**Query parameters:**

| Name | Type | Description |
|---|---|---|
| `t` | string | The authentication token (also accepted as `token=`) |

**Path variations:**

- `GET /{slug}/auth/magic?t=<token>` — query parameter form
- `GET /{slug}/auth/magic?token=<token>` — alternative query parameter
- `GET /{slug}/auth/magic/<token>` — path parameter form

**Request example:**

```bash
curl -i "https://x.spnty.co/pollo-campero/auth/magic?t=aBcD1234_-XyZ5678"
```

**Response example:**

```
HTTP/1.1 302 Found
Location: https://auth.spoonity.com/v1/magic/aBcD1234_-XyZ5678
Cache-Control: no-store
Referrer-Policy: no-referrer
```

Same token validation as `/auth/magic?t=` and same redirect to the engine landing page.

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 404 | not_found | Token format invalid or too short/long |

### GET /{slug}/mesa/{storeId}/{table}

The table QR: the code printed on a restaurant table, on the shared host only
(`https://x.spnty.co/<slug>/mesa/<storeId>/<table>`, spoonity-links #20). A phone
with the brand's app installed opens it in the app through the brand's
association files (which already claim `/<slug>/*`), so this route is reached
only when the app is not installed. It is matched only on exactly this shape,
so `/{slug}/{code}` short links are unaffected, and `mesa` is never read as a
short code.

**Auth:** None.

**Path parameters:**

| Name | Type | Description |
|---|---|---|
| `slug` | string | The vendor's current slug or one of its previous slugs (a renamed brand's old prefix still works) |
| `storeId` | string | Digits only, 1 to 12 |
| `table` | string | 1 to 16 characters of `A-Z`, `a-z`, `0-9` and `-` (for example `7` or `A-12`) |

**Behaviour:**

- If the vendor has `settings.ordering_url` set (see
  [`PUT /vendor/settings`](#put-apiv1vendorsettings)): `302` to that URL with
  `restaurant_uid=<spoonity vendor id>_<storeId>`, `mode=table` and
  `table=<table>` added to its query string, and `Cache-Control: no-store`.
  A stored value that is not an https URL is treated as unset.
- Otherwise: `200` with a branded "open the app" HTML page (Spanish copy),
  showing the brand's name and logo and App Store / Google Play buttons when the
  vendor's deep-link config has an https fallback URL for that platform.
- A malformed slug, store or table, a reserved slug, or an unknown vendor:
  `404` with a branded "invalid table code" HTML page.

**Request example:**

```bash
curl -i "https://x.spnty.co/pollo-campero/mesa/1234/7"
```

**Response example:**

```
HTTP/1.1 302 Found
Location: https://order.pollocampero.example/?restaurant_uid=4821_1234&mode=table&table=7
Cache-Control: no-store
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 404 | (HTML page) | Bad slug, store id or table, or no such vendor |
| 500 | internal | `{ "error": "internal", "message": "Table link failed" }` |

### GET /{code}

Resolve a short code. This is the hot path: a browser or `curl -L` hitting a
Spoonity Links QR code or printed URL lands here.

**Auth:** None.

**Path parameters:**

| Name | Type | Description |
|---|---|---|
| `code` | string | The short code (custom or auto-generated) |

**Query parameters:** `utm_source`, `utm_medium` and `utm_campaign` are
recorded on the click when present (they default to the link's own
`source`/`medium`/`campaign`).

**Request example:**

```bash
curl -i https://links.spoonity.com/fall-menu
```

**Response example:**

```
HTTP/1.1 302 Found
Location: https://acme-cafe.example.com/menu/seasonal
```

Behavior varies by link state and caller, all on the same path:

| Condition | Response |
|---|---|
| Active link | `302` to `destination_url`, or to a routed destination (geo, OS, A/B or time-of-day routing) |
| Active link with a deep link, opened on the matching mobile OS | `200` HTML interstitial that tries the app and falls back to the store or web URL |
| Expired, over `max_clicks`, before `starts_at`, or outside its `active_hours` | Browser gets `410` HTML dead-link page; JSON clients get `410` JSON error body |
| Password-protected | `200` HTML password form |
| Known bot or crawler user agent (for example Twitterbot) | `200` HTML with Open Graph tags, so link previews render instead of redirecting the crawler |
| Unknown or deactivated code | Browser gets `404` HTML dead-link page; JSON clients get `404` JSON error body |

The dead-link page (for browsers on expired or unknown codes) is a small self-contained HTML page with vendor name, logo, and brand colour when known (https logos and hex colours only; names escaped; no JavaScript). The vendor name falls back from a placeholder like "Vendor 2111957" to the title-cased enrollment slug (e.g. `pollo-campero` → "Pollo Campero"); if the slug is numeric or missing, the page names no brand.

**Content negotiation:**

- **Browsers** (requests with `Accept: text/html,…`) get an HTML page with HTTP status `404` or `410` and vendor branding (when available).
- **JSON clients** (requests with `Accept: application/json`, `*/*`, or no Accept header) get the JSON error body and HTTP status `404` or `410`, unchanged.

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 404 | not_found | Short code not found. Browsers receive an HTML dead-link page; JSON clients receive `{"error": "not_found", "message": "Short link not found"}` |
| 410 | expired | Link expired, not yet started, outside its active hours, or click cap reached. Browsers receive an HTML dead-link page; JSON clients receive `{"error": "expired", "message": "This link has expired"}` |
| 500 | internal | Internal resolution error |

### POST /{code}

Submit the password for a password-protected link (the form rendered by
`GET /{code}` posts here).

**Auth:** None.

**Path parameters:**

| Name | Type | Description |
|---|---|---|
| `code` | string | The short code |

**Request body:**

| Field | Type | Required | Description |
|---|---|---|---|
| `password` | string | Yes | Plaintext password, compared against the stored bcrypt hash |

**Request example:**

```bash
curl -i -X POST https://links.spoonity.com/vip-menu \
  -d "password=letmein"
```

**Response example:**

```
HTTP/1.1 302 Found
Location: https://acme-cafe.example.com/vip-menu
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | Password missing from the request body |
| 401 | (HTML) | Incorrect password. The HTML form is re-rendered with an error |
| 404 | not_found | Link not found, or not password-protected |

### GET /{code}/preview

Returns link metadata as JSON without counting as a click. Used to build
rich previews without triggering analytics or the redirect itself.

**Auth:** None.

**Path parameters:**

| Name | Type | Description |
|---|---|---|
| `code` | string | The short code |

**Request example:**

```bash
curl https://links.spoonity.com/fall-menu/preview
```

**Response example:**

```json
{
  "code": "fall-menu",
  "title": "Fall Menu 2026",
  "description": "Seasonal drink lineup",
  "destination_url": "https://acme-cafe.example.com/menu/seasonal",
  "has_deep_link": true,
  "has_password": false,
  "expires_at": "2026-12-31T23:59:59Z",
  "created_at": "2026-08-01T12:00:00Z"
}
```

A password-protected link's `destination_url` is always returned as `null`
here, so the preview cannot defeat the password gate.

**Errors:**

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

### GET /{code}/qr

Generate a QR code image pointing at the short link, using the link's saved
colors unless overridden.

**Auth:** None.

**Path parameters:**

| Name | Type | Description |
|---|---|---|
| `code` | string | The short code |

**Query parameters:**

| Name | Type | Description |
|---|---|---|
| `format` | string | `png` (default) or `svg` |
| `size` | integer | Pixels, clamped to 64 to 2048. Default `400`. |
| `fg` | string | Foreground hex color override |
| `bg` | string | Background hex color override |

**Request example:**

```bash
curl https://links.spoonity.com/fall-menu/qr?size=600&format=png -o qr.png
```

**Response example:** Binary image (`image/png` or `image/svg+xml`), cached
`public, max-age=86400`.

**Errors:**

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

### POST /{code}/opened

Deferred deep-link attribution beacon. Sent by the interstitial page once the
mobile app actually takes focus, so a click can be credited to the app open
that followed it.

**Auth:** None.

**Path parameters:**

| Name | Type | Description |
|---|---|---|
| `code` | string | The short code |

**Request body:** None required.

**Request example:**

```bash
curl -i -X POST https://links.spoonity.com/fall-menu/opened
```

**Response example:** `204 No Content`, always, even if the code doesn't
match anything (this is a best-effort beacon, never an error to the caller).

**Errors:** None returned to the caller.

### GET /api/v1/resolve/{code}

JSON resolution for a vendor's own installed app. Exists because Universal
Links / App Links intercept the short-code *path* before the HTTP redirect
above ever runs when the app is already installed; the app calls this
instead to learn where the code points, then navigates in-app. Counted as a
click identically to a browser hit.

**Auth:** None.

**Path parameters:**

| Name | Type | Description |
|---|---|---|
| `code` | string | The short code |

**Request example:**

```bash
curl https://links.spoonity.com/api/v1/resolve/fall-menu
```

**Response example:**

```json
{
  "found": true,
  "title": "Fall Menu 2026",
  "destination_url": "https://acme-cafe.example.com/menu/seasonal",
  "ios_url": "acmecafe://menu?category=seasonal",
  "android_url": "acmecafe://menu?category=seasonal",
  "ios_fallback": "https://apps.apple.com/app/acme-cafe/id123456",
  "android_fallback": "https://play.google.com/store/apps/details?id=com.acmecafe.app"
}
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 404 | not_found | `{ "found": false, "error": "not_found" }` |
| 409 | password_required | `{ "found": false, "error": "password_required" }`. The app cannot render a password form; send the user to the web page instead |
| 410 | expired | `{ "found": false, "error": "expired" }` (also returned before `starts_at`, outside `active_hours`, or over `max_clicks`) |
| 500 | internal | `{ "found": false, "error": "internal" }` |

### GET /api/v1/deeplinks/match/{vendor_id}

Deferred deep linking: a freshly installed app asks "was there a click from
this device before install?" and gets back the link that was tapped, so it
can open the screen the customer originally wanted. Public on purpose: a
first-launch app holds no credentials yet.

**Auth:** None.

**Path parameters:**

| Name | Type | Description |
|---|---|---|
| `vendor_id` | string | The Spoonity vendor id (numeric). Links vendor ids now equal Spoonity vendor ids, and a pre-migration Links id is also accepted |

**Query parameters:**

| Name | Type | Description |
|---|---|---|
| `os` | string | Reported OS (e.g. `ios`, `android`) |
| `os_version` | string | Reported OS version |

**Request example:**

```bash
curl "https://links.spoonity.com/api/v1/deeplinks/match/12345?os=android&os_version=14"
```

**Response example:**

```json
{
  "matched": true,
  "code": "fall-menu",
  "path": "/menu?category=seasonal",
  "link": {
    "id": 42,
    "code": "fall-menu",
    "destination_url": "https://acme-cafe.example.com/menu/seasonal",
    "ios_url": "acmecafe://menu?category=seasonal",
    "android_url": "acmecafe://menu?category=seasonal",
    "tags": ["seasonal"],
    "custom_attributes": {}
  }
}
```

Matching is probabilistic (hashed IP + OS + OS version, mobile/tablet only,
within the last hour, each click claimable once). On Android prefer the Play
Install Referrer, which is exact, when available. A miss returns
`{ "matched": false }` with a `200`, not an error.

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | `vendor_id` is not numeric |
| 500 | internal | The database is unreachable and nothing is cached for this device (`{"error": "internal", "message": "Matching failed"}`) |

During a database outage the endpoint replays the last answer it gave the
same device (same `vendor_id`, hashed IP, `os` and `os_version`) instead of
failing, so a match can be handed out twice. Treat a repeated match as
idempotent.

---

## Links

Short link CRUD and smart-routing configuration. All routes here require
`links:read`/`links:write` and a vendor context. Every link object the API
returns has `password_hash` removed and a `has_password` boolean added.

### GET /api/v1/links

List the vendor's links, paginated and filterable.

**Auth:** API key with `links:read` scope, or dashboard JWT.

**Query parameters:**

| Name | Type | Description |
|---|---|---|
| `page` | integer | Default `1` |
| `limit` | integer | Default `20`, max `100` |
| `search` | string | Substring match on title, code, or destination URL |
| `campaign` | string | Exact match on the link's `campaign` |
| `tags` | string | Comma-separated tag list; a link matches if it has any of them |
| `is_active` | boolean | `true` or `false` |
| `sort` | string | `created_at` (default), `title`, `total_clicks` or `code`; anything else falls back to `created_at` |
| `order` | string | `asc` or `desc` (default `desc`) |

**Request example:**

```bash
curl "https://links.spoonity.com/api/v1/links?page=1&limit=20" \
  -H "X-API-Key: slk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{
  "data": [
    {
      "id": 42,
      "vendor_id": 12345,
      "code": "fall-menu",
      "destination_url": "https://acme-cafe.example.com/menu/seasonal",
      "title": "Fall Menu 2026",
      "tags": ["seasonal", "menu"],
      "campaign": "fall-launch",
      "is_active": true,
      "total_clicks": 512,
      "has_password": false,
      "created_at": "2026-08-01T12:00:00.000Z",
      "updated_at": "2026-08-01T12:00:00.000Z"
    }
  ],
  "pagination": { "page": 1, "limit": 20, "total": 1, "total_pages": 1 }
}
```

Each item is the full link row (deep-link URLs, QR colors, routing configs,
schedule fields and so on), plus `total_clicks`.

**Errors:**

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

### POST /api/v1/links

Create a new short link.

**Auth:** API key with `links:write` scope, or dashboard JWT.

**Request body:**

| Field | Type | Required | Description |
|---|---|---|---|
| `destination_url` | string | Yes | Target URL. Must be `http` or `https` and pass the URL safety scan |
| `code` | string | | Custom short code: 3 to 20 letters, digits and single hyphens, no leading or trailing hyphen, not a reserved word (`api`, `admin`, `dashboard`, `docs`, `health`, `l`, `login`, and a few others). Globally unique across **all** vendors. Auto-generated (7 characters) if omitted |
| `title` | string | | |
| `description` | string | | |
| `tags` | string[] | | |
| `campaign` / `source` / `medium` | string | | UTM attribution, used as the click's default `utm_*` values |
| `deep_link` | object | | `{ ios_url, android_url, ios_fallback, android_fallback }` |
| `qr` | object | | `{ foreground, background, logo_url }`; colors must be `#RRGGBB` |
| `password` | string | | Password-protects the link (stored as a bcrypt hash) |
| `expires_at` | ISO 8601 | | After this, the link answers `410` |
| `starts_at` | ISO 8601 | | Before this, the link answers `410` |
| `active_hours` | array | | `[{ "day": 0-6, "start": "HH:MM", "end": "HH:MM" }]`, evaluated in the vendor's `settings.timezone` (UTC if unset); outside every window the link answers `410` |
| `max_clicks` | number | | After this many clicks the link answers `410` and a `link.cap_reached` webhook fires once |
| `custom_attributes` | object (string values) | | Returned to the app by the deferred deep-link match |

**Request example:**

```bash
curl -X POST https://links.spoonity.com/api/v1/links \
  -H "X-API-Key: slk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{
    "destination_url": "https://acme-cafe.example.com/menu/seasonal",
    "code": "fall-menu",
    "title": "Fall Menu 2026",
    "tags": ["seasonal", "menu"],
    "campaign": "fall-launch"
  }'
```

**Response example (`201`):**

```json
{
  "id": 42,
  "vendor_id": 12345,
  "code": "fall-menu",
  "destination_url": "https://acme-cafe.example.com/menu/seasonal",
  "title": "Fall Menu 2026",
  "tags": ["seasonal", "menu"],
  "campaign": "fall-launch",
  "is_active": true,
  "has_password": false,
  "short_url": "https://x.spnty.co/acme-cafe/fall-menu",
  "created_at": "2026-08-01T12:00:00.000Z",
  "updated_at": "2026-08-01T12:00:00.000Z"
}
```

`short_url` is the full public URL for the vendor's current domain mode
(`https://x.spnty.co/<slug>/<code>` on the shared host, the custom domain when
one is connected, otherwise `https://links.spoonity.com/<code>`). It is only
present on this single create; bulk create, `GET`, `PUT` and duplicate
responses omit it.

**Errors** (all with `"error": "AppError"`, see [Error bodies](#error-bodies)):

| Status | Meaning |
|---|---|
| 400 | Invalid destination URL, URL blocked by the safety scan, invalid or reserved custom code, or invalid QR color |
| 409 | Custom code already in use (codes are unique across every vendor, not just this one) |

### GET /api/v1/links/{id}

Fetch one short link's full record.

**Auth:** API key with `links:read` scope, or dashboard JWT.

**Path parameters:**

| Name | Type | Description |
|---|---|---|
| `id` | integer | Link id |

**Request example:**

```bash
curl https://links.spoonity.com/api/v1/links/42 \
  -H "X-API-Key: slk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:** Same shape as a list item, including `total_clicks`.

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | Invalid link ID |
| 404 | not_found | Link not found |

### PUT /api/v1/links/{id}

Update a short link's destination or metadata.

**Auth:** API key with `links:write` scope, or dashboard JWT.

**Path parameters:**

| Name | Type | Description |
|---|---|---|
| `id` | integer | Link id |

**Request body:** Any subset of the `POST` fields except `code` (immutable
after creation), plus `is_active`. Omitted fields are left unchanged.
`password: null` removes the password; `custom_attributes: null` and
`active_hours: null` clear those fields. An updated `destination_url` must be
a valid `http`/`https` URL but is not re-run through the safety scan.

**Request example:**

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

**Response example:** The updated link object (no `short_url`, no
`total_clicks`).

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | Invalid link ID |
| 400 | AppError | Invalid destination URL |
| 404 | AppError | Link not found |

### DELETE /api/v1/links/{id}

Soft-deletes (deactivates) the link. The short code stays reserved and
starts answering `404` on the redirect surface; the link still appears in
`GET /links` with `is_active: false`.

**Auth:** API key with `links:write` scope, or dashboard JWT.

**Path parameters:**

| Name | Type | Description |
|---|---|---|
| `id` | integer | Link id |

**Request example:**

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

**Response example:** `204 No Content`

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | Invalid link ID |
| 404 | AppError | Link not found |

### POST /api/v1/links/bulk

Create up to 100 links in one call.

**Auth:** API key with `links:write` scope, or dashboard JWT.

**Request body:**

| Field | Type | Required | Description |
|---|---|---|---|
| `links` | array of link objects | Yes | 1 to 100 items, each the same shape as the `POST /links` body |

Items are created one after another. The first item that fails stops the
call with that item's error, and the items before it stay created, so
re-sending the same array after a failure hits `409` on the custom codes that
already went through.

**Request example:**

```bash
curl -X POST https://links.spoonity.com/api/v1/links/bulk \
  -H "X-API-Key: slk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{"links": [{"destination_url": "https://acme-cafe.example.com/a"}, {"destination_url": "https://acme-cafe.example.com/b"}]}'
```

**Response example (`201`):**

```json
{ "created": 2, "links": [ { "id": 43, "code": "x7f2aQd", "...": "..." }, { "id": 44, "code": "q9d1zRt", "...": "..." } ] }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | `links` array missing or empty |
| 400 | AppError | More than 100 links, or an item failed validation |
| 409 | AppError | An item's custom code is already in use |

### GET /api/v1/links/{id}/routing

Read a link's smart-routing configuration.

**Auth:** API key with `links:read` scope, or dashboard JWT.

**Path parameters:**

| Name | Type | Description |
|---|---|---|
| `id` | integer | Link id |

**Request example:**

```bash
curl https://links.spoonity.com/api/v1/links/42/routing \
  -H "X-API-Key: slk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{
  "link_id": 42,
  "geo_routing": null,
  "os_routing": null,
  "ab_test": {
    "enabled": true,
    "variants": [
      { "name": "control", "destination_url": "https://acme-cafe.example.com/a", "weight": 50 },
      { "name": "variant", "destination_url": "https://acme-cafe.example.com/b", "weight": 50 }
    ]
  },
  "time_routing": null
}
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | Invalid link ID |
| 404 | not_found | Link not found |

### PUT /api/v1/links/{id}/routing

Configure geo, OS, A/B and time-of-day smart routing. Pass `null` for a
config to clear it; omit it to leave it unchanged. At least one of the four
must be present.

**Auth:** API key with `links:write` scope, or dashboard JWT.

**Path parameters:**

| Name | Type | Description |
|---|---|---|
| `id` | integer | Link id |

**Request body:**

| Field | Type | Required | Description |
|---|---|---|---|
| `geo_routing` | object or null | | `{ enabled, rules: [{ country, region?, destination_url, ios_url?, android_url? }], fallback_behavior: "original" or "block" }` |
| `os_routing` | object or null | | `{ enabled, rules: [{ os, destination_url, ios_url?, android_url? }] }`. `os` is one of `ios`, `android`, `windows`, `macos`, `linux`, `other`, at most one rule per OS |
| `ab_test` | object or null | | `{ enabled, variants: [{ name, destination_url, weight, ios_url?, android_url? }] }`. At least 2 variants, each weight 1 to 100, and weights must sum to 100 when `enabled` |
| `time_routing` | object or null | | `{ enabled, timezone?, rules: [{ label, start_hour, end_hour, days?, destination_url }] }`. `timezone` is an IANA name (the vendor's zone when omitted), `start_hour` 0 to 23, `end_hour` 0 to 24, `days` integers 0 (Sunday) to 6 |

Every `destination_url` must pass the URL safety scan.

**Request example:**

```bash
curl -X PUT https://links.spoonity.com/api/v1/links/42/routing \
  -H "X-API-Key: slk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{"ab_test": {"enabled": true, "variants": [{"name": "control", "destination_url": "https://acme-cafe.example.com/a", "weight": 50}, {"name": "variant", "destination_url": "https://acme-cafe.example.com/b", "weight": 50}]}}'
```

**Response example:** The updated link object.

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | Invalid link ID, or none of the four configs present |
| 400 | validation | One or more rules failed validation. The response includes an `errors` array, one message per problem |
| 404 | not_found | Link not found |

### POST /api/v1/links/{id}/duplicate

Clone a link with a new auto-generated code. The copy keeps the destination,
title (with ` (copy)` appended), description, tags, UTM fields, deep-link
URLs, QR colors, `expires_at` and `max_clicks`. It does not copy the
password, `starts_at`, `active_hours`, `custom_attributes` or any routing
config.

**Auth:** API key with `links:write` scope, or dashboard JWT.

**Path parameters:**

| Name | Type | Description |
|---|---|---|
| `id` | integer | Link id |

**Request example:**

```bash
curl -X POST https://links.spoonity.com/api/v1/links/42/duplicate \
  -H "X-API-Key: slk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:** The new link object, `201`.

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | Invalid link ID |
| 404 | AppError | Link not found |

---

## Analytics

Requires `analytics:read`. Every endpoint that takes `from`/`to` defaults to
the last 30 days. A date-only `from` starts at 00:00 UTC and a date-only `to`
runs to 23:59:59 UTC; an unparseable value falls back to the default, and a
reversed range is swapped.

### GET /api/v1/analytics/stream

Live click feed over Server-Sent Events, one `click` event per redirect
served for this vendor, plus a `: ping` comment every 30 seconds.

**Auth:** Any credential with `analytics:read`. Browsers using `EventSource`
cannot set headers, so they pass a dashboard JWT as `?token=`; a server can
send `X-API-Key` or `Authorization` as usual.

**Query parameters:**

| Name | Type | Description |
|---|---|---|
| `token` | string | Dashboard JWT (only needed when no auth header is sent) |

**Request example:**

```bash
curl -N https://links.spoonity.com/api/v1/analytics/stream \
  -H "X-API-Key: slk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```
retry: 5000

event: click
data: {"link_id":42,"code":"fall-menu","device_type":"mobile","country":"US","referrer_domain":"instagram.com","resolved_to":"web","clicked_at":"2026-08-15T10:03:00.000Z"}
```

**Errors:** The usual `401`/`403` JSON errors before the stream opens.

### GET /api/v1/analytics/overview

Dashboard summary for the vendor.

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

**Request example:**

```bash
curl https://links.spoonity.com/api/v1/analytics/overview \
  -H "X-API-Key: slk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{
  "total_links": 128,
  "active_links": 110,
  "total_clicks": 48213,
  "unique_visitors": 30110,
  "clicks_today": 342,
  "clicks_this_week": 2110,
  "clicks_this_month": 8760,
  "top_links": [ { "id": 42, "code": "fall-menu", "total_clicks": 512, "...": "..." } ],
  "device_breakdown": { "mobile": 620, "desktop": 180, "tablet": 20 },
  "recent_clicks": [ { "link_id": 42, "country": "US", "device_type": "mobile", "clicked_at": "2026-08-15T10:03:00.000Z", "...": "..." } ]
}
```

`top_links` is the ten active links with the most clicks (full link rows);
`device_breakdown` covers the last 30 days; `recent_clicks` is the latest 20
raw click rows. "This week" and "this month" are the last 7 and 30 days.

**Errors:** None specific.

### GET /api/v1/analytics/links/{id}

Per-link analytics for a date range.

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

**Path parameters:**

| Name | Type | Description |
|---|---|---|
| `id` | integer | Link id |

**Query parameters:**

| Name | Type | Description |
|---|---|---|
| `from` | date (ISO 8601) | Range start |
| `to` | date (ISO 8601) | Range end |
| `granularity` | string | Bucket size for `timeseries`: `hour`, `day` (default), `week`, `month` |

**Request example:**

```bash
curl "https://links.spoonity.com/api/v1/analytics/links/42?from=2026-08-01&to=2026-08-31" \
  -H "X-API-Key: slk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{
  "summary": { "total_clicks": 512, "unique_visitors": 401, "app_opens": 120, "web_fallbacks": 392 },
  "timeseries": [ { "timestamp": "2026-08-01T00:00:00.000Z", "clicks": 12, "unique_visitors": 10 } ],
  "devices": [ { "type": "mobile", "clicks": 400 } ],
  "geo": [ { "country": "US", "clicks": 450, "percentage": 87.89 } ],
  "referrers": [ { "domain": "instagram.com", "clicks": 210 } ]
}
```

`app_opens` counts clicks confirmed by the interstitial's attribution beacon;
every other click is counted as a web or store fallback. A link id that does
not belong to the vendor returns zeros, not `404`.

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | Invalid link ID |

### GET /api/v1/analytics/links/{id}/clicks

Raw, paginated click events for one link, newest first.

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

**Path parameters:**

| Name | Type | Description |
|---|---|---|
| `id` | integer | Link id |

**Query parameters:**

| Name | Type | Description |
|---|---|---|
| `page` | integer | Default `1` |
| `limit` | integer | Default `50`, max `100` |

**Request example:**

```bash
curl "https://links.spoonity.com/api/v1/analytics/links/42/clicks?page=1&limit=50" \
  -H "X-API-Key: slk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{
  "data": [ { "id": 9001, "link_id": 42, "clicked_at": "2026-08-15T10:03:00.000Z", "country": "US", "device_type": "mobile", "os": "iOS", "resolved_to": "app", "app_opened": 1, "...": "..." } ],
  "pagination": { "page": 1, "limit": 50, "total": 512, "total_pages": 11 }
}
```

Each row is the stored click event (visitor id, hashed IP, user agent, OS,
browser, geo, referrer, UTM fields, `resolved_to`, `app_opened`).

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | Invalid link ID |

### GET /api/v1/analytics/campaigns/{campaign}

Aggregate click analytics for one campaign.

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

**Path parameters:**

| Name | Type | Description |
|---|---|---|
| `campaign` | string | Campaign name |

**Query parameters:** `from`, `to` (ISO 8601).

**Request example:**

```bash
curl https://links.spoonity.com/api/v1/analytics/campaigns/fall-launch \
  -H "X-API-Key: slk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{
  "summary": { "link_count": 6, "total_clicks": 900, "unique_visitors": 710 },
  "links": [ { "id": 42, "code": "fall-menu", "title": "Fall Menu 2026", "destination_url": "https://acme-cafe.example.com/menu/seasonal", "clicks": 512 } ],
  "timeseries": [ { "timestamp": "2026-08-01T00:00:00.000Z", "clicks": 40, "unique_visitors": 33 } ]
}
```

`summary` counts clicks whose recorded `utm_campaign` equals the name (a
`?utm_campaign=` on the click overrides the link's own campaign); `links` lists
the links whose `campaign` field equals it. `timeseries` is the vendor's
daily series for the range, not filtered to the campaign.

**Errors:** None specific.

### GET /api/v1/analytics/timeseries

Click counts bucketed over time, for charting.

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

**Query parameters:**

| Name | Type | Description |
|---|---|---|
| `from` / `to` | date (ISO 8601) | Range |
| `granularity` | string | `hour`, `day` (default), `week`, `month` |
| `link_id` | integer | Filter to one link |

**Request example:**

```bash
curl "https://links.spoonity.com/api/v1/analytics/timeseries?from=2026-08-01&to=2026-08-31&granularity=day" \
  -H "X-API-Key: slk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
[ { "timestamp": "2026-08-01T00:00:00.000Z", "clicks": 34, "unique_visitors": 30 }, { "timestamp": "2026-08-02T00:00:00.000Z", "clicks": 41, "unique_visitors": 37 } ]
```

Buckets with no clicks are omitted, not returned as zero. The `timestamp`
format follows the granularity: `day` and `week` buckets come back as ISO
8601 midnights (`2026-08-01T00:00:00.000Z`, a week keyed on its Monday),
`hour` as `"2026-08-01 10:00:00"` and `month` as `"2026-08-01"`.

**Errors:** None specific.

### GET /api/v1/analytics/geo

Click breakdown by country, top 50.

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

**Query parameters:** `from`, `to` (ISO 8601).

**Request example:**

```bash
curl https://links.spoonity.com/api/v1/analytics/geo \
  -H "X-API-Key: slk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
[ { "country": "US", "clicks": 700, "percentage": 85.37 }, { "country": "CA", "clicks": 120, "percentage": 14.63 } ]
```

**Errors:** None specific.

### GET /api/v1/analytics/devices

Click breakdown by device type, OS and browser combination, top 50.

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

**Query parameters:** `from`, `to` (ISO 8601).

**Request example:**

```bash
curl https://links.spoonity.com/api/v1/analytics/devices \
  -H "X-API-Key: slk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
[ { "device_type": "mobile", "os": "iOS", "browser": "Mobile Safari", "clicks": 400 }, { "device_type": "desktop", "os": "Windows", "browser": "Chrome", "clicks": 150 } ]
```

**Errors:** None specific.

### GET /api/v1/analytics/referrers

Click breakdown by referring domain, top 50.

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

**Query parameters:** `from`, `to` (ISO 8601).

**Request example:**

```bash
curl https://links.spoonity.com/api/v1/analytics/referrers \
  -H "X-API-Key: slk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
[ { "domain": "instagram.com", "clicks": 310 }, { "domain": "t.co", "clicks": 88 } ]
```

**Errors:** None specific.

### GET /api/v1/analytics/funnel

Wallet-pass conversion funnel: sent, clicked, confirmed, downloaded.

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

**Query parameters:** `from`, `to` (ISO 8601).

**Request example:**

```bash
curl https://links.spoonity.com/api/v1/analytics/funnel \
  -H "X-API-Key: slk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "sent": 500, "clicked": 340, "confirmed": 210, "downloaded": 150 }
```

`sent` counts wallet enrollments started in the range; `clicked` counts
distinct visitors who clicked a link pointing at a `/loyalty/<slug>/join`
page; `confirmed` counts enrollments that reached `registered` or
`downloaded`; `downloaded` counts those that reached `downloaded`. A Google
Wallet enrollment can be confirmed but never downloaded, because Google
Wallet has no "user saved the pass" signal to relay. That is expected, not a
broken funnel.

**Errors:** None specific.

### GET /api/v1/analytics/export

Export raw click rows as CSV or JSON, newest first, capped at 10,000 rows.

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

**Query parameters:**

| Name | Type | Description |
|---|---|---|
| `format` | string | `json` (default) or `csv` |
| `from` / `to` | date (ISO 8601) | Range |
| `link_id` | integer | Filter to one link |

**Request example:**

```bash
curl "https://links.spoonity.com/api/v1/analytics/export?format=csv&from=2026-08-01&to=2026-08-31" \
  -H "X-API-Key: slk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -o clicks.csv
```

**Response example (JSON mode):**

```json
{ "rows": 2, "data": [ { "link_id": 42, "visitor_id": "a1b2c3", "device_type": "mobile", "os": "iOS", "browser": "Mobile Safari", "country": "US", "region": "CA", "city": "San Francisco", "referrer_domain": "instagram.com", "utm_source": null, "utm_medium": null, "utm_campaign": "fall-launch", "resolved_to": "web", "app_opened": 0, "clicked_at": "2026-08-15T10:03:00.000Z" } ] }
```

CSV mode returns the same 15 columns as `text/csv` with
`Content-Disposition: attachment; filename="analytics-<date>.csv"`.

**Errors:** None specific.

---

## Deep Links

Per-platform app configuration: what goes into the association files
(`/.well-known/apple-app-site-association`, `/.well-known/assetlinks.json`)
and how a URL maps to an app screen. Requires `deeplinks:read` /
`deeplinks:write` (except the public matching endpoint documented above).
`platform` is always one of `ios`, `android`, `web`.

### GET /api/v1/deeplinks/config

List this vendor's per-platform deep-link configuration.

**Auth:** API key with `deeplinks:read` scope, or dashboard JWT.

**Request example:**

```bash
curl https://links.spoonity.com/api/v1/deeplinks/config \
  -H "X-API-Key: slk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
[
  { "id": 3, "vendor_id": 12345, "platform": "android", "app_id": null, "app_scheme": "acmecafe", "team_id": null, "package_name": "com.acmecafe.app", "sha256_fingerprints": ["AA:BB:CC:DD"], "fallback_url": "https://play.google.com/store/apps/details?id=com.acmecafe.app", "route_patterns": [], "created_at": "2026-08-01T12:00:00.000Z", "updated_at": "2026-08-01T12:00:00.000Z" },
  { "id": 2, "vendor_id": 12345, "platform": "ios", "app_id": "com.acmecafe.app", "app_scheme": "acmecafe", "team_id": "ABCDE12345", "package_name": null, "sha256_fingerprints": [], "fallback_url": "https://apps.apple.com/app/id123456", "route_patterns": [], "created_at": "2026-08-01T12:00:00.000Z", "updated_at": "2026-08-01T12:00:00.000Z" }
]
```

**Errors:** None specific.

### PUT /api/v1/deeplinks/config/{platform}

Create or update one platform's config. Fields you omit (or send empty) keep
their stored value, so one field can be changed without resending the rest.

**Auth:** API key with `deeplinks:write` scope, or dashboard JWT.

**Path parameters:**

| Name | Type | Description |
|---|---|---|
| `platform` | string | `ios`, `android` or `web` |

**Request body:**

| Field | Type | Description |
|---|---|---|
| `app_id` | string | iOS bundle id. With `team_id`, forms the AASA `appID` |
| `team_id` | string | Apple team id |
| `app_scheme` | string | Custom URL scheme used when building app URLs |
| `package_name` | string | Android package name |
| `sha256_fingerprints` | string[] | Android signing-certificate fingerprints for `assetlinks.json` |
| `fallback_url` | string | Store or web URL when the app is not installed |
| `route_patterns` | array | Replaces the whole list; see `POST /deeplinks/routes` for the item shape |

**Request example:**

```bash
curl -X PUT https://links.spoonity.com/api/v1/deeplinks/config/ios \
  -H "X-API-Key: slk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{"app_id": "com.acmecafe.app", "team_id": "ABCDE12345", "app_scheme": "acmecafe"}'
```

**Response example:** The saved config object, same shape as a
`GET /deeplinks/config` item.

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | AppError | `platform` is not `ios`, `android` or `web` |

### DELETE /api/v1/deeplinks/config/{platform}

Remove this vendor's deep-link configuration for one platform. The platform
drops out of the association files.

**Auth:** API key with `deeplinks:write` scope, or dashboard JWT.

**Path parameters:**

| Name | Type | Description |
|---|---|---|
| `platform` | string | Platform to remove |

**Request example:**

```bash
curl -X DELETE https://links.spoonity.com/api/v1/deeplinks/config/ios \
  -H "X-API-Key: slk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:** `204 No Content`, also when nothing was configured.

**Errors:** None specific.

### GET /api/v1/deeplinks/routes

List route patterns across all platforms, each tagged with the platform
config it is stored on.

**Auth:** API key with `deeplinks:read` scope, or dashboard JWT.

**Request example:**

```bash
curl https://links.spoonity.com/api/v1/deeplinks/routes \
  -H "X-API-Key: slk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
[ { "pattern": "/menu/:category", "screen": "menu", "param_mapping": { "category": "category" }, "platforms": ["ios"], "platform": "ios" } ]
```

**Errors:** None specific.

### POST /api/v1/deeplinks/routes

Append a route pattern to an existing platform config.

**Auth:** API key with `deeplinks:write` scope, or dashboard JWT.

**Request body:**

| Field | Type | Required | Description |
|---|---|---|---|
| `platform` | string | Yes | The config to store the pattern on |
| `pattern` | string | Yes | URL path pattern; `:name` segments capture parameters |
| `screen` | string | Yes | App screen the pattern opens |
| `param_mapping` | object | Yes | Captured parameter name to app parameter name |
| `platforms` | string[] | Yes | Platforms the pattern applies to (`ios`, `android`, `web`). Also controls which paths the AASA claims |

Everything except `platform` is stored as the pattern record, unvalidated. A
pattern without `platforms` or `param_mapping` breaks `POST /deeplinks/test`
and association-file generation for that vendor, so always send both.

**Request example:**

```bash
curl -X POST https://links.spoonity.com/api/v1/deeplinks/routes \
  -H "X-API-Key: slk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{"platform": "ios", "pattern": "/menu/:category", "screen": "menu", "param_mapping": {"category": "category"}, "platforms": ["ios"]}'
```

**Response example:** The updated platform config, `201`.

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | `platform` required |
| 404 | AppError | No config exists yet for that platform (create it with `PUT /deeplinks/config/{platform}` first) |

### POST /api/v1/deeplinks/test

Test how a URL resolves against the stored route patterns for one platform.

**Auth:** API key with `deeplinks:write` scope, or dashboard JWT.

**Request body:**

| Field | Type | Required | Description |
|---|---|---|---|
| `url` | string | Yes | The path to test, such as `/menu/seasonal`. It is split on `/` and compared segment by segment, so a full URL with scheme and host never matches a pattern |
| `platform` | string | Yes | Platform to test against |

**Request example:**

```bash
curl -X POST https://links.spoonity.com/api/v1/deeplinks/test \
  -H "X-API-Key: slk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{"url": "/menu/seasonal", "platform": "ios"}'
```

**Response example:**

```json
{ "matched": true, "screen": "menu", "params": { "category": "seasonal" }, "app_url": "acmecafe://menu?category=seasonal", "fallback_url": "https://apps.apple.com/app/id123456" }
```

No config or no matching pattern returns `{ "matched": false }`.

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | `url` and `platform` required |

---

## QR Codes

Gated by `links:read` / `links:write` (QR codes are treated as part of the
link resource, not a separate scope area).

### GET /api/v1/qr/{linkId}

Generate a QR code for a specific link (management-API equivalent of the
public `GET /{code}/qr`, with more parameters).

**Auth:** API key with `links:read` scope, or dashboard JWT.

**Path parameters:**

| Name | Type | Description |
|---|---|---|
| `linkId` | integer | Link id |

**Query parameters:**

| Name | Type | Description |
|---|---|---|
| `format` | string | `png` (default) or `svg` |
| `size` | integer | 64 to 2048, default `400` |
| `fg` / `bg` | string | Hex color overrides |
| `margin` | integer | Default `2` |
| `ec` | string | Error correction: `L`, `M` (default), `Q`, `H` |

**Request example:**

```bash
curl "https://links.spoonity.com/api/v1/qr/42?size=600" \
  -H "X-API-Key: slk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -o qr.png
```

**Response example:** Binary image.

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | Invalid link ID |
| 404 | not_found | Link not found |

### GET /api/v1/qr/{linkId}/download

High-resolution QR download as an attachment (error correction fixed at `H`), named
`qr-<code>.png` or `.svg`.

**Auth:** API key with `links:read` scope, or dashboard JWT.

**Path parameters:**

| Name | Type | Description |
|---|---|---|
| `linkId` | integer | Link id |

**Query parameters:**

| Name | Type | Description |
|---|---|---|
| `format` | string | `png` (default) or `svg` |
| `size` | integer | 64 to 2048, default `1024` |

**Request example:**

```bash
curl "https://links.spoonity.com/api/v1/qr/42/download?size=2048" \
  -H "X-API-Key: slk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -o qr-hires.png
```

**Response example:** Binary image with `Content-Disposition: attachment`.

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | Invalid link ID |
| 404 | not_found | Link not found |

### POST /api/v1/qr/custom

Generate a QR code for an arbitrary URL, not tied to a link.

**Auth:** API key with `links:write` scope, or dashboard JWT.

**Request body:**

| Field | Type | Required | Description |
|---|---|---|---|
| `url` | string | Yes | Any URL |
| `format` | string | | `png` (default) or `svg` |
| `size` | integer | | 64 to 2048, default `400` |
| `foreground` / `background` | string | | Hex colors, default `#000000` / `#FFFFFF` |
| `margin` | integer | | Default `2` |
| `error_correction` | string | | `L`/`M`/`Q`/`H`, default `M` |

**Request example:**

```bash
curl -X POST https://links.spoonity.com/api/v1/qr/custom \
  -H "X-API-Key: slk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://acme-cafe.example.com"}' \
  -o qr.png
```

**Response example:** Binary image.

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | `url` required |

### GET /api/v1/qr/templates/list

List the printable QR templates `POST /qr/batch` accepts. The path is
`/templates/list`; a bare `GET /qr/templates` is read as a link id and
answers `400 Invalid link ID`.

**Auth:** API key with `links:read` scope, or dashboard JWT.

**Request example:**

```bash
curl https://links.spoonity.com/api/v1/qr/templates/list \
  -H "X-API-Key: slk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
[
  { "id": "table-tent", "name": "Table Tent", "description": "Perfect for restaurant tables. Large QR with title below." },
  { "id": "receipt", "name": "Receipt", "description": "..." },
  { "id": "poster", "name": "Poster", "description": "..." },
  { "id": "sticker", "name": "Sticker", "description": "..." },
  { "id": "digital-signage", "name": "Digital Signage", "description": "..." }
]
```

**Errors:** None specific.

### POST /api/v1/qr/batch

Generate a printable HTML page with embedded QR codes (e.g. for table tents).

**Auth:** API key with `links:write` scope, or dashboard JWT.

**Request body:**

| Field | Type | Required | Description |
|---|---|---|---|
| `template` | string | | A template id from `GET /qr/templates/list`. Default `table-tent`; an unknown id also falls back to `table-tent` |
| `link_ids` | integer[] | | Links to include (only this vendor's active links). When omitted, the 50 most recent active links |

**Request example:**

```bash
curl -X POST https://links.spoonity.com/api/v1/qr/batch \
  -H "X-API-Key: slk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{"template": "table-tent", "link_ids": [42, 43]}' \
  -o batch.html
```

**Response example:** `text/html` page with one printable card per link.

**Errors:** None specific.

---

## Webhooks

Requires `webhooks:read` / `webhooks:write`.

Valid event types: `link.created`, `link.updated`, `link.deleted`,
`link.clicked`, `link.expired`, `link.cap_reached`, `qr.scanned`. All seven
are now emitted: `link.created` (on create, bulk create and duplicate),
`link.updated` (`PUT /links/:id` or `PUT /links/:id/routing`, with
`data.changes` listing the names of the fields written — never their values,
so a password change shows up as `"password"` only), `link.deleted` (once,
when `DELETE /links/:id` deactivates the link; repeating the delete is still
a `204` but sends nothing), `link.expired` (once per link, on the first
redirect refused because `expires_at` has passed; changing `expires_at`
re-arms it — nothing is sent at the moment of expiry itself, and a link
nobody visits after it expires never sends it; a link refused for
`starts_at`, active hours, or click cap does not send this event, those
have no event or use `link.cap_reached`), `link.clicked` (every redirect
served), `link.cap_reached` (once, on the click that reaches `max_clicks`)
and `qr.scanned` (sent for a loyalty enrollment, with `data.event` set to
`loyalty_enrollment`).

**Delivery format.** Each event is a `POST` to the webhook URL with a JSON
body `{ "id": "<uuid>", "type": "<event>", "vendor_id": 12345, "timestamp": "<ISO 8601>", "data": { ... } }`
and these headers:

| Header | Value |
|---|---|
| `X-Webhook-Id` | The event `id` |
| `X-Webhook-Event` | The event type |
| `X-Webhook-Signature` | `sha256=<hex HMAC-SHA256 of the raw body, keyed with the webhook secret>` |
| `X-Webhook-Timestamp` | The event `timestamp` |

A non-2xx response or a network error is retried twice more (after 2 and 4
seconds), three attempts in total, and then dropped. Delivery is in-process
and best effort: nothing is queued across a restart.

### GET /api/v1/webhooks

List registered webhook endpoints for this vendor.

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

**Request example:**

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

**Response example:**

```json
[ { "id": 3, "url": "https://acme-cafe.example.com/webhooks/links", "events": ["link.created", "link.clicked"], "secret": "whsec_abcd...", "is_active": true } ]
```

The `secret` is always masked to its first 10 characters on read.

**Errors:** None specific.

### POST /api/v1/webhooks

Register a new webhook endpoint.

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

**Request body:**

| Field | Type | Required | Description |
|---|---|---|---|
| `url` | string | Yes | A public `http`/`https` URL. It is resolved in DNS and rejected if it points at a private, loopback or otherwise internal address |
| `events` | string[] | Yes | One or more of the valid event types |

**Request example:**

```bash
curl -X POST https://links.spoonity.com/api/v1/webhooks \
  -H "X-API-Key: slk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://acme-cafe.example.com/webhooks/links", "events": ["link.created", "link.clicked"]}'
```

**Response example:**

```json
{
  "id": 3,
  "vendor_id": 12345,
  "url": "https://acme-cafe.example.com/webhooks/links",
  "secret": "whsec_0123456789abcdef0123456789abcdef0123456789abcdef",
  "events": ["link.created", "link.clicked"],
  "is_active": 1,
  "created_at": "2026-08-01T12:00:00.000Z",
  "updated_at": "2026-08-01T12:00:00.000Z",
  "_note": "Store the `secret` securely ..."
}
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | `url` and `events[]` required, unparseable URL, or an unrecognized event name |
| 400 | AppError | The URL failed the SSRF check: not `http`/`https`, does not resolve in DNS, or resolves to a private or internal address |

### PUT /api/v1/webhooks/{id}

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

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

**Path parameters:**

| Name | Type | Description |
|---|---|---|
| `id` | integer | Webhook id |

**Request body:** Any of `url`, `events`, `is_active`. A new `url` goes
through the same SSRF check as on create. The secret cannot be rotated here;
delete and recreate the webhook for a new one.

**Request example:**

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

**Response example:** The updated webhook (secret masked).

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | Unrecognized event name |
| 400 | AppError | The new URL failed the SSRF check |
| 404 | not_found | Webhook not found, or the body contained none of `url`, `events`, `is_active` (body `{"error": "not_found"}` with no message) |

### DELETE /api/v1/webhooks/{id}

Remove a webhook endpoint.

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

**Path parameters:**

| Name | Type | Description |
|---|---|---|
| `id` | integer | Webhook id |

**Request example:**

```bash
curl -X DELETE https://links.spoonity.com/api/v1/webhooks/3 \
  -H "X-API-Key: slk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "deleted": true }
```

**Errors:**

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

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

Send a signed test ping to the webhook's URL.
SSRF-guarded (validates the target URL and every redirect hop).

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

**Path parameters:**

| Name | Type | Description |
|---|---|---|
| `id` | integer | Webhook id |

**Request example:**

```bash
curl -X POST https://links.spoonity.com/api/v1/webhooks/3/test \
  -H "X-API-Key: slk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{ "success": true, "status": 200, "statusText": "OK" }
```

The ping body is `{ "event": "ping", "webhook_id": 3, "timestamp": "<ISO 8601>", "data": { "message": "This is a test ping from Spoonity Links" } }`,
signed the same way as a real delivery but sent with only the
`X-Webhook-Signature` and `X-Webhook-Event: ping` headers, a 10 second
timeout and no retries. It is sent even when the webhook is inactive.

This always returns `200` to the caller, even when the ping itself failed.
Check the `success` field, not the HTTP status; a connection failure returns
`{ "success": false, "status": 0, "error": "<reason>" }`.

**Errors:**

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

---

## Bio Pages

Link-in-bio landing pages. The public render is unauthenticated; managing the
page's content requires `bio:read` / `bio:write`.

### GET /bio/{slug}

Render a vendor's bio page as HTML.

**Auth:** None.

**Path parameters:**

| Name | Type | Description |
|---|---|---|
| `slug` | string | The bio page's own slug (defaults to the vendor slug when the page is created). Inactive pages answer `404` |

**Request example:**

```bash
curl https://links.spoonity.com/bio/acme-cafe
```

**Response example:** `text/html`, cached `public, max-age=60`.

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 404 | (HTML) | No active bio page at that slug (returns a 404 HTML page, not JSON) |

### GET /api/v1/bio

Get the vendor's bio page config.

**Auth:** API key with `bio:read` scope, or dashboard JWT.

**Request example:**

```bash
curl https://links.spoonity.com/api/v1/bio \
  -H "X-API-Key: slk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

```json
{
  "id": 1,
  "vendor_id": 12345,
  "slug": "acme-cafe",
  "title": "Acme Cafe",
  "subtitle": null,
  "avatar_emoji": null,
  "avatar_url": null,
  "theme": { "mode": "brand", "brand_color": "#A42518", "...": "..." },
  "links": [ { "id": "order", "label": "Order Now", "url": "https://acme-cafe.example.com/order" } ],
  "social_links": { "instagram": "https://instagram.com/acmecafe" },
  "is_active": 1,
  "created_at": "2026-08-01T12:00:00.000Z",
  "updated_at": "2026-08-01T12:00:00.000Z"
}
```

If no page exists yet the response is `{ "exists": false }`. An existing page
has no `exists` field.

**Errors:** None specific.

### PUT /api/v1/bio

Create or update the vendor's bio page.

**Auth:** API key with `bio:write` scope, or dashboard JWT.

**Request body:**

| Field | Type | Required | Description |
|---|---|---|---|
| `title` | string | At least one of `title`, `links`, `slug` | Defaults to the vendor name on first create |
| `subtitle` | string | | |
| `slug` | string | | The public `/bio/{slug}` path. Defaults to the vendor slug on first create |
| `avatar_emoji` / `avatar_url` | string | | |
| `theme` | object | | `{ mode: "dark" or "light" or "brand", brand_color, background_color, text_color, card_color, font_family, border_radius }` |
| `links` | array | | `[{ id, label, url, icon?, style?, is_featured? }]`; each `url` must be `http`, `https`, `mailto` or `tel`. Replaces the whole list |
| `social_links` | object | | Network name to URL, same URL rule |
| `is_active` | boolean | | |

On an existing page, omitted or empty fields keep their stored value, so a
text field cannot be cleared back to empty through this endpoint.

**Request example:**

```bash
curl -X PUT https://links.spoonity.com/api/v1/bio \
  -H "X-API-Key: slk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{"title": "Acme Cafe", "slug": "acme-cafe", "links": [{"label": "Order Now", "url": "https://acme-cafe.example.com/order"}]}'
```

**Response example:** The saved bio page object.

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | At least one of `title`, `links`, or `slug` is required |
| 400 | AppError | A link or social URL uses a disallowed scheme (for example `javascript:`) |

---

## Loyalty

Public QR sign-up flow for rewards programs. The loyalty router is mounted
twice, at `/loyalty` and at `/api/v1/loyalty`, so every route below answers
under both prefixes.

### GET /loyalty/{slug}/join

Serve the public loyalty sign-up page for a QR code scan.

**Auth:** None.

**Path parameters:**

| Name | Type | Description |
|---|---|---|
| `slug` | string | Vendor slug |

**Request example:**

```bash
curl https://links.spoonity.com/loyalty/acme-cafe/join
```

**Response example:** `text/html` enrollment landing page.

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 404 | (HTML) | Vendor not found (returns HTML, not JSON) |

### GET /loyalty/{slug}/qr

QR code linking to the loyalty sign-up page.

**Auth:** None.

**Path parameters:**

| Name | Type | Description |
|---|---|---|
| `slug` | string | Vendor slug |

**Query parameters:**

| Name | Type | Description |
|---|---|---|
| `format` | string | `png` (default) or `svg` |
| `size` | integer | 128 to 2048, default `512` |

**Request example:**

```bash
curl "https://links.spoonity.com/loyalty/acme-cafe/qr?size=512" -o loyalty-qr.png
```

**Response example:** Binary image.

**Errors:**

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

### POST /api/v1/loyalty/enroll

Submit a loyalty enrollment. Also reachable at `POST /loyalty/enroll` (same
handler, mounted twice).

**Auth:** None.

**Request body:**

| Field | Type | Required | Description |
|---|---|---|---|
| `firstName` | string | Yes | |
| `email` | string | Yes | Validated format |
| `phone` | string | | |
| `vendorSlug` | string | Yes | |
| `ref` | string | | Originating click's visitor id, for funnel attribution |

**Request example:**

```bash
curl -X POST https://links.spoonity.com/api/v1/loyalty/enroll \
  -H "Content-Type: application/json" \
  -d '{"firstName": "Jamie", "email": "jamie@example.com", "vendorSlug": "acme-cafe"}'
```

**Response example (`201`, vendor connected to a wallet program):**

```json
{
  "success": true,
  "redirectUrl": "https://wallet-api.spoonity.com/v1/enroll/session/abc123",
  "message": "Welcome to Acme Cafe Rewards!",
  "vendor": { "name": "Acme Cafe", "slug": "acme-cafe" }
}
```

**Response example (`201`, vendor not yet wallet-connected, simulated path):**

```json
{
  "success": true,
  "enrollment_id": "enr_1735297200000_ab12cd",
  "message": "Welcome to Acme Cafe Rewards!",
  "vendor": { "name": "Acme Cafe", "slug": "acme-cafe" }
}
```

The `redirectUrl` (single-use, 15-minute TTL) must be followed by the client
to actually receive the wallet pass; the member is not created until then.

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | Missing `firstName`/`email`/`vendorSlug`, or invalid email format |
| 404 | not_found | Vendor not found |
| 502 | enrollment_failed | The wallet-pass enrollment session could not be started |

---

## Vendor Settings, Domain, Usage & API Keys

Requires `vendor:read` / `vendor:write` for settings, domain, enroll, usage,
locations and the legacy-key routes. `/vendor/api-keys` (named key
management) requires a dashboard JWT session regardless of scope.

### GET /api/v1/vendor/locations

Proxies Spoonity's public store directory so the dashboard can offer a
location picker. Cached in-memory a few minutes per vendor.

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

**Request example:**

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

**Response example:**

```json
{ "locations": [ { "id": "501", "name": "Downtown", "region": "CA", "city": "San Francisco" } ] }
```

Sorted by region, then name. A response served from the five-minute cache
also carries `"cached": true`; a vendor with no Spoonity vendor id gets
`{ "locations": [] }`.

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 502 | upstream | Could not reach Spoonity's store directory |

### GET /api/v1/vendor/settings

Fetch this vendor's account-level settings.

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

**Request example:**

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

**Response example:**

```json
{ "id": 12345, "spoonity_vendor_id": "12345", "name": "Acme Cafe", "slug": "acme-cafe", "custom_domain": null, "default_domain": "links.spoonity.com", "short_path_prefix": null, "domain_provider": "shared", "logo_url": null, "brand_color": "#A42518", "settings": { "timezone": "America/Los_Angeles" }, "created_at": "2026-08-01T12:00:00.000Z", "updated_at": "2026-09-30T12:00:00.000Z" }
```

This is a whitelist (`src/utils/vendorSerializer.ts`'s `publicVendor()`),
used by this endpoint, `PUT` of the same path, and every other route that
returns a vendor (login, select-vendor, switch-vendor, dev-login,
`/auth/me` — those may carry a subset of these fields but never others, and
never a field not listed here). Credentials and internal columns
(`api_key_hash`, `api_key_hint`, `wallet_api_key`, `wallet_program_id`,
`wallet_api_base`, `hosting_site_id`) are never returned; a column added to
the table later stays private until someone deliberately whitelists it.
The legacy key's last four characters are available from
`GET /vendor/api-key/status` instead.

`default_domain` is a legacy column: usually `links.spoonity.com` (or the
dead `l.spnty.co`), never used to build a short URL or QR code. It is still
matched as a `Host` when serving `/.well-known/*` files. It does **not**
reflect the shared host: where this vendor's short links actually resolve is
`mode` + `short_link_base` on `GET /vendor/domain` (or `GET /vendor/enroll`),
not this endpoint.

**Errors:**

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

### PUT /api/v1/vendor/settings

Update this vendor's account-level settings.

**Auth:** API key with `vendor:write` scope, or dashboard JWT.

**Request body:**

| Field | Type | Required | Description |
|---|---|---|---|
| `name` | string | | Display name |
| `slug` | string | | 2 to 63 lowercase letters, digits and single hyphens, not a reserved path. A rename keeps the previous slug resolving as an alias while the vendor is on the shared host (up to ten aliases). Same rules as `POST /vendor/enroll` |
| `logo_url` | string | | https URL or `data:image` URI |
| `brand_color` | string | | Hex color |
| `settings` | object | | Merged into existing settings (`JSON_MERGE_PATCH`); `settings.timezone` must be a valid IANA zone name; `settings.ordering_url`, the brand's ordering site that [table QR codes](#get-slugmesastoreidtable) redirect to, must be an https URL (`null` or `""` clears it) |

`custom_domain` is **not settable through this endpoint**, even though an
earlier version of the OpenAPI spec listed it as a field here (the upstream
spec still does). The handler
only reads `name`, `slug`, `logo_url`, `brand_color`, `settings` from the
body and silently ignores anything else. Use `PUT /vendor/domain`, which
enforces uniqueness and provisions the TLS mapping.

**Request example:**

```bash
curl -X PUT https://links.spoonity.com/api/v1/vendor/settings \
  -H "X-API-Key: slk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{"brand_color": "#A42518", "settings": {"timezone": "America/Los_Angeles"}}'
```

**Response example:** The same whitelisted vendor object as
`GET /vendor/settings`, read back after the update. Credentials such as
`api_key_hash` and `wallet_api_key` are never returned — before this was
fixed, `PUT` returned the whole row straight from `SELECT *`, including the
legacy key's hash and the Pass Studio wallet key.

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | Invalid `brand_color`, `logo_url`, `settings.timezone`, or malformed `slug`; or `settings.ordering_url` that is not https (`settings.ordering_url must be an https URL like https://order.example.com/`, spoonity-links #20) |
| 400 | reserved_slug | `slug` is a path this service already serves |
| 409 | slug_taken | Another vendor already has that slug, current or previous |
| 409 | too_many_aliases | This vendor already keeps ten previous slugs resolving |

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

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

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

**Request example:**

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

**Response example:**

```json
{ "exists": true, "hint": "9f3a", "last_rotated": "2026-06-01T00:00:00Z" }
```

**Errors:** None specific.

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

Generate a new legacy vendor-wide key (`scopes: ['*']`), invalidating the
previous one immediately.

**Auth:** Gated by `requireFullAccessCredential` (`src/middleware/auth.ts`),
not just `vendor:write` — minting a full-access credential needs a
credential at least as powerful as the one it hands back:

| Caller | Result |
|---|---|
| Dashboard session (JWT) | `200` |
| An `slk_` key that already has `*` (the legacy key itself, or a named `*` key) | `200` |
| Any other `slk_` key, including one with `vendor:write` | `403 forbidden` |
| A service identity (Google OIDC token or `slp_` platform key) | `403 forbidden` |
| No credential | `401 unauthorized` |

A key scoped to `vendor:write` alone can no longer call this route to mint
itself a `*` key.

**Request example:**

```bash
curl -X POST https://links.spoonity.com/api/v1/vendor/api-key/rotate \
  -H "X-API-Key: slk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Response example:**

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

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 401 | unauthorized | Missing or invalid credential |
| 403 | forbidden | Credential is scoped (lacks `*`) or is a service identity. Message: "This action requires a dashboard session or a full-access API key" |

### Short-link domain

`PUT`/`GET`/`DELETE /api/v1/vendor/domain` govern **where this vendor's short
links resolve**: the shared host, a custom domain, or neither. Every
response (including `PUT`'s) carries `mode`, which is what a consumer should
branch on, and `slug_aliases` (`[]` for most vendors; the brand's previous
shared-host slugs, present in every mode so a caller never has to branch on
the field existing):

| `mode` | Short link shape | Meaning |
|---|---|---|
| `shared` | `x.spnty.co/<slug>/<code>` | the shared host ([SHARED-HOST.md](https://github.com/Spoonity/spoonity-links/blob/main/docs/SHARED-HOST.md) upstream). No DNS record, no certificate, and the recommended setup for a new vendor |
| `custom` | `go.yourbrand.com/<code>`, or `brand.spnty.co/l/<code>` on a deprecated merchant host | the vendor's own domain |
| `none` | `links.spoonity.com/<code>` | no domain connected |

Only already-minted links keep their old shape: switching mode changes what
NEW links and QR codes are built with, never what an existing code resolves
to.

### PUT /api/v1/vendor/domain

Either moves the vendor onto the shared host (no DNS, no certificate, active
immediately), or connects a custom domain: it provisions a managed,
auto-renewed TLS certificate and returns the DNS records to create. Whatever
the vendor was using before is released first (a Firebase merchant host is
removed, a Cloud Run domain mapping is deleted).

**Auth:** API key with `vendor:write` scope, or dashboard JWT.

**Request body:**

| Field | Type | Required | Description |
|---|---|---|---|
| `mode` | `"shared"` or `"custom"` | | `shared` moves the vendor onto `x.spnty.co` and ignores `domain`. `custom` requires `domain` and forces the custom-domain path |
| `domain` | string | Unless `mode` is `shared` | The custom domain to connect, lowercased. Without `mode`, sending the shared host's own hostname is equivalent to `{"mode": "shared"}`. A single label under `.spnty.co` (for example `brand.spnty.co`) is provisioned as a deprecated Firebase merchant host serving `/l/<code>`; any other host gets a Cloud Run domain mapping |

**Request example (shared host):**

```bash
curl -X PUT https://links.spoonity.com/api/v1/vendor/domain \
  -H "X-API-Key: slk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{"mode": "shared"}'
```

**Response example (shared host):**

```json
{
  "domain": "x.spnty.co",
  "mode": "shared",
  "state": "active",
  "short_link_base": "x.spnty.co/your-brand",
  "slug_aliases": [],
  "records": [],
  "dns_ok": true,
  "message": "Short links are served from x.spnty.co/your-brand/<code> ... no DNS record is needed."
}
```

**Request example (custom domain):**

```bash
curl -X PUT https://links.spoonity.com/api/v1/vendor/domain \
  -H "X-API-Key: slk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{"domain": "links.acme-cafe.example.com"}'
```

**Response example (custom domain):**

```json
{ "domain": "links.acme-cafe.example.com", "mode": "custom", "state": "awaiting_dns", "slug_aliases": [], "records": [ { "name": "links", "type": "CNAME", "rrdata": "ghs.googlehosted.com." } ], "dns_ok": false }
```

`state` for a custom domain is one of `none | awaiting_dns |
provisioning_certificate | active | action_required | unavailable`; the
shared host is always `active` and never has records to add.

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | `domain` missing, `mode` is neither `shared` nor `custom`, or the domain is reserved (`links.spoonity.com`, `x.spnty.co`, or the service's own host) |
| 404 | not_found | Vendor not found |
| 409 | conflict | Domain already connected to another vendor |
| 422 | domain_setup | The domain name is invalid, or the TLS mapping could not be created |

### GET /api/v1/vendor/domain

Current mode + certificate/DNS status.

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

**Request example:**

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

**Response example:**

```json
{ "domain": null, "mode": "none", "state": "none", "slug_aliases": [], "records": [] }
```

**Errors:** None specific.

### DELETE /api/v1/vendor/domain

Disconnect the custom domain, or leave the shared host. Either way, the
vendor returns to `mode: "none"` (`links.spoonity.com/<code>`).

**Auth:** API key with `vendor:write` scope, or dashboard JWT.

**Request example:**

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

**Response example:** `204 No Content`

**Errors:** None specific.

### POST /api/v1/vendor/enroll

Everything a brand needs in order to have working short links, in one
idempotent call: its slug, the shared host, and its app association details.
The slug rules, the mode switch and the iOS/Android deep-link upsert are
composed into one request, so callers do not each have to get that order
right on their own. `GET` returns the same shape, read-only,
so a caller can ask "is this brand set up?" before it builds.

**Auth:** Any credential with `vendor:write`: a dashboard session, an OIDC
service token, a platform API key, or an `slk_` key with `vendor:write`.

**Request body:** every field is optional; `{}` enrolls the vendor on the
shared host under its current slug:

| Field | Type | Description |
|---|---|---|
| `slug` | string | `^[a-z0-9]+(-[a-z0-9]+)*$`, 2 to 63 chars, not a reserved path (`admin`, `api`, `assets`, `auth`, `bio`, `dashboard`, `dashboard-legacy`, `docs`, `health`, `healthz`, `l`, `login`, `loyalty`, `qr`, `r`, `static`, `well-known`, `www`). Equal to the current slug is a no-op. A rename keeps the old slug as an alias that still resolves. Another vendor's current slug or alias → `409 slug_taken`; a rename when ten aliases already exist → `409 too_many_aliases`. |
| `mode` | `"shared"` \| `"none"` | `shared` (the default) moves the vendor onto `x.spnty.co` unless it already has an active custom domain, which stays connected and is reported as `mode: "custom"`. `none` only undoes the shared host; it never disconnects a custom domain. |
| `ios` / `android` | object | Upserted exactly as `PUT /deeplinks/config/{platform}` does: an omitted field keeps its stored value, so one platform updates without wiping the other. |

**Request example:**

```bash
curl -X POST https://links.spoonity.com/api/v1/vendor/enroll \
  -H "X-API-Key: slk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{"android": {"package_name": "com.spoonity.bb", "sha256_fingerprints": ["AA:BB:…"]}}'
```

**Response example (`200`, `GET` returns the same shape):**

```json
{
  "vendor_id": 2111721,
  "spoonity_vendor_id": "2111721",
  "slug": "breakfast-bonanza",
  "slug_aliases": ["mary-browns"],
  "mode": "shared",
  "short_link_base": "x.spnty.co/breakfast-bonanza",
  "short_link_example": "https://x.spnty.co/breakfast-bonanza/abc123",
  "deep_links": {
    "ios": { "configured": true, "app_id": "com.spoonity.bb", "team_id": "VDXUR6BU8Z" },
    "android": { "configured": false }
  },
  "well_known": {
    "aasa": "https://x.spnty.co/.well-known/apple-app-site-association",
    "assetlinks": "https://x.spnty.co/.well-known/assetlinks.json"
  }
}
```

`short_link_base` and `well_known` follow the vendor's actual mode: the
shared host in `shared`, the vendor's own host in `custom`,
`links.spoonity.com` in `none`. `short_link_example` is illustrative, not a
real link. `configured` means the platform would appear in the association
file: iOS needs both `app_id` and `team_id`, Android needs a `package_name`
and at least one fingerprint. No API key is ever returned.

Not transactional: the steps apply in order (slug, then mode, then deep
links), and the first failure stops the rest. Every step is idempotent:
re-sending the same body converges a partially applied enrollment rather than
compounding it.

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | Malformed `slug`, `mode` is neither `shared` nor `none`, or an `ios`/`android` block that is not an object (or whose `sha256_fingerprints` is not an array of strings) |
| 400 | reserved_slug | `slug` is a reserved path |
| 403 | insufficient_scope | Credential lacks `vendor:write` (`vendor:read` for `GET`) |
| 404 | not_found | Vendor not found |
| 409 | slug_taken | Another vendor already has that slug, current or alias |
| 409 | too_many_aliases | This vendor already has ten aliased slugs |

### GET /api/v1/vendor/enroll

The read-only half of `POST /vendor/enroll`: the same response shape,
changing nothing. What a dashboard setup page shows and what a release
pipeline checks before it builds.

**Auth:** Any credential with `vendor:read`.

**Request example:**

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

**Response example:** Same as `POST /vendor/enroll`.

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 403 | insufficient_scope | Credential lacks `vendor:read` |
| 404 | not_found | Vendor not found |

### GET /api/v1/vendor/usage

Fetch this vendor's current usage against its plan limits.

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

**Request example:**

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

**Response example:**

```json
{ "total_links": 128, "active_links": 110, "total_clicks": 48213, "monthly_clicks": 6120 }
```

**Errors:** None specific.

### GET /api/v1/vendor/api-keys

List the vendor's named API keys, newest first, active and revoked (never
returns a secret).

**Auth:** Dashboard JWT only.

**Request example:**

```bash
curl https://links.spoonity.com/api/v1/vendor/api-keys \
  -H "Authorization: Bearer <dashboard-jwt>"
```

**Response example:**

```json
[ { "id": 5, "name": "Marketing Automation", "key_hint": "9f3a", "scopes": ["links:write", "analytics:read"], "is_active": true, "last_used_at": "2026-08-20T09:00:00.000Z", "revoked_at": null, "created_at": "2026-07-01T00:00:00Z", "created_by": "jamie@acme-cafe.com" } ]
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 403 | forbidden | Caller is not a dashboard session (e.g. tried with an API key) |

### POST /api/v1/vendor/api-keys

Create a named, scoped key. A vendor can hold at most 20 active keys.

**Auth:** Dashboard JWT only.

**Request body:**

| Field | Type | Required | Description |
|---|---|---|---|
| `name` | string | Yes | Max 100 chars |
| `scopes` | string[] | Yes | From the scope vocabulary above |

**Request example:**

```bash
curl -X POST https://links.spoonity.com/api/v1/vendor/api-keys \
  -H "Authorization: Bearer <dashboard-jwt>" \
  -H "Content-Type: application/json" \
  -d '{"name": "Marketing Automation", "scopes": ["links:write", "analytics:read"]}'
```

**Response example:**

```json
{
  "id": 5,
  "name": "Marketing Automation",
  "api_key": "slk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  "hint": "9f3a",
  "scopes": ["links:write", "analytics:read"],
  "message": "Store this key securely. It will not be shown again."
}
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | `name`/`scopes` missing or invalid, or the 20-key-per-vendor limit is reached |
| 403 | forbidden | Caller is not a dashboard session |

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

Revoke a named key. Idempotent: revoking an already revoked key answers
`204` again.

**Auth:** Dashboard JWT only.

**Path parameters:**

| Name | Type | Description |
|---|---|---|
| `id` | integer | Key id |

**Request example:**

```bash
curl -X DELETE https://links.spoonity.com/api/v1/vendor/api-keys/5 \
  -H "Authorization: Bearer <dashboard-jwt>"
```

**Response example:** `204 No Content`

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | Invalid key ID |
| 404 | not_found | Key not found |

---

## Vendor Authentication (dashboard login flow)

These endpoints exist to authenticate a human into the Links dashboard, not
for a server-to-server integration. A machine integration should use an API
key or (for trusted Spoonity services only) the OIDC path above.

### POST /api/v1/auth/login

Step 1 of login: authenticate against the Spoonity Identity Server.

**Auth:** None (this issues credentials).

**Request body:**

| Field | Type | Required | Description |
|---|---|---|---|
| `email` | string | Yes | Must be on an allowed email domain |
| `password` | string | Yes | |

There is no `vendor_id` field on this call. An earlier version of the
OpenAPI spec required one (the upstream spec still does); the real handler only reads `email` and
`password`. Vendor selection is a separate step (see below).

**Request example:**

```bash
curl -X POST https://links.spoonity.com/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email": "jamie@spoonity.com", "password": "hunter2"}'
```

**Response example (single authorized vendor, login complete):**

```json
{
  "success": true,
  "requires_vendor_selection": false,
  "token": "<jwt>",
  "vendor": { "id": 12345, "spoonity_vendor_id": "12345", "name": "Acme Cafe", "slug": "acme-cafe" },
  "user": { "email": "jamie@spoonity.com" },
  "identities": [{ "id": "12345", "name": "Acme Cafe" }]
}
```

**Response example (multiple vendors, selection required):**

```json
{
  "success": true,
  "requires_vendor_selection": true,
  "selection_token": "<short-lived-jwt>",
  "identities": [{ "id": "12345", "name": "Acme Cafe" }, { "id": "67890", "name": "Acme Bakery" }]
}
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | `email` and `password` required |
| 401 | unauthorized | Invalid credentials |
| 403 | forbidden | Email domain not allowed, the vendor list could not be fetched, or the account has no authorized vendors |
| 429 | rate_limit | More than 10 login attempts per minute from this IP |
| 500 | internal | The identity server is unreachable |
| 503 | maintenance | Login temporarily disabled |

### POST /api/v1/auth/select-vendor

Step 2 of login (only needed with more than one authorized vendor).

**Auth:** None (completes login).

**Request body:**

| Field | Type | Required | Description |
|---|---|---|---|
| `vendor_id` | string | Yes | |
| `selection_token` | string | Preferred | From `/auth/login` |
| `email` / `password` | string | Legacy alternative to `selection_token` | |
| `vendor_name` | string | | Used only if the vendor must be auto-provisioned |

**Request example:**

```bash
curl -X POST https://links.spoonity.com/api/v1/auth/select-vendor \
  -H "Content-Type: application/json" \
  -d '{"selection_token": "<token-from-login>", "vendor_id": "12345"}'
```

**Response example:**

```json
{
  "token": "<jwt>",
  "vendor": { "id": 12345, "spoonity_vendor_id": "12345", "name": "Acme Cafe", "slug": "acme-cafe", "logo_url": null, "brand_color": "#A42518" },
  "user": { "email": "jamie@spoonity.com", "id": "jamie@spoonity.com", "first_name": "", "last_name": "" },
  "session_key": null
}
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | `vendor_id` and `selection_token` (or `email`+`password`) required |
| 401 | unauthorized | Selection token invalid or expired (it lasts 15 minutes) |
| 403 | forbidden | Account not authorized for that vendor, or email domain not allowed |
| 429 | rate_limit | More than 10 attempts per minute from this IP |
| 500 | internal | The identity server is unreachable |
| 503 | maintenance | Login temporarily disabled |

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

The route source also defines `POST /api/v1/auth/dev-login`, a credential-free
login gated on `config.isDev`. It returns a plain `404 not_found` whenever the
service is not running in development mode, so **it is never reachable in
production** and is not part of the public API surface. Documented here only
so its existence is not a surprise when reading route source.

### GET /api/v1/auth/me

Get the identity and vendor behind the current credential.

**Auth:** Any credential (dashboard JWT, API key, OIDC service token or
platform key). No scope is required. For an API key, `user.id` is
`api-key:<key name>` (or `api-key` for the legacy key); for a platform key
it is `platform:<label>`.

**Request example:**

```bash
curl https://links.spoonity.com/api/v1/auth/me \
  -H "Authorization: Bearer <dashboard-jwt>"
```

**Response example:**

```json
{ "user": { "email": "jamie@spoonity.com", "id": "jamie@spoonity.com" }, "vendor": { "id": 12345, "spoonity_vendor_id": "12345", "name": "Acme Cafe", "slug": "acme-cafe", "logo_url": null, "brand_color": "#A42518" } }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 401 | unauthorized | Missing or invalid session |
| 403 | forbidden | No vendor context on the credential |

### POST /api/v1/auth/switch-vendor

Re-issue a token scoped to a different vendor the session is already
authorized for.

**Auth:** Dashboard JWT. Other credentials carry no `allowedVendors` list, so
they always get `403`.

**Request body:**

| Field | Type | Required | Description |
|---|---|---|---|
| `vendor_id` | string | Yes | Spoonity vendor id; must be in the session's `allowedVendors` (fixed at login) |
| `vendor_name` | string | | Used only if the vendor must be auto-provisioned |

**Request example:**

```bash
curl -X POST https://links.spoonity.com/api/v1/auth/switch-vendor \
  -H "Authorization: Bearer <dashboard-jwt>" \
  -H "Content-Type: application/json" \
  -d '{"vendor_id": "67890"}'
```

**Response example:**

```json
{ "token": "<new-jwt>", "vendor": { "id": 67890, "spoonity_vendor_id": "67890", "name": "Acme Bakery", "slug": "acme-bakery", "logo_url": null, "brand_color": null } }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | `vendor_id` required |
| 403 | forbidden | Vendor not in the session's authorized list; log in again |

---

## Discovery and health

Public, unauthenticated files the operating systems and uptime monitors read.
They are answered on every host, including the shared host.

### GET /.well-known/apple-app-site-association

The Apple App Site Association file for universal links, built from each
vendor's `ios` deep-link config (both `app_id` and `team_id` must be set for a
vendor to appear).

**Auth:** None.

**Parameters:** None. The `Host` header chooses the content:

| Host | File contents |
|---|---|
| `x.spnty.co` (shared host) | One entry per shared-host vendor, each claiming only `/<slug>/*` and `/<previous slug>/*` plus its route patterns under those prefixes |
| A vendor's own custom domain | That vendor alone. A deprecated merchant host claims only its `/l` prefix |
| Anything else (`links.spoonity.com`) | Every vendor's entry, claiming `/*` with the service's own pages (`/`, `/bio/*`, `/docs*`, `/dashboard*`, `/api/*`, `/loyalty*`, `/health*`) excluded |

On that aggregate (multi-vendor) path, `webcredentials.apps` is built by
`mergeAASA()` (`src/services/deeplinkService.ts`) as the **deduplicated
union** of every vendor's app on the host — not just the first or last one
enumerated — and is required for passkeys/AutoFill to work for any of those
apps against the shared domain; both `routes/wellKnown.ts` aggregate paths
(the default-domain fallback and the shared host) go through it.

**Request example:**

```bash
curl https://x.spnty.co/.well-known/apple-app-site-association
```

**Response example:**

```json
{ "applinks": { "apps": [], "details": [ { "appID": "ABCDE12345.com.acmecafe.app", "components": [ { "/": "/acme-cafe/*" } ], "paths": ["/acme-cafe/*"] } ] }, "webcredentials": { "apps": ["ABCDE12345.com.acmecafe.app"] } }
```

**Errors:** None. During a database outage the last good file for that host
is served; with nothing cached, an empty `details` list.

### GET /.well-known/assetlinks.json

The Android Digital Asset Links file, one statement per vendor whose
`android` config has a `package_name` and at least one fingerprint. Chosen by
`Host` the same way as the AASA (a statement names an app and a host, never a
path, so the shared host's file lists every shared-host vendor).

**Auth:** None.

**Request example:**

```bash
curl https://x.spnty.co/.well-known/assetlinks.json
```

**Response example:**

```json
[ { "relation": ["delegate_permission/common.handle_all_urls", "delegate_permission/common.get_login_creds"], "target": { "namespace": "android_app", "package_name": "com.acmecafe.app", "sha256_cert_fingerprints": ["AA:BB:CC:DD"] } } ]
```

**Errors:** None; a failure returns `[]`.

### GET /health

Liveness probe. Checks the database and, when configured, Redis. Not rate
limited.

**Auth:** None.

**Request example:**

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

**Response example:**

```json
{ "status": "healthy", "timestamp": "2026-09-30T10:41:26.824Z", "uptime": 18079.04, "checks": { "mysql": { "status": "ok", "latency": 3 }, "redis": { "status": "disabled" } } }
```

`status` is `healthy`, `degraded` (database fine, Redis failing) or
`unhealthy`. Only the database decides the HTTP status.

**Errors:**

| Status | Meaning |
|---|---|
| 503 | Database check failed (`"status": "unhealthy"`) |

## Internal-only endpoints (not part of the public surface)

These exist in the Links codebase but are not integrator-callable and are
intentionally not documented above beyond this note:

- **`POST /api/v1/wallet-events/{token}`**: a server-to-server callback from
  Spoonity's own wallet-passkit-integration service, authenticated by a
  shared secret in the URL path, that advances the wallet enrollment funnel.
- **`GET /docs`** and **`GET /docs/openapi.yaml`**: the service's own Swagger
  UI and its upstream OpenAPI file. The spec copy published with these docs
  corrects that file in several places.
- **`/dashboard`**: the Links web dashboard.

## Rate Limits

| Surface | Default limit |
|---|---|
| Short-link redirect surface (`/{code}`, `/l/{code}`, `/{slug}/{code}` and their `/preview`, `/qr`, `/opened` variants) and `GET /api/v1/resolve/{code}` | 1000 requests/min per IP (`RATE_LIMIT_REDIRECT_RPM`) |
| Everything else under `/api/v1`, including the auth routes and the public `/deeplinks/match` and `/loyalty/enroll` | 100 requests/min (`RATE_LIMIT_API_RPM`), keyed by a hash of the presented credential (bearer token or API key), or by IP when no credential is sent. See [Conventions](/docs/conventions#rate-limits) |
| Login endpoints (`/auth/login`, `/auth/select-vendor`) | Additionally 10 requests/min per IP |
| `/bio/{slug}`, `/loyalty/{slug}/*`, `/.well-known/*`, `/health` | Not rate limited |

A rate-limited request receives `429` with `{"error": "rate_limit", "message": "..."}`
and the standard `RateLimit-*` headers.
