# Spoonity Auth API

Spoonity Auth is the platform's **passwordless consumer identity service**: it
signs a brand's *end customers* into that brand's app, website, kiosk and POS
without a password. One-time codes over SMS, WhatsApp and email; magic links;
passkeys; Sign in with Apple and Google; and an out-of-band "approve on your
phone" flow for POS terminals and second devices.

**Base URL:** `https://auth.spoonity.com`
**Machine-readable spec:** [/docs/openapi/auth.yaml](/docs/openapi/auth.yaml)
(OpenAPI 3.1, 60 paths). The service also publishes it live at
`https://auth.spoonity.com/openapi.json`.

## Do not confuse this with /docs/authentication

Two different things share a word, and picking the wrong one wastes a day:

| | [Authentication](/docs/authentication) | **This page** |
|---|---|---|
| Question it answers | "How does *my backend* prove itself to a Spoonity API?" | "How does *my customer* sign in to my brand's app?" |
| Credential | Vendor API keys, scoped keys, operator sessions, service OIDC | The customer's phone, email, passkey or social account |
| Who holds it | You, the integrator | The end customer |
| Issues | Nothing; you are given a key | Short-lived JWTs for that customer |

If you are wiring a server-to-server integration against CMS, Links or
Wallet, you want [Authentication](/docs/authentication). If you are building
the sign-in screen of a restaurant brand's mobile app, you are in the right
place.

## What it is for

- **Brand mobile apps and web ordering.** The primary caller. The app holds
  an access token for the customer and refreshes it in the background.
- **POS terminals and kiosks.** Identify a member at the counter by having
  them approve a prompt on their own phone, or by typing a short code. The
  terminal never handles the customer's credential.
- **Prism operators**, through the Identity section, which is a UI over the
  admin API below. Operators do not call this service directly.

It sits **in front of** the Spoonity loyalty platform rather than replacing
it. Every successful sign-in also returns a `loyalty.session_key`, so an app
keeps calling the loyalty API exactly as it does today (see
[The loyalty bridge](#the-loyalty-bridge)).

## The surfaces

| Prefix | Audience | Credential |
|---|---|---|
| `/v1/*` | Consumer apps, web, POS | None, a guest token, or a customer's access token |
| `/admin/v1/*` | Prism only | Google-signed OIDC service identity |
| `/internal/*` | Spoonity infrastructure | OIDC; not callable by integrators |
| `/.well-known/*`, `/health`, `/ready`, `/openapi.json` | Anyone | None |

## Multi-tenancy: the vendor header

Every JSON `/v1` request must name the tenant:

```
X-Spoonity-Vendor: 2111603
```

This is the same `spoonityVendorId` header the Prism BFF, Links and CMS use.
Omit it and you get `400 tenant_required`; send one that is unknown or whose
configuration has `enabled: false` and you get `403 tenant_disabled`. The
two cases are deliberately indistinguishable to a caller, so the endpoint
cannot be used to enumerate vendors.

The three HTML pages a browser opens from a message
(`GET /v1/magic/{token}`, `GET /v1/deferred/pair/{id}` and
`GET /v1/sec/revoke`) are the exception: a browser cannot send the header, so
they resolve the tenant from the token or pairing id instead.

## Device identity

Two more headers travel with every consumer request:

| Header | Required | Meaning |
|---|---|---|
| `X-Device-Id` | Strongly recommended | A UUID v4 the app mints **once per install** and keeps. Sessions are bound to it, and it is what "new device" detection and the device list key on. `POST /v1/devices/push-token` refuses a request without it. |
| `X-Device-Info` | Optional | Base64 of `{"platform","model","os","app_version","locale"}`. Drives the human-readable device names an operator and the customer see, and `platform` decides the client type for [client proof](#client-proof-and-abuse-controls) (`ios`/`android` = app, `web` = web, anything else follows the web rules). A malformed blob is ignored, never fatal; it only costs metadata. |

A request with no `X-Device-Id` still works, but the customer loses the
session list, new-device alerts and one-tap revoke for that session.

## Tokens

| Token | Format | Lifetime | Notes |
|---|---|---|---|
| `access_token` | JWT RS256, `iss=https://auth.spoonity.com`, `aud=spoonity:<vendorId>` | 15 min (tenant-configurable 5 to 60) | Claims below |
| `refresh_token` | Opaque, 43-char base64url, stored only as a SHA-256 hash | 60 days sliding (1 to 180) | Single-use, rotating, device-bound, with reuse detection |
| `guest_token` | JWT RS256, `sub=guest:<uuid>`, `amr=["guest"]`, `acr=urn:spoonity:loa:0` | 24 h | Upgraded into a real session, never refreshed |
| `loyalty.session_key` | The loyalty platform's own session identifier | Loyalty platform rules | Passed through untouched; see [the loyalty bridge](#the-loyalty-bridge) |

Access-token claims:

```json
{
  "iss": "https://auth.spoonity.com",
  "aud": "spoonity:2111603",
  "sub": "sub_01J0000000000000000000",
  "iat": 1757700000,
  "exp": 1757700900,
  "jti": "…",
  "tid": "2111603",
  "did": "d6a0…",
  "sid": "ses_01J…",
  "amr": ["otp:sms"],
  "acr": "urn:spoonity:loa:1",
  "lid": 3487211,
  "spn": "eyJ…"
}
```

- `tid` tenant (vendor id) · `did` device · `sid` session row
- `amr` the method that opened this session: `otp:sms`, `otp:whatsapp`,
  `otp:email` (also used for a magic link), `passkey`, `social:apple`,
  `social:google`, `social:gcip`, or `deferred` on a POS token. A refresh
  keeps the session's original value.
- `acr` assurance: `urn:spoonity:loa:0` = guest; `urn:spoonity:loa:1` = one
  verified factor; `urn:spoonity:loa:2` = a passkey sign-in or a fresh OTP
  step-up
- `lid` loyalty user id, absent until the subject is linked
- `spn` encrypted offline claims; see [Offline claims](#offline-claims)

Verify tokens against `GET /.well-known/jwks.json`. It publishes the current
signing key first, followed by any previous keys, so a rotation keeps the old
key verifiable while tokens signed with it are still alive.

### The token response

Every endpoint that completes a sign-in returns the same envelope:

```json
{
  "token_type": "Bearer",
  "access_token": "…",
  "expires_in": 900,
  "refresh_token": "…",
  "refresh_expires_in": 5184000,
  "subject": {
    "id": "sub_01J…",
    "created_at": "2026-09-13T18:02:11Z",
    "identifiers": [
      { "id": "idn_…", "kind": "phone", "value_masked": "+1•••••••4242", "verified_at": "2026-09-13T18:02:11Z", "primary": true }
    ]
  },
  "loyalty": { "session_key": "…", "user_id": 3487211, "vendor_id": 2111603, "status": "linked" },
  "next": null
}
```

`loyalty.status` ∈ `linked | pending_email | claim_required | unavailable`.

`next` ∈ `null | collect_email | collect_profile | offer_passkey`, a hint for
progressive profiling. **The tokens are valid regardless of `next`**; it tells
the app what to ask for, not whether the customer is signed in.

When a guest token was presented, the response also carries
`"upgraded_from": "guest:<uuid>"`.

## Conventions

- JSON in and out, `application/json; charset=utf-8`. Request bodies are
  capped at 64 KB (`413 payload_too_large`).
- Errors are RFC 9457 problem details, served as
  `application/problem+json; charset=utf-8`:

  ```json
  {
    "type": "https://auth.spoonity.com/errors/code_invalid",
    "title": "Invalid code",
    "status": 400,
    "code": "code_invalid",
    "detail": "the code does not match",
    "attempts_remaining": 3,
    "instance": "0f1c…"
  }
  ```

  Branch on **`code`**, never on `title` or `detail`; those are prose and may
  be reworded. Some errors add machine-readable fields beside `code`, such as
  `attempts_remaining`, `required_acr`, `retry_after` or, on a validation
  failure, an `errors` array of `{ path, message }`. `instance` is the request
  id, also returned in the `X-Request-Id` response header; quote it in a
  support ticket.
- A body that fails validation, or is not JSON, is `400 invalid_request`. A
  missing, invalid or expired bearer token is `401 unauthorized`. An
  unknown route is `404 not_found`.
- Timestamps are ISO 8601 UTC. Durations are seconds.
- Phone numbers are normalized to E.164; emails are lower-cased and trimmed.
  Those normalized forms are the identity-stitching keys, so `+1 (613)
  555-4242` and `+16135554242` are the same person.
- `POST /v1/otp/start`, `POST /v1/deferred/init` and
  `POST /v1/deferred/upgrade` accept an `Idempotency-Key` header. A repeat
  with the same key while the earlier challenge or pairing is still live
  returns it instead of sending again.
- Rate limits answer `429 rate_limited` with `retry_after` in seconds, also
  sent as a `Retry-After` header.

## Client proof and abuse controls

Every endpoint that can make the engine send a message
(`POST /v1/otp/start`, `POST /v1/otp/resend`, `POST /v1/me/identifiers/start`
and `POST /v1/deferred/upgrade`) can additionally demand evidence that the
caller is the brand's real app or website:

```
X-Client-Proof: <type> <token>
```

| `type` | For | What it is |
|---|---|---|
| `app_check` | Apps | A Firebase App Check token |
| `turnstile` | Web | A Cloudflare Turnstile token |
| `recaptcha` | Web | A reCAPTCHA v3 token |

The tenant's `client_proof.mode` is `off` (the default), `monitor` (verify
and record, never block) or `enforce`. Under `enforce`, a missing or
unsupported proof is `403 client_proof_required` and one that fails
verification is `403 client_proof_invalid`; both carry `client_proof_reason`.
Separately, a tenant can restrict SMS and WhatsApp to a list of countries; a
number outside it is `403 destination_not_allowed`. These checks run before
any rate-limit counter moves, so a flood of rejected requests cannot lock a
real member out of their code.

## Assurance levels and step-up

Some operations can demand `urn:spoonity:loa:2`. Which ones is per tenant
(`session.step_up_for`, default `deferred_approve`, `identifier_change`,
`passkey_remove`). Today the engine enforces `deferred_approve` (approving a
POS pairing) and `passkey_remove`; `identifier_change` is accepted in the
configuration but not yet enforced. When the caller's token is not strong
enough the response is `403 step_up_required` carrying `required_acr`, and
the app either presents a passkey assertion inline or runs
`POST /v1/otp/start` with `purpose=step_up`, whose verify mints a new session
at `loa:2`.

---

# Consumer API (`/v1`)

## Guest sessions

### POST /v1/guest

Mint an anonymous token so a customer can build a cart before identifying
themselves.

**Auth:** none (tenant header only).

#### Example request

```bash
curl -X POST https://auth.spoonity.com/v1/guest \
  -H 'X-Spoonity-Vendor: 2111603' \
  -H 'X-Device-Id: 6f1d9b0e-7a1e-4f3b-9d2c-1a2b3c4d5e6f'
```

#### Example response

```json
{ "guest_token": "eyJ…", "expires_in": 86400, "guest_id": "guest:0b8e3c1a-…" }
```

`guest_id` is a fresh random UUID, not the device id. It is what an ordering
or cart system keys anonymous state on. `POST /v1/otp/start`,
`/v1/otp/verify`, `/v1/magic/consume`, `/v1/passkeys/authenticate/verify`,
`/v1/social/verify` and `/v1/deferred/upgrade` accept
`Authorization: Bearer <guest_token>`; when the sign-in completes, the token
response carries `"upgraded_from": "guest:<uuid>"` and a `guest_upgraded`
security event fires, so the cart can be merged by whichever system owns it.

#### Errors

| Status | Code | When |
|---|---|---|
| 400 | `tenant_required` | No `X-Spoonity-Vendor` header |
| 403 | `tenant_disabled` | Unknown vendor, or authentication is off for it |

---

## One-time codes

### POST /v1/otp/start

Send a one-time code over SMS, WhatsApp or email.

**Auth:** none, or a guest token to carry the guest id through the upgrade.
`purpose=link_identifier` and `purpose=step_up` require a member access
token (`401 unauthorized` otherwise).

#### Request body

| Field | Type | Required | Notes |
|---|---|---|---|
| `channel` | `sms` \| `whatsapp` \| `email` | yes | Must be enabled for the tenant |
| `destination` | string | yes | E.164 phone or email; normalized server-side |
| `purpose` | `login` \| `link_identifier` \| `step_up` \| `deferred_upgrade` | no | Defaults to `login` |
| `locale` | string | no | BCP 47, picks the message template; falls back to `X-Device-Info.locale` |
| `android_sms_hash` | string | no | The 11-character SMS Retriever hash for *this* build |

Optional headers: `Idempotency-Key`, `X-Client-Proof`.

#### Example request

```bash
curl -X POST https://auth.spoonity.com/v1/otp/start \
  -H 'X-Spoonity-Vendor: 2111603' \
  -H 'X-Device-Id: 6f1d9b0e-7a1e-4f3b-9d2c-1a2b3c4d5e6f' \
  -H 'Idempotency-Key: 5f2c8a90-1111-2222-3333-444455556666' \
  -H 'content-type: application/json' \
  -d '{"channel":"sms","destination":"+1 613 555 4242","purpose":"login","locale":"en-CA"}'
```

#### Example response

```json
{
  "challenge_id": "chl_01J…",
  "channel": "sms",
  "destination_masked": "+1•••••••4242",
  "code_length": 6,
  "expires_in": 300,
  "resend_after": 30,
  "magic_link": false,
  "delivery": "sent"
}
```

`delivery` ∈ `sent | queued | fallback_sms`. `magic_link` is `true` on email
when the message also carries a tap-to-sign-in link (on by default for
email).

The magic link is **not** a Links short code. It is
`<links.app_link_base>/auth/magic?t=<token>` when the tenant sets
`links.app_link_base` (the brand's own path on the shared Links host, for
example `https://x.spnty.co/pollo-campero`), and
`https://<links.domain>/auth/magic?t=<token>` otherwise. Set `app_link_base`
for every brand app: `links.domain` is claimed by all of them, so iOS hands
the link to whichever app claims it first, while `/<slug>/*` is claimed by one
app only. The app claims the URL, reads the token and calls
`POST /v1/magic/consume`. Opened anywhere else (desktop mail, no app, a mail
scanner's prefetch), Links forwards `/auth/magic` to the
[browser landing page](#get-v1magictoken), which never consumes the token.
Magic links are an email feature; SMS keeps OS one-time-code autofill.

**The response never contains the code.** Only a salted hash is stored, so it
cannot be read back by anyone, including Spoonity.

#### Autofill

Codes are delivered in the origin-bound format so **iOS AutoFill offers the
code automatically and Android's SMS Retriever reads it without the SMS
permission**:

```
<brand>: your sign-in code is 483920.

@links.spoonity.com #483920
```

The domain on that line is the tenant's links domain and must be in the app's
Associated Domains / `assetlinks.json`; for a brand already using universal
links, it is. Pass `android_sms_hash` and the Android one-tap line is
appended too.

**iOS exception.** For clients whose `X-Device-Info.platform` is `ios`, the
`@<links-domain> #<code>` line is left out and the SMS is the brand line
alone (plus the Android hash only if one was supplied, which iOS never does).
This applies to start, resend and the SMS sent when WhatsApp delivery falls
back. On iOS 27.0 the keyboard rejects every domain-bound code even when the
app's `webcredentials:` association is approved, so the binding blocked
AutoFill instead of scoping it; a plain code is offered by the keyboard's
ordinary SMS detection. The cost is that an iOS code is not scoped to the
brand's domain. Android and web are unchanged.

Apps should **auto-submit** as soon as `code_length` digits are present,
whether typed or autofilled. No "Continue" tap.

#### Rate limits

| Scope | Default |
|---|---|
| Per destination | 5 per 15 minutes |
| Per device | 10 per hour |
| Per IP | 30 per hour |

All tenant-configurable, and the per-device and per-IP limits can be set
separately for web clients. A trip returns `429 rate_limited` with
`retry_after`.

#### Errors

| Status | Code | When |
|---|---|---|
| 400 | `tenant_required` | Missing vendor header |
| 400 | `invalid_request` | Body failed validation, or the destination is not a parseable phone or email |
| 401 | `unauthorized` | `link_identifier` or `step_up` without a member access token |
| 403 | `method_disabled` | Channel not enabled for this tenant |
| 403 | `client_proof_required` / `client_proof_invalid` | Client proof enforced and missing or rejected |
| 403 | `destination_not_allowed` | Country not in the tenant's allow-list |
| 403 | `tenant_disabled` | Unknown or disabled tenant |
| 429 | `rate_limited` | Any limit above; `retry_after` in seconds |

---

### POST /v1/otp/verify

Exchange a code for tokens.

**Auth:** none, or a guest token to upgrade it.

#### Request body

| Field | Type | Required |
|---|---|---|
| `challenge_id` | string | yes |
| `code` | string | yes |

#### Example request

```bash
curl -X POST https://auth.spoonity.com/v1/otp/verify \
  -H 'X-Spoonity-Vendor: 2111603' \
  -H 'X-Device-Id: 6f1d9b0e-7a1e-4f3b-9d2c-1a2b3c4d5e6f' \
  -H 'content-type: application/json' \
  -d '{"challenge_id":"chl_01J…","code":"483920"}'
```

#### Example response

The [token response](#the-token-response). If the identifier is new for this
tenant a subject is created; if it matches an existing one,
[stitching](#identity-stitching) runs first.

#### Errors

| Status | Code | When |
|---|---|---|
| 400 | `code_invalid` | Wrong code; the body carries `attempts_remaining` |
| 403 | `forbidden` | The subject has been disabled by an operator |
| 404 | `challenge_not_found` | Unknown `challenge_id` |
| 410 | `challenge_expired` | Past the TTL (default 300 s) |
| 410 | `challenge_exhausted` | Out of attempts (default 5, tenant-configurable), or the challenge was already used |

---

### POST /v1/otp/resend

Send a fresh code to the same destination, optionally switching channel
(WhatsApp to SMS, say). Honours `resend_after` from the original start.

**Auth:** none. Body: `{ "challenge_id": "chl_…", "channel": "sms" }`
(`channel` optional). Returns the same shape as `/v1/otp/start`, with a
**new** `challenge_id`; the old challenge and its code stop working.

| Status | Code | When |
|---|---|---|
| 404 | `challenge_not_found` | Unknown `challenge_id` |
| 410 | `challenge_exhausted` | The original challenge was already used or replaced |
| 403 | `method_disabled` | The requested channel is not enabled |
| 403 | `client_proof_required` / `client_proof_invalid` / `destination_not_allowed` | As on `/v1/otp/start` |
| 429 | `rate_limited` | Called before `resend_after` elapsed, or a start limit tripped |

---

## Magic links

### GET /v1/magic/{token}

The browser landing page for a link tapped in an email. **HTML, never JSON,
and it never returns a token to a browser or completes the sign-in itself.**

When the browser carries an `spn_device` cookie equal to the `X-Device-Id`
that started the challenge, the page records the confirmation and tells the
customer to return to the app. Otherwise it renders the masked destination
and "open the app to finish". An unknown link renders a "this link is no
longer valid" page (404); an expired or already-used one renders a matching
page (410). The app finishes the sign-in with `POST /v1/magic/consume`.

**Auth:** none, and no vendor header. The token in the URL is the
credential; it is single-use and expires with the code it carries
(`min(otp.ttl_seconds, 15 minutes)`).

### POST /v1/magic/consume

What the **app** calls after a universal link opens it.

**Auth:** none (tenant header), or a guest token to upgrade. Body:
`{ "token": "…" }` → the [token response](#the-token-response).

| Status | Code | When |
|---|---|---|
| 403 | `challenge_mismatch` | The challenge was started by another device (`X-Device-Id`). The token is **not** spent, so the link still works on the right phone and the code still works anywhere |
| 404 | `challenge_not_found` | Unknown token, or a token issued for another tenant (not spent either) |
| 410 | `challenge_expired` | Past the code's expiry (`min(otp.ttl_seconds, 15 minutes)`) |
| 410 | `challenge_exhausted` | Already consumed |

The token is spent atomically, so concurrent taps spend it once. The tenant
check runs before the spend, so a request from another tenant cannot burn it.
The landing page only peeks at the token; the app's `consume` is what spends
it.

---

## Passkeys (WebAuthn / FIDO2)

Discoverable credentials with user verification required, so the customer
taps Face ID and is signed in, with no identifier typed at all. The four
ceremony endpoints use `@simplewebauthn/server`'s request and response
shapes.

The **RP ID** is per tenant (`methods.passkeys.rp_id`, default
`auth.spoonity.com`; a brand may use its own links domain). That host must
serve `apple-app-site-association` with a `webcredentials` entry and
`assetlinks.json` with `delegate_permission/common.get_login_creds` naming
the app. Accepted origins are `https://<rp_id>` plus one
`android:apk-key-hash:<hash>` per entry in
`methods.passkeys.android_apk_key_hashes`, and nothing else.

Passkeys are off by default (`methods.passkeys.enabled`); while off, the
ceremony endpoints answer `403 method_disabled`.

### POST /v1/passkeys/register/options

`PublicKeyCredentialCreationOptions` for a new credential
(`residentKey: required`, `userVerification: required`).

**Auth:** member access token.

### POST /v1/passkeys/register/verify

Verify the attestation and store the credential.

**Auth:** member access token. Body: `{ "credential": <attestation>, "nickname"?: "iPhone" }`

```json
{ "credential_id": "AbCd…", "created_at": "2026-09-13T18:40:02Z", "backed_up": true, "transports": ["internal","hybrid"] }
```

Emits a `credential_change` security event (`passkey_added`).

### POST /v1/passkeys/authenticate/options

`PublicKeyCredentialRequestOptions` with an **empty `allowCredentials`**, which
is what makes conditional UI ("passkey autofill") work.

**Auth:** none. Body: `{ "hint"?: "+16135554242" }`. `hint` is accepted but
ignored, so the response never reveals whether an identifier has a passkey.

### POST /v1/passkeys/authenticate/verify

**Auth:** none, or a guest token to upgrade. Body:
`{ "credential": <assertion> }` → the
[token response](#the-token-response) with `amr: ["passkey"]` and
`acr: urn:spoonity:loa:2`.

### GET /v1/passkeys

**Auth:** member access token. Returns `{ "passkeys": [ … ] }`, each with
`credential_id`, `nickname`, `backed_up`, `transports`, `created_at`,
`last_used`, `aaguid` and `device_type`.

### DELETE /v1/passkeys/{id}

**Auth:** member access token, and `acr loa:2` when the tenant lists
`passkey_remove` in `session.step_up_for` (the default). Answers `204`.
Emits `credential_change` (`passkey_removed`).

| Status | Code | When |
|---|---|---|
| 400 | `passkey_invalid` | Attestation/assertion failed verification |
| 400 | `challenge_mismatch` | No ceremony in flight for that challenge, or it expired or was used |
| 403 | `method_disabled` | Passkeys not enabled for this tenant |
| 403 | `step_up_required` | Tenant requires `loa:2`; carries `required_acr` |
| 404 | `passkey_not_found` | Unknown credential for this subject |
| 409 | `conflict` | The credential is already registered to another subject |

---

## Social identity

### POST /v1/social/verify

Sign in with Apple, Google, or a Google Cloud Identity Platform token.

**Auth:** none, or a guest token to upgrade.

#### Request body

| Field | Type | Required | Notes |
|---|---|---|---|
| `provider` | `apple` \| `google` \| `gcip` | yes | Must be enabled for the tenant |
| `id_token` | string | yes | Verified against the provider's JWKS |
| `nonce` | string | no | When sent, must match the token's nonce (raw, or its SHA-256 in hex or base64url) |
| `authorization_code` | string | no | Accepted for Apple; not used by the engine today |
| `user` | object | no | `{ "name": { "givenName", "familyName" } }`. **Apple returns the name only on the very first sign-in**, so send it through then or lose it |

`aud` must be one of the tenant's configured `client_ids` for that provider,
so list every client id (iOS, Android, web) that signs in. For `gcip` the
token is verified against the tenant's Identity Platform project, which keeps
Firebase Auth available for brands already using it, without making it
mandatory.

#### Example response

The [token response](#the-token-response), with `amr: ["social:apple"]`, plus:

```json
{ "social": { "provider": "apple", "subject_identifier": "000…", "email_verified": true, "relay": true, "linked": true } }
```

A verified email becomes an identifier and [stitching](#identity-stitching)
runs. Apple private-relay addresses are kept, flagged `relay: true`, and are
never auto-merged against a real address; they become a review candidate
instead.

| Status | Code | When |
|---|---|---|
| 400 | `social_invalid` | Signature, `aud`, or `exp` failed, or the token has no subject |
| 400 | `nonce_mismatch` | Nonce did not match |
| 403 | `method_disabled` | Provider not enabled, or no client ids configured for it |

---

## The signed-in subject

### GET /v1/me

**Auth:** member access token.

```json
{
  "subject": {
    "id": "sub_01J…",
    "created_at": "2026-09-13T18:02:11Z",
    "status": "active",
    "display_name": "Sam",
    "identifiers": [
      { "id": "idn_…", "kind": "phone", "value_masked": "+1•••••••4242", "verified_at": "…", "primary": true }
    ]
  },
  "loyalty": { "user_id": 3487211, "vendor_id": 2111603, "status": "linked" },
  "passkeys_count": 1,
  "acr": "urn:spoonity:loa:1",
  "amr": ["otp:sms"]
}
```

Identifiers are **always masked** on this endpoint.

### DELETE /v1/me

Member-initiated account deletion (App Store guideline 5.1.1(v)). Irreversible.

**Auth:** member access token.

#### Request body

```json
{ "confirm": "DELETE" }
```

Anything else is `400 confirmation_required` and changes nothing — a bare
`DELETE`, a retried request that lost its body, or a confused client can
never erase an account.

In order: loyalty-side deletion is requested (while a loyalty session is
still open); the member's Sign in with Apple tokens are revoked; every
session is revoked (closing each loyalty `session_key` it minted);
identifiers, passkeys, devices, OTP challenges and Apple tokens are erased;
the subject becomes a tombstone (`status: "disabled"`, `display_name: null`,
`deleted_at` set) so support can finish a `pending_support` loyalty deletion;
and `auth.event.account_deleted` plus an `audit_log` row are written. The
engine account is deleted whatever the loyalty and Apple outcomes are —
neither can fail the request.

#### Example response

```json
{
  "deleted": true,
  "subject_id": "sub_01J…",
  "sessions_revoked": 2,
  "loyalty": {
    "user_id": 3487211,
    "deletion": "confirmation_sent",
    "reason": null
  },
  "apple": { "revoke": "revoked" }
}
```

`loyalty.deletion` is `confirmation_sent` (loyalty-api emailed the member a
code; the app offers to finish with the anonymous
`DELETE /vendor/{vendorId}/customers { code, vendor }` call, exactly like the
password-era screen), `pending_support` (no deliverable loyalty email, or
loyalty-api failed — support completes it; `reason` ∈ `no_deliverable_email`
\| `no_api_key` \| `no_session` \| `request_failed`), or `not_linked`.
`apple.revoke` is `revoked`, `not_applicable` (no Apple identifier),
`skipped_no_key` (no `apple-signin-key` secret), `skipped_no_token` or
`failed` — best effort; it never fails the request.

The client must discard its tokens on `200`. A second call with the
(still-unexpired) access token answers `404 not_found`, as does `GET /v1/me`.

#### Errors

| Status | Code | When |
|---|---|---|
| 400 | `confirmation_required` | Body was not `{ "confirm": "DELETE" }` |
| 401 | `unauthorized` | Missing or invalid access token |
| 404 | `not_found` | Already deleted |

### POST /v1/me/identifiers/start

Add a second identifier, such as a phone on an email-only account. Same body
as `/v1/otp/start` without `purpose` (`link_identifier` is implied), and the
same response and errors, including client proof.

**Auth:** member access token.

### POST /v1/me/identifiers/verify

Same body as `/v1/otp/verify`. Attaches the identifier, emits
`credential_change` (`identifier_added`) and returns a fresh
[token response](#the-token-response). If the identifier already belongs to
another subject, [stitching](#identity-stitching) decides the outcome.

**Auth:** member access token.

### DELETE /v1/me/identifiers/{id}

Remove an identifier. Answers `204` and emits `credential_change`
(`identifier_removed`).

**Auth:** member access token. The `identifier_change` step-up setting is
not enforced here yet.

| Status | Code | When |
|---|---|---|
| 404 | `not_found` | Unknown identifier for this subject |
| 409 | `last_identifier` | Refuses to delete the only verified identifier, which would lock the customer out |

---

## Sessions, devices and tokens

### GET /v1/sessions

Every session of this subject as `{ "sessions": [ … ] }`. Each carries `id`,
`current` (true on the caller's own), `created_at`, `last_used`,
`expires_at`, `amr`, `acr`, `ip` and a `device` object (`id`, `platform`,
`model`, `os`, `app_version`, `trusted`, `last_seen`).

**Auth:** member access token.

### DELETE /v1/sessions/{id}

Revoke one session. Answers `204`; `404 not_found` for a session that is not
this subject's. **Auth:** member access token.

### POST /v1/sessions/revoke-all

Revoke every session. Keeps the caller's own unless
`{ "include_current": true }`. Returns `{ "revoked": <count> }`.

**Auth:** member access token.

### POST /v1/token/refresh

**Auth:** none; the refresh token *is* the credential. Body:
`{ "refresh_token": "…" }` → a fresh [token response](#the-token-response).
The session's expiry slides forward by the refresh lifetime.

Refresh tokens are **single-use and rotating**. Presenting the previous,
already-rotated token is treated as theft: the entire session is revoked, a
`refresh_reuse` security event fires, and the customer is signed out on that
device. Store the new `refresh_token` from every response and never retry a
refresh with the old one.

| Status | Code | When |
|---|---|---|
| 401 | `unauthorized` | Unknown, expired or revoked token, or a rotated token replayed (the session is then revoked); `detail` says which |
| 403 | `forbidden` | The subject has been disabled |

### POST /v1/token/revoke

**Auth:** none. Body `{ "refresh_token": "…" }`. Revokes the token and its
session and answers `204` whether or not the token existed. Call this on
sign-out.

### POST /v1/devices/push-token

Register where security alerts go. **Auth:** member access token, plus
`X-Device-Id` (`400 invalid_request` without it). Body:
`{ "fcm_token": "…", "platform": "ios" }` (`platform` optional; falls back
to `X-Device-Info`). Answers `204`.

### GET /v1/sec/revoke

The one-tap **"That wasn't me"** link from a security notification. Revokes
the named session, marks the device untrusted, renders a confirmation page. The page carries an "Open the app" button
(label: message template `revoke_page_open_app`, default "Open the app") that
only navigates to the app's `home` link; the revoke has already happened on the GET.

**Auth:** the single-use `token` query parameter, 7-day TTL; no vendor
header. HTML, not JSON. An unknown or used token renders a 404 page.

---

## POS and second-device pairing

The out-of-band flow, modelled on RFC 8628 device authorization. The terminal
never touches the customer's credential.

1. The terminal calls `POST /v1/deferred/init` and shows the QR code or the
   short `user_code`.
2. The customer scans it, which opens the brand app, or types the code on a
   signed-in web page.
3. The app calls `POST /v1/deferred/approve` after a biometric prompt.
4. The terminal's poll returns a POS-scoped token, exactly once.

The flow is on by default (`pos.deferred_enabled`); a tenant that turns it
off gets `403 method_disabled` from init and approve.

### POST /v1/deferred/init

**Auth:** none. Headers: tenant, plus `X-Client-Id: pos:<terminalId>` (or
`client_id` in the body; `400 invalid_request` when neither is sent). Body,
all optional: `{ "client_label": "Terminal 3, Bank St", "client_id": "pos:t3" }`.
Accepts `Idempotency-Key`.

```json
{
  "session_id": "dfr_01J…",
  "user_code": "482-913",
  "nonce": "…",
  "verification_uri": "https://links.spoonity.com/aB3dE",
  "qr_png_url": "https://links.spoonity.com/aB3dE/qr",
  "expires_in": 300,
  "interval": 2,
  "status": "authorization_pending"
}
```

`nonce` is the single-use value the approving app must echo back; it is
also embedded in the link. `verification_uri` is a Links short link when
Links is configured, and the engine's own `/v1/deferred/pair/{id}` URL
otherwise. A repeat with the same `Idempotency-Key` returns the live pairing
without a `nonce`.

### GET /v1/deferred/session/{id}/status

Poll. Supports **long-polling up to 20 seconds** with `?wait=20`; use it
rather than a tight loop. `interval` is the floor for plain polling.

**Auth:** none (the `session_id` is the secret).

`status` ∈ `authorization_pending | approved | denied | expired | consumed`.
Every response carries `session_id` and `client` (`{ "type": "pos", "label" }`);
a pending one also carries `interval` and `expires_in`.

The single `approved` response also carries:

```json
{
  "status": "approved",
  "session_id": "dfr_01J…",
  "client": { "type": "pos", "label": "Terminal 3, Bank St" },
  "tokens": {
    "token_type": "Bearer",
    "access_token": "…",
    "expires_in": 900,
    "subject": { "id": "sub_01J…" },
    "loyalty": { "session_key": "…", "user_id": 3487211, "vendor_id": 2111603, "status": "linked" },
    "member": { "display_name": "Sam", "tier": "gold", "points_balance": 1250, "user_id": 3487211 }
  }
}
```

That access token has `aud: spoonity:<vendor>:pos`, `amr: ["deferred"]`, a
`cid` claim naming the terminal, and **no refresh token**. `member` is for the
cashier's screen. Later polls return `"status": "consumed"`; the tokens are
returned exactly once.

| Status | Code | When |
|---|---|---|
| 404 | `deferred_not_found` | Unknown `session_id` |

### POST /v1/deferred/approve

**Auth:** member access token, at `acr loa:2` when the tenant lists
`deferred_approve` in `session.step_up_for` (the default). The app performs a
local biometric prompt and, when the device has a passkey, includes a fresh
assertion in `assertion`; otherwise step up through `POST /v1/otp/start`
with `purpose=step_up` first.

Body: `{ "session_id": "dfr_…", "nonce": "…", "assertion"?: {…} }` →
`{ "status": "approved", "client": { "type": "pos", "label": "Terminal 3, Bank St" } }`

Emits a `deferred_approved` security event.

### POST /v1/deferred/deny

Body `{ "session_id" }` → `{ "status": "denied" }`. **Auth:** member access
token.

### POST /v1/deferred/code

The web fallback: a signed-in web session submits the typed `user_code`
(`{ "user_code": "482-913", "assertion"?: {…} }`; digits only are fine). No
nonce is needed. Same result and step-up rule as approve, plus `session_id`.
**Auth:** member access token.

### POST /v1/deferred/upgrade

Guest to member convenience wrapper. Same body as `/v1/otp/start` without
`purpose`, called with the guest token; sets `purpose=deferred_upgrade` and
returns the start result plus `guest_id`. Accepts `Idempotency-Key` and
`X-Client-Proof`, with the same errors as `/v1/otp/start`.

**Auth:** none, or a guest token.

### GET /v1/deferred/pair/{id}

HTML landing page for the pairing link when the app is **not** installed.
Shows the `user_code`, approves nothing, never returns a token. No vendor
header. An unknown id renders a 404 page; a pairing that is no longer
pending renders a 410 page.

Errors across the pairing endpoints:

| Status | Code | When |
|---|---|---|
| 400 | `invalid_request` | Missing `X-Client-Id`, nonce does not match, or a malformed `user_code` |
| 403 | `method_disabled` | Pairing is turned off for this tenant |
| 403 | `step_up_required` | Approving needs `loa:2`; carries `required_acr` |
| 404 | `deferred_not_found` | Unknown `session_id`, or no pending pairing for that `user_code` |
| 409 | `deferred_consumed` | Tokens already collected |
| 409 | `deferred_denied` | The customer declined |
| 409 | `conflict` | Already approved |
| 410 | `deferred_expired` | Past the 300-second window |

---

## Offline claims

Access tokens carry `spn`: `{ "uid", "tier", "bal", "iat" }` encrypted with
the tenant's offline key (JWE, `dir` + A256GCM). It is present only when the
tenant has an `offline-key` secret. A POS that is offline can render and
trust a member's barcode from it; when connectivity returns it can confirm.

### POST /v1/offline/verify

**Auth:** none (tenant header). Body `{ "spn": "…", "ts": 1757700000, "hmac": "<hex>" }`, where `hmac` is
`HMAC-SHA256(offline key, "<spn>|<ts>")` and `ts` is unix seconds accepted
within ±60 s.

```json
{ "valid": true, "uid": 3487211, "tier": "gold", "bal": 1250, "iat": 1757700000, "age_seconds": 42 }
```

| Status | Code | When |
|---|---|---|
| 400 | `offline_invalid` | Bad HMAC, skewed `ts`, or undecryptable `spn` |
| 403 | `method_disabled` | The tenant has no offline key |

---

## The loyalty bridge

### POST /v1/loyalty/session

Re-mint `loyalty.session_key` when the loyalty API answers 401.

**Auth:** member access token. →
`{ "loyalty": { "session_key": "…", "user_id": 3487211, "vendor_id": 2111603, "status": "linked" }, "next": null }`

Loyalty sessions never expire on their own, so **every** revocation here (by
the customer, an operator, the "not me" link, or refresh-reuse detection)
also closes the loyalty session it minted, on a best-effort basis.

`status` values worth handling:

| Status | Meaning | What the app should do |
|---|---|---|
| `linked` | Fully linked | Nothing |
| `pending_email` | Phone-only subject, tenant requires an email | Collect one (`next: "collect_email"`) |
| `claim_required` | The email already belongs to a password-era member | Follow the tenant's claim flow |
| `unavailable` | The loyalty platform did not answer | Retry later; the sign-in itself is still valid |

---

# Admin API (`/admin/v1`)

**Not an integration surface.** These endpoints exist for the Prism operator
console and are reachable only by Spoonity's own service identities. They are
documented here because the Identity section of Prism is a thin UI over them,
so knowing the shapes explains what an operator can and cannot see.

**Auth:** a Google-signed OIDC ID token for an allowlisted service account
(`aud` = the engine's own origin, or another configured audience), plus:

| Header | Meaning |
|---|---|
| `X-Spoonity-Vendor` | The tenant being administered; must match `{vendor}` in the path |
| `X-Spoonity-User` | The operator's email, recorded in the audit log |
| `X-Spoonity-Role` | The operator's role for that vendor |

`admin` is required for writes; `editor` may read and send test messages. A
missing or unrecognized role is treated as `viewer`, which may do neither.
Every write lands in the audit log with the forwarded operator email.

## Configuration

| Endpoint | Purpose |
|---|---|
| `GET /admin/v1/tenants/{vendor}/config` | The stored configuration, the `resolved` configuration with platform defaults applied, and its `config_version` (also the `ETag`) |
| `PUT /admin/v1/tenants/{vendor}/config` | Replace the stored configuration, with an optional `If-Match: <config_version>` |
| `GET /admin/v1/tenants/{vendor}/config/schema` | The JSON Schema the form is generated from |
| `POST /admin/v1/tenants/{vendor}/config/test-delivery` | `{ channel, destination, locale? }`: send a real test message, with a throwaway code, through the tenant's own gateway |
| `GET /admin/v1/tenants/{vendor}/readiness` | Per-channel delivery readiness — never a secret value |

`PUT` is optimistic-concurrency controlled: a stale `If-Match` gets
`412 precondition_failed` (carrying the current `config_version`) rather than
silently clobbering another operator's edit. A document that fails the schema
is `400 config_invalid` with an `errors` array. The body must be a JSON
object sent as `Content-Type: application/json` (either the document itself
or `{ "config": … }`); anything the JSON parser did not read, such as a
mangled `Content-Type` header, is `400 invalid_request` and **nothing is
stored**. Previously such a body was stored as `{}` and reset the tenant to
engine defaults.

Two optional settings were added (`a449ef2`):

| Path | Type | Rule |
|---|---|---|
| `loyalty.api_url` | string \| null | The vendor's own loyalty-api origin, e.g. `https://api-pollocampero.spoonity.com`. Must match `^https://([a-z0-9-]+\.)*spoonity\.com/?$` (https, `*.spoonity.com`, no path); re-validated at runtime. `null` (default) = the shared `LOYALTY_API_URL`. Every loyalty call for the tenant goes there: deferred register/authenticate, email lookup, profile, logout, account deletion and the `loyalty-sms` adapter. Its `loyalty-apikey` must be a role-7 (`BACKOFFICE_ONSCREEN`) key for that host |
| `links.app_link_base` | string \| null | The brand's own path on the shared Links host, e.g. `https://x.spnty.co/pollo-campero`. Must match `^https://([a-z0-9-]+\.)*(spnty\.co\|spoonity\.com)/[a-z0-9][a-z0-9-]*/?$` (https host under `spnty.co` or `spoonity.com`, then exactly one slug segment). `null` (default) keeps `https://<links.domain>`. See [magic links](#magic-links) |

`GET …/readiness` answers roles `admin`, `editor` and `viewer`:

```json
{
  "methods": {
    "sms": { "enabled": true, "ready": true, "adapter": "sns", "issues": [] },
    "email": { "enabled": true, "ready": false, "adapter": "ses", "issues": ["sender_missing"] },
    "whatsapp": {
      "enabled": false,
      "ready": false,
      "adapter": "meta-whatsapp",
      "issues": ["secret_missing", "no_allowed_countries"],
      "meta": null
    }
  }
}
```

`ready` is `enabled` and no blocking issue. Blocking: `secret_missing` (the
adapter's gateway secret — `gateway-sns`, `loyalty-apikey` for
`loyalty-sms`, `gateway-ses`, `gateway-meta-whatsapp` — is not stored),
`secret_invalid` (stored but unusable), `sender_missing` (email via `ses`
with no `from`). Warnings: `console_adapter` (the channel only logs);
WhatsApp only: `sms_fallback_unavailable` (SMS disabled or not ready),
`no_allowed_countries` (empty `whatsapp_allowed_countries` — unrestricted),
`webhook_not_configured` (no status webhook can be verified: neither the
tenant secret nor the platform Meta app `auth-meta-app` has an `app_secret`),
`late_fallback_unavailable` (no `OTP_FALLBACK_KEY`: a failure Meta reports
after the start call is not answered by SMS). Issues are reported whether or
not the channel is enabled.

WhatsApp's entry always carries `meta`: `null` when not checked (disabled, or
no valid secret) or unknown, else
`{ "can_send_message": "AVAILABLE" | "LIMITED" | "BLOCKED", "errors": [{ "entity_type", "error_code", "error_description" }] }`
from Meta's own `GET /{phone_number_id}?fields=health_status` (3 s timeout,
cached 5 minutes per tenant). `template_missing` (the configured template does not exist on the WABA) and
`template_not_approved` (it has no approved version) are blocking too; both need
`waba_id` in the secret. `meta_blocked` is blocking (Meta will not
deliver — e.g. a broken WABA payment method, where a send still answers `200`
and is dropped); `meta_limited` and `meta_health_unknown` (the check failed
or timed out; the route itself never fails) are warnings. Calling/SIP errors
are removed from `errors` and never affect `can_send_message`.

Configuration covers which methods are enabled and their adapters, OTP length
and TTLs, session and refresh lifetimes, risk rules, rate limits, client
proof and destination allow-lists, the loyalty linking policy, stitching
behaviour, security-notification channels, the links domain and app schemes,
per-locale message templates, POS policy, and the optional CMS message
overlay. **Secrets are never in this document.**

## Secrets

| Endpoint | Purpose |
|---|---|
| `GET /admin/v1/tenants/{vendor}/secrets/{name}` | Metadata only (version id and timestamps), **never the value** |
| `PUT /admin/v1/tenants/{vendor}/secrets/{name}` | Store a new version: `{ "value": "…" }` |
| `DELETE /admin/v1/tenants/{vendor}/secrets/{name}` | Remove it (`204`) |

`name` ∈ `loyalty-apikey`, `gateway-sns`, `gateway-meta-whatsapp`,
`gateway-ses`, `fcm-service-account`, `offline-key`, `client-proof-turnstile`,
`client-proof-recaptcha`, `apple-signin-key`; any other name is
`404 not_found`. Values go to Secret Manager; only the version id is recorded
in the database. There is no endpoint anywhere in this service that reads a
secret value back.

`apple-signin-key` is JSON `{ "team_id", "key_id", "private_key_p8" }` — the
10-character Apple team id, the 10-character key id, and the `.p8` PEM Apple
issued (EC P-256) — used to sign the `client_secret` Sign in with Apple's
token and revoke endpoints expect. Without it, Apple sign-ins still verify,
but token exchange is skipped and [account deletion](#delete-v1me) cannot
revoke the member's Apple tokens (`apple.revoke: "skipped_no_key"`).

## Subjects

| Endpoint | Purpose |
|---|---|
| `GET /admin/v1/tenants/{vendor}/subjects?q=&cursor=&limit=` | Search by phone, email or id. **Identifiers come back masked** |
| `GET /admin/v1/tenants/{vendor}/subjects/{id}` | One subject with identifiers, passkeys, devices, sessions, loyalty link and recent events |
| `POST …/subjects/{id}/sessions/revoke-all` | Sign the customer out everywhere |
| `DELETE …/subjects/{id}/sessions/{sid}` | Revoke one session |
| `DELETE …/subjects/{id}/passkeys/{cid}` | Remove a passkey on the customer's behalf |
| `POST …/subjects/{id}/disable` | Disable the subject and revoke its sessions |
| `POST …/subjects/{id}/enable` | Re-enable |

## Review, feed and reporting

| Endpoint | Purpose |
|---|---|
| `GET …/merge-candidates?resolved=&limit=` | The stitching review queue |
| `POST …/merge-candidates/{id}/merge` | Merge the two subjects; optional `{ "survivor": "a" \| "b" }`, otherwise the older subject survives |
| `POST …/merge-candidates/{id}/dismiss` | Dismiss the candidate |
| `GET …/events?type=&subject_id=&since=&cursor=&limit=` | Security event feed |
| `GET …/events/{id}` | One event |
| `GET …/stats?range=7d` | `7d` or `30d`: sign-ins by method and day, OTP conversion, delivery failures, active sessions, new devices, pairing approvals and abuse-control counters |
| `GET …/deferred?status=&limit=` | Live POS pairings; `status=authorization_pending` excludes pairings past `expires_at`, `status=expired` includes them, and a lapsed row now reports `expired` rather than `authorization_pending` |
| `DELETE …/deferred/{id}` | Delete a pairing |
| `GET …/audit?cursor=&limit=` | Admin audit log, newest first (`at` descending, ties by `id` descending; it was sorted by id string before) |

List endpoints page by cursor: pass the previous page's `next_cursor`, which
is `null` on the last page. The audit cursor is the last row's `id` and pages on `(at, id)`; it keeps the same shape.

---

## OpenID Connect clients

Per-tenant registry of the partner applications allowed to sign a member in
through the [OpenID Connect provider](#openid-connect-partners). Prism's
**Applications** page (`/identity/applications`) is the UI. Registering clients
works whether or not `oidc.enabled` is on. `GET` needs `admin` or `editor`;
every write needs `admin`.

| Endpoint | Returns |
|---|---|
| `GET /admin/v1/tenants/{vendor}/oidc/clients` | `{ oidc: { enabled, issuer, discovery_url, ready, issues[] }, clients[] }`, newest first, at most 50 |
| `POST /admin/v1/tenants/{vendor}/oidc/clients` | `201`: the client plus `client_secret` (confidential only, **shown once**) |
| `GET /admin/v1/tenants/{vendor}/oidc/clients/{client_id}` | `200`: the client |
| `PATCH /admin/v1/tenants/{vendor}/oidc/clients/{client_id}` | `200`: any of `name`, `redirect_uris`, `post_logout_redirect_uris`, `scopes`, `logo_url`, `enabled`. `type` and `token_endpoint_auth_method` are immutable. Optional `If-Match: <version>` (`412` on mismatch) |
| `DELETE /admin/v1/tenants/{vendor}/oidc/clients/{client_id}` | `204`: soft delete; revokes every grant; the `client_id` is never reused |
| `POST /admin/v1/tenants/{vendor}/oidc/clients/{client_id}/secret` | `200`: rotation. Body `{ grace_period_seconds }` (0–604800, default 0). Returns the client plus the new `client_secret` (shown once) |
| `POST /admin/v1/tenants/{vendor}/oidc/clients/{client_id}/revoke-grants` | `200 { "revoked": n }`: every member session this client holds |

A client has `client_id` (`cli_…`), `name`, `type` (`confidential` or
`public`), `token_endpoint_auth_method`, `redirect_uris`,
`post_logout_redirect_uris`, `scopes`, `logo_url`, `enabled`, `secret`
(`{ hint, created_at, previous_expires_at }` or `null`), `version` and the
created/updated stamps. Redirect URIs must be `https:` (or `http:` on
`localhost`, `127.0.0.1`, `[::1]`), with no fragment, userinfo or `*`, and are
matched exactly.

**Show-once secrets.** The plaintext `client_secret` exists in exactly two
responses, the create and the rotation. The engine stores only its SHA-256 and
the last four characters (`secret.hint`). The Prism BFF passes those two
responses through to the requesting operator and strips any `client_secret`
key from every other admin response, so it can never be read back. A lost
secret is replaced by rotating.

The tenant switch is `oidc.enabled` in the config document
(`PUT /admin/v1/tenants/{vendor}/config`). The engine refuses to turn it on
(`400 config_invalid`, path `/oidc/enabled`) unless web `client_proof.mode` is
`enforce`, `turnstile` is an accepted web proof and `oidc.turnstile_site_key`
is set.

# Identity stitching

Stitching runs only when an identifier is **verified by a signed-in member
adding it to their own account**: `purpose=link_identifier`
(`/v1/me/identifiers/*`), or an identity provider's own proof that a provider
identity carries a verified email. A plain sign-in (`/v1/otp/verify` with
`purpose=login` or `deferred_upgrade`, `/v1/magic/consume`, `/v1/social/verify`)
that happens to carry another member's access token is an **account switch**:
the caller signs in as the identifier's owner, and nothing is merged or
recorded. A code proves control of that one identifier, not that its owner and
the token's subject are one person. Only the `link_identifier` flow, then,
produces merges or merge candidates, so the review queue in Prism is not
populated by ordinary sign-ins. When it runs, the engine checks whether the
identifier already belongs to somebody:

1. **Exact match on a verified identifier** owned by another active subject:
   if the tenant allows auto-merge (`stitching.auto_merge_verified`, default
   on) the two subjects merge. The **older** subject survives; sessions,
   passkeys, devices and identifiers move to it; the other is marked
   `merged`. A `credential_change` event fires with `change: "merged"`.
2. **Anything weaker** (an unverified match, an Apple relay address against a
   real one, a loyalty email match) creates a **merge candidate** for an
   operator to review in Prism rather than merging automatically.

Reasons you will see: `verified_identifier_conflict`, `same_email_unverified`,
`apple_relay_vs_email`, `loyalty_email_match`.

**The loyalty platform has no account-merge API**, so the engine never
deletes or alters anything on that side. The surviving subject keeps the
loyalty user that was linked first, and the other loyalty user id is
recorded on the merge candidate for support follow-up.

---

# Security events

Published to Pub/Sub, consumed by the engine's own notification workers, and
surfaced in Prism's Identity feed. On the wire and in the admin feed each
type carries an `auth.event.` prefix (`auth.event.new_device_login`); the
feed's `type` filter accepts either form.

| Type | Fires when |
|---|---|
| `new_device_login` | A sign-in from a device not seen before |
| `credential_change` | `passkey_added`, `passkey_removed`, `identifier_added`, `identifier_removed`, `social_linked`, `merged` |
| `deferred_approved` | A POS pairing was approved |
| `session_revoked` | Any revocation |
| `refresh_reuse` | A rotated refresh token was presented again |
| `guest_upgraded` | A guest became a member; the cue to merge a cart |
| `high_value_redemption` | A loyalty redemption at or above the tenant's `security.high_value_points` (default 5000), reported by the loyalty platform |
| `client_proof_failed` | A client proof arrived and was rejected (in `monitor` or `enforce`) |
| `account_deleted` | A member finished [`DELETE /v1/me`](#delete-v1me); notifies nobody — there is nobody left to notify |
| `whatsapp_failed` | Meta accepted a WhatsApp OTP send and then reported it undelivered on the status webhook (a *late* fallback, distinct from a send Meta rejects outright); notifies nobody. `payload`: `challenge_id`, `provider_message_id`, `destination_masked`, `fallback` (`sms` \| `unavailable` \| `error`), `sms_adapter`, and Meta's `errors[]` |

`otp_abuse` is reserved in the event vocabulary but no code path emits it
today; OTP rate-limit trips show up as `429` responses and in the stats
abuse counters.

Each event carries the device (model, OS, app version, IP, approximate
location) and, where relevant, a one-tap `revoke_url`. For
`new_device_login`, `credential_change`, `deferred_approved`,
`refresh_reuse` and `high_value_redemption`, notifications go by push to the
subject's **other** trusted devices, and by email or SMS for
`new_device_login` and `credential_change`, subject to the tenant's
`security.notify_channels`.

---

# OpenID Connect (partners)

A partner site (an ordering partner, a POS vendor portal, a franchisee's own
site) can sign a loyalty member in with a standard OpenID Connect library
without ever seeing the member's credentials or phone number. First-party
merchant sites do not use this; they use the native API above.

**Switched on per tenant, and not generally available.** Every tenant has its
own issuer; a tenant that has not enabled it answers `404` for everything
under `/oidc/{vendor}`.

| | |
|---|---|
| Issuer | `https://auth.spoonity.com/oidc/{vendor}` |
| Discovery | `{issuer}/.well-known/openid-configuration` |
| JWKS | `{issuer}/jwks` |
| Flow | Authorization code with PKCE (`S256`, required for public clients); refresh tokens with `offline_access` |
| Client authentication | `client_secret_basic` or `client_secret_post` (confidential), `none` (public) |

The root `/.well-known/openid-configuration` described below is **not** this
document: it stays informational. Always discover from the tenant's issuer.

**Scopes and claims.** `openid` returns `sub` (the engine subject id, which
changes if the member's accounts are merged). `email` adds `email` and
`email_verified`; `phone` adds `phone_number` and `phone_number_verified`;
`profile` releases nothing today; `offline_access` issues a refresh token. Only
verified identifiers are released. Loyalty data and `loyalty.session_key` are
never released.

**How to register a client.** Spoonity staff register it for you in Prism,
under *Identity → Applications*: give it a name, choose confidential or public,
list the exact redirect URIs and pick the scopes. For a confidential client
Prism shows the client secret once; store it immediately. To replace a secret
(planned rotation with a grace period, or immediately when leaked) staff rotate
it. A client can be disabled without losing its grants, or deleted.

# Discovery and operations

| Endpoint | Returns |
|---|---|
| `GET /.well-known/openid-configuration` | Issuer, `jwks_uri`, signing algorithm, the `amr`, `acr` and claims vocabulary, and a `service_documentation` link to `/openapi.json` |
| `GET /.well-known/jwks.json` | The current signing key first, then any previous keys |
| `GET /openapi.json` | This service's OpenAPI 3.1 document |
| `GET /health` | `{ "status": "ok", "version": "<revision>", "storage": "postgres" }` |
| `GET /ready` | `{ "ready": true, "storage": "postgres", "version": "<revision>" }`; 503 when not serving |

The discovery document is informational metadata, not OAuth 2.0
authorization-server metadata: it advertises no authorization, token or
userinfo endpoint for standard OIDC clients. Use the native API described in
this document.

`POST /internal/pubsub/push` and `POST /internal/events/ingest` exist for
Spoonity's own infrastructure and are not callable by integrators.

---

# Error codes

Every error is RFC 9457 problem detail; branch on `code`.

| Code | Status | Meaning |
|---|---|---|
| `invalid_request` | 400 | Body failed validation or is not JSON, a destination is not a phone or email, or another malformed input |
| `tenant_required` | 400 | No `X-Spoonity-Vendor` header |
| `unauthorized` | 401 | Missing, invalid or expired bearer token; a guest token where a member token is required; or a bad refresh token |
| `forbidden` | 403 | Disabled subject, or an admin caller without the needed role |
| `tenant_disabled` | 403 | Unknown vendor, or authentication is off for it |
| `method_disabled` | 403 | That channel, provider, passkeys, pairing or offline claims are not enabled for the tenant |
| `client_proof_required` | 403 | Client proof enforced and none (or an unsupported type) was sent |
| `client_proof_invalid` | 403 | Client proof enforced and it failed verification |
| `destination_not_allowed` | 403 | The destination's country is not allowed for that channel |
| `step_up_required` | 403 | Needs `loa:2`; carries `required_acr` |
| `not_found` | 404 | Unknown route, session, identifier, subject or secret name |
| `code_invalid` | 400 | Wrong one-time code; carries `attempts_remaining` |
| `challenge_not_found` | 404 | Unknown challenge or magic link |
| `challenge_expired` | 410 | Code or magic link past its TTL |
| `challenge_exhausted` | 410 | Too many wrong attempts, or the challenge was already used |
| `challenge_mismatch` | 400 | No passkey ceremony is in flight for that challenge |
| `passkey_invalid` | 400 | Attestation or assertion failed verification |
| `passkey_not_found` | 404 | Unknown credential |
| `social_invalid` | 400 | Provider token failed verification |
| `nonce_mismatch` | 400 | Nonce did not match |
| `deferred_not_found` | 404 | Unknown pairing |
| `deferred_expired` | 410 | Pairing window elapsed |
| `deferred_consumed` | 409 | Pairing tokens already collected |
| `deferred_denied` | 409 | Customer declined |
| `conflict` | 409 | Pairing already approved, passkey registered elsewhere, or merge candidate already resolved |
| `last_identifier` | 409 | Refuses to remove the only verified identifier |
| `offline_invalid` | 400 | Bad offline HMAC or claims |
| `config_invalid` | 400 | A tenant configuration failed schema validation |
| `invalid_request` | 400 | `PUT …/config` with a body that was not parsed as a JSON object (wrong or mangled `Content-Type`) |
| `precondition_failed` | 412 | Stale `If-Match` on a config write |
| `payload_too_large` | 413 | Request body over 64 KB |
| `rate_limited` | 429 | Carries `retry_after` |
| `internal_error` | 500 | Unexpected failure; quote `instance` |

---

# Integration checklist

1. Get your `spoonityVendorId` and have Spoonity enable the tenant.
2. Decide which methods to turn on. SMS and email are the usual starting pair;
   passkeys are worth adding early because they remove the code round-trip
   entirely.
3. Mint and persist an `X-Device-Id` per install, and send `X-Device-Info`
   with the right `platform`.
4. Implement `POST /v1/guest` first if you have a cart before sign-in.
5. Wire OTP start/verify, and **auto-submit at `code_length` digits**.
6. Store `refresh_token` from every response, and treat a `401` from
   `/v1/token/refresh` as a forced sign-out rather than a retryable error.
7. Keep calling the loyalty API with `loyalty.session_key` exactly as before.
8. If the tenant will turn on client proof, send `X-Client-Proof` from the
   start so a `monitor` rollout shows your traffic as passing.
9. For passkeys, add the `webcredentials` and `get_login_creds` entries on the
   RP ID host before testing; a mismatch there is the single most common
   cause of a passkey that registers but will not authenticate.

# See also

- [Authentication](/docs/authentication): how *your backend* authenticates to
  Spoonity APIs, which is a different question from this page
- [Conventions](/docs/conventions): cross-service rules
- [Links](/docs/links): the short-link and deep-link service behind magic
  links, pairing QR codes and one-tap revoke URLs
- [/docs/openapi/auth.yaml](/docs/openapi/auth.yaml): the machine-readable spec
