# Aylla Vault API — v1 reference

For the **mobile/hybrid app** and the **website**. (The owner console and the institution portal have their own docs: `ADMIN_CONSOLE_API.md`, `INSTITUTION_PORTAL_API.md`.)

- Base URL (live test server): `https://ayllaapi.immidots.com/api/v1`
- Base URL (local, if you run it yourself): `http://127.0.0.1:8000/api/v1`
- Health check: `GET /health` → `{"status":"ok"}`
- Import `docs/aylla-vault.postman_collection.json` into Postman to try every endpoint (it saves your tokens automatically).

> **Read section 3 (Authentication) first.** Almost every integration problem comes from token handling.

---

## 1. Quick start

```bash
# 1. Sign in
curl -X POST $BASE/auth/login -H 'Content-Type: application/json' \
  -d '{"email":"alex@aylla.test","credential":"Aylla#Test2026","deviceInfo":{"deviceName":"iPhone 15","deviceType":"ios"}}'

# 2. Call any endpoint with the access token
curl $BASE/cards -H "Authorization: Bearer <accessToken>"
```

Test account (local / staging only, the seeder refuses to run in production):

| Role | Email | Password |
|---|---|---|
| user | `alex@aylla.test` | `Aylla#Test2026` |

---

## 2. Conventions

| Topic | Rule |
|---|---|
| Format | JSON in, JSON out. Send `Content-Type: application/json` (`multipart/form-data` for file uploads). The API always answers JSON, even if you omit `Accept`. |
| Keys | **camelCase** everywhere (`fullName`, `documentTypeId`). |
| Dates | ISO-8601, UTC (`2026-09-29T15:09:39+00:00`). Date-only fields use `YYYY-MM-DD` (`dob`). |
| IDs | Opaque **prefixed strings**: `usr_…`, `dev_…`, `card_…`, `pf_…` (card field), `att_…`, `sh_…`, `req_…`, `ntf_…`. Never parse them, never assume length. |
| Document type IDs | Stable codes such as `AU_PASSPORT`, `AU_DRIVER_LICENCE` (see `GET /schemes`). |
| Lists | Plain JSON arrays for the app endpoints. |
| Empty values | Missing optional values come back as `null`. |
| Money / numbers | Points are integers. |

### Errors

Every error uses one envelope. **Branch on `code`, show `message`, map `errors` onto form fields.**

```json
{
  "status": "error",
  "code": "validation_failed",
  "message": "The given data was invalid.",
  "errors": { "email": ["The email has already been taken."] }
}
```

| HTTP | `code` | Meaning / what the client should do |
|---|---|---|
| 401 | `unauthenticated` | Access token missing, invalid **or expired** → call `/auth/refresh` once, retry, else go to sign-in. |
| 401 | `session_revoked` | This device was revoked → sign out locally. |
| 401 | `invalid_credentials` | Wrong email / password / PIN (deliberately identical for unknown emails). |
| 401 | `refresh_token_missing` · `refresh_token_invalid` | Refresh token absent, expired (7 days) or unknown → sign in again. |
| 401 | `refresh_token_reused` | An old refresh token was replayed (possible theft). The device session is killed → sign in again. |
| 403 | `forbidden` | Your role may not do this. |
| 403 | `account_suspended` | Account suspended by an admin. |
| 404 | `not_found` | Unknown route, or a resource that is not yours (ids of other users' data are not confirmable). |
| 409 | `duplicate` · `request_not_pending` · `request_not_fulfilled` · `request_closed` | State conflict. |
| 410 | `share_revoked` · `share_paused` · `share_expired` · `share_exhausted` · `request_overdue` | Gone. |
| 422 | `validation_failed` · `missing_required_fields` · `attachment_limit` | Fix the input (`errors` explains). |
| 423 | `share_locked` | Too many wrong passcodes on a share link. |
| 429 | `too_many_requests` | Rate limited. Read the `Retry-After` header (seconds). |
| 501 | `not_implemented` | Feature not enabled yet (biometric login). |
| 502 | `ai_upstream_error` | Google AI call failed; retry or fall back. |
| 503 | `ai_not_configured` | Voice / OCR not configured on this server. |

### Rate limits

| Scope | Limit |
|---|---|
| Default (per signed-in user, else per IP) | 100 / minute |
| `register`, `login`, `PUT /auth/pin`, `PUT /auth/password` | **5 / minute** per email + IP |
| `POST /auth/refresh` | 30 / minute per IP |
| Public share view / unlock | 30 / minute per IP · **5 / minute** per share + IP |
| `voice/query`, `cards/ocr-scan` | 20 / minute |
| Attachment upload | 30 / minute |

Responses carry `X-RateLimit-Limit`, `X-RateLimit-Remaining` and, when limited, `Retry-After`.

### CORS

Browsers may only call the API from origins listed in the server's `CORS_ALLOWED_ORIGINS`. Tell the backend the exact origin(s) of the website / app WebView (e.g. `https://app.aylla.com`). Native (non-browser) HTTP clients are not affected.

---

## 3. Authentication (read this)

The API uses **two tokens per device**:

| Token | Lifetime | Where it goes | Purpose |
|---|---|---|---|
| **accessToken** | **15 minutes** | `Authorization: Bearer <accessToken>` on every call | Proves who you are. Short-lived so a stolen token is nearly useless. |
| **refreshToken** | **7 days**, rotated on every use | Only ever sent to `POST /auth/refresh` | Silently gets a new access token so the user is **not** logged out every 15 minutes. |

The user stays signed in as long as they open the app at least once every 7 days. They are signed out when: they tap Logout, the refresh token is 7+ days unused, they (or an admin) revoke the device, or a refresh token is replayed.

### Flow

```
login/register ──► accessToken (15 min) + refreshToken (7 d)
      │
      ├─ every API call:  Authorization: Bearer <accessToken>
      │
      └─ API answers 401 unauthenticated?
            └─► POST /auth/refresh { refreshToken }
                  ├─ 200 → store BOTH new tokens (the old refresh token is now dead) → retry the call once
                  └─ 401 → clear tokens → show sign-in screen
```

**Rotation rule (important):** every successful refresh returns a **new** `refreshToken` and invalidates the old one. Always overwrite the stored one. If two requests refresh at the same time with the same token, the second one looks like a replay and **kills the session**, so **serialise refreshes** (one in-flight refresh; other requests wait for it).

### Reference implementation (TypeScript / fetch)

```ts
let refreshing: Promise<boolean> | null = null;

async function refreshTokens(): Promise<boolean> {
  const res = await fetch(`${BASE}/auth/refresh`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ refreshToken: storage.refreshToken }),
  });
  if (!res.ok) return false;
  const t = await res.json();
  storage.accessToken = t.accessToken;
  storage.refreshToken = t.refreshToken;      // overwrite: the old one is dead
  return true;
}

export async function api(path: string, init: RequestInit = {}, retry = true): Promise<Response> {
  const res = await fetch(`${BASE}${path}`, {
    ...init,
    headers: { 'Content-Type': 'application/json', ...init.headers, Authorization: `Bearer ${storage.accessToken}` },
  });
  if (res.status !== 401 || !retry) return res;

  const body = await res.clone().json().catch(() => ({}));
  if (body.code !== 'unauthenticated') return res;

  refreshing ??= refreshTokens().finally(() => (refreshing = null));   // one refresh at a time
  if (await refreshing) return api(path, init, false);

  signOutLocally();                                                    // go to the login screen
  return res;
}
```

**Where to store tokens:** native/hybrid app → Keychain / Keystore (secure storage), not plain local storage.

### Website: HttpOnly-cookie mode (recommended for browsers)

Browsers should not keep a refresh token where JavaScript can read it. Send header `X-Auth-Mode: cookie` on `login`, `register` and `refresh`:

- The response **omits** `refreshToken` and instead sets an **HttpOnly, Secure** cookie `aylla_refresh` (path `/api/v1/auth`, 7 days).
- Call `POST /auth/refresh` with **no body**, header `X-Auth-Mode: cookie`, and `credentials: 'include'`.
- Keep only the `accessToken` in memory (a JS variable), not in `localStorage`.
- Requires the site origin to be listed in `CORS_ALLOWED_ORIGINS` (exact origin, not `*`).

```ts
fetch(`${BASE}/auth/refresh`, { method: 'POST', credentials: 'include', headers: { 'X-Auth-Mode': 'cookie' } });
```

### Endpoints

#### `POST /auth/register` — public, 5/min
Creates a normal user (role is always `user`; staff accounts are created by an admin) and signs the device in.

| Field | Type | Rules |
|---|---|---|
| `fullName` | string | required, ≤255 |
| `email` | string | required, valid, unique |
| `password` | string | required, ≥8, letters + numbers. **Send the plain password over HTTPS** — the server hashes it (bcrypt). Do **not** pre-hash it. |
| `phone` | string | optional, e.g. `+61412345678` |
| `dob` | string | optional, `YYYY-MM-DD`, before today |
| `vaultPublicKey` | string | optional |
| `deviceInfo` | object | optional: `deviceName`, `deviceType` (`ios`/`android`/`web`/`other`, any casing), `pushToken`, `location` |

**201** when email verification is **off** (signed in at once), or **202** when it is **on** (see below).
```json
{
  "status": "success",
  "tokenType": "Bearer",
  "accessToken": "1|o0YczcfC...",
  "refreshToken": "ZNGEUYWLNb3j...",
  "expiresIn": 900,
  "deviceId": "dev_01m3pvanxazdj7v431hctnhjqn",
  "user": {
    "id": "usr_01m3pvanvpw9f4cbcqcp0ep40g", "fullName": "Live Tester", "email": "live@example.com",
    "phone": "+61412345678", "dob": "1992-06-15", "role": "user", "organisation": null,
    "status": "active", "emailVerified": true, "phoneVerified": false, "hasPin": false, "createdAt": "2026-09-29T15:07:59+00:00"
  }
}
```

**202, when `GET /config` says `emailVerificationRequired: true`.** No tokens yet. We email a 6-digit code (valid 10 minutes). Show a code screen, then call `POST /auth/verify-email`.
```json
{ "status": "verification_required", "message": "We sent a 6-digit code to your email. Enter it to finish creating your account.", "email": "live@example.com" }
```

#### `POST /auth/login` — public, 5/min per email+IP
| Field | Type | Notes |
|---|---|---|
| `email` | string | required |
| `authMethod` | string | `password` (default) or `pin`. `biometric_signature` returns **501 `not_implemented`** for now. |
| `credential` | string | required — the password or the PIN |
| `deviceInfo` | object | as in register. Sending it makes the device list readable. |

Response: same as register (**200**). A sign-in from a device the user has not used before also creates a `security` notification.

When email verification is on and the email is not verified yet: **403 `email_not_verified`**, and a fresh code is emailed (at most one a minute). Send the person to the code screen.

> **Biometrics:** do Face ID / fingerprint **on the device** to unlock the stored refresh token or PIN. The server-side `biometric_signature` challenge is not enabled yet.

#### `POST /auth/refresh` — public, 30/min
Body `{ "refreshToken": "..." }` (or cookie mode, above). **200** returns the same shape as login (new `accessToken` **and** new `refreshToken`). Errors: `refresh_token_missing` / `refresh_token_invalid` / `refresh_token_reused` (all 401).

#### Email verification and forgotten passwords — public
Codes are 6 digits, valid 10 minutes, used once, and locked after 5 wrong tries (`422 code_expired`: ask for a new one). A wrong code is `422 invalid_code`. Asking for codes is limited (3 a minute per email, 20 an hour per network address: `429`).

| Call | Body | Result |
|---|---|---|
| `POST /auth/verify-email` (5/min) | `{ "email", "code", "deviceInfo"? }` | **200**, same as login: the person is verified **and signed in**. |
| `POST /auth/resend-verification` | `{ "email" }` | Always **200** (it never says whether an account exists). |
| `POST /auth/forgot-password` | `{ "email" }` | Always **200**. Emails a reset code to vault users and institution staff. Owner-console accounts are not reset this way. |
| `POST /auth/reset-password` (5/min) | `{ "email", "code", "password" }` | **200**. Sets the password, signs **every** device out and emails a "password changed" alert. The person then signs in again. A reset also verifies the email. |

Verification can be switched off on a server (`emailVerificationRequired: false`): then register signs in at once, as before. Always read `GET /config` instead of assuming.

#### `GET /config` — public
What this server can do right now: `{ "emailVerificationRequired": true, "channels": { "email": true, "sms": false }, "sharePasscodeInEmail": true }`. Hide options that are `false` (for example the SMS choice when sharing).

#### Mobile number verification — Bearer, **switched off for now**
`POST /auth/phone/send-code` and `POST /auth/phone/verify` `{ "code" }` exist but answer **503 `sms_not_enabled`** until a text-message provider is connected. When on, a verified number (`user.phoneVerified`) can be found by institutions; changing the number clears the verification. Do not build screens for these yet.

#### `POST /auth/logout` · `POST /auth/logout-all` — Bearer
Revoke this device / every device. Also clear stored tokens on the client.

#### `GET /auth/me` · `PUT /auth/me` — Bearer
`PUT` accepts any of `fullName`, `phone`, `dob`, `vaultPublicKey`. Returns the user object.

#### `PUT /auth/pin` — Bearer, 5/min
`{ "pin": "482913", "currentPassword": "…" }` — PIN is 4–8 digits. After this, `authMethod: "pin"` works at login.

#### `PUT /auth/password` — Bearer, 5/min
`{ "currentPassword": "…", "password": "…" }` → all **other** devices are signed out (`revokedSessions` = how many).

#### `GET /auth/sessions` — Bearer
```json
[
  { "id": "dev_01m3…", "deviceName": "iPhone 15 Pro (This Device)", "deviceType": "ios", "location": null,
    "ipAddress": "103.216.88.19", "lastActive": "2026-09-29T15:09:33+00:00", "isCurrent": true, "trusted": true }
]
```
Only non-revoked devices are listed. `isCurrent` marks the calling device.

#### `DELETE /auth/sessions/{sessionId}` — Bearer
Remote sign-out of a device → `{ "revoked": true, "message": "Session terminated and encryption keys cleared." }`. That device's access **and** refresh tokens stop working immediately.

---

## 4. Document schemes & the 100-point engine

**Australia has no single national "100 points" rule.** Each relying organisation (NSW Police Firearms, WA Police, SA Police, banks…) has its own point values and rules. The API therefore has *schemes*: `GENERAL_100_TEMPLATE` (default, the common 70/40/35/25 pattern), plus the official police schemes. Some schemes don't use points at all (`ACIC_NPCS_CURRENT` needs a *mix of document categories*).

| Scoring model | How it decides |
|---|---|
| `Points` | Sum of points ≥ `threshold` **and** minimums (primary / photo / address / count) met |
| `Category mix` | Needs N documents per category (e.g. 1 commencement + 1 primary-use + 2 secondary) |
| `Single document` | One listed document is enough |
| `External form` | Rules not loaded — the result is `unsupported`; follow the organisation's own form |

### `GET /schemes` — Bearer
Document schemas the user can add to the vault, with the points each is worth **under one scheme**.

Query: `schemeId` (default `GENERAL_100_TEMPLATE`), `scope=catalogue` (return **every** document type, with `points: null` for ones the scheme doesn't list), `q` (search name).

Five catalogue fields are switched off and never appear in `defaultFields` or on cards: `document_image`, `verification_method`, `verification_result`, `verified_at`, `document_status`. Aylla keeps no document images, verifies nothing, and the card's own status (`status` / `displayStatus`) replaces a separate document status, so apps must not ask for them. If an app sends them on a card they are ignored (not stored). The list is `hidden_fields` in `config/aylla.php`.

```json
[
  {
    "id": "AU_PASSPORT",
    "title": "Australian passport",
    "shortName": "Australian passport",
    "points": 70,
    "tier": "Primary (70 pts)",
    "category": "Commencement / primary",
    "schemeId": "GENERAL_100_TEMPLATE",
    "schemeCategory": "Primary",
    "isPrimary": true,
    "conditions": "Configurable baseline only",
    "issuer": "Australian Government",
    "hasPhoto": "Yes", "showsAddress": "No", "dvsVerification": "Yes",
    "notes": null,
    "defaultFields": [
      {
        "key": "passport_number", "label": "Passport number", "type": "text", "inputControl": "Masked text",
        "section": "Passport", "isSensitive": true, "isRequired": true, "captureRequirement": "Required",
        "validation": "Issuer-defined; preserve leading zeros; do not use one global regex",
        "displayFormat": "Uppercase alphanumeric", "maskingRule": "Last 3 characters", "defaultDisclosure": "Verify only",
        "dropdownListId": null, "options": null
      },
      {
        "key": "issuing_country", "label": "Country of issue", "type": "select", "inputControl": "Dropdown",
        "section": "Document", "isSensitive": false, "isRequired": false, "captureRequirement": "Conditional",
        "validation": "Use ISO country code", "dropdownListId": "COUNTRY_ISO3166",
        "options": [ { "value": "AF", "label": "Afghanistan" }, { "value": "AU", "label": "Australia" } ]
      }
    ]
  }
]
```

A passport has ~15 fields (name, date of birth, passport number, country, issue/expiry dates, status…). `validation`, `displayFormat` and `maskingRule` are hints from the government data dictionary: **`validation` is guidance text, not a regex** (the issuers' formats differ), so don't hard-fail on it.

**Building the "add a card" form from `defaultFields`** (nothing is hard-coded in the app):

| `type` | Render as |
|---|---|
| `text` | text input (use `inputControl: "Masked text"` → password-style with reveal) |
| `select` | dropdown from `options` (`value` is what you store, `label` is what you show). Any field with a list of options is a `select`. |
| `multiselect` | multi-select from `options` |
| `date` | date picker → `YYYY-MM-DD` (partial dates `YYYY-MM` / `YYYY` exist for some fields) |
| `datetime` | date-time picker |
| `boolean` | checkbox / switch → store **`"Yes"` / `"No"`** (these are the `options` values) |
| `number` | numeric input |
| `address` | address input |
| `file` | file picker (use the attachment endpoint) |

`isRequired` → mark as required. `isSensitive` → mask in lists and require biometric/PIN to reveal. Send the same `key` and `label` back when you create the card.

### `GET /schemes/registry` — Bearer
List of rule sets: `id`, `name`, `jurisdiction`, `useCase`, `scoringModel`, `threshold`, `minTotalDocuments`, `minPrimary`, `minPhoto`, `minAddress`, `minPrimaryUse`, `minSecondary`, `status`, `essentialRules`, `isAuthoritative`. Use it for a "verify against…" picker. `isAuthoritative=false` means *template / reference only*; show a disclaimer.

### `GET /schemes/registry/{schemeId}` — Bearer
Rule set + `documents[]` (every document it scores: `documentTypeId`, `points`, `schemeCategory`, `isPrimary`, `photoOnDocument`, `addressOnDocument`, `conditions`, …).

### `POST /schemes/evaluate-score` — Bearer
```json
{ "schemeId": "GENERAL_100_TEMPLATE", "cardIds": ["card_01m3…", "card_01m3…"] }
```
`schemeId` is optional (default template). Only the caller's own cards; unknown ids → 422. **200:**
```json
{
  "schemeId": "GENERAL_100_TEMPLATE", "schemeName": "Configurable 100-point onboarding template",
  "scoringModel": "Points", "schemeStatus": "Template — not authoritative", "threshold": 100,
  "totalPoints": 110, "hasPrimary": true, "hasSecondary": true,
  "isVerified100Points": true, "result": "pass",
  "primaryPoints": 70, "secondaryPoints": 40,
  "deficiencies": [], "warnings": [], "categoryCounts": null,
  "breakdown": [
    { "cardId": "card_01m3…", "title": "Passport", "documentTypeId": "AU_PASSPORT", "counted": true, "points": 70, "category": "Primary", "reason": null },
    { "cardId": "card_01m3…", "title": "Passport 2", "documentTypeId": "AU_PASSPORT", "counted": false, "points": 0, "category": null, "reason": "Duplicate document type; it can only be used once." }
  ],
  "disclaimer": "Preliminary result only. The receiving organisation makes the final identity decision."
}
```
- `result`: `pass` · `fail` · `unsupported`.
- Only cards that are not expired or pending (`displayStatus` of `current` or `expiring_soon`) and have a `documentTypeId` count. Duplicates of one document type count once.
- **Always show `disclaimer`** and any `warnings`. Show `deficiencies` as "what's missing".

### `GET /identity-score` — Bearer
The **Identity Score** screen: where the signed-in person stands against the general 100-point guide, in plain words, and which documents would finish it. Build one tab or screen from it; do not show points anywhere else (the vault list, card badges).

```json
{
  "schemeId": "GENERAL_100_TEMPLATE",
  "guideName": "General 100-point guide",
  "threshold": 100,
  "totalPoints": 40,
  "mainPoints": 0,
  "supportingPoints": 40,
  "pointsToGo": 60,
  "complete": false,
  "missing": [
    {
      "kind": "points",
      "amount": 60,
      "text": "60 more points"
    },
    {
      "kind": "main",
      "text": "One main ID, such as a passport or birth certificate"
    }
  ],
  "counted": [
    {
      "cardId": "card_01m3…",
      "title": "Driver Licence",
      "documentTypeId": "AU_DRIVER_LICENCE",
      "points": 40,
      "group": "supporting",
      "showsPhoto": true,
      "showsAddress": true,
      "expiryDate": "2030-05-01",
      "expiringSoon": false
    }
  ],
  "notCounted": [
    {
      "cardId": "card_01m4…",
      "title": "Old passport",
      "documentTypeId": "AU_PASSPORT",
      "reason": "Expired. Renew it to count it again.",
      "canRenew": true
    }
  ],
  "expiringSoon": [],
  "suggestions": [
    {
      "documentTypeId": "AU_PASSPORT",
      "name": "Australian passport",
      "points": 70,
      "group": "main",
      "showsPhoto": true,
      "showsAddress": false,
      "helps": [
        "points",
        "main"
      ],
      "finishesIt": true
    }
  ],
  "combinations": [],
  "disclaimer": "A guide only. The organisation you apply to makes the final identity decision."
}
```
- `missing[]` is what is still missing, as ready-to-show sentences (`kind`: `points` · `main` · `photo` · `address`). Empty when `complete` is true.
- `counted[]` are the documents that earn points; `group` is `main` (a main ID such as a passport or birth certificate) or `supporting` (Medicare, bank card, utility bill). `notCounted[]` explains in a sentence why a card does not count (`canRenew` = expired: link to edit that card).
- `suggestions[]` are document types the person does not hold, best first: those with `finishesIt: true` complete the score on their own. `helps` says what each fills in. When no single document finishes it, `combinations[]` lists up to 3 pairs that do.
- `expiringSoon[]` are counted documents that expire within 60 days: warn the person.
- To add a suggested document, open your Add document screen with that `documentTypeId` already chosen, and return to this screen after saving so the new score is the first thing seen.
- Expired and not-yet-received cards never count, each document type counts once. Only the general guide is used.

### Lookups — Bearer
- `GET /lookups/dropdowns?list=STATE_TERRITORY,CARD_NETWORK` → `{ "STATE_TERRITORY": [ { "value": "NSW", "label": "New South Wales" } ] }` (omit `list` for all 33 lists; the list id of a field is its `dropdownListId`). Country values are ISO codes (`AU`).
- `GET /lookups/state-variants` → per-state card names and format notes.
- `GET /lookups/sources` → official sources for the rules (for a "where do these rules come from" screen).

---

## 5. Cards (the vault)

Sensitive values are **encrypted at rest** (AES-256 via the server key). A user only ever sees their own cards; another user's card id returns `404`.

**Card object**
```json
{
  "id": "card_01m3pvaq080kfmzh3dm1nw9e18",
  "title": "Australian Passport (Live)",
  "category": "Passport",
  "documentTypeId": "AU_PASSPORT",
  "documentPoints": 70,
  "status": "valid",
  "displayStatus": "expiring_soon",
  "expiryDate": "2026-12-01",
  "lastSharedWith": { "name": "Mira Bank", "at": "2026-10-12T09:30:00+00:00" },
  "notes": null,
  "createdAt": "2026-09-29T15:08:00+00:00",
  "updatedAt": "2026-09-29T15:08:00+00:00",
  "fields": [
    { "id": "pf_01m3…", "key": "passport_number", "label": "Passport Number", "value": "PA9823410", "type": "text", "isSensitive": true, "isRequired": false }
  ],
  "attachments": [
    { "id": "att_01m3…", "name": "passport_scan.png", "mimeType": "image/png", "sizeBytes": 2516582, "size": "2.4 MB",
      "url": "https://…/api/v1/cards/card_…/attachments/att_…?expires=…&signature=…" }
  ]
}
```
- `status` is what the person sets: `valid` (default) or `pending` (applied for, not received yet). Older values `verified`, `expired` and `rejected` are still accepted and returned but apps should no longer offer them.
- **`displayStatus` is what to show.** The server works it out, so every app agrees: `current` · `expiring_soon` (expiry within 60 days) · `expired` (expiry passed, or set by hand) · `not_received` (`status` = `pending`) · `rejected`.
- `expiryDate` (`yyyy-mm-dd` or `null`) is read from the card's field `expiry_date` (or any field labelled "expiry"); dd/mm/yyyy values are understood. Nobody has to maintain "expired" by hand.
- `lastSharedWith` (`{ "name", "at" }` or `null`) is the last recipient of a share link or an answered request. It is a fact from history, not something the person declares. Show it as "Shared with Mira Bank on 12 Oct".
- `documentPoints` is computed by the server (default scheme); it is ignored if you send it. It is still returned, but **do not show points on the vault list or on card badges**: points belong on the Identity Score screen (`GET /identity-score`).
- `attachments[].url` is a **signed link valid for 10 minutes** — use it directly in `<img src>` or open it in the browser (no bearer token needed). Fetch the card again to get a fresh link.

### `GET /cards` — Bearer
Optional: `category`, `status`, `documentTypeId`, `q` (title search), **`masked=1`** (sensitive values come back as `••••••410` — use this for list screens and reveal on demand with `GET /cards/{id}`).

### `POST /cards` — Bearer → **201** (card object)
| Field | Rules |
|---|---|
| `title` | required |
| `category` | required, free text |
| `documentTypeId` | optional, must be a code from `GET /schemes?scope=catalogue` |
| `status` | optional (default `valid`) |
| `notes` | optional, ≤5000 |
| `fields[]` | optional. Each: `label` (required), `value`, `key`, `type`, `isSensitive`, `isRequired`. Fields whose dictionary entry is *Restricted* (passport number, licence number, Medicare number…) are **always** stored sensitive, whatever you send. |

### `GET /cards/{cardId}` · `PUT|PATCH /cards/{cardId}` · `DELETE /cards/{cardId}`
`PUT` is partial. If you send `fields`, it is the **complete** list: entries with an existing `id` are updated in place, entries without an `id` are created, and existing fields you omit are **deleted**. `DELETE` permanently removes the card and its files → `{ "deleted": true }`.

### Attachments
- `POST /cards/{cardId}/attachments` — `multipart/form-data`, field **`file`** (jpg, jpeg, png, webp, pdf; ≤8 MB; ≤10 per card). Returns **201** with the updated card. Files are encrypted before being stored.
- `DELETE /cards/{cardId}/attachments/{attachmentId}` → `{ "deleted": true }`.

### `POST /cards/ocr-scan` — Bearer, 20/min
`multipart/form-data`, field **`file`** (image or PDF, ≤8 MB). The image is read by AI and **not stored**.
```json
{ "detectedScheme": "AU_DRIVER_LICENCE", "detectedName": "Australian driver licence", "confidence": 0.98,
  "extractedFields": { "licence_number": "98201948", "date_of_birth": "1992-06-15" } }
```
`extractedFields` keys are the same `key`s as `defaultFields` — pre-fill the form and **let the user confirm**. If nothing was recognised, `detectedScheme` is `null` and `extractedFields` is `{}`. **503 `ai_not_configured`** until the server has a Gemini key.

---

## 6. Sharing (time-limited links)

Owner flow: create → recipient opens `shareUrl` → recipient enters passcode → fields shown. The recipient needs **no account and no token** — just the link.

### `POST /shares` — Bearer → **201**
| Field | Rules |
|---|---|
| `cardId` | required, your card |
| `selectedFieldIds[]` | required, ≥1 — `pf_…` ids **of that card**; only these are ever shown |
| `recipientName` | required |
| `recipientContact` | optional (email / phone) |
| `deliveryChannel` | optional: `email` (we email the link to `recipientContact`, which must then be an email address; the passcode is in the email too unless `sharePasscodeInEmail` is false in `GET /config`) · `sms` (**422 `channel_unavailable`** until text messages are switched on). `push` is not a share channel. At most 20 share emails per user per day (**429 `share_email_limit`**). |
| `expirationMinutes` | optional, default 60, max 525,600 (1 year). Suggested choices: 15 min, 1 hour, 24 hours, 7 days, 30 days, 90 days, 1 year. |
| `neverExpires` | optional boolean. `true` = no expiry date (ignores `expirationMinutes`); see the rules below. |
| `maxAccessCount` | optional, default 1, max 50 (max 1000 when `neverExpires` is true) |
| `passcode` | optional, 4–8 digits |

```json
{ "shareId": "sh_qzkkzmtteklrktnwixnovvun", "shareUrl": "https://<portal>/portal/sh_qzkk…",
  "encryptedToken": "enc_k5B5c1DddOMLekJDrPpg0BoFFD0NvEdjhUaqaxf8", "expiresAt": "2026-09-29T16:09:36+00:00" }
```
A link with **no expiry date** (`neverExpires: true`) keeps working until the owner revokes it, so it has guard rails: a `passcode` is required (`422 passcode_required`), no sensitive field may be included (`422 sensitive_fields_blocked`; sensitive = passport, licence, Medicare numbers and other Restricted fields), and `maxAccessCount` may go up to 1000 (50 for links that expire). If nobody opens it for 90 days it pauses itself (`status: paused`); the owner turns it back on with `POST /shares/{id}/resume`. The owner is reminded by email once a month while such links are on.

`expiresAt` is **`null`** (and `neverExpires` is `true`) for such a link, in the create response, the owner list, and the recipient calls.

`encryptedToken` is optional extra protection: if the recipient app sends it as `token` (body) or `X-Share-Token` (header) on unlock, it must match. Show/send `shareUrl` to the user.

### Owner endpoints — Bearer
- `GET /shares` → list (`shareId, shareUrl, cardTitle, recipientName, status, hasPasscode, expiresAt, maxAccessCount, accessCount, remainingViews, …`). `status`: `active` · `expired` · `revoked` · `exhausted` · `paused`. Each item also has `neverExpires` and `pausedAt`.
- `GET /shares/{shareId}` → the same plus `selectedFieldIds` and `accessLog[]` (`result`, `ipAddress`, `at`).
- `POST /shares/{shareId}/resume` → `{ "resumed": true, "status": "active" }`. Turns a **paused** link back on (counts as fresh activity). `410 share_revoked` if it was revoked.
- `POST /shares/{shareId}/revoke` → `{ "revoked": true }`. Takes effect instantly.

### Recipient endpoints — **public**
- `GET /shares/public/{shareId}` → `{ "recipientName", "isPasscodeRequired", "expiresAt", "remainingViews" }`. Does **not** use up a view.
- `POST /shares/public/{shareId}/unlock` → body `{ "passcode": "7821" }` (omit if none):
```json
{ "cardTitle": "Driver Licence", "fields": [ { "label": "Licence Number", "value": "98201948" } ], "remainingViews": 2, "expiresAt": "…" }
```
Each successful unlock uses **one view** and notifies the owner. 5 wrong passcodes lock the link (`423 share_locked`). Errors: `403 passcode_incorrect` (message says attempts left), `410 share_revoked|share_paused|share_expired|share_exhausted`, `404 share_not_found`.

---

## 7. Requests and institutions

Institutions work in their own portal. In the app a person sees what institutions **asked** for, and can **send fields on their own** to a registered institution.

```
pending ──person fulfils──► fulfilled ──institution──► approved | rejected
   ├─ person declines ─► declined
   └─ institution cancels ─► cancelled
```

**Request object**
```json
{
  "id": "req_01m3…", "institutionName": "Mira Insurance", "initiatedBy": "institution",
  "title": "100-Point KYC Identity Verification", "message": null, "schemeId": null,
  "requestedFields": [ { "category": "Driver License", "fieldLabels": ["Licence Number"], "isRequired": true } ],
  "status": "pending", "dueDate": "2026-12-01T00:00:00+00:00", "submittedAt": null, "reviewedAt": null, "reviewNotes": null,
  "createdAt": "2026-09-29T15:09:39+00:00"
}
```
`institutionName` is the institution's name. `initiatedBy` is `institution` (they asked) or `user` (you sent documents on your own).

| Endpoint | Notes |
|---|---|
| `GET /requests?status=pending` | Requests sent to you and documents you sent to institutions. |
| `GET /requests/{id}` | Adds `submissions[]`; you only see a **masked echo** of what you sent. |
| `POST /requests/{id}/fulfill` | `{ "submittedData": [ { "cardId", "fieldLabel", "value?" } ] }` |
| `POST /requests/{id}/decline` | |
| `POST /requests/{id}/withdraw` | Take back documents you sent on your own, while unreviewed. |
| `GET /institutions?q=` | Find a registered institution by name (max 20): `[{ id, name, category }]`. |
| `POST /institutions/{id}/share` | `{ message?, items: [ { cardId, fieldIds[] } ] }`. Sends only the chosen fields. 201 `{ id, institution, status, fieldsShared, sentAt }`. 20/min. |

**Fulfil rules:** the request must be `pending` and not past `dueDate` (`410 request_overdue`); every `isRequired` label must be present (`422 missing_required_fields`, `errors.missing[]`); each `cardId` must be your own card and contain a field with that `fieldLabel`. The value **actually sent** is always the vault's stored value.

Institution staff are normal users: `GET /auth/me` and the login response include `institutions: [{ id, name, role }]` (empty for most people) so an app can offer a link to the institution portal.

---

## 8. Voice assistant

### `POST /voice/query` — Bearer, 20/min
```json
{ "prompt": "What is my passport expiry date?", "language": "en-AU", "accent": "Australian",
  "vaultContextCardIds": ["card_01m3…"], "includeAudio": true, "audioFormat": "mp3", "voiceName": "en-AU-Neural2-A", "rate": 0.95 }
```
Only the cards listed in `vaultContextCardIds` (max 5, must be the user's) are sent to the AI; nothing else from the vault is. **200:**
```json
{ "transcript": "What is my passport expiry date?", "responseText": "Your Australian passport expires on 9 April 2031.",
  "audioBase64": "SUQzBAAAAAAA…", "audioMimeType": "audio/mpeg",
  "speechConfig": { "languageCode": "en-AU", "voiceName": "en-AU-Neural2-A", "rate": 0.95 } }
```
- `audioBase64` is MP3 by default (`audioFormat: "wav"` for WAV). It is `null` if text-to-speech is unavailable → speak `responseText` with the device's own speech engine.
- Convert the base64 to a `data:audio/mpeg;base64,…` URL to play it.
- **503 `ai_not_configured`** until the server has the Google keys; **502 `ai_upstream_error`** if Google fails.

---

## 9. Notifications & activity

### `GET /notifications` — Bearer
Query: `type` (`security`·`sharing`·`kyc`·`system`), `unread=1`, `limit` (≤100).
```json
{ "unreadCount": 2, "notifications": [
  { "id": "ntf_01m3…", "type": "sharing", "title": "Your shared card was opened",
    "body": "Qantas Airways Check-in opened \"Driver Licence\". 2 view(s) remaining.",
    "data": { "shareId": "sh_…" }, "isRead": false, "createdAt": "2026-09-29T15:09:38+00:00" } ] }
```
`data` carries ids you can deep-link with (`shareId`, `requestId`, `deviceId`).

### `PATCH /notifications/mark-read`
`{ "ids": ["ntf_…"] }` or `{ "all": true }` → `{ "updated": 1 }`.

### `GET /notifications/preferences` · `PUT /notifications/preferences`
`{ "pushEnabled": true, "smsEnabled": false, "emailEnabled": true, "emailKyc": true, "emailSharing": false }` — `PUT` accepts any subset.
- `emailEnabled`: master switch for emails about activity.
- `emailKyc`: email when an institution asks for documents, sends a reminder or answers one (default on).
- `emailSharing`: email when someone opens a link you shared (default off).
- Security emails (new device sign-in, changed password) are always sent and cannot be switched off. Emails never contain document values.
- When you send documents to an institution (`POST /institutions/{id}/share`) you also get a short "Documents sent" email (and in-app notification) as a confirmation; every active admin of the institution is told.
> **Email delivery works** (when the server has mail configured). **Push** is for the mobile app only and is not sent from the server yet; the app registers `deviceInfo.pushToken` at login. **SMS** is switched off.

### `GET /audit-logs` — Bearer
The user's own security trail (`?limit=`): `action` (e.g. `auth.login`, `card.created`, `share.unlocked`, `kyc.fulfilled`), `entityType`, `entityId`, `ipAddress`, `createdAt`.

---

## 11. Enumerations

| Name | Values |
|---|---|
| Request source (`initiatedBy`) | `institution`, `user` |
| Account status | `active`, `suspended` |
| Device types | `ios`, `android`, `web`, `other` |
| Card status (set by the person) | `valid`, `pending` (older: `verified`, `expired`, `rejected`) |
| Card display status (computed) | `current`, `expiring_soon`, `expired`, `not_received`, `rejected` |
| Share status | `active`, `expired`, `revoked`, `exhausted`, `paused` |
| Delivery channel (shares) | `email`, `sms` (switched off: `422 channel_unavailable`). `push` is not a share channel. |
| KYC status | `pending`, `fulfilled`, `approved`, `rejected`, `declined`, `cancelled` |
| Notification type | `security`, `sharing`, `kyc`, `system` |
| Scoring model | `Points`, `Category mix`, `Single document`, `External form` |
| Field `type` | `text`, `select`, `multiselect`, `date`, `datetime`, `boolean`, `number`, `address`, `file` |
| Score `result` | `pass`, `fail`, `unsupported` |

---

## 12. What changed from the original spec document

The first spec was a design sketch. These are the differences the frontend needs to know:

| Original spec | Now |
|---|---|
| `passwordHash` in register | Send **`password`** (plain, over HTTPS). Server hashes it. |
| Single access token | `accessToken` (15 min) + **`refreshToken`** (7 d, rotated) + `POST /auth/refresh`. |
| HttpOnly refresh cookie | Native apps: token in the body. Websites: opt in with `X-Auth-Mode: cookie`. |
| `authMethod: biometric_signature` | Returns 501 for now — do biometrics on-device. |
| Ids like `usr_109283` | Prefixed opaque strings (`usr_01m3…`). |
| Document ids like `passport`, `driver_licence` | Codes like `AU_PASSPORT`, `AU_DRIVER_LICENCE` (71 documents from the government reference data). |
| Fixed points per document | Points **per scheme**. `GET /schemes?schemeId=…`, `POST /schemes/evaluate-score` takes `schemeId`. Result gained `result`, `breakdown`, `warnings`, `disclaimer`. |
| `defaultFields[].options` = string list | `options` = `[{ value, label }]`. |
| Card `attachments` in create body | Upload files separately (`POST /cards/{id}/attachments`); URLs are 10-minute signed links. |
| Share unlock | Each unlock uses one view; wrong passcodes lock the link after 5. |
| `GET /requests` only | Added `POST /requests` (operator), `GET /requests/{id}`, decline, cancel. |
| `GET /notifications` bare array | `{ unreadCount, notifications[] }`; `mark-read` body is `{ ids }` or `{ all: true }`. |
| Voice audio = WAV | MP3 by default (`audioFormat` to choose), plus `audioMimeType`. |
| — | New: `/auth/me`, `/auth/pin`, `/auth/password`, `/auth/logout`, `/auth/logout-all`, `/shares` list/detail, `/schemes/registry`, `/lookups/*`, `/audit-logs`, institutions and sending fields to them. |

## 13. Not built yet (planned)

- Biometric-signature server challenge (`authMethod: biometric_signature`).
- Push (FCM/APNs) sent from the server, and SMS (built but switched off).
- Voice and OCR need the Google API keys configured on the server.
