# UCall REST & Real-Time WebSocket API Documentation
**Version:** 1.0.0  
**Base URL:** `http://localhost:8080` (or configured production gateway)  
**Protocol:** HTTP/1.1, HTTP/2, WebSocket (WSS)  
**Content-Type:** `application/json`  
**Security Model:** End-to-End Encrypted Messaging (Zero-Plaintext Server Relay) & WebRTC SRTP/DTLS Calling

---

## Table of Contents
1. [Global Standards & Authentication](#1-global-standards--authentication)
2. [Standard Response & Error Formats](#2-standard-response--error-formats)
3. [Module 1: Authentication & Session Management](#module-1-authentication--session-management)
4. [Module 2: Application Management & Multi-Tenancy](#module-2-application-management--multi-tenancy)
5. [Module 3: Universal Identity Resolution](#module-3-universal-identity-resolution)
6. [Module 4: Devices & Signaling Endpoints](#module-4-devices--signaling-endpoints)
7. [Module 5: Smart Communication Routing Engine](#module-5-smart-communication-routing-engine)
8. [Module 6: Address Book & Contact Synchronization](#module-6-address-book--contact-synchronization)
9. [Module 7: WebRTC Calling Control Plane & TURN](#module-7-webrtc-calling-control-plane--turn)
10. [Module 8: Messaging & WhatsApp-Style Cursor Sync](#module-8-messaging--whatsapp-style-cursor-sync)
11. [Module 9: E2EE PreKey Management (X3DH / Ratchet)](#module-9-e2ee-prekey-management-x3dh--ratchet)
12. [Module 10: Real-Time WebSocket Signaling Gateway](#module-10-real-time-websocket-signaling-gateway)
13. [End-to-End Client Workflow Guide](#13-end-to-end-client-workflow-guide)

---

## 1. Global Standards & Authentication

### Headers
| Header | Type | Description |
| :--- | :--- | :--- |
| `Authorization` | `string` | Format: `Bearer <jwt_access_token>`. Required for all protected routes. |
| `Content-Type` | `string` | Must be `application/json` for request payloads. |
| `X-Idempotency-Key` or `Idempotency-Key` | `UUID string` | Optional on state-mutating requests (`POST /messages`, `POST /calls`). Prevents double-submissions during network retries. |

### Authentication Lifecycles
- **Access Tokens:** Standard JWT with 24-hour expiration. Encodes user UUID as `sub`.
- **Refresh Tokens:** Long-lived cryptographically secure tokens. Stored as SHA-256 hashes in MySQL with single-use transactional rotation and replay detection.
- **WebSocket Tickets:** Short-lived (60s TTL), single-use tickets issued via `POST /api/v1/auth/ws-ticket` to avoid exposing raw JWTs in WebSocket query URLs.

---

## 2. Standard Response & Error Formats

### Success Envelope
All HTTP endpoints return responses inside a standardized JSON envelope:
```json
{
  "code": 200,
  "message": "success",
  "data": { ... }
}
```

### Error Envelope
```json
{
  "code": 400,
  "message": "Invalid prekey signature: signature verification failed",
  "data": null
}
```

Common status codes:
- `200 OK` — Success.
- `400 Bad Request` — Validation failure, malformed payload, or invalid cryptographic signature.
- `401 Unauthorized` — Missing, expired, or invalid JWT / WebSocket ticket.
- `403 Forbidden` — Access denied to the requested call, conversation, or resource.
- `404 Not Found` — Resource, user, or conversation does not exist.
- `409 Conflict` — State conflict (e.g., call already ended or rejected).
- `422 Unprocessable Entity` — Syntactic or cryptographic structure error.
- `500 Internal Server Error` — Database or infrastructure failure.

---

## Module 1: Authentication & Session Management

### 1.1 Register User
Idempotently register or fetch a user account via E.164 phone number. Automatically provisions a unique Universal ID (`UID:...`).

- **Endpoint:** `POST /api/v1/auth/register`
- **Auth:** Public
- **Request Body:**
```json
{
  "phone": "+14155552671",
  "display_name": "Alice Smith"
}
```
- **Response (200 OK):**
```json
{
  "code": 200,
  "message": "success",
  "data": {
    "user_id": "018d3b7d-3b7d-7bad-8bdd-111122223333",
    "universal_id": "UID:1:0000000001",
    "phone": "+14155552671",
    "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "refresh_token": "rt_8f1498b5a8c9b21f3d874a...",
    "expires_in": 86400
  }
}
```

---

### 1.2 Login User
Authenticate using registered phone number or Universal ID.

- **Endpoint:** `POST /api/v1/auth/login`
- **Auth:** Public
- **Request Body:**
```json
{
  "identifier": "+14155552671",
  "device_id": "d1e2f3a4-0001-4000-8000-000000000001"
}
```
- **Response (200 OK):**
```json
{
  "code": 200,
  "message": "success",
  "data": {
    "user_id": "018d3b7d-3b7d-7bad-8bdd-111122223333",
    "universal_id": "UID:1:0000000001",
    "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "refresh_token": "rt_99e82c1a3b5f7e...",
    "expires_in": 86400
  }
}
```

---

### 1.3 Refresh Access Token
Rotates the refresh token transactionally. Using an old/previously used token triggers automated session revocation across all devices.

- **Endpoint:** `POST /api/v1/auth/refresh`
- **Auth:** Public
- **Request Body:**
```json
{
  "refresh_token": "rt_99e82c1a3b5f7e..."
}
```
- **Response (200 OK):**
```json
{
  "code": 200,
  "message": "success",
  "data": {
    "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "refresh_token": "rt_new_token_77d8...",
    "expires_in": 86400
  }
}
```

---

### 1.4 Logout
Revokes the current refresh token and invalidates active sessions.

- **Endpoint:** `POST /api/v1/auth/logout`
- **Auth:** Bearer Token
- **Request Body:**
```json
{
  "refresh_token": "rt_new_token_77d8..."
}
```
- **Response (200 OK):**
```json
{
  "code": 200,
  "message": "User logged out successfully",
  "data": null
}
```

---

### 1.5 Create WebSocket Ticket
Generates a single-use, 60-second authentication ticket for connecting to the WebSocket gateway.

- **Endpoint:** `POST /api/v1/auth/ws-ticket`
- **Auth:** Bearer Token
- **Request Body:** `{}`
- **Response (200 OK):**
```json
{
  "code": 200,
  "message": "success",
  "data": {
    "ticket": "wst_a9b8c7d6e5f41234...",
    "expires_in_seconds": 60
  }
}
```

---

### 1.6 Get Current User Profile
- **Endpoint:** `GET /api/v1/users/me`
- **Auth:** Bearer Token
- **Response (200 OK):**
```json
{
  "code": 200,
  "message": "success",
  "data": {
    "id": "018d3b7d-3b7d-7bad-8bdd-111122223333",
    "universal_id": "UID:1:0000000001",
    "phone": "+14155552671",
    "display_name": "Alice Smith",
    "created_at": "2026-10-23T12:00:00Z"
  }
}
```

---

### 1.7 Update Profile
- **Endpoint:** `PATCH /api/v1/users/me`
- **Auth:** Bearer Token
- **Request Body:**
```json
{
  "display_name": "Alice S. (Mobile)"
}
```
- **Response (200 OK):** Returns updated User Profile.

---

## Module 2: Application Management & Multi-Tenancy

For developer platforms and third-party app embeddings.

### 2.1 Create Application
- **Endpoint:** `POST /api/v1/apps`
- **Auth:** Bearer Token
- **Request Body:**
```json
{
  "name": "Acme Dialer Pro"
}
```
- **Response (200 OK):**
```json
{
  "code": 200,
  "message": "success",
  "data": {
    "app_id": "app_9f8e7d6c5b4a",
    "name": "Acme Dialer Pro",
    "client_secret": "sec_live_3847291847192847",
    "created_at": "2026-10-23T12:00:00Z"
  }
}
```

### 2.2 Issue Embedded SDK Token
- **Endpoint:** `POST /api/v1/auth/sdk-token`
- **Auth:** Public (Authenticated via `client_secret`)
- **Request Body:**
```json
{
  "app_id": "app_9f8e7d6c5b4a",
  "client_secret": "sec_live_3847291847192847",
  "universal_id": "UID:1:0000000001",
  "endpoint_id": "d1e2f3a4-0001-4000-8000-000000000001"
}
```
- **Response (200 OK):**
```json
{
  "code": 200,
  "message": "success",
  "data": {
    "sdk_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "universal_id": "UID:1:0000000001",
    "endpoint_id": "d1e2f3a4-0001-4000-8000-000000000001"
  }
}
```

---

## Module 3: Universal Identity Resolution

### 3.1 Resolve Identity
Translate a Universal ID into system user metadata.

- **Endpoint:** `GET /api/v1/identity/:universal_id`
- **Auth:** Bearer Token
- **Response (200 OK):**
```json
{
  "code": 200,
  "message": "success",
  "data": {
    "universal_id": "UID:1:0000000002",
    "user_id": "018d3b7d-3b7d-7bad-8bdd-999988887777",
    "display_name": "Bob Jones",
    "is_registered": true
  }
}
```

---

## Module 4: Devices & Signaling Endpoints

### 4.1 Register Device
Registers hardware specifications and push notification tokens.

- **Endpoint:** `POST /api/v1/endpoints/device`
- **Auth:** Bearer Token
- **Request Body:**
```json
{
  "device_id": "d1e2f3a4-0001-4000-8000-000000000001",
  "device_name": "Pixel 8 Pro",
  "platform": "android",
  "push_token": "fcm_token_sample_xyz..."
}
```
- **Response (200 OK):** Returns registered device record.

---

### 4.2 Delete / Deregister Device
- **Endpoint:** `DELETE /api/v1/devices/:device_id`
- **Auth:** Bearer Token
- **Response (200 OK):**
```json
{
  "code": 200,
  "message": "Device deregistered successfully",
  "data": null
}
```

---

### 4.3 Register Active Signaling Endpoint
Registers an ephemeral WebSocket connection endpoint in Redis with presence state.

- **Endpoint:** `POST /api/v1/endpoints`
- **Auth:** Bearer Token
- **Request Body:**
```json
{
  "endpoint_id": "e9a8b7c6-0000-4000-8000-000000000001",
  "device_id": "d1e2f3a4-0001-4000-8000-000000000001",
  "capabilities": ["audio", "video", "e2ee_messaging"]
}
```
- **Response (200 OK):** Endpoint registration confirmation.

---

### 4.4 Get User Endpoints
List active signaling endpoints for a Universal ID.

- **Endpoint:** `GET /api/v1/endpoints/user/:universal_id`
- **Auth:** Bearer Token
- **Response (200 OK):**
```json
{
  "code": 200,
  "message": "success",
  "data": [
    {
      "endpoint_id": "e9a8b7c6-0000-4000-8000-000000000001",
      "device_id": "d1e2f3a4-0001-4000-8000-000000000001",
      "is_online": true,
      "capabilities": ["audio", "video", "e2ee_messaging"]
    }
  ]
}
```

---

## Module 5: Smart Communication Routing Engine

The core decision engine powering the UCall Unified Dialer & Messenger.

### 5.1 Resolve Destination
Inspects an entered number/ID, recipient presence, capability matrix, and blocklists. Instructs the mobile client whether to initiate a high-definition WebRTC internet call/message or fallback to native carrier cellular telephony.

- **Endpoint:** `POST /api/v1/communication/resolve`
- **Auth:** Bearer Token
- **Request Body:**
```json
{
  "destination": "+14155552672",
  "requested_action": "audio_call",
  "client_platform": "android"
}
```

#### Response: UCall-to-UCall Internet Calling
```json
{
  "code": 200,
  "message": "success",
  "data": {
    "destination": "+14155552672",
    "route_type": "ucall_internet",
    "recipient_universal_id": "UID:1:0000000002",
    "is_ucall_user": true,
    "can_do_audio": true,
    "can_do_video": true,
    "can_do_messaging": true,
    "recommended_action": "ucall_webrtc_call",
    "fallback_action": "native_carrier_call"
  }
}
```

#### Response: Non-UCall User (Carrier Fallback)
```json
{
  "code": 200,
  "message": "success",
  "data": {
    "destination": "+19995551212",
    "route_type": "native_cellular",
    "recipient_universal_id": null,
    "is_ucall_user": false,
    "can_do_audio": false,
    "can_do_video": false,
    "can_do_messaging": false,
    "recommended_action": "native_carrier_call",
    "fallback_action": "native_carrier_sms"
  }
}
```

---

## Module 6: Address Book & Contact Synchronization

### 6.1 Sync Contacts
Uploads client address book hashes/numbers. Automatically discovers which contacts are active UCall users.

- **Endpoint:** `POST /api/v1/contacts/sync`
- **Auth:** Bearer Token
- **Request Body:**
```json
{
  "contacts": [
    {
      "client_contact_id": "raw_contact_101",
      "phone_number": "+14155552672",
      "contact_name": "Bob Jones"
    },
    {
      "client_contact_id": "raw_contact_102",
      "phone_number": "+15551234567",
      "contact_name": "Charlie External"
    }
  ]
}
```
- **Response (200 OK):**
```json
{
  "code": 200,
  "message": "success",
  "data": {
    "matches": [
      {
        "client_contact_id": "raw_contact_101",
        "phone_number": "+14155552672",
        "contact_name": "Bob Jones",
        "is_ucall_user": true,
        "universal_id": "UID:1:0000000002",
        "avatar_url": null
      },
      {
        "client_contact_id": "raw_contact_102",
        "phone_number": "+15551234567",
        "contact_name": "Charlie External",
        "is_ucall_user": false,
        "universal_id": null,
        "avatar_url": null
      }
    ]
  }
}
```

---

### 6.2 Get Saved Contacts
- **Endpoint:** `GET /api/v1/contacts`
- **Auth:** Bearer Token
- **Response (200 OK):** Returns array of synchronized contact records.

---

### 6.3 Delete Contact
- **Endpoint:** `DELETE /api/v1/contacts/:contact_id`
- **Auth:** Bearer Token
- **Response (200 OK):** `{ "code": 200, "message": "Contact deleted", "data": null }`

---

## Module 7: WebRTC Calling Control Plane & TURN

### 7.1 Initiate Call
Initiates an audio or video call session. Validates callee presence and rings callee endpoints via WebSocket.

- **Endpoint:** `POST /api/v1/calls`
- **Auth:** Bearer Token
- **Headers:** `X-Idempotency-Key: <uuid>` (Optional)
- **Request Body:**
```json
{
  "callee_universal_id": "UID:1:0000000002",
  "call_type": "audio",
  "client_request_id": "req-987654"
}
```
- **Response (200 OK):**
```json
{
  "code": 200,
  "message": "success",
  "data": {
    "call_id": "c1d2e3f4-0000-4000-8000-000000000001",
    "caller_universal_id": "UID:1:0000000001",
    "callee_universal_id": "UID:1:0000000002",
    "call_type": "audio",
    "status": "ringing",
    "created_at": "2026-10-23T12:00:00Z"
  }
}
```

---

### 7.2 Accept Call
- **Endpoint:** `POST /api/v1/calls/:call_id/accept`
- **Auth:** Bearer Token
- **Request Body:**
```json
{
  "endpoint_id": "e9a8b7c6-0000-4000-8000-000000000002"
}
```
- **Response (200 OK):** Call status transitions to `active`.

---

### 7.3 Reject / End / Cancel Call
- **Reject:** `POST /api/v1/calls/:call_id/reject`
- **Cancel:** `POST /api/v1/calls/:call_id/cancel`
- **End:** `POST /api/v1/calls/:call_id/end` or `POST /api/v1/calls/:call_id/hangup`
- **Request Body:**
```json
{
  "reason": "user_hung_up"
}
```
- **Response (200 OK):** Call status transitions to `ended`, `rejected`, or `cancelled`.

---

### 7.4 Get Ephemeral TURN Credentials
Generates short-lived HMAC-SHA1 Coturn / STUN / TURN server credentials scoped to an active call.

- **Endpoint:** `GET /api/v1/calls/:call_id/turn-credentials`
- **Auth:** Bearer Token
- **Response (200 OK):**
```json
{
  "code": 200,
  "message": "success",
  "data": {
    "uris": [
      "stun:turn.ucall.chat:3478",
      "turn:turn.ucall.chat:3478?transport=udp",
      "turns:turn.ucall.chat:5349?transport=tcp"
    ],
    "username": "1730000000:UID:1:0000000001",
    "password": "BASE64_HMAC_SHA1_SECRET_STRING",
    "ttl_seconds": 86400
  }
}
```

---

### 7.5 Get Call History
- **Endpoint:** `GET /api/v1/calls/history?limit=20`
- **Auth:** Bearer Token
- **Response (200 OK):**
```json
{
  "code": 200,
  "message": "success",
  "data": [
    {
      "id": "c1d2e3f4-0000-4000-8000-000000000001",
      "peer_universal_id": "UID:1:0000000002",
      "direction": "outgoing",
      "call_type": "audio",
      "status": "ended",
      "duration_seconds": 142,
      "created_at": "2026-10-23T12:00:00Z"
    }
  ]
}
```

---

## Module 8: Messaging & WhatsApp-Style Cursor Sync

### 8.1 Send Message (Blind E2EE Relay)
Submits an encrypted envelope to the recipient's mailbox. Sequence assignment is protected by row-level locking on `user_mailboxes`, ensuring zero race conditions and strictly contiguous sequences.

- **Endpoint:** `POST /api/v1/messages`
- **Auth:** Bearer Token
- **Headers:** `X-Idempotency-Key: <client_msg_uuid>`
- **Request Body:**
```json
{
  "recipient_universal_id": "UID:1:0000000002",
  "message_type": "e2ee",
  "sender_device_id": "d1e2f3a4-0001-4000-8000-000000000001",
  "recipient_device_id": "d1e2f3a4-0002-4000-8000-000000000002",
  "payload": "{\"sender_device_id\":\"...\",\"dh_pub\":\"...\",\"sequence_num\":0,\"previous_chain_len\":0,\"ciphertext\":\"...\",\"nonce\":\"...\"}"
}
```
- **Response (200 OK):**
```json
{
  "code": 200,
  "message": "success",
  "data": {
    "id": "018d3b7d-3b7d-7bad-8bdd-333344445555",
    "recipient_seq": 42,
    "seq": 10842,
    "status": "sent",
    "created_at": "2026-10-23T12:05:00Z"
  }
}
```

---

### 8.2 Incremental Cursor Synchronization
Enables mobile clients to recover missed messages upon reconnect or app resume. Guarantees zero missed events via monotonic sequences.

- **Endpoint:** `GET /api/v1/messages/sync?since_seq=41&limit=50`
- **Auth:** Bearer Token
- **Query Parameters:**
  - `since_seq` (integer, default `0`): Retrieve messages strictly greater than this sequence.
  - `limit` (integer, default `50`, max `100`): Maximum batch size.
- **Response (200 OK):**
```json
{
  "code": 200,
  "message": "success",
  "data": {
    "messages": [
      {
        "id": "018d3b7d-3b7d-7bad-8bdd-333344445555",
        "recipient_seq": 42,
        "sender_user_id": "018d3b7d-3b7d-7bad-8bdd-111122223333",
        "message_type": "e2ee",
        "payload": "{\"sender_device_id\":\"...\",\"dh_pub\":\"...\",\"sequence_num\":0,\"previous_chain_len\":0,\"ciphertext\":\"...\",\"nonce\":\"...\"}",
        "status": "delivered",
        "created_at": "2026-10-23T12:05:00Z"
      }
    ],
    "has_more": false
  }
}
```

---

### 8.3 Get Conversation Summaries
Returns inbox conversation previews sorted by recent activity.

- **Endpoint:** `GET /api/v1/conversations?limit=20&offset=0`
- **Auth:** Bearer Token
- **Response (200 OK):**
```json
{
  "code": 200,
  "message": "success",
  "data": [
    {
      "peer_user_id": "018d3b7d-3b7d-7bad-8bdd-999988887777",
      "peer_universal_id": "UID:1:0000000002",
      "peer_display_name": "Bob Jones",
      "last_message_id": "018d3b7d-3b7d-7bad-8bdd-333344445555",
      "last_message_type": "e2ee",
      "last_message_time": "2026-10-23T12:05:00Z",
      "unread_count": 1
    }
  ]
}
```

---

### 8.4 Mark Message Delivered / Read
- **Mark Delivered:** `POST /api/v1/messages/:message_id/delivered`
- **Mark Read:** `POST /api/v1/messages/:message_id/read`
- **Auth:** Bearer Token
- **Response (200 OK):** Status updated and acknowledgment dispatched to sender.

---

## Module 9: E2EE PreKey Management (X3DH / Ratchet)

### 9.1 Publish PreKey Bundle
Publishes device Ed25519 identity key, signed X25519 prekey with signature, and a batch of single-use One-Time PreKeys (OPKs).

- **Endpoint:** `POST /api/v1/e2ee/keys`
- **Auth:** Bearer Token
- **Request Body:**
```json
{
  "device_id": "d1e2f3a4-0001-4000-8000-000000000001",
  "identity_key": "BASE64_32_BYTE_ED25519_PUBLIC_KEY",
  "signed_prekey_id": 1,
  "signed_prekey": "BASE64_32_BYTE_X25519_PUBLIC_KEY",
  "signed_prekey_sig": "BASE64_64_BYTE_ED25519_SIGNATURE",
  "one_time_prekeys": [
    {
      "key_id": 1,
      "public_key": "BASE64_32_BYTE_X25519_PUBLIC_KEY"
    },
    {
      "key_id": 2,
      "public_key": "BASE64_32_BYTE_X25519_PUBLIC_KEY"
    }
  ]
}
```
- **Response (200 OK):**
```json
{
  "code": 200,
  "message": "success",
  "data": {
    "device_id": "d1e2f3a4-0001-4000-8000-000000000001",
    "published_opk_count": 2,
    "total_available_opks": 100
  }
}
```

---

### 9.2 Fetch Device PreKey Bundle (X3DH Session Initiation)
Fetches public keys for initiating an encrypted session. Atomically consumes a single-use OPK using row-level locks and a 60-second Redis retry cache window.

- **Endpoint:** `GET /api/v1/e2ee/keys/:universal_id/:device_id`
- **Auth:** Bearer Token (Mandatory)
- **Response (200 OK):**
```json
{
  "code": 200,
  "message": "success",
  "data": {
    "device_id": "d1e2f3a4-0002-4000-8000-000000000002",
    "user_id": "018d3b7d-3b7d-7bad-8bdd-999988887777",
    "identity_key": "BASE64_32_BYTE_ED25519_PUBLIC_KEY",
    "signed_prekey_id": 1,
    "signed_prekey": "BASE64_32_BYTE_X25519_PUBLIC_KEY",
    "signed_prekey_sig": "BASE64_64_BYTE_ED25519_SIGNATURE",
    "one_time_prekey": {
      "key_id": 42,
      "public_key": "BASE64_32_BYTE_X25519_PUBLIC_KEY"
    }
  }
}
```

---

### 9.3 Get Remaining OPK Count
Clients check their remaining server prekeys. When available count drops below 20, client automatically replenishes.

- **Endpoint:** `GET /api/v1/e2ee/keys/count?device_id=d1e2f3a4-0001-4000-8000-000000000001`
- **Auth:** Bearer Token
- **Response (200 OK):**
```json
{
  "code": 200,
  "message": "success",
  "data": {
    "device_id": "d1e2f3a4-0001-4000-8000-000000000001",
    "available_opks": 84
  }
}
```

---

## Module 10: Real-Time WebSocket Signaling Gateway

### 10.1 Connection Handshake
- **URL:** `ws://localhost:8080/api/v1/ws?ticket=wst_a9b8c7d6e5f41234...`
- The ticket is verified and atomically consumed from Redis via `GETDEL`.

---

### 10.2 Wire Event Format
All WebSocket frames are serialized JSON objects conforming to:
```json
{
  "type": "event_name",
  "data": { ... }
}
```

---

### 10.3 Inbound Events (Client $\rightarrow$ Server)

#### 1. `call.offer` (WebRTC SDP Offer)
```json
{
  "type": "call.offer",
  "data": {
    "call_id": "c1d2e3f4-0000-4000-8000-000000000001",
    "callee_universal_id": "UID:1:0000000002",
    "sdp": "v=0\r\no=- 42 2 IN IP4 127.0.0.1...",
    "call_type": "audio"
  }
}
```

#### 2. `call.answer` (WebRTC SDP Answer)
```json
{
  "type": "call.answer",
  "data": {
    "call_id": "c1d2e3f4-0000-4000-8000-000000000001",
    "sdp": "v=0\r\no=- 43 2 IN IP4 127.0.0.1..."
  }
}
```

#### 3. `call.candidate` (ICE Candidate)
```json
{
  "type": "call.candidate",
  "data": {
    "call_id": "c1d2e3f4-0000-4000-8000-000000000001",
    "candidate": "candidate:842163049 1 udp 1677729535 192.168.1.100 54321 typ host...",
    "sdp_mid": "0",
    "sdp_m_line_index": 0
  }
}
```

#### 4. `msg.delivery_ack` (Recipient Received Message)
```json
{
  "type": "msg.delivery_ack",
  "data": {
    "message_id": "018d3b7d-3b7d-7bad-8bdd-333344445555",
    "sender_user_id": "018d3b7d-3b7d-7bad-8bdd-111122223333"
  }
}
```

#### 5. `msg.read_ack` (Recipient Opened Conversation Viewport)
```json
{
  "type": "msg.read_ack",
  "data": {
    "message_id": "018d3b7d-3b7d-7bad-8bdd-333344445555",
    "sender_user_id": "018d3b7d-3b7d-7bad-8bdd-111122223333"
  }
}
```

---

### 10.4 Outbound Events (Server $\rightarrow$ Client)

#### 1. `msg.receive` (Live Encrypted Message)
```json
{
  "type": "msg.receive",
  "data": {
    "message_id": "018d3b7d-3b7d-7bad-8bdd-333344445555",
    "seq": 10842,
    "recipient_seq": 42,
    "sender_universal_id": "UID:1:0000000001",
    "sender_device_id": "d1e2f3a4-0001-4000-8000-000000000001",
    "recipient_device_id": "d1e2f3a4-0002-4000-8000-000000000002",
    "message_type": "e2ee",
    "payload": "{\"sender_device_id\":\"...\",\"dh_pub\":\"...\",\"sequence_num\":0,\"previous_chain_len\":0,\"ciphertext\":\"...\",\"nonce\":\"...\"}",
    "created_at": "2026-10-23T12:05:00Z"
  }
}
```

#### 2. `msg.delivered` (Delivery Receipt to Sender)
```json
{
  "type": "msg.delivered",
  "data": {
    "message_id": "018d3b7d-3b7d-7bad-8bdd-333344445555",
    "delivered_at": "2026-10-23T12:05:01Z"
  }
}
```

#### 3. `msg.read` (Read Receipt to Sender)
```json
{
  "type": "msg.read",
  "data": {
    "message_id": "018d3b7d-3b7d-7bad-8bdd-333344445555",
    "read_at": "2026-10-23T12:05:05Z"
  }
}
```

#### 4. `call.incoming` (Call Alert)
```json
{
  "type": "call.incoming",
  "data": {
    "call_id": "c1d2e3f4-0000-4000-8000-000000000001",
    "caller_universal_id": "UID:1:0000000001",
    "call_type": "audio",
    "sdp": "v=0\r\no=- 42 2 IN IP4 127.0.0.1..."
  }
}
```

---

## 13. End-to-End Client Workflow Guide

### Flow A: Registration & E2EE Setup
```bash
# 1. Register User
curl -X POST http://localhost:8080/api/v1/auth/register \
  -H "Content-Type: application/json" \
  -d '{"phone": "+14155550001", "display_name": "Alice"}'

# 2. Register Device
curl -X POST http://localhost:8080/api/v1/endpoints/device \
  -H "Authorization: Bearer <ALICE_JWT>" \
  -H "Content-Type: application/json" \
  -d '{"device_id": "alice-dev-01", "device_name": "Alice Phone", "platform": "android"}'

# 3. Publish E2EE PreKey Bundle
curl -X POST http://localhost:8080/api/v1/e2ee/keys \
  -H "Authorization: Bearer <ALICE_JWT>" \
  -H "Content-Type: application/json" \
  -d '{
    "device_id": "alice-dev-01",
    "identity_key": "<BASE64_ED25519_PUB>",
    "signed_prekey_id": 1,
    "signed_prekey": "<BASE64_X25519_PUB>",
    "signed_prekey_sig": "<BASE64_SIG>",
    "one_time_prekeys": [{"key_id": 1, "public_key": "<BASE64_X25519_PUB>"}]
  }'
```

### Flow B: Sending an E2EE Message
```bash
# 1. Fetch Bob's PreKey Bundle
curl -X GET http://localhost:8080/api/v1/e2ee/keys/UID:1:0000000002/bob-dev-01 \
  -H "Authorization: Bearer <ALICE_JWT>"

# 2. Derive Double Ratchet session locally, encrypt payload, and submit envelope
curl -X POST http://localhost:8080/api/v1/messages \
  -H "Authorization: Bearer <ALICE_JWT>" \
  -H "Content-Type: application/json" \
  -H "X-Idempotency-Key: c9a8b7c6-1111-4000-8000-000000000001" \
  -d '{
    "recipient_universal_id": "UID:1:0000000002",
    "message_type": "e2ee",
    "payload": "{\"sender_device_id\":\"alice-dev-01\",\"recipient_device_id\":\"bob-dev-01\",\"dh_pub\":\"...\",\"sequence_num\":0,\"previous_chain_len\":0,\"ciphertext\":\"...\",\"nonce\":\"...\"}"
  }'
```

### Flow C: Incremental Sync Upon Reconnect
```bash
# Query messages received since last local sequence watermark (e.g. seq 42)
curl -X GET "http://localhost:8080/api/v1/messages/sync?since_seq=42&limit=50" \
  -H "Authorization: Bearer <BOB_JWT>"
```
