# CyanText API

Production base: `https://cyantext.com` (AU alias: `cyantext.com.au` → same app).

Auth (Twilio-shaped):

```http
Authorization: Basic base64(AccountSid:AuthToken)
Authorization: Bearer AuthToken
```

## SMS

| Method | Path | Notes |
|---|---|---|
| POST | `/api/v1/messages` | JSON `{ to, body, media?, from?, priority?, purpose?, idempotencyKey?, sendAt?, forceSend? }` — `to` may be a string, `string[]`, or comma/newline list. `media: [{ url, contentType }]` forces MMS. `from` is optional SIM/line (E.164 or subscription id). `priority`: `normal` (default) or `high` / `otp` |
| POST | `/api/v1/media` | multipart `file` / `files` (JPEG/PNG/GIF/WebP, ≤1 MiB, ≤3). Returns public `{ media: [{ url, contentType }] }` for enqueue |
| GET | `/api/v1/media/{id}` | Local-file mode only — serves an uploaded object when Supabase Storage is unset |
| POST | `/api/2010-04-01/Accounts/{Sid}/Messages.json` | form `To` (repeatable or comma-separated), `Body`, `From`, `MediaUrl`, `Purpose`, `Priority`, `ForceSend`, `SendAt`, `StatusCallback` |
| GET | `/api/v1/messages` | List (+ optional `?purpose=` / `?status=failed` / `?tag=` or `?deviceTag=`) — tag keeps messages whose last-known `deviceId` has that device label (case-insensitive) |
| GET | `/api/v1/messages/{id}` | One message + events |
| DELETE | `/api/2010-04-01/Accounts/{AccountSid}/Messages/{MessageSid}.json` | Same Basic auth as send. Cancels one **queued** outbound message. Response `status` is `canceled`. `sending`, `sent`, and `delivered` return 409 and stay unchanged. |
| POST | `/api/v1/messages/{id}/retry` | Manual re-queue of `failed` / `undelivered` (resets attempt budget) |
| GET | `/api/v1/messages/export` | Download archive. Query: `format=csv\|ndjson` (default `csv`), optional `conversation=+E164` (or `peer`). Auth: operator token or portal cookie. |
| GET | `/api/v1/stats` | Portal analytics: `volumeToday`, `volume7d`, `deliveryPercent`, `failedCount`, `freshDevices`, `devicesTotal`. Same auth as messages. Optional `?tag=` / `?deviceTag=` scopes volume/delivery/failed to messages for devices with that label. |

Quiet hours (account setting; **default off**): when enabled, message is **accepted** and stays `queued` with `notBefore` until the window ends. Configure via `GET/PATCH /api/v1/settings` (portal or phone). `forceSend: true` skips the hold. Claim never returns held messages. High/`otp` priority does **not** bypass quiet hours.

### Dual-SIM `From` + per-message priority

- **`from` / `From`**: optional. Pass an E.164 number, Android `subscriptionId`, `sub:N`, or `slot:N`. Stored on the message and returned on claim. Android ≥0.3.12 prefers the matching SIM via `SmsManager.createForSubscriptionId` when dual-SIM lines are available; otherwise the default SMS subscription is used.
- **`priority` / `Priority`**: `normal` (default) or `high` (alias `otp`). High-priority queued messages are claimed before older normal ones (server + on-phone send queue). Quiet hours and the primary-phone claim gate still apply.
- **Device lines**: heartbeat may include `lines: [{ subscriptionId, phoneNumber?, slotIndex?, carrierName?, displayName? }]`. Portal compose shows a From dropdown from reported lines.

### Bulk send

One request can target many recipients. CyanText enqueues **one message per number** with the same body/media/purpose/`forceSend`/`sendAt`.

- JSON: `"to": ["+61411111111", "+61422222222"]` or `"to": "+61411111111, +61422222222"`
- Twilio form: repeated `To=` fields, or one comma/newline-separated `To`
- Idempotency: single-To keeps the key as-is (Cyandex AuthToken path unchanged). Multi-To suffixes each key as `{prefix}:{E.164}`
- Response: **one** recipient → same shape as before (`{ message, twilio, created }` or Twilio object). **Many** → `{ messages, twilio, created, bulk: true }`

### Retry + dead-letter

Failed radio sends and expired claim leases count as attempts (`attemptCount`). After **N** failures (env `CYANTEXT_MAX_SEND_ATTEMPTS`, default **3**) the message stops auto-requeue and is marked `failed` with a clear `Dead-lettered after N…` error. Portal inbox shows failed messages and a **Retry send** button; API: `POST /api/v1/messages/{id}/retry`.

## Devices / phone

| Method | Path | Notes |
|---|---|---|
| POST | `/api/v1/devices` | Register Android phone; gets next `priority` |
| GET | `/api/v1/devices` | Sorted by priority. Includes `tags[]`, `primary`, `mayClaim`, `claimRole`, `primaryDeviceId`, `preferredClaimDeviceId`. Optional `?tag=` filters by label (case-insensitive). Also runs a throttled gateway-alert check. |
| GET | `/api/v1/devices/heartbeats` | Recent heartbeat log (`?deviceId=` / `?limit=`). Portal Settings → Phones. |
| PATCH | `/api/v1/devices` | `{ primaryDeviceId }` or `{ order: string[] }` (index 0 = primary) or `{ deviceId, tags: string[] }` (replace labels; max 20, ≤40 chars). Lower `priority` wins claim; tags do not. |
| GET/POST | `/api/v1/monitor/gateway` | Cron/operator: evaluate low battery + stale heartbeat; send Twilio urgent SMS. Auth: `Bearer CRON_SECRET` or operator token. |

**Heartbeat log + urgent alerts:** every device heartbeat is stored (`heartbeat_logs`, 7-day retention). Portal Settings → Phones configures urgent SMS (admin + optional backup To, Twilio From, battery %, stale seconds, cooldown). Alerts leave via Twilio (`TWILIO_ACCOUNT_SID` + `TWILIO_AUTH_TOKEN`), not the spare phone. Settings field: `gatewayAlerts` on `GET/PATCH /api/v1/settings`. Migration `20261113200000_gateway_alerts_heartbeat_logs`. Vercel cron hits `/api/v1/monitor/gateway` every minute.

**Device tags:** string labels for portal organization/filter. FileStore: `devices[].tags` in `data/cyantext.json`. Supabase: `devices.tags` jsonb (`20261010192000_device_tags`). AuthToken / portal session unchanged. Claim gate and dual-SIM `lines` are unaffected. Inbox `GET /api/v1/messages?tag=` (alias `deviceTag`) and optional `GET /api/v1/stats?tag=` filter by the message’s last-known sending/receiving device; queued outbound with no `deviceId` yet is excluded.

**FCM wake (optional):** heartbeat may include `fcmToken`. On new outbound enqueue the server attempts a high-priority FCM data message when `FIREBASE_SERVER_KEY` or HTTP v1 service-account env is set; otherwise no-op and phones keep polling. Portal Settings → Push wake. Supabase: `devices.fcm_token` (`20261010194000_device_fcm_token`). Device list exposes `fcmRegistered` (token itself is redacted).
| GET/POST | `/api/v1/jobs` | Device Bearer token — claim returns `{ id, to, from, body, channel, media[], priority }`; heartbeat optional `manufacturer` / `model` / `lines[]` / `fcmToken`. Android ≥0.3.12 matches `from` to a SIM, jumps high-priority jobs in the local queue, downloads `media[].url` for MMS (delivery often tops at **sent**). ≥0.3.13 may register FCM for optional server wake. Each heartbeat also appends a diagnostic log and may trigger low-battery / recovery alerts. |
| POST | `/api/v1/jobs/{id}` | Report parts |
| POST | `/api/v1/inbound` | |

**Device priority / dual-token races:** only the preferred **fresh** Android phone may claim SMS or call jobs. Primary (lowest `priority`) wins while online; a fresh standby takes over if primary is stale. Portal Settings surfaces Primary and Set primary / reorder. Prefer one live gateway token per SIM; keep standby tokens installed but deferred.

## Calls (Phase 2)

| Method | Path | Notes |
|---|---|---|
| POST | `/api/v1/calls` | `{ techNumber, customerNumber, jobRef?, forceSend? }` — Cyandex or portal operator enqueue |
| GET | `/api/v1/calls` | List + `summary` (`queueDepth`, `activeBridges`, `deviceBusy`, `busyDevices`) |
| GET | `/api/v1/calls/{id}` | Call + events |
| PUT | `/api/v1/calls` | Device: `{ action: "claim" }` or `{ action: "report", callId, status, error? }` — same priority gate as SMS claim. Android ≥0.3.14 reports phase notes in `error` (e.g. `leg1_tech_offhook`, `sequential_dial;merge_not_verified`). |
| POST | `/api/v1/calls/inbound` | Device Bearer while the SIM is ringing. Body `{ from, withheld?, knownOnDevice?, handsetBusy? }`. Returns `{ action, number, reason }` where action is `bridge`, `deflect`, `ring`, or `reject`. |

One active bridge per phone; extras stay queued. Portal **Settings → Call queue** uses GET/POST with portal session or AuthToken; Android owns dialing via claim/report. **Conference merge is a foothold only** (sequential dial A→B; not verified on-device).

When the account webhook URL and secret are set, `POST /api/v1/calls/inbound` waits (1–12s, portal setting) for `inbound_call_lookup`. Timeout, HTTP error, or an unusable reply deflects to the saved fallback number, or uses the local contact and block rules when that number is empty. Portal **Settings → Calls → Inbound routing** stores the timeout, fallback number, known-caller action, unknown-caller action, portal contacts (optional own forward number), and block list. A caller in the Android contacts or that portal list is known. The block list and “block withheld” win over Cyandex.

## Missed calls (inbound foothold)

Android (≥0.3.13) watches `READ_PHONE_STATE` / optional `READ_CALL_LOG` for missed or rejected inbound rings and POSTs them to the gateway. This is **not** call divert or conference bridge — store + optional account webhook only.

| Method | Path | Notes |
|---|---|---|
| POST | `/api/v1/events/missed-call` | Device Bearer. Body `{ from, at?, deviceId? }`. `from` E.164 (or `unknown` for withheld). `deviceId` must match the token when sent. |
| GET | `/api/v1/events/missed-call?limit=10` | Operator AuthToken / portal session. Recent events (`id`, `from`, `at`, `deviceId`, `createdAt`). |

When a per-account webhook URL + secret are configured, CyanText also POSTs JSON with `event: "missed_call"` and the same `X-CyanText-Signature` HMAC-SHA256 body signing. See Webhooks below and `docs/cyandex-integration.md` (lookup hook shape).

## SMS templates

Named per-account bodies with `{{var}}` placeholders (e.g. `Hi {{name}}, job {{job}}`). Auth: operator AuthToken / Basic or portal session cookie (same as messages). Inbox and Cyandex AuthToken send paths are unchanged — templates are optional compose helpers.

| Method | Path | Notes |
|---|---|---|
| GET | `/api/v1/templates` | `{ templates: [{ id, name, body, variables, createdAt, updatedAt }] }` |
| POST | `/api/v1/templates` | `{ name, body }` → `201 { template }` |
| PATCH | `/api/v1/templates` | `{ id, name?, body? }` → `{ template }` |
| DELETE | `/api/v1/templates` | JSON `{ id }` or `?id=` → `{ ok, id }` |

Portal: **Settings → SMS templates** for CRUD; compose can insert a template and fill variables before send. Local FileStore keeps templates in `data/cyantext.json`; Supabase uses `sms_templates`.

## Settings

| Method | Path | Notes |
|---|---|---|
| GET | `/api/v1/settings` | Quiet hours + `verify` (`configured`, `verifyTo`, `phoneNumber` for device auth, `pending`, `message`). Operator/portal also get `webhook` (`url`, `secretConfigured`, `secretHint`, `lastError`, `lastErrorAt`, `lastSuccessAt`, `deliveries` — newest-first last ~20 attempts: `at`, `event`, `httpStatus`, `error`, `success`) and `credentials` (`accountSid`, `authTokenConfigured`, `authTokenHint` — never the raw Auth Token). |
| PATCH or POST | `/api/v1/settings` | Update quiet hours (operator AuthToken or device token). Operator/portal may also set `webhook: { url?, secret?, generateSecret?, clearSecret? }` — on `generateSecret: true` the response includes one-time `webhookSecret`. Operator/portal may send `revealAuthToken: true` to include `authToken` once (for Cyandex Settings). |

## Phone number verify (SIM → inbound webhook)

Android often cannot expose MSISDN (`phoneNumber` stays null). CyanText discovers it without Twilio Programmable Messaging **send**:

1. Set `CYANTEXT_VERIFY_TO` to an SMS-capable E.164 number (Twilio or any provider).
2. Point that number’s **inbound SMS webhook** to `POST https://www.cyantext.com/api/v1/twilio/sms` (alias: `/api/v1/verify/inbound`).
3. Optional: set `TWILIO_AUTH_TOKEN` so CyanText validates `X-Twilio-Signature`.
4. Authenticated `POST /api/v1/verify/start` creates a short-lived challenge `{ code, verifyTo, smsBody }` (`CTV <code>`).
5. The **customer SIM** sends that SMS via Android `SmsManager` to `CYANTEXT_VERIFY_TO`.
6. Webhook `From` is normalized to E.164 and stored on `devices.phone_number`.

| Method | Path | Notes |
|---|---|---|
| POST | `/api/v1/verify/start` | Operator: `{ deviceId }`. Device token: own device. `503` if `CYANTEXT_VERIFY_TO` unset (gateway otherwise fine). |
| GET | `/api/v1/verify/{id}` | Poll challenge status (`pending` / `complete` / `expired`) |
| POST | `/api/v1/twilio/sms` | Twilio-style form `From` / `To` / `Body` |
| POST | `/api/v1/verify/inbound` | Same handler as `/api/v1/twilio/sms` |

## Health

`GET /api/v1/health` — database mode, quiet hours, capabilities (includes `phoneVerify`), phone freshness. Authenticated callers get account quiet hours.

## Webhooks

### Per-account status / inbound (portal Settings → Webhooks)

Configure `url` + signing `secret` via `GET/PATCH /api/v1/settings` (`webhook` object) or the portal. On outbound status changes (`queued` → `sending` / `sent` / `delivered` / `failed` / `undelivered`) and inbound receive, CyanText POSTs JSON to that URL:

```http
POST {webhook.url}
Content-Type: application/json
X-CyanText-Signature: <hmac-sha256-hex-of-raw-body>
```

Body fields mirror the Twilio-shaped names Cyandex already knows (`MessageSid`, `MessageStatus`, `SmsStatus`, `To`, `From`, `Body`, `NumMedia`, …) plus `event` (`message.status` | `message.inbound` | `missed_call`).

For `missed_call`:

```json
{
  "event": "missed_call",
  "CallSid": "mcall_…",
  "AccountSid": "AC…",
  "From": "+614…",
  "To": "+614…",
  "DeviceId": "dev_…",
  "At": "2026-10-10T12:00:00.000Z",
  "Direction": "inbound"
}
```

Failed deliveries retry a few times with backoff; the last error is stored on the account and shown in the portal (`webhook.lastError`). Each final attempt (after retries) is also appended to `webhook.deliveries` (capped at 20) for the Settings → Webhooks table. HMAC signing and the Cyandex per-message AuthToken / StatusCallback form path are unchanged.

### Per-message StatusCallback + env form hooks (Cyandex AuthToken path)

Per-message `StatusCallback` / `statusCallback` and optional `CYANTEXT_STATUS_WEBHOOK` / `CYANTEXT_INBOUND_WEBHOOK` still POST `application/x-www-form-urlencoded` with both `X-CyanText-Signature` and `X-Twilio-Signature` (HMAC-SHA1 of URL + sorted params, Twilio-compatible). Unchanged for Cyandex.

Inbound phone-verify uses Twilio’s Auth Token when `TWILIO_AUTH_TOKEN` is set.
