> **Client contract note:** Apply [`shared/response-envelope.md`](../shared/response-envelope.md) to JSON responses after the response-contract release. Legacy wrapper examples below may reflect the prior API; the documented endpoint-specific payload fields are still useful. Not staging-verified.

# Realtime — Flutter API handoff (source-verified)

**Repository:** `alalmiyalhura/outlet`, branch `main`, reviewed 2026-11-22. **API prefix:** `/api/v1`. **Coverage:** 1/1 Realtime HTTP endpoint. This is a source-code contract, **not** a staging or device test. All example values are illustrative.

## 1. POST `/api/v1/realtime/auth` — authorize private socket subscription

**Purpose:** Authorize the *currently signed-in user* to subscribe to a private Pusher-protocol channel. This endpoint does **not** create a socket connection and does **not** return the application's ordinary `data` envelope.

| Attribute | Contract |
|---|---|
| Method / path | `POST /api/v1/realtime/auth` |
| Authentication | `auth:sanctum`; `Authorization: Bearer <access_token>` |
| Throttle | `60` requests per minute |
| Request Content-Type | `application/json` (recommended) |
| Success | `200 OK`, broadcaster-generated authentication object |
| Authorization | Channel registry checks caller ID and audience membership before signing |
| Path/query parameters | None |

### Request body — complete field table

| Field | JSON type | Required | Backend validation | Flutter handling |
|---|---|---|---|---|
| `channel_name` | string | Yes | `required|string|max:120` | Exact private channel returned/constructed from allowed audience, e.g. `private-users.7` |
| `socket_id` | string | Yes | `required|string|max:64` | Obtain from the active socket connection; not the device ID or FCM token |

```http
POST /api/v1/realtime/auth HTTP/1.1
Authorization: Bearer <access_token>
Accept: application/json
Content-Type: application/json

{"channel_name":"private-users.7","socket_id":"1234.5678"}
```

### Success response

The response is returned by the configured broadcaster's `validAuthenticationResponse(...)`, **not** `ApiResponse::ok`. For a compatible private-channel Pusher broadcaster, the typical response is:

```json
{"auth":"<broadcaster-generated-signature>"}
```

| JSON path | Type | Required? | Meaning |
|---|---|---|---|
| `auth` | string | Driver-dependent | Authorization signature for the socket subscription |
| Other broadcaster fields | Driver-dependent | Driver-dependent | Do not discard fields that the configured broadcaster/socket client requires |

**Do not** expect `{"data":{"auth":...}}`. The exact successful shape depends on the broadcaster; the test's fake driver verifies a top-level `auth` field.

### Supported channel names and access rules

| Channel | Access | Flutter use |
|---|---|---|
| `private-users.{userId}` | Only the user whose authenticated ID equals `{userId}` | Personal notifications, orders and other user-scoped invalidation hints |
| `private-tenants.{tenantId}` | Only if the server's tenant-membership rule allows the authenticated user | Tenant-scoped hints, when tenancy is configured |
| Any other name, e.g. `private-orders.1`, `users.7`, `presence-users.7` | Denied by the registry | Do not subscribe |

`{userId}` and `{tenantId}` must be positive decimal integers without leading zeroes, matching `^private-(users|tenants)\.([1-9][0-9]{0,18})$`. Unknown channel kinds fail closed. A tenant channel without membership support/permission is denied. **Never** use `private-user.7` (singular): the supported name is `private-users.7`.

### Errors and HTTP status

| Status | Code / response | Trigger | Flutter action |
|---|---|---|---|
| `401` | Authentication failure | Missing/invalid Sanctum token | Refresh/re-authenticate; do not repeatedly retry socket authorization without a valid token |
| `422` | Validation error | Missing/non-string/overlong `channel_name` or `socket_id` | Fix client request; no automatic retry |
| `403` | `channel_forbidden` | Channel is unknown, malformed or caller lacks permission | Do not join; verify user/channel selection |
| `501` | `realtime_not_configured` | Server broadcast driver is `null` or `log` | Disable socket UI behavior and use normal API refresh/polling fallback |
| `429` | Rate limit | More than configured auth requests | Back off; avoid reconnection loops |

**403 example (exact controller keys; values illustrative):**

```json
{"error":{"code":"channel_forbidden","message":"You may not subscribe to this channel.","request_id":"<request-id-or-null>"}}
```

**501 example:**

```json
{"error":{"code":"realtime_not_configured","message":"No socket server is configured (BROADCAST_CONNECTION).","request_id":"<request-id-or-null>"}}
```

The controller reads `request_id` from the request attribute; it may be null. The standard framework-generated `401`, `422` and `429` response bodies are not defined by this controller and should be handled by status rather than by assuming the above custom error shape.

## 2. Socket events — no additional Flutter HTTP endpoints

The Realtime module publishes an event named **`invalidate`** to authorized private channels. The message is a *hint* to refresh relevant API data, **not** the actual order/notification object.

**Example broadcast payload** (source-backed shape, illustrative timestamp):

```json
{"v":1,"topics":["notifications","orders"],"at":"2026-05-01T10:00:00+00:00"}
```

| JSON path | Type | Meaning |
|---|---|---|
| `v` | integer | Hint schema version; currently `1` |
| `topics` | array of strings | Names of invalidated resources; deduplicated and sorted by backend |
| `at` | ISO-8601 datetime string | Publication timestamp |

Topics may include broad names such as `orders`, `notifications` and scoped names such as `orders:15`; these are **not** authorization channel names. Valid topic syntax is lower-case letters/digits followed by lower-case letters/digits/`.`/`_`/`:`/`-`, maximum 64 characters, maximum 20 topics per hint by current config. Do not assume a closed enum of topics.

### Recommended Flutter flow

1. After login, get the authenticated user ID from `/api/v1/me` or the auth response; establish the configured Pusher-compatible socket connection.
2. Subscribe to `private-users.<authenticatedUserId>`; configure the channel authorizer to `POST /api/v1/realtime/auth` with the Bearer token, channel name and **socket-provided** socket ID.
3. Only subscribe to `private-tenants.<tenantId>` if the app has a legitimate tenant context and the backend permits membership.
4. Listen for `invalidate`. For each `topics` entry, invalidate/refetch the corresponding REST-backed cache; do not treat hints as full resource payloads.
5. Coalesce rapid hints and refresh after reconnect/app resume to recover events missed while offline. Handle `403` and `501` as non-retryable until context/configuration changes.
6. On logout/account switch, disconnect/unsubscribe and clear the previous user's cached data. Push notifications are a separate integration (see `push.md` and `devices.md`).

**Delivery semantics:** Hints are dispatched after transaction commit; rolled-back changes do not generate hints. Backend sends asynchronously through a queued job (up to 3 job attempts, backoff 2 and 10 seconds). The socket can be unavailable; the app must not rely on hints as its only way to obtain current state. The server can disable realtime with `REALTIME_ENABLED=false`.

## 3. Verification and implementation checklist

- [x] Route and `auth:sanctum` / throttle reviewed.
- [x] Request validation, channel format and authorization registry reviewed.
- [x] `403`, `501` custom error payloads reviewed.
- [x] Event name, hint payload, topic validation and queue semantics reviewed.
- [x] Repository tests checked for own-channel success, other-user denial, tenant membership, unknown channels, missing auth and disabled broadcaster.
- [ ] Verify actual configured socket server, host, TLS and credentials in the target environment (not exposed by this endpoint).
- [ ] Capture a real authorized subscription and `invalidate` event on staging with Flutter.
- [ ] Test reconnect/offline cache refresh and token expiry on devices.

### Sources

- [`modules/Realtime/Routes/api.php`](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Realtime/Routes/api.php)
- [`ChannelAuthController.php`](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Realtime/Interfaces/Http/Controllers/ChannelAuthController.php)
- [`ChannelRegistry.php`](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Realtime/Application/ChannelRegistry.php)
- [`Audience.php`](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Realtime/Domain/Audience.php)
- [`Topics.php`](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Realtime/Domain/Topics.php)
- [`SendHintJob.php`](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Realtime/Infrastructure/SendHintJob.php)
- [`RealtimeTest.php`](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Realtime/Tests/RealtimeTest.php)
