# TORAZ Backend — API Contract

**Status:** Grows one module section per recovery batch (plan item P1, approved 2026-10-07). Each section is written and checked against the frontend before that batch's code. The document is finalized in Recovery 10.

Everything here is RECONSTRUCTED. The original API contract was lost; no path, status code or field below is claimed to be what the lost backend used unless a source is cited. Source tags (MP, R01–R07, FE) and gap IDs are defined in `RECOVERY_BASELINE.md` and `RECOVERY_GAPS.md`.

| Section | Module | Batch | State |
|---|---|---|---|
| 1 | Conventions | Recovery 1 | Written |
| 2 | Health | Recovery 1 | Written |
| 3 | Authentication | Recovery 2 | Written |
| 4 | Operational commands | Recovery 2 | Written |
| 5 | Profile | Recovery 3 | Written |
| 6 | Photos | Recovery 3 | Written |
| 7 | Effective privacy (gap C8, decision AD-19) | Recovery 3 | Written |
| 8 | Discovery | Recovery 4 | Written (decisions AD-23 to AD-26) |
| 9 | Matching | Recovery 4 | Written (decisions AD-22, AD-27) |
| 10 | Messaging | Recovery 5 | Written (decisions AD-32 to AD-36) |
| 11 | Real-time (Socket.IO) | Recovery 5 | Written (decisions AD-32 to AD-36) |
| 12 | Safety: blocks, reports, moderation events | Recovery 6 | Written (decisions AD-38 to AD-46) |
| 13 | Verification | Recovery 7 | Written (decisions AD-47 to AD-54; gap defaults B10, B13, C1, D21) |
| 14 | Premium (payment-disabled) | Recovery 8 | Written (decisions AD-55 to AD-64; gap defaults D22, B13, B12) |
| 15 | Admin and moderation operations | Recovery 9 | Implemented in Recovery 9-A to 9-D, runtime-unverified (decisions AD-65 to AD-83; P-02, P-04, P-13, the retention part of P-12, N-3, retention periods and the verification admin-trust policy pending). *Recovery 9B correction: this row still described Recovery 9-A.* *2026-10-26: P-02 is AD-90 (conditional), P-04 is AD-91 (not approved; production blocker), N-3 is AD-92; see §15* |
| 16 | Member settings: the counters and the Online Activity Indicator | Recovery 9B | **Written and implemented** (decisions AD-19, AD-34, AD-70, AD-71); runtime-unverified |
| — | Other settings, sessions, pause, deletion, export, purge | Recovery 9B | **Not written**: design only (`docs/reports/RECOVERY_9B_DATA_LIFECYCLE_DESIGN.md`), decisions pending |

---

## 1. Conventions

### 1.1 Envelopes (MP §29; R01 §5)

```json
{ "success": true,  "message": "…", "data": { } }
{ "success": true,  "message": "…", "data": [ ], "pagination": { } }
{ "success": false, "message": "…", "errors": { } }
```

`errors` is always an object. For validation failures it maps a field path to one message. For OTP failures it carries `reason`.

### 1.2 Status codes

| Status | Meaning |
|---|---|
| 200 | Success |
| 201 | Created: a profile registered, a photo uploaded |
| 400 | Validation failed, malformed body, unsupported field names |
| 401 | Not authenticated: missing, invalid or expired token; revoked or expired session |
| 403 | Authenticated but not allowed; suspended account; origin not allowed |
| 404 | Route or resource not found |
| 409 | Conflict with existing data |
| 410 | The thing addressed has expired (OTP request) |
| 413 | Body too large, or a photo over `MAX_FILE_SIZE_MB` |
| 429 | Rate limit or attempt limit reached |
| 500 | Unexpected error; the message is always `Internal server error` |
| 503 | A required service is unavailable or disabled |

### 1.3 Authentication transport (MP §9; R06)

- **Access token:** a JWT sent as `Authorization: Bearer <token>`. Returned in the JSON body by verify-OTP and refresh.
- **Refresh token:** a JWT carried only in an HttpOnly cookie named `toraz_refresh`, scoped to the path `/api/auth`. It never appears in a response body and is never accepted from a request body.
- Identity, role and account status are always read from the database for the session named in the verified token. Nothing identity-related is accepted from the request (R01 §4).

### 1.4 Other rules

- Every response carries a server-generated `X-Request-Id`.
- Request bodies are JSON. Keys that start with `$`, contain `.`, or are `__proto__`, `constructor` or `prototype` are refused with 400, as are repeated query parameters.
- Unknown body fields are dropped by the validators before a controller sees them.
- A browser request from an origin not listed in `FRONTEND_URL` is refused with 403.

---

## 2. Health

### `GET /api/health`

| | |
|---|---|
| Frontend service | none |
| Authentication | none |
| Rate limit | exempt |

- **200** `data: { "status": "ok", "database": "connected", "timestamp": "<ISO 8601>" }`
- **503** `errors: { "database": "disconnected" }`

---

## 3. Authentication

Mobile number and one-time code only; there are no passwords (FE:`lib/validations/auth.ts`).

Six routes, all with an explicit method and path in MP §8. Three are called by the frontend's `authService`; three (refresh, logout, current user) have no frontend method yet.

### 3.1 Summary

| # | Method and path | Frontend method | Authentication |
|---|---|---|---|
| 1 | `POST /api/auth/request-otp` | `authService.requestOtp(input)` | none |
| 2 | `POST /api/auth/verify-otp` | `authService.verifyOtp(input)` | none |
| 3 | `POST /api/auth/resend-otp` | `authService.resendOtp(requestId)` | none |
| 4 | `POST /api/auth/refresh` | none | refresh cookie |
| 5 | `POST /api/auth/logout` | none | access token or refresh cookie, both optional |
| 6 | `GET /api/auth/me` | none | access token |

Routes 1–4 share a per-IP rate limit separate from the global one (`AUTH_RATE_LIMIT_MAX` per `AUTH_RATE_LIMIT_WINDOW_MS`).

### 3.2 OTP rules

| Rule | Value | Basis |
|---|---|---|
| Code | 6 digits, from a cryptographic random source | FE `otpCodeSchema`; MP §8 |
| Storage | keyed hash bound to the request ID; the code itself is never stored or logged | MP §8 |
| Validity | 5 minutes from the most recent send | **Confirmed** (R02) |
| Resend cooldown | 30 seconds | **Confirmed** (R02) |
| Wrong-code attempts per request | 5; reset by a resend | FE auth mock |
| Resends per request | 5; each resend issues a new code | FE auth mock (count); new code is a reconstruction choice |
| Sends per number | per hour and per day caps | MP §8; numbers provisional |
| Use | single use; a newer request for the same number invalidates older ones | MP §8 |
| Account existence | never revealed: the response to request-otp is the same for a known and an unknown number | MP §8 |
| Country code | `+91` only | FE `PhoneInput` offers no other |

**Delivery.** A code is sent through the SMS adapter when `SMS_ENABLED=true`. The `channel` value `whatsapp` is accepted and delivered by SMS (gap D20). When SMS is disabled, request-otp and resend-otp answer 503 unless a development code is configured: `OTP_DEV_FIXED_CODE` makes every code that fixed value, is refused by configuration validation in production, and is never returned in any response (gap D7).

### 3.3 `POST /api/auth/request-otp`

**Request**

```json
{ "countryCode": "+91", "phoneNumber": "<10 digits>", "channel": "sms" }
```

| Field | Rule |
|---|---|
| `countryCode` | required; `+91` |
| `phoneNumber` | required; exactly 10 digits |
| `channel` | optional; `sms` or `whatsapp`; default `sms` |

**200**

```json
{
  "success": true,
  "message": "Verification code sent",
  "data": { "requestId": "<opaque>", "expiresInSeconds": 30, "maskedPhoneNumber": "98765•••••" }
}
```

- `requestId` is a random 32-character hexadecimal string. It is not a database ID.
- `expiresInSeconds` is the **resend cooldown** (30), which is what the frontend uses it for. It is not the code's validity (gap C6).
- `maskedPhoneNumber` shows the first five digits and masks the rest, as the frontend mock does.

**Errors**

| Status | When | `errors` |
|---|---|---|
| 400 | validation | field messages |
| 429 | a code was sent to this number in the last 30 seconds; or the hourly or daily cap for the number is reached; or the per-IP limit is reached | `{}` |
| 503 | no delivery method is available, or the SMS provider failed | `{}` |

### 3.4 `POST /api/auth/verify-otp`

**Request**

```json
{ "requestId": "<opaque>", "code": "<6 digits>" }
```

**200**

```json
{
  "success": true,
  "message": "Number verified",
  "data": {
    "isNewUser": true,
    "accessToken": "<JWT>",
    "accessTokenExpiresIn": 900,
    "user": {
      "id": "<account id>",
      "countryCode": "+91",
      "maskedPhoneNumber": "98765•••••",
      "role": "USER",
      "phoneVerified": true,
      "registrationCompleted": false
    }
  }
}
```

The response also sets the `toraz_refresh` cookie.

- `isNewUser` is `true` until the account has completed registration (gap C5). It is the same fact as `user.registrationCompleted === false`.
- On first verification for a number, the account is created. A number never gets a second account.
- Verifying a mobile number is not identity verification (MP §6).

**Errors**

| Status | `errors.reason` | When |
|---|---|---|
| 400 | `invalid_code` | the code does not match; the attempt is counted |
| 410 | `expired` | the request is unknown, already used, replaced by a newer one, or older than 5 minutes |
| 429 | `too_many_attempts` | 5 wrong attempts have been made on this request |
| 400 | — | validation failure (field messages) |
| 403 | — | the account is suspended or otherwise not active |
| 429 | — | per-IP limit reached (no `reason`) |

The three `reason` values are exactly the frontend's `VerifyOtpFailureReason`.

### 3.5 `POST /api/auth/resend-otp`

**Request**

```json
{ "requestId": "<opaque>" }
```

**200** — same shape as request-otp, with the same `requestId`. A new code is issued, the 5-minute validity restarts, and the wrong-attempt count resets.

**Errors**

| Status | When | `errors` |
|---|---|---|
| 410 | the request is unknown, already used or replaced | `{ "reason": "expired" }` |
| 429 | resent within 30 seconds; or 5 resends already made; or the number's hourly or daily cap is reached; or per-IP limit | `{}` |
| 503 | no delivery method, or the SMS provider failed | `{}` |

### 3.6 `POST /api/auth/refresh`

No body. Reads the `toraz_refresh` cookie.

**200**

```json
{ "success": true, "message": "Session refreshed", "data": { "accessToken": "<JWT>", "accessTokenExpiresIn": 900 } }
```

The refresh token is **rotated**: the response sets a new cookie and the previous token stops working.

**Errors**

| Status | When |
|---|---|
| 401 | cookie missing; token invalid or expired; session revoked, expired or unknown |
| 401 | the token presented is not the session's current one. This is treated as reuse of a rotated token and **the session is revoked** |
| 403 | the account is suspended |

Two refresh calls made at the same moment with the same token: exactly one succeeds. The other is indistinguishable from reuse, so the session ends revoked and the user signs in again. A client must therefore not refresh in parallel.

### 3.7 `POST /api/auth/logout`

No body. Revokes the session named by a valid access token, or failing that by a valid refresh cookie, and clears the cookie. Always answers **200** `Logged out`, including when no valid credential was sent, so it is safe to call repeatedly. From Recovery 5, every Socket.IO connection of the revoked session is disconnected at once (§11.2).

### 3.8 `GET /api/auth/me`

**200** `data: { "user": { … } }` with the same `user` object as verify-otp.

**Errors:** 401 (no or bad token, revoked or expired session, account deleted), 403 (account suspended).

### 3.9 Authorization rules for every authenticated route

Applied by the `authenticate` middleware on each request, in this order:

1. The `Authorization` header holds a Bearer access token with a valid signature and expiry.
2. The session it names exists, is not revoked, has not expired, and belongs to the account it names.
3. The account exists and its status is `active`. `suspended` answers 403; anything else answers 401.

Role comes from the account record at that moment. `requireAdmin` then requires role `ADMIN`; otherwise 403. A role is never read from a token claim, a header, a query string or a body.

### 3.10 How a frontend adapter would map these (for reference; no frontend work is done)

| Frontend expectation | Backend response |
|---|---|
| `RequestOtpResult` | `data` of 3.3 / 3.5, unchanged |
| `VerifyOtpResult` `{ success: true, isNewUser }` | 200; `data.isNewUser` |
| `VerifyOtpResult` `{ success: false, reason }` | 400, 410 or 429 with `errors.reason` |
| `AuthServiceError("rate_limited")` | 429 without `errors.reason` |
| `AuthServiceError("network_error")` | 5xx, 503, or resend answering 410 |

---

## 4. Operational commands

These are run on the server by an operator. They are not HTTP routes and add nothing to the route inventory.

### 4.1 Create the first administrator (gap D13; approved reconstruction)

There is no HTTP route that creates an administrator or changes a role, and no request field is ever read as a role. The first administrator is created by promoting an existing account from the command line.

```bash
npm run admin:create-first -- --country-code +91 --phone <10 digits>            # dry run
npm run admin:create-first -- --country-code +91 --phone <10 digits> --confirm  # performs it
```

**Preconditions, all enforced by the command**

1. The person has already signed in once through the normal OTP flow, so the account exists and its number is verified. The command never creates an account and never bypasses OTP.
2. The account's status is `active` and its role is `USER`.
3. **No administrator exists yet.** If one does, the command refuses. It creates the first administrator only.

**Behaviour**

- Without `--confirm` it changes nothing: it reports what it would do and exits 0.
- With `--confirm` it promotes the account, then counts administrators again. If more than one now exists (two operators ran it at once), it reverses its own change and fails.
- It revokes the account's existing sessions, so the new role takes effect at the next sign-in.
- It prints the number masked and writes one structured log line. It never prints the full number, a token or a secret.

**Exit codes:** `0` done or dry run; `1` refused (the reason is printed); `2` wrong usage.

**Not covered:** creating a second administrator, and removing one. No surviving source defines either; both are left open rather than invented.

### 4.2 Build database indexes

```bash
npm run db:indexes
```

Creates the indexes declared by the models. It only adds indexes; it never drops one. In development and tests indexes are also built automatically; in production this command is the only thing that builds them.

### 4.3 Start-up requires transactions (decision AD-31)

The server, `npm run db:indexes` and `npm run admin:create-first` all connect through one function, which checks after connecting that MongoDB can run multi-document transactions: the deployment must be a replica-set member (not an arbiter) or a mongos, with sessions, wire version ≥ 9 (MongoDB 4.4, the first version whose transactions may create a collection), and a real read-only test transaction must succeed. Otherwise the process prints why and how to fix it (a one-member replica set: `replSetName`, `rs.initiate()`, `replicaSet=` in `MONGODB_URI`), closes the connection and exits with code 1. There is no non-transactional fallback. The message names no host or credential. Setup: README, "MongoDB must be a replica set".

---

## 5. Profile

Field rules: `FRONTEND_BACKEND_FIELD_MAPPING.md` §2. Storage: `DATABASE_DESIGN.md` §3.

Four routes. All require an access token (`authenticate`, §3.9) and act only on the caller's own profile: there is no profile ID in any path, so no profile route can address another account. Authentication is applied to the whole `/api/profile` tree, so any path under it, even one that does not exist, answers 401 without a token.

None of these four paths is in the master prompt; MP §40 names the capabilities ("get profile, update profile, register profile") and the frontend adds `saveDraft`. The paths follow the `/api/profile/me/...` form that MP §11 uses for photos. All four are RECONSTRUCTED.

| # | Method and path | Frontend method | Success |
|---|---|---|---|
| 1 | `GET /api/profile/me` | `getCurrentProfile()` | 200 `data: CurrentProfile` |
| 2 | `POST /api/profile/me` | `registerProfile(input)` | 201 `data: { profileId }` |
| 3 | `PUT /api/profile/me` | `updateProfile(input)` | 200 `data: { savedAt }` |
| 4 | `PUT /api/profile/me/draft` | `saveDraft(input)` | 200 `data: { savedAt }` |

### 5.1 `GET /api/profile/me`

Returns the caller's profile in the frontend's `CurrentProfile` shape plus `profileCompletion` (mapping §2.3). Works for a draft as well as a registered profile.

| Status | When |
|---|---|
| 200 | a profile exists (draft or registered) |
| 404 | nothing has been saved yet |

### 5.2 `POST /api/profile/me` — register

Body: the full form (`RegistrationFormValues`). `photos`, the account fields and any unknown field are ignored.

On success the profile is marked registered, the account's registration is marked complete (so `isNewUser` becomes `false`, §3.4), the member receives 3 Super Likes (AD-22), and the response is 201 `{ "profileId": "<id>" }`. The three writes are one transaction (AD-30): a failed registration changes nothing, and the draft stays as it was.

| Status | `errors` | When |
|---|---|---|
| 400 | field messages | validation |
| 400 | `{ "photos": "Add a primary photo to continue" }` | no photo uploaded yet (the frontend's own message) |
| 409 | `{ "reason": "duplicate_submission" }` | already registered (the frontend's `ProfileServiceError` code) |

Two simultaneous registrations: exactly one succeeds; the other gets 409.

### 5.3 `PUT /api/profile/me` — update

Body: the full form, as Edit Profile sends it. A full replacement: an optional field absent from the body is cleared. Consents must still be `true`; their original acceptance time is kept.

| Status | `errors` | When |
|---|---|---|
| 200 | — | saved; `data: { savedAt }` |
| 400 | field messages, or `{ "photos": … }` | validation, or no photo |
| 409 | `{ "reason": "not_registered" }` | the profile has not been registered |

### 5.4 `PUT /api/profile/me/draft` — save draft

Body: any subset of the form. Only shape rules apply (mapping §2.2). Provided fields are saved, a field sent as `""` is cleared, fields not sent are left alone. Consents are not recorded from a draft.

Two first saves at the same moment converge on one profile and both succeed; a first save racing a registration either lands before it or gets 409.

| Status | `errors` | When |
|---|---|---|
| 200 | — | saved; `data: { savedAt }` |
| 400 | field messages | a value has the wrong type, an unknown option, or exceeds a maximum |
| 409 | `{ "reason": "already_registered" }` | the profile is registered; drafts are for registration only |

---

## 6. Photos

Pipeline and storage: `DATABASE_DESIGN.md` §4.

| # | Method and path | Purpose | Path source |
|---|---|---|---|
| 1 | `POST /api/profile/me/photos` | Upload one photo | MP §11, explicit |
| 2 | `PATCH /api/profile/me/photos/:photoId` | Make a photo primary | MP §11, explicit |
| 3 | `DELETE /api/profile/me/photos/:photoId` | Delete a photo | MP §11, explicit |
| 4 | `GET /api/photos/:photoId` | Fetch the image | RECONSTRUCTED (R01 §5 "secure serving") |

All four require an access token. Routes 1–3 act only on the caller's own photos.

**Shape returned by routes 1–3:** `ProfilePhoto = { id, url, isPrimary }`, with `url` = `/api/photos/<id>`. Lists are in upload order; two uploads within the same millisecond are ordered by slot.

### 6.1 `POST /api/profile/me/photos`

`multipart/form-data` with exactly one file in the field **`photo`** (R06) and no other parts.

Checks, in order. Each refusal names no internal detail.

| # | Check | Refusal |
|---|---|---|
| 1 | Per-account upload limit (`PHOTO_UPLOAD_RATE_LIMIT_MAX` per `PHOTO_UPLOAD_RATE_LIMIT_WINDOW_MS`) | 429 |
| 2 | Exactly one file, in field `photo` | 400 |
| 3 | Size ≤ `MAX_FILE_SIZE_MB` (10, decision AD-18), counted while streaming | 413 |
| 4 | The account has fewer than 5 photos | 409 `{ "reason": "photo_limit" }` |
| 5 | The file's first bytes are a JPEG, PNG or WEBP signature | 400 |
| 6 | The declared type and the file-name extension are allowed and agree with the signature | 400 |
| 7 | It decodes as that format | 400 |
| 8 | Width and height within `MIN_IMAGE_DIMENSION` … `MAX_IMAGE_WIDTH` × `MAX_IMAGE_HEIGHT` | 400 |
| 9 | Re-encoded to JPEG: orientation applied, longest side at most `PHOTO_OUTPUT_MAX_DIMENSION`, all metadata (EXIF, GPS, ICC, XMP) removed | — |

The original upload is never written to disk. The client's file name is never used for anything but the extension check in step 6.

**201** `data: { "photo": ProfilePhoto, "photos": ProfilePhoto[] }`. The first photo becomes primary (more exactly: a new photo becomes primary whenever the account has no primary at that moment).

Messages: 400 `"Use a JPEG, PNG or WebP photo."` (the frontend's own) for checks 5 and 6; `"This photo could not be read. Try another photo."` for check 7; `"Photos can be at most 8000 × 8000 pixels."` or `"Photos must be at least 320 pixels on each side."` for check 8 (numbers from configuration); `"Choose a photo to upload"` when no file is sent; `"Send exactly one photo, in the field \"photo\"."` for any other multipart problem. 413 `"Photos must be under 10MB."` (the frontend's own, with the configured size). 429 `"Too many photo uploads. Please try again later."`. Each 400 and 413 also carries `errors: { "photo": <message> }`.

### 6.2 `PATCH /api/profile/me/photos/:photoId`

Body `{ "isPrimary": true }`. Makes this photo the only primary. `isPrimary: false` is refused (400): a primary is changed by choosing another.

**200** `data: { "photos": ProfilePhoto[] }` · **404** not found or not the caller's · **400** malformed ID or body.

### 6.3 `DELETE /api/profile/me/photos/:photoId`

Deletes the record and the file. If it was the primary, the oldest remaining photo becomes primary.

**200** `data: { "photos": ProfilePhoto[] }` · **404** not found or not the caller's · **409** `{ "reason": "last_photo" }` when the profile is registered and this is its only photo (the frontend refuses to save a profile without one).

### 6.4 `GET /api/photos/:photoId`

Returns the JPEG bytes: `Content-Type: image/jpeg`, `Cache-Control: private, max-age=3600`, `X-Content-Type-Options: nosniff`. No other route serves uploaded files, and the uploads folder is never served statically.

**Who may fetch a photo** is decided by `canViewProfileOf()` in `src/services/visibility.service.js`, the same function that decides who may open a profile card (§8.4):

| Viewer | Rule |
|---|---|
| The owner | always |
| Anyone else | the owner's account is `active`, the profile is registered, no block exists in either direction (Recovery 4), **and** (the profile is visible in discovery, **or** the two are matched, **or** the owner has liked the viewer) (Recovery 4) |

Since Recovery 9B, pause is part of the same function (AD-89): a paused member is not visible in discovery, so only a match or a member they liked may fetch their photos (§16.6).

**404** for every refusal, so a caller cannot tell "does not exist" from "not allowed". A record whose file is missing on disk is also 404 (and logged). **400** only for an ID that is not 24 lower-case hexadecimal characters, which no photo can have. Photo IDs are random, not sequential, so they cannot be enumerated.

---

## 7. Effective privacy (gap C8, decision AD-19)

The frontend has two sets of privacy controls: four on the profile (`privacy`, set in Registration and Edit Profile) and five in Settings (`PrivacySettings`, Recovery 9). Where they cover the same thing, **the more restrictive one wins**. The result is computed by one function, `effectivePrivacy(profilePrivacy, settingsPrivacy)` in `src/services/privacy.service.js`, and every view of a profile shown to another member is built from it.

| What it controls | Profile control | Settings control | Effective rule |
|---|---|---|---|
| Online status shown | `showOnlineStatus` | `onlineActivityIndicator` | shown only if **both** allow it |
| Exact age shown | `showExactAge` | `displayExactAge` | shown only if **both** allow it; otherwise `age` is `null` |
| Approximate distance shown | `showApproxDistance` | `approximateProximity` | shown only if the profile allows it. Distance is always approximate: the backend never holds or shows an exact distance (R01 §5). The settings control chooses between rounded and exact, so turning it off asks for something less private than what is always given, and changes nothing |
| Appears in discovery | `visibleInDiscovery` | pause (`UserSettings.paused`, AD-89) | only if visible **and** not paused |
| Dating intention and diet | — | `intentAndDietaryPrivacy` | when on, the intention is withheld from anyone who is not a match. Diet is never in the public view |
| State and hometown | — | `culturalHeritageAndHometown` | neither is in the public view; no effect today |
| Orientation, religion, politics | `show…OnProfile` | — | none of them is in the public view; no effect today |

**Recovery 9B status:** `UserSettings` holds the Online Activity Indicator (AD-85), Display Exact Age (AD-93) and pause (AD-89) (§16). Each applies to every view, the more restrictive winning. **For every control without a stored value**, the settings side imposes no restriction (and the member is not paused); the profile controls alone apply. `approximateProximity` (AD-94) and `culturalHeritageAndHometown` (AD-96) are not approved and are refused; `intentAndDietaryPrivacy` is deferred (AD-95): no default is chosen, it is refused, and `effectivePrivacy` never receives it. Note for that decision: the frontend's mock starts "Intent & Dietary Privacy" switched **on**, which under this rule would hide every member's intention from non-matches by default.

**Where it is enforced.** In Recovery 3 no route returns another member's profile data; the only cross-member output is a photo (§6.4). The public view (`FRONTEND_BACKEND_FIELD_MAPPING.md` §4) is built by `toPublicProfile()` from `effectivePrivacy()`, is tested now, and is the only function Recovery 4 may use to show a profile to another member.

---

## 8. Discovery

Fields: `FRONTEND_BACKEND_FIELD_MAPPING.md` §5. Storage: `DATABASE_DESIGN.md` §5. Decisions: AD-22 to AD-28.

| # | Method and path | Frontend method | Success | Path source |
|---|---|---|---|---|
| 1 | `GET /api/discovery` | `getRecommended()`, `search(filters)` | 200, paginated `MemberCard[]` | MP §12, explicit |
| 2 | `GET /api/discovery/featured` | `getFeatured()` | 200 `MemberCard`; 404 when nobody is eligible | RECONSTRUCTED |
| 3 | `GET /api/discovery/members/:memberId` | `getById(id)` | 200 `MemberCard`; 404 when not viewable | RECONSTRUCTED |

All three need an access token (§3.9). A caller whose own profile is not registered gets **409 `{ "reason": "profile_not_registered" }`**, here and on every matching route: discovery and matching are for registered members (the frontend sends a new member to registration before these screens).

### 8.1 Pagination

Query `page` (1–1000, default 1) and `limit` (1–50, default 20); provisional values. Response `pagination: { page, limit, hasMore }`. No total count is returned: it would reveal how many members are eligible. Order: most recently signed in first (`User.lastLoginAt`, gap D19), then account ID, so pages are stable.

### 8.2 Eligibility: who may appear to the viewer

A candidate appears only if **every** rule holds. The same rules are applied by the database query and, for single members, by one policy module (`src/services/eligibility.service.js`).

| # | Rule | Source |
|---|---|---|
| E1 | Not the viewer | MP §12; AD-23 |
| E2 | The candidate's account is `active` | MP §12; R2-12 |
| E3 | The candidate's profile is registered, and has at least one photo | Recovery 3 contract; the card needs a photo |
| E4 | Effective privacy lets the candidate appear in discovery (`visibleInDiscovery` and not paused, AD-89, §16.6) | AD-19 |
| E5 | No block between the two, in either direction | MP §12; plan item P3 |
| E6 | **Mutual compatibility (AD-23):** the viewer's `interestedIn` admits the candidate's `gender`, and the candidate's `interestedIn` admits the viewer's `gender` | AD-23 |
| E7 | No match between them, and the viewer has not liked, Super Liked or passed the candidate. A candidate who liked the viewer still appears, so the viewer can like back | MP §12; AD-27 |
| E8 | The viewer's filters: `ageMin`/`ageMax`, `datingIntention`, `query`. **While an age filter is active, members who hide their exact age (profile `showExactAge` or settings `displayExactAge`, AD-93) are left out**: filtering on a hidden age would let repeated searches narrow it down, which AD-26 forbids. Without an age filter they appear, with `age: null`. `distanceKm` is validated and includes every member, since every distance is unknown (AD-24). `onlineOnly=true` keeps only members whose presence is `online` and who show their online status (§11.6; AD-25, switched on in Recovery 5). **Without the parameter, or with `onlineOnly=false`, nobody is excluded for presence: the backend has no online-only default** (§8.5) | `DiscoveryFilters` |

**Compatibility uses only `gender` and `interestedIn`.** No age, distance or other partner preference is stored by the frontend; those exist only as the viewer's search filters. `sexualOrientation` is a self-description, not a preference. No compatibility score is computed.

| `interestedIn` | Admits `gender` |
|---|---|
| `women` | `woman` |
| `men` | `man` |
| `everyone` | `man`, `woman`, `non_binary`, `self_describe`, `prefer_not_to_say` |

**Documented consequence (AD-23):** a member whose gender is `non_binary`, `self_describe` or `prefer_not_to_say` is discoverable only by members who chose `everyone`. Because the rule is mutual, they also see only members who would accept them.

### 8.3 Search safety

`query` is trimmed and limited to 60 characters. Every regular-expression character in it is escaped before it reaches the database, and it is matched case-insensitively as a literal substring of the first name (the first word of `fullName`), the city or the profession. A query containing a space cannot match a first name. Filters are validated by schema; unknown parameters are dropped, wrong values are 400 with field messages, and `ageMin` above `ageMax` is 400.

### 8.4 `GET /api/discovery/members/:memberId`

Returns the card if the viewer may see the member, decided by `canViewProfileOf()` in `src/services/visibility.service.js`, the same function that guards photos (§6.4):

| Viewer | Rule |
|---|---|
| The member themself | Not served here: 404 (their own profile has its own route) |
| Anyone else | Member active and registered, no block either way, **and** (visible in discovery, **or** matched with the viewer, **or** the member has liked the viewer) |

Compatibility (E6) and relationship exclusions (E7) do not apply: a match must be able to open their match's profile, and Liked-you entries must open. Every refusal is 404.

### 8.5 `onlineOnly`: enforced filter, not a backend default (reviewed 2026-10-12, ledger R5-29)

| | Status | Evidence |
|---|---|---|
| **Supporting and enforcing `onlineOnly=true`** | **Approved and implemented** | MP: "implement every filter that actually exists in the approved frontend, including … online state". AD-25: "Recovery 5 must switch the filter on" (approved knowing the Discover screen sends `true` by default; Recovery 4 decision request, Q4). AD-34: presence |
| **Online-only as the default Discover experience** | **Not a backend behaviour. Decided 2026-10-12 (AD-37): Discover is to default to `onlineOnly: false`** in a future, separately approved frontend change | The only source is the frontend's `useState(true)` in `DiscoverScreen.tsx`. No recovered requirement, decision or recovery-package document says the Discover default is online-only. The backend default, with the parameter absent, includes everyone |

Indications inside the frontend that the default may not be intended (evidence, not proof):

- It has a separate "Online Now" tab that forces `onlineOnly: true`. With the default also `true`, that tab gives the same result as "Recommended".
- The "Online members only" checkbox sits in a filter panel that is closed by default.
- The empty-state button ("Adjust Distance Filter") switches `onlineOnly` off, so the screen expects online-only to be what empties it.
- In the mock, 4 of 5 members are online, so the default hid almost nothing in the demo. With real presence, it hides everyone not connected at that moment.

The backend is **unchanged**. It enforces the parameter as sent and imposes no default. **Decision AD-37 (gap D26, closed):** the Discover screen is to start with `onlineOnly: false`; the "Online Now" tab and the checkbox remain the explicit presence filters. That change belongs to a future, separately approved frontend integration; **the surviving frontend still sends `true` by default until then.** Making the backend ignore `onlineOnly` would contradict AD-25 and is not proposed.

---

## 9. Matching

| # | Method and path | Frontend method | Success | Path source |
|---|---|---|---|---|
| 1 | `POST /api/matching/:memberId/like` | `like(id)` | 200 `{ relationship }` | MP §14, explicit |
| 2 | `POST /api/matching/:memberId/super-like` | `superLike(id)` | 200 `{ relationship, superLikesRemaining }` | MP §15, explicit |
| 3 | `POST /api/matching/:memberId/pass` | `pass(id)` | 200 `{ relationship }` | RECONSTRUCTED, after MP §14's form |
| 4 | `DELETE /api/matching/:memberId/pass` | — (backend only, AD-27 item 6) | 200 `{ relationship }` | RECONSTRUCTED |
| 5 | `DELETE /api/matching/:memberId/like` | — (backend only, AD-27 item 6) | 200 `{ relationship }` | RECONSTRUCTED |
| 6 | `GET /api/matching/matches` | `getMatches()` | 200, paginated `MemberCard[]` | MP §16, explicit |
| 7 | `GET /api/matching/liked-you` | `getLikedYou()` | 200, paginated `MemberCard[]` | RECONSTRUCTED |
| 8 | `GET /api/matching/super-likes/balance` | — (also in `PremiumEntitlement.superLikesRemaining`, §14) | 200 `{ superLikesRemaining }`; in production, 503 `super_likes_unavailable` for an account with simulated credits (AD-61) | RECONSTRUCTED |

All need an access token and a registered profile (§8). `:memberId` is the other member's account ID (the frontend's own name for it, `like(memberId)`; MP §14 writes the same path as `:userId`); the acting member is always the token's account. Every answer's `relationship` is recomputed from the database after the change (mapping §5.3). Extra response fields (`superLikesRemaining`) are harmless to the frontend's `{ relationship }` type.

Writes (routes 1–5) share a per-account rate limit: **120 per 15 minutes** (provisional; `MATCHING_RATE_LIMIT_MAX`, `MATCHING_RATE_LIMIT_WINDOW_MS`).

### 9.1 Who may be liked, Super Liked or passed

The target must be: not the caller (400 `{ reason: "self" }`); an active account with a registered profile; not blocked either way; mutually compatible (AD-23); and visible in discovery **or** someone who has liked the caller. Otherwise 404, the same answer as for a member who does not exist. Like withdrawal and pass revocation touch only the caller's own record and need no target check.

### 9.2 One record per direction

The caller's decision about another member is **one record**: a like, a Super Like, or a pass (`DATABASE_DESIGN.md` §5.1). A pass and a like to the same person cannot coexist, which is exactly AD-27 items 2 and 4, enforced by a unique index instead of by coordination.

### 9.3 Like

| State before (caller → member) | Result | Answer |
|---|---|---|
| Nothing | Like stored; if the member already likes the caller, a Match is made | `liked` or `matched` |
| Pass | The pass becomes a like (AD-27 item 4); Match as above | `liked` or `matched` |
| Like or Super Like | Nothing changes (idempotent; a Super Like is never downgraded) | current state |
| Matched | Nothing changes | `matched` |

### 9.4 Super Like (AD-22)

| State before | Result | Answer |
|---|---|---|
| Nothing, pass, or a like | One Super Like is debited, the record becomes a Super Like, a Match is made if the member likes the caller | `super_liked` or `matched` |
| Already a Super Like, or matched | Nothing changes, nothing is debited | current state |
| Balance zero | **409 `{ reason: "no_super_likes" }`**; nothing changes. Never turned into a like | — |

Turning an existing like into a Super Like costs exactly one Super Like (**decision AD-29**, approved 2026-10-09). The balance is never taken from the client.

**Exactly one debit, and never a debit without the Super Like** (AD-29, AD-30). The debit, the record change and any Match are written in **one transaction**: they all commit, or none does. A crash, a failed write or a 409 at any point leaves no debit. The debit's ledger key names the record and the version it changes (`DATABASE_DESIGN.md` §5.5), so a retried transaction cannot pay twice. Two simultaneous Super Likes on the same member are serialised by the pair lock (§9.7): one debits and writes the Super Like, the other then finds it done and debits nothing. Two simultaneous Super Likes on *different* members with a balance of 1 compete for the next ledger position; one commits and the other is re-run, sees a zero balance and is refused with 409 `no_super_likes`.

### 9.5 Pass and its revocation (AD-27)

| Operation | Effect | Answer |
|---|---|---|
| `POST …/pass`, no record or a pass | Pass stored (or kept). The member leaves the caller's discovery and Liked-you list; their own like to the caller is kept | `none` |
| `POST …/pass` over the caller's like or Super Like, no match | The like becomes a pass: withdrawn, no refund | `none` |
| `POST …/pass` when matched | Refused, nothing changes | 409 `{ reason: "already_matched" }` |
| `DELETE …/pass` | Pass removed; the member may appear again if every rule holds | recomputed state |
| `DELETE …/pass` with no pass | Nothing changes | current state |

### 9.6 Like withdrawal (AD-27)

| State | Effect | Answer |
|---|---|---|
| The caller's like or Super Like, no match | Removed; a Super Like is not refunded | `none` or `liked_you` |
| No like (nothing, or a pass) | Nothing changes | current state |
| Matched | Refused, nothing changes | 409 `{ reason: "already_matched" }` |

### 9.7 Making a Match (one transaction; decisions AD-30, AD-31)

A like or Super Like and the Match it completes are written in **one MongoDB transaction**:

1. **Pair lock.** The first write increments a lock counter on the pair's first member's account (`DATABASE_DESIGN.md` §5.8), so two transactions about the same pair cannot both proceed on stale reads; MongoDB aborts one, and it is re-run.
2. The caller's record is read; if it is already sealed, nothing more happens.
3. The caller's record is written as a like (from nothing or a pass), or, for a Super Like, the debit is written and then the record (§9.4). A like or Super Like already in place is kept.
4. If the member's record towards the caller is a like or Super Like, both records are **sealed** with the pair's Match ID and the Match document is inserted. The Match ID is derived from the pair; the unique pair index keeps one Match.

If any write fails, or the process stops before the commit, MongoDB discards every write of the transaction: there is never a Match without both seals, a seal without a Match, mutual likes left without their Match, or a debit without its Super Like. Conflicts with a concurrent transaction (a duplicate key, a write conflict, a conditional write that no longer matches) abort the attempt and the whole operation is re-run against the committed state, at most 5 times. The server does not start without a MongoDB deployment that supports transactions (§4.3).

A sealed record cannot be withdrawn or passed: those single writes require an unsealed record. So a withdrawal or pass racing a like-back either commits first (no Match is made) or finds the records sealed (409 `already_matched`).

Responses are unchanged by the transaction. One effect of the retries: under sustained contention on one pair (five aborted attempts in a row), the request fails without writing anything, with 409 `Resource already exists` or 500; repeating it is safe.

### 9.8 Lists

`GET /api/matching/matches`: the caller's matches, newest first, as cards with `relationship: "matched"`. A match whose other member is no longer active, or is blocked either way, is left out; the Match still exists. `GET /api/matching/liked-you`: members whose like or Super Like to the caller is unanswered (no match), whom the caller has not passed or liked, who are active and registered and not blocked either way, newest first. Compatibility and discovery visibility do not filter this list: these members chose to reach the caller. Both are paginated as §8.1.

### 9.9 Super Like balance

`GET /api/matching/super-likes/balance` answers `{ superLikesRemaining }` from the ledger. It exists so the balance can be checked before Recovery 8 builds `PremiumEntitlement`; nothing can change it from here.

### 9.10 Errors

| Status | `errors` | When |
|---|---|---|
| 400 | field messages | malformed `:memberId`, bad filters or pagination |
| 400 | `{ "reason": "self" }` | acting on oneself |
| 404 | — | member missing or not eligible (one answer for both) |
| 409 | `{ "reason": "profile_not_registered" }` | the caller has no registered profile |
| 409 | `{ "reason": "already_matched" }` | pass or like withdrawal on a match |
| 409 | `{ "reason": "no_super_likes" }` | Super Like with a zero balance |
| 429 | — | matching write limit |

---

## 10. Messaging (Recovery 5)

Decisions AD-32 to AD-36. Everything in this section is a **reconstructed** contract: the paths come from MP §17, the shapes from the frontend's `services/messages/types.ts`; the rest is decided here and labelled. The frontend is not yet wired to it.

| # | Method and path | Frontend method | Success |
|---|---|---|---|
| 1 | `GET /api/messages/conversations` | `getConversations()` | 200, paginated `Conversation[]` |
| 2 | `GET /api/messages/conversations/:conversationId` | `getMessages(conversationId)` | 200, cursor-paginated `ChatMessage[]` |
| 3 | `POST /api/messages/conversations/:conversationId/messages` | `sendMessage(conversationId, text)` | 201 `ChatMessage` (200 on an idempotent repeat) |
| 4 | `PATCH /api/messages/:messageId/read` | — (backend only) | 200 `{ conversationId, upToMessageId, unreadCount }` |

All four need an access token (§3.9) and a registered profile (409 `profile_not_registered` otherwise, as §8). The caller is always the token's account; no sender, recipient, read state, timestamp or moderation state is ever read from a request.

### 10.1 Who may use a conversation

A conversation exists for every Match and only for one; it is created in the same transaction as the Match (§9.7, AD-36). A caller may read it, send to it or mark it read only when **all** of these hold, checked afresh on every request:

1. the conversation exists and the caller is one of its two members;
2. the pair's Match exists;
3. the other member's account is `active` and their profile registered;
4. no block exists in either direction (AD-38: hide and freeze; checked through the safety policy, §12.1).

Otherwise the answer is **404 `Conversation not found`**, one answer for every case, so a caller cannot tell a conversation that does not exist from one they may not use. Nothing is deleted when access is lost; access returns if the condition clears (for example, a reinstated account).

### 10.2 `Conversation` (FE `Conversation`)

| Field | Value |
|---|---|
| `id` | The conversation's own random ID (24 hex). Not the Match ID, which stays internal (R4-03) |
| `memberId` | The other member's account ID |
| `memberName` | The other member's **first name** only, as everywhere else (Recovery 3 public view). The frontend mock shows full names; full names are never shared |
| `memberPhoto` | URL of their primary photo (`/api/photos/:photoId`, §6), or `""` if they have none |
| `onlineState` | `online`, `recently_active` or `offline` (§11.6) |
| `isVerified` | `false` until Recovery 7 |
| `matchedOnLabel` | **omitted**: nothing real supplies it (D19) |
| `lastMessagePreview` | Text of the latest message, cut to 120 characters, or `""` if none |
| `lastMessageAt` | ISO time of the latest message, or of the conversation's creation if none (D2) |
| `unreadCount` | Messages from the other member to the caller that the caller has not read |
| `isPro` | `false` until Recovery 8 (B12: the viewer's own calling entitlement) |

Conversations whose other member fails 10.1 (3) or (4) are left out.

**Pagination (reviewed 2026-10-12, ledger R5-05).** The list is paginated by **page number**, not by cursor:

| Item | Value |
|---|---|
| Query | `page`: integer 1–1000, default 1. `limit`: integer 1–50, default 20. Same rules and values as §8.1 (`DISCOVERY_LIMITS`, provisional). Other parameters are ignored; a bad value is 400 |
| Response | `{ "success": true, "message": "Conversations", "data": Conversation[], "pagination": { "page", "limit", "hasMore" } }` |
| `hasMore` | `true` when at least one conversation exists after this page |
| A page past the end | `data: []`, `hasMore: false` (not an error) |
| Total count | Not returned (as §8.1) |
| Order | `lastMessageAt` descending (the latest message, or the conversation's creation when it has none), then conversation `id` ascending as the tie-break. Total and deterministic for a given state |
| Cursor | **None.** The list has no cursor; only the message history (§10.4) does |

Consequence of page numbers over an activity order: if a message arrives between two page requests, conversations move, so a client paging through can see one twice or miss one. Page 1 is always the current most active conversations. Clients that need a complete list should re-read from page 1 after a `message:new` push.

**Bounded response, not bounded reads:** every response holds at most 50 conversations, but building it reads all of the caller's conversations and their latest messages (one indexed query per conversation) before sorting and slicing. This is the same known limit as Matches (R4-20) and is correct at launch scale. Making the reads bounded would mean storing a last-activity time on `Conversation`, which turns every send into a two-document write needing a transaction. That is a design change, not made here (`DATABASE_DESIGN.md` §6.3).

**Frontend integration requirement (not done; needs a separately approved frontend change):** `messagesService.getConversations()` takes no arguments, so an integrated frontend would receive only page 1 (20 conversations). Its "Unread" and "Waiting" filters and the header's total unread count are computed in the browser from what it received, so they would undercount for a member with more than 20 conversations. The frontend method must pass `page`/`limit` and follow `hasMore` (gap D27).

### 10.3 `ChatMessage` (FE `ChatMessage`)

| Field | Value |
|---|---|
| `id` | Message ID (24 hex), increasing in creation order on one server |
| `conversationId` | |
| `senderId` | `"me"` when the viewer sent it, otherwise the sender's account ID (D3) |
| `text` | As sent, after trimming. Plain text; never HTML |
| `sentAt` | ISO time set by the server when the message was stored (D2) |
| `status` | For the viewer's own messages: `read` if the other member has read it, else `delivered` if delivered to them, else `sent`. For messages to the viewer: `read` if the viewer has read it, else `delivered`. `sending` and `failed` are client-side states; the server never produces them |
| `moderation` | The **hold state** in the frontend's vocabulary (`clear`, `pending_review`, `blocked`): whether the message is held back, not whether anyone checked it. Recovery 5 never holds a message, so it is always `clear`: "not held, delivered normally". See *Unchecked messages* below |
| `moderationChecked` | **Backend addition.** `true` only if a moderation provider evaluated this message. Always `false` in Recovery 5, because no provider exists (AD-33). `moderation: "clear"` therefore never means "checked and found acceptable" unless this is `true` |

**Unchecked messages (reviewed 2026-10-12, ledger R5-07).** An unchecked message is sent as `moderation: "clear"` with `moderationChecked: false`. On its own, `"clear"` could be read as "a provider checked it and it passed". It is kept anyway, because:

- The frontend's `ModerationStatus` type (`services/messages/types.ts`) allows exactly `clear`, `pending_review` and `blocked`. A fourth value such as `unchecked`, or `null`, would break that surviving contract, which this recovery may not change.
- In the frontend's own usage, `clear` means "not held". `MessageBubble` reacts only to `pending_review`, and the frontend mock itself assigns `clear` without moderating anything.
- The truth is never lost. The stored state is `unmoderated` (`DATABASE_DESIGN.md` §6.2), and `moderationChecked: false` says so on every message, over REST and Socket.IO alike.
- Unchecked messages cannot arise in production: production refuses to start without moderation (AD-33, §10.7). They exist only in development and test.

**Rule for consumers:** read `moderationChecked` before treating `moderation` as a verdict. Only `moderationChecked: true` with `moderation: "clear"` means "checked and acceptable".

**Required future migration (not done; gap D28).** When a moderation provider is integrated and the frontend is integrated (each separately approved):

1. Extend the frontend's `ModerationStatus` with an explicit unchecked value, or have it read `moderationChecked`.
2. Serve stored `unmoderated` messages with that value.
3. Never re-label messages stored as `unmoderated` as checked. Messages created before the provider existed stay unchecked unless the provider actually evaluates them.

Until then, the representation above is the contract.

### 10.4 `GET /api/messages/conversations/:conversationId`

Query: `before` (optional; a message ID from this conversation, the cursor) and `limit` (optional; 1–100, default 30). Unknown parameters are ignored.

Answer: `data` is the page, **oldest to newest** (the order the screen renders); `pagination` is `{ nextCursor, hasMore, limit }`. The first page holds the newest messages; to load older ones, pass `before = nextCursor`. `nextCursor` is the ID of the oldest message on the page, or `null` when `hasMore` is false. Clients treat it as opaque. Order is `sentAt`, then ID, so it is total and stable.

Fetching marks the page's messages **to the caller** as delivered (AD-35); it never changes read state.

| Status | When |
|---|---|
| 400 | malformed `:conversationId`, `before` or `limit`; `before` is not a message of this conversation |
| 404 | §10.1 |

### 10.5 `POST /api/messages/conversations/:conversationId/messages`

Body: `{ "text": string, "clientMessageId"?: string }`. Unknown fields are ignored; `senderId`, `sentAt`, `status`, `moderation` and the like are never read.

| Field | Rule |
|---|---|
| `text` | Required string. Trimmed; then 1 to **2000** characters (provisional, `MESSAGING_LIMITS.textMaxLength`), counted as Unicode code points. Control characters other than line feed, carriage return and tab are refused |
| `clientMessageId` | Optional. 1–64 characters of `A–Z a–z 0–9 _ -` (a UUID fits). Makes the send idempotent (below) |

Order of work (MP §17): authenticate → validate → access (10.1, read fresh) → an idempotent repeat is answered here → moderate (§10.7) → **store** → answer → push (§11). Nothing is pushed for a message that was not stored, and an error answer means nothing was stored (the one exception is a request that stops right after storing, for example a crash: the message is then stored and retrievable, but not pushed).

**Idempotency.** With `clientMessageId`, a repeat of the same send by the same member returns the stored message with **200** instead of storing a second one; it is not pushed again. Reusing a `clientMessageId` for a different conversation or a different text is **409 `{ "reason": "client_message_id_conflict" }`**. Without `clientMessageId`, every request stores a new message (the frontend sends none today).

| Status | `errors` | When |
|---|---|---|
| 201 | — | stored |
| 200 | — | idempotent repeat |
| 400 | field messages | validation |
| 404 | — | §10.1 |
| 409 | `{ "reason": "client_message_id_conflict" }` | see above |
| 429 | — | messaging write limit (§10.8) |
| 503 | `{ "reason": "moderation_unavailable" }` | the moderation adapter returned an outcome Recovery 5 cannot act on (§10.7); nothing stored |

### 10.6 `PATCH /api/messages/:messageId/read`

No body. **Read up to (AD-35):** `:messageId` must be a message addressed **to the caller**; every message the other member sent to the caller in that conversation, up to and including it (by `sentAt`, then ID), is marked read, and also delivered if it was not. Messages already read keep their first read time. Nothing the caller sent, and nothing in another conversation, is touched.

Answer: `{ conversationId, upToMessageId, unreadCount }`, `unreadCount` being what remains unread in that conversation. Repeating it changes nothing and answers the same (idempotent). If it changed anything, `message:read` is pushed (§11.5).

| Status | When |
|---|---|
| 400 | malformed `:messageId` |
| 404 | the message does not exist, is not addressed to the caller, or §10.1 fails |

### 10.7 Moderation (AD-33)

The send path calls a server-side moderation adapter (`src/services/moderation/`, MP §19). Recovery 5 contains **only its disabled mode**, which checks nothing and says so: messages are stored with the internal state `unmoderated` and returned with `moderation: "clear"`, `moderationChecked: false`. The provider's API is not known, and no provider, URL or credential is invented.

- `AI_MODERATION_ENABLED=true` without `AI_MODERATION_URL` and `AI_MODERATION_API_KEY`: configuration error, the process does not start.
- `AI_MODERATION_ENABLED=true` with them: the server **refuses to start**, because this build has no provider implementation.
- `NODE_ENV=production` with moderation disabled: the server **refuses to start** (AD-33). **Consequence: the production chat server cannot start until a moderation provider is integrated.** The commands `db:indexes` and `admin:create-first` are not affected.

If an adapter ever returns anything other than an unchecked pass, the Recovery 5 send path refuses the message with 503 `moderation_unavailable` and stores nothing: holding, notifying and `ModerationEvent` records belong to Recovery 6 (D8). **Recovery 6 (AD-42) replaces this for the valid outcomes: see §12.7.** Malformed or unknown outcomes are still refused with 503.

### 10.8 Limits

| Limit | Value (provisional, named configuration) |
|---|---|
| Messaging writes (send and mark-read) per account | 60 per minute (`MESSAGING_RATE_LIMIT_MAX`, `MESSAGING_RATE_LIMIT_WINDOW_MS`) |
| Message text | 2000 characters (`MESSAGING_LIMITS.textMaxLength`) |
| History page | default 30, at most 100 (`MESSAGING_LIMITS`) |
| Conversation list page | as §8.1 |

The REST limit and the socket limits (§11.7) are counted separately.

### 10.9 Errors

| Status | `errors` | When |
|---|---|---|
| 400 | field messages | malformed IDs, cursor, limit or body |
| 401 / 403 | — | §3.9 |
| 404 | — | conversation or message not found or not usable (one answer) |
| 409 | `{ "reason": "profile_not_registered" }` | caller has no registered profile |
| 409 | `{ "reason": "client_message_id_conflict" }` | §10.5 |
| 429 | — | §10.8 |
| 503 | `{ "reason": "moderation_unavailable" }` | §10.7 |

Private message text never appears in an error, a log line or a list other than the conversation's own (§11.9).

---

## 11. Real-time: Socket.IO (Recovery 5)

Decisions AD-32 (authentication), AD-34 (presence), AD-35 (read and delivery), AD-36 (events). **Reconstructed contract:** no Socket.IO client exists in the frontend, so nothing here is recovered. Socket.IO 4, default path `/socket.io`, on the same HTTP server and port as the API. Allowed origins: `FRONTEND_URL`, as for CORS.

### 11.1 Connecting

```js
io(API_ORIGIN, { auth: { token: "<access token>" } })
```

The access token travels in Socket.IO's handshake `auth` payload, never in the URL, a header or a cookie, and is never logged. On the handshake the server runs **the same checks as REST** (§3.9) through the same function: signature, issuer, type and expiry; the session exists, belongs to the account, is not revoked or expired; the account exists and is `active`.

Refusal arrives as the client's `connect_error`, with `err.message` and `err.data = { code }`:

| `code` | When |
|---|---|
| `unauthenticated` | no token, a token that fails any check, a revoked or expired session. As in REST, the reason is not narrowed further |
| `account_suspended` | the account is suspended (REST answers 403) |
| `too_many_connections` | the account already has `SOCKET_MAX_CONNECTIONS_PER_ACCOUNT` sockets (default 5) |

On success the server puts the socket in a private room for its account. The client cannot name, join or leave that room. A registered profile is not required to connect, but every event below requires one.

### 11.2 Staying authenticated

| Event | Server action |
|---|---|
| Every client event | Before handling it, the session and the account are **read again** from the database, exactly as for a REST request. If either fails, the event is answered with `unauthenticated` or `account_suspended` and the socket is disconnected |
| Access token expires | The server disconnects the socket at the token's expiry time, and refuses any event arriving after it. The client gets a server-initiated disconnect (`reason: "io server disconnect"`) and must reconnect with a fresh token (§3.6 refresh) |
| Logout (§3.7) | Every socket of the revoked session is disconnected immediately |
| Other revocations (refresh-token reuse), suspension, deletion | Take effect at that socket's next event, or at its token's expiry, whichever comes first |

A server-initiated disconnect always means "authenticate again"; Socket.IO does not reconnect automatically after one, so the client reconnects with a new token.

### 11.3 Acknowledgements and errors

Every client → server event **must** be sent with an acknowledgement callback. An event without one is dropped unprocessed (nothing is stored or changed).

```
success: { ok: true,  data: <event-specific> }
failure: { ok: false, error: { code, message, fields? } }
```

| `code` | Meaning | REST equivalent |
|---|---|---|
| `invalid_payload` | payload not an object, or a field fails its rule; `fields` names each field with a message | 400 |
| `unauthenticated` | §11.2; socket then disconnected | 401 |
| `account_suspended` | §11.2; socket then disconnected | 403 |
| `profile_not_registered` | caller has no registered profile | 409 |
| `not_found` | conversation or message not found or not usable (§10.1) | 404 |
| `client_message_id_conflict` | §10.5 | 409 |
| `rate_limited` | §11.7 | 429 |
| `moderation_unavailable` | §10.7; nothing stored | 503 |
| `internal_error` | anything else; nothing is reported about it | 500 |

`message` is a short English sentence for developers. Failures carry no private data.

### 11.4 Client → server events

All IDs are 24 lowercase hex characters. Unknown payload fields are ignored; fields the server owns (`senderId`, `sentAt`, `status`, `moderation`, `readAt`, a room name) are never read.

| Event | Payload | Checks | Success `data` |
|---|---|---|---|
| `conversation:join` | `{ conversationId }` | §11.2; §10.1 | `{ conversationId, items: ChatMessage[], pagination }`: the newest page exactly as §10.4 without `before`; these messages to the caller are marked delivered **only when the join succeeds**: the page is read, the socket joins the room, and then the messages are marked (ledger R6-26). A join that fails answers an error and leaves no delivery mark (one exception, as for any single write: a delivery write that was performed before its failure stands, R5-28). If the room join itself or the later delivery write fails, the server **attempts** to remove the room membership this join may have created, never membership from an earlier successful join (ledger R6-27). The attempt can itself fail; the membership then remains (it was authorized, and a later block still evicts it), and the failure is logged without any message content. The socket joins the conversation's room. **Synchronized with block and unblock (AD-46, ledger R6-25):** the access check, the page and the room join run inside the pair's gate, so a join either completes before a block commits (and the block then evicts the socket) or is refused with the ordinary `not_found`, with no room and no history |
| `conversation:leave` | `{ conversationId }` | §11.2; ID format only | `{ conversationId }`. Leaves the room; leaving a room never joined is not an error |
| `message:send` | `{ conversationId, text, clientMessageId? }` | §11.2; §10.1 and §10.5, fresh | `{ message: ChatMessage, created: boolean }`; `created: false` for an idempotent repeat. Sent only after the message is stored |
| `message:read` | `{ messageId }` | §11.2; §10.6 | `{ conversationId, upToMessageId, unreadCount }` |

`message:send` and `message:read` call the same service functions as REST routes 3 and 4. The rules, the answers and the pushes are identical, whichever transport is used.

**What a conversation room means in Recovery 5.** Joining is the authorized way to open a conversation: it checks access, returns the resync page (use it after every reconnect) and marks those messages delivered. The server pushes **every** event through the members' private rooms (11.5), so a member receives new messages and read receipts for all their conversations, joined or not. Nothing is pushed to conversation rooms in Recovery 5. A room is never used to decide who may receive anything.

### 11.5 Server → client events

Every push is addressed by the server to the private room of an account it has just authorized; payloads are serialized per receiving member (`"me"` as in §10.3).

| Event | Sent to | Payload | When |
|---|---|---|---|
| `message:new` | The recipient's sockets. Also the sender's other sockets: not the socket that sent it, and all of them for a REST send | `ChatMessage` | After the message is stored; never for an idempotent repeat |
| `message:read` | Both members' sockets | `{ conversationId, readerId, upToMessageId, readAt }`. `readerId` is `"me"` in the reader's copy, which also carries `unreadCount`; the other member's copy carries the reader's account ID and no count | After a mark-read that changed at least one message |
| `presence:update` | Sockets of members who share a usable conversation with the member (§10.1 checked at that moment) | `{ memberId, onlineState }` | The member's first socket connects (`online`), or their last socket disconnects (`recently_active`) |

**Delivery acknowledgement (AD-35).** A recipient's client should acknowledge `message:new` by calling its callback (any argument). The first acknowledgement from any of the recipient's sockets within `SOCKET_DELIVERY_ACK_TIMEOUT_MS` (default 10 s) marks the message delivered. No event tells the sender; the sender sees `delivered` the next time they fetch.

**No delivery guarantee.** A push is attempted once. A recipient with no connected socket, a socket that drops mid-push, or a missing acknowledgement means nothing more is sent. Every message is stored before it is pushed, so a client that reconnects gets everything with `conversation:join` or the §10.4 route. Nothing is queued in memory. The `recently_active → offline` transition is not pushed: clients read it from the REST lists.

### 11.6 Presence (AD-34)

| State | Condition |
|---|---|
| `online` | The member has at least one connected socket |
| `recently_active` | No socket, and the last one disconnected less than `PRESENCE_RECENTLY_ACTIVE_MINUTES` ago (default 15, provisional) |
| `offline` | Otherwise, including every member not seen since this server process started |

**Respecting the member's choice.** A member whose effective privacy hides their online status (`showOnlineStatus: false`, §7: today the profile switch; from Recovery 9 also the "Online Activity Indicator" setting, the more restrictive winning) is always shown as `offline`, is never kept by `onlineOnly`, and no `presence:update` is sent about them.

Presence is shown only where the viewer may already see the member: their conversations (§10.2 `onlineState`), and cards (§8, `MemberCard.isOnline` is `true` exactly when the shown state is `online`). A blocked member, either way, sees nothing, because they see no card and no conversation. `onlineOnly=true` in discovery (§8) keeps only members shown as `online` (AD-25).

Presence is held in this process's memory. It resets when the server restarts, and is correct only with a **single server instance** (§11.8). **Since Recovery 9B the "Online Activity Indicator" setting applies to all of it** (§16): conversation `onlineState`, card `isOnline`, discovery's `onlineOnly`, and the `presence:update` audience.

### 11.7 Limits (provisional, named configuration)

| Limit | Default | Variable |
|---|---|---|
| Events per socket | 60 per minute; beyond it, `rate_limited` | `SOCKET_EVENT_RATE_LIMIT_MAX`, `SOCKET_EVENT_RATE_LIMIT_WINDOW_MS` |
| Sockets per account | 5 | `SOCKET_MAX_CONNECTIONS_PER_ACCOUNT` |
| Largest incoming packet | 16 KiB; larger packets close the connection (Socket.IO's own limit) | `SOCKET_MAX_PAYLOAD_BYTES` |
| Delivery acknowledgement wait | 10 s | `SOCKET_DELIVERY_ACK_TIMEOUT_MS` |

### 11.8 Deployment

- **One Node.js process only: a hard restriction.** Rooms, presence, the per-account connection count, the logout disconnect **and the pair gate that guarantees no push reaches a member, and no socket enters a conversation room, after a block (AD-46)** live in one process. Cluster mode, multiple workers and multiple instances are **not supported**. Several processes would need a shared adapter, shared presence and a separately designed distributed synchronization mechanism; none is built (AD-36, AD-46).
- A reverse proxy in front of the API must pass WebSocket upgrades on `/socket.io/` (Socket.IO falls back to long-polling otherwise; with several upstreams it would also need sticky sessions).

### 11.9 Privacy and logging

- Message text is never logged, by either transport.
- Message text is never included in an error, an acknowledgement other than the sender's own `message:send`, or a push to anyone but the two members.
- Socket logs record connection counts, event names, error codes and account IDs only; never a token, a payload or text.

### 11.10 Voice and video call signaling

Calls use the authenticated Socket.IO connection and acknowledgement format in §§11.1–11.3. They are available only inside an existing, usable matched conversation (§10.1). Starting a call also requires the caller's trusted `callingEnabled` premium entitlement (§14.3); the recipient may accept or reject without a premium entitlement. Both `audio` and `video` are supported.

| Client event | Payload | Result |
|---|---|---|
| `call:start` | `{ conversationId, mediaType: "audio" \| "video" }` | `{ callId, conversationId, mediaType, state: "ringing", expiresAt }`; pushes `call:incoming` to the recipient. The recipient must have a connected socket. |
| `call:accept` | `{ callId }` | `{ callId, state: "accepted", mediaType }`; pushes `call:accepted` to both members' other sockets. |
| `call:reject` | `{ callId }` | Ends a ringing call with reason `rejected`. Only the recipient may use it. |
| `call:cancel` | `{ callId }` | Ends a ringing call with reason `cancelled`. Only the caller may use it. |
| `call:end` | `{ callId }` | Ends an accepted call. Either participant may use it. |
| `call:offer`, `call:answer` | `{ callId, sdp }` | Relays the SDP to the other participant's socket; offer is caller-to-recipient, answer is recipient-to-caller. `sdp` is limited to 12,000 characters. |
| `call:ice-candidate` | `{ callId, candidate }` | Relays one ICE candidate (or `null` end-of-candidates) to the other participant's socket. |

Server pushes are `call:incoming`, `call:ringing`, `call:accepted`, `call:offer`, `call:answer`, `call:ice-candidate` and `call:ended`. Signaling events include `callId` and a server-derived `fromUserId`; clients cannot choose a recipient or socket. Acknowledgements report only whether signaling was accepted for relay, not whether the peer applied it.

Calls are ephemeral, held in this single Node.js process, limited to one active call per member and per conversation, and ring for 30 seconds. Disconnecting a participant, a block, a reject, a cancel or an end clears the call. A block ends it after the block commits while holding the pair gate. A server restart loses active call state. Signaling and call state are not persisted or logged.

**Media boundary:** this backend relays setup data only. Clients still need `getUserMedia` and `RTCPeerConnection`; the audio/video media flows directly between devices. A production deployment needs working STUN/TURN infrastructure (or an SFU) for networks that cannot connect peer-to-peer. The current backend does not provide TURN credentials or relay media. Since payments are currently disabled and `callingEnabled` is premium-only, free test accounts cannot initiate calls unless they receive a trusted development entitlement.

---

## 12. Safety: blocks, reports, moderation events (Recovery 6)

Decisions AD-38 to AD-45. **Reconstructed contract.** Paths come from MP §20–21. The frontend has no service for any of these (gap D29); its Block and Report dialogs exist but call nothing. The frontend is not changed.

| # | Method and path | Frontend method | Success |
|---|---|---|---|
| 1 | `POST /api/users/:memberId/block` | — (the Block dialog has no service call) | 201 when created, 200 when already blocked: `{ memberId, blocked: true, blockedAt }` |
| 2 | `DELETE /api/users/:memberId/block` | — | 200 `{ memberId, blocked: false }` |
| 3 | `GET /api/users/blocked` | — | 200, paginated `[{ memberId, firstName, blockedAt }]` |
| 4 | `POST /api/reports` | — (the Report dialog has no service call) | 201 when created, 200 for an existing open report: `{ reportId, status, createdAt }` |

All four need an access token (§3.9) and a registered profile (409 `profile_not_registered`, as §8). The caller is always the token's account. `:memberId` is an account ID; the parameter is named as in §9, where MP §20 writes `:userId` (same URL shape; ledger R4-16).

Route count: 34.

### 12.1 The safety policy (AD-38)

One service decides whether two accounts are separated by a block, in either direction. Every consumer asks it:
- discovery;
- profile and photo viewing;
- likes, Super Likes and passes;
- Matches and Liked-you;
- conversations, history, sending and mark-read;
- Socket.IO joins and pushes;
- presence.

None of them reads blocks directly. While a block exists, either way:

| Effect | Behaviour |
|---|---|
| Visibility | Each is absent from the other's discovery, Matches, Liked-you and conversation lists; profile, card and photo answer 404 |
| Interactions | Like, Super Like, pass, conversation read, send, mark-read, join: **404, the same answer as for a member who does not exist**. This includes a pair that is already matched (from Recovery 6, a like on a matched pair that is blocked answers 404 instead of `matched`) |
| Records | **Nothing is deleted or changed**: likes (including sealed ones), the Match, the Conversation, messages, delivery and read state, and ledger entries stay as they are. No refund |
| Notification | None. The blocked member gets no event, no push and no different error |
| Presence | Neither sees the other's presence; no `presence:update` passes between them |
| Unblock | Removing the block restores everything above to exactly what it was, under the normal rules |

### 12.2 `POST /api/users/:memberId/block`

| Rule | Behaviour |
|---|---|
| Self | 400 `{ reason: "self" }` |
| Unknown account | 404 `Member not found` |
| Any existing account | May be blocked, whatever its status, registration, visibility or relationship to the caller (so a member can block someone already hidden from them) |
| Repeat | 200 with the original `blockedAt`; nothing changes |
| Both directions | Each member's block is their own. A blocks B and B blocks A are two records; each is removed only by its owner |
| Consistency | One transaction that takes the pair's lock (DATABASE_DESIGN §7.5): no Match can be created after it commits (AD-45) |
| Sockets | After commit, both members' sockets leave that pair's conversation room (§11.4); nothing is sent to either |
| Rate limit | Blocks and unblocks share 60 per hour per account (provisional, `BLOCK_RATE_LIMIT_MAX`, `BLOCK_RATE_LIMIT_WINDOW_MS`); 429 beyond |

### 12.3 `DELETE /api/users/:memberId/block`

Removes **the caller's own** block on that member; a block the other member placed is untouched. Self 400; unknown account 404. No block is not an error: 200 `{ blocked: false }` (idempotent). It is the same pair-locked transaction as 12.2, and is rate-limited with it. The relationship becomes visible again only if **neither** member blocks the other.

### 12.4 `GET /api/users/blocked` (AD-44)

`page` 1–1000 (default 1), `limit` 1–50 (default 20), as §8.1. Response `data: [{ memberId, firstName, blockedAt }]`, `pagination: { page, limit, hasMore }`, no total.

- **Only accounts the caller blocked.** Never the accounts that blocked the caller.
- Order: newest `blockedAt` first, then `memberId`.
- `firstName` comes from the member's profile (`""` if they have none).
- No photo, no other field; the photo route keeps refusing blocked pairs.
- Members are listed whatever their account status, so a block can always be lifted.

### 12.5 `POST /api/reports` (AD-39, AD-40, AD-41)

Body: `{ "targetType": "user" | "profile" | "message", "targetId": "<24 hex>", "reason"?: string }`. Unknown fields are ignored; `status`, `resolution`, `internalNote`, `moderation`, the reporter and any evidence are never read from a request.

| Rule | Behaviour |
|---|---|
| `reason` | Optional. Trimmed; empty means absent; at most **1000** code points (provisional); control characters other than line breaks and tab are refused. No category list |
| `user`, `profile` | `targetId` is an **account ID**. The account must exist (404 otherwise), whatever its status, and **even if either member blocks the other**. Reporting oneself: 400 `{ reason: "self" }` |
| `message` | `targetId` is a message ID. The caller must be the message's **recipient**, and a member of its conversation, checked by participation, not current access, so a block does not prevent it. A message the caller cannot see (their own, another pair's, or one held from them by moderation) answers 404, the same as an unknown ID |
| Evidence (AD-41) | For a message report, the message's text and sent time are copied into the report **in the same transaction that creates it**. Never returned to any member; never logged |
| One open report | At most one **open** (`OPEN` or `UNDER_REVIEW`) report per reporter, `targetType` and target, **enforced by a unique database index**. A repeat, even a simultaneous one, answers **200 with the existing report** and creates nothing. After that report is `RESOLVED` or `REJECTED`, a new one may be created |
| Rate limit (AD-39) | **10 reports created per account per 24 hours** (rolling window; provisional, `REPORT_RATE_LIMIT_MAX`, `REPORT_RATE_LIMIT_WINDOW_MS`). Counted in the same transaction that creates the report, which serializes one reporter's reports, so simultaneous submissions cannot exceed it. The 11th answers **429 `{ reason: "report_limit" }`**. A duplicate answered from an existing report does not count |
| Answer | `{ reportId, status, createdAt }`, nothing about the target, the evidence or other reports. New reports are always `OPEN` |
| The reported member | Never notified, never shown the report, the reporter or the evidence; no route lists reports about oneself |

| Status | `errors` | When |
|---|---|---|
| 201 / 200 | — | created / existing open report |
| 400 | field messages, or `{ reason: "self" }` | validation; self-report |
| 404 | — | unknown or not-visible target |
| 409 | `{ reason: "profile_not_registered" }` | caller not registered |
| 429 | `{ reason: "report_limit" }` | §12.5 limit |

### 12.6 Report states and the administrative hooks (AD-43)

`OPEN` → `UNDER_REVIEW`, `RESOLVED` or `REJECTED`; `UNDER_REVIEW` → `RESOLVED` or `REJECTED`; `RESOLVED` and `REJECTED` are final. Each transition is one conditional update on the expected current state, so of two simultaneous transitions only one succeeds; the other is a conflict.

The report service has administrative operations (list by status, get one, transition with `resolution` and `internalNote`). **No HTTP route reaches them in Recovery 6.** They must be wired to the mandatory audit record before any admin route exposes them (Recovery 9, MP §21, gap B14).

### 12.7 Held messages and moderation events (AD-42)

Amends §10.5, §10.7 and §11.5. The adapter's outcome decides:

| Outcome `{ checked, status }` | Stored as | Recipient | Event |
|---|---|---|---|
| `{ false, "unmoderated" }` (the only outcome of this build's disabled adapter) | `unmoderated`, delivered normally (§10) | Yes | No |
| `{ true, "clear" }` (a future provider) | `clear`, delivered normally | Yes | No |
| `{ true, "pending_review" }` | `pending_review`, **held** | **No** | Yes |
| `{ true, "blocked" }` | `blocked`, **held** | **No** | Yes |
| anything else | nothing stored | — | — (503 `moderation_unavailable`, as before) |

- **Atomic.** A held message and its `ModerationEvent` are written in **one transaction**.
- **Sender.** The answer is 201 with the stored `ChatMessage` (`moderation: "pending_review"` or `"blocked"`, `moderationChecked: true`). The sender's history includes it; their other sockets receive `message:new`. The frontend already shows "Under review" for `pending_review`.
- **Recipient.** A held message is **invisible** everywhere. It is:
  - not in history or `conversation:join`;
  - not the list preview, `lastMessageAt` or unread count;
  - never `message:new`;
  - never marked delivered or read, and never a cursor;
  - not reportable or markable by its ID (404).
- **No release, appeal or recipient decision** exists (MP §19; the frontend has none). A held message stays held.
- **AD-33 is unchanged:** production refuses to start without a provider, and enabling moderation is refused. So in every runnable configuration of this build, the adapter can only return the first row; the held path is exercised by tests with a fake adapter.

### 12.8 Block versus concurrent actions (AD-45)

| Interleaving | Guarantee | Mechanism |
|---|---|---|
| Block and a like or Super Like that would complete a Match | **No Match or Conversation is created after the block commits** | Both are transactions that write the pair lock first; matching re-checks the block inside its transaction, after the lock |
| Block and a message send | **No message is stored after the block commits** | The send becomes a transaction: pair lock → access re-check (including the block) → insert (→ event). It is serialized with the block on the pair lock |
| Block and the **push** of a message, read receipt or presence update | **Nothing is emitted to or about the other member after the block commits** | The in-process **pair gate** (AD-46): block, unblock, send (through its pushes), mark-read (through its receipts), conversation join (through the room join) and each presence push between the pair run one at a time per pair, and every push re-reads the block inside the gate (DATABASE_DESIGN §7.6). **Valid only with a single Node.js process** (§11.8) |
| Block and `conversation:join` (corrected in Recovery 6.1, ledger R6-25) | **No socket enters the pair's conversation room after the block commits** | The join takes the same pair gate. Inside it: the caller's registration and the full §10.1 access check again (membership, Match, the other member's account and profile, the block both ways), the history page, then the room join; the gate is released only after the socket is in the room. A block that took the gate first makes the join answer `not_found` with no room and no history; a join that took it first finishes, and the block then evicts the socket. A check made before the gate decides nothing |
| Block and history or list reads | A read that began before the commit may return what existed before the block; every read that starts after the commit is refused or filtered | Access is checked on every request (§10.1) |

The bytes of a push handed to the transport before the block committed may still reach the client a moment later. That is transport latency, not a decision taken after the block.

---

## 13. Verification (Recovery 7)

Decisions AD-47 to AD-54; gap defaults B10, B13, C1, D21 as recorded. Database side: `DATABASE_DESIGN.md` §8. The paths are **new**: the original ones did not survive (baseline rows 34–37).

**No real verification provider is implemented** (AD-53). DigiLocker, e-KYC and face matching are not integrated. With the default configuration every action answers 503 and nobody can become verified.

### 13.1 Routes

| Method and path | FE call (`services/verification`) | Success |
|---|---|---|
| `GET /api/verification/status` | `getStatus` | 200 `VerificationStatus` |
| `POST /api/verification/start` | `startDigilocker` | 200 `VerificationStatus` |
| `POST /api/verification/liveness` | `simulateLiveness` | 200 `VerificationStatus` |
| `POST /api/verification/retry` | `retry` | 200 `VerificationStatus` |

All four need an access token (§3.9) and a registered profile (409 `profile_not_registered`). The caller is always the token's account; **no route takes an account ID**. Request bodies and query strings are **ignored**: `{ "verified": true }`, `state`, `percentComplete`, `providerRef`, `userId` or anything else changes nothing (MP §22). Start, liveness and retry share a per-account limit: **10 per hour** (provisional; `VERIFICATION_RATE_LIMIT_MAX`, `VERIFICATION_RATE_LIMIT_WINDOW_MS`), 429 beyond.

### 13.2 Modes and the provider gate (B10, B13, AD-50)

A pure function resolves the mode from configuration, with strict inputs:

| Input | True only when |
|---|---|
| non-production | `NODE_ENV` is exactly `development` or `test` (anything else counts as production) |
| provider enabled | `VERIFICATION_PROVIDER_ENABLED` is the boolean `true` |
| provider configured | `VERIFICATION_PROVIDER_URL` and `VERIFICATION_PROVIDER_KEY` are both non-empty |
| simulation requested | `VERIFICATION_DEV_SIMULATION` is the boolean `true` |

Rule, in order: enabled **and** configured → `real`; enabled but not configured → `unavailable` (never simulation); simulation requested in a non-production environment → `dev_simulation`; otherwise → `unavailable`.

| Case | Non-production | Enabled | Configured | Simulation | Mode |
|---|---|---|---|---|---|
| G1 | yes | no | — | no | `unavailable` |
| G2 | yes | no | — | yes | `dev_simulation` |
| G3 | no | no | — | no | `unavailable` |
| G4 | no | no | — | yes | `unavailable` |
| G5 | yes | yes | yes | no | `real` |
| G6 | yes | yes | yes | yes | `real` |
| G7 | no | yes | yes | no | `real` |
| G8 | no | yes | yes | yes | `real` |
| G9 | any | yes | no | any | `unavailable` |

**Start-up rules:**
- `VERIFICATION_DEV_SIMULATION=true` with `NODE_ENV=production` → **refused** (B13).
- `VERIFICATION_PROVIDER_ENABLED=true` without URL or key → refused (existing provider validation; https required in production).
- Mode `real` in production while this build has **no real-provider implementation** → **refused** with a non-secret explanation (AD-50). In development and test the server starts with a warning, and every action answers 503 and writes nothing.
- The resolved mode is logged at start-up, without URL or key.

Simulation cannot run in production even if configuration validation were bypassed: the gate never returns it there, the simulation adapter refuses to be built there, the service refuses to be built with it there, and simulated records are never trusted there (§13.6).

### 13.3 `VerificationStatus` (FE `VerificationStatus`)

```json
{ "state": "mobile_verified", "percentComplete": 15, "updatedAt": "2026-10-13T07:30:00.000Z" }
```

| Field | Rule |
|---|---|
| `state` | One of the ten frontend states (C1). A member without a record is `mobile_verified` (or `not_started` without a verified phone, which no account in this build lacks) |
| `percentComplete` | Derived from the frontend mock's table: `not_started` 0, `mobile_verified` 15, `digilocker_pending` 25, `digilocker_verified` 40, `selfie_pending` 55, `face_match_processing` 75, `retry_required` 55, `manual_review` 85, `verified` 100, `failed` 55 |
| `updatedAt` | When the state last changed; for a member without a record, when the phone was verified |

Nothing else is ever returned: no provider name or reference, no provenance, no version, no record ID.

### 13.4 Actions and transitions (D21, AD-47)

| Action | Allowed from | `dev_simulation` | `real` (when a provider exists) | `unavailable`, or `real` without implementation |
|---|---|---|---|---|
| status | any | read | read | read (200) |
| start | `not_started`, `mobile_verified` | → `digilocker_verified` | provider `document_verified` → `digilocker_verified` | 503 |
| liveness | `digilocker_verified` | → `verified` | provider `verified`, `retry_required`, `manual_review` or `failed` → that state | 503 |
| retry | `retry_required`, `failed` | → `digilocker_verified` | → `digilocker_verified` (no provider call) | 503 |

- An action from any other state answers **409 `invalid_verification_state`**. A repeat of a successful action is such a case.
- In `unavailable` mode the 503 is answered **before** the state is examined.
- `manual_review` is left only by an admin decision (Recovery 9; not built).
- Retry has no lifetime attempt cap (AD-47); the rate limit applies.
- Intermediate states (`digilocker_pending`, `selfie_pending`, `face_match_processing`) are not stored by this build: simulation and a synchronous provider pass through them within one request.

### 13.5 Errors

| Condition | Status | `errors` |
|---|---|---|
| No or invalid token, revoked session, account neither active nor suspended | 401 | — |
| Suspended account | 403 | — (§3.9) |
| Profile not registered | 409 | `{ reason: "profile_not_registered" }` |
| Mode `unavailable`; `real` without implementation; provider error, timeout, or malformed or unexpected provider result | **503** | `{ reason: "verification_unavailable" }` |
| Action not allowed from the current state; the record changed during the request (stale provider result, concurrent request) | 409 | `{ reason: "invalid_verification_state" }` |
| Rate limit | 429 | — |

No error answer contains provider detail.

### 13.6 Provenance and what `verified` means (AD-51)

Verification produced by simulation is never production-trusted (`DATABASE_DESIGN.md` §8.2):
- In production, a record produced, even in part, by simulation is shown as if it did not exist (`mobile_verified`, `isVerified: false`), and the member may start again.
- In development and test, a simulated `verified` is shown as verified, so the screens can be exercised.
- Only a validated real-provider chain could be trusted in production, and none exists in this build.

### 13.7 Provider results (AD-53)

The provider interface takes the account ID only. Every result is validated before use:
- exactly the keys `outcome` and `providerRef`;
- an `outcome` allowed for that call;
- `providerRef` `null` or 1–200 characters of `[A-Za-z0-9._:-]`.

Anything else is rejected: 503, nothing written, logged with the step name only. A provider call that fails or takes longer than `VERIFICATION_PROVIDER_TIMEOUT_MS` (provisional, 15 s) is treated the same way. The provider reference is stored internally and is never returned or logged.

### 13.8 `isVerified` elsewhere

`MemberCard.isVerified` (discovery, featured, member card, matches, liked-you; §8–9) and `Conversation.isVerified` (§10.2) are `true` exactly when the member's verification is trusted under §13.6. They come from one batched read per list; no other verification field appears in those outputs.

---

## 14. Premium and payment-disabled architecture (Recovery 8)

Decisions AD-55 to AD-64; gap defaults D22, B13 and B12 as recorded. Database side: `DATABASE_DESIGN.md` §9. The paths are **new** (baseline rows 39–44: the original paths did not survive).

**No real payment provider exists.** Nothing here takes or records a payment. With the default configuration, the three actions answer 503 and change nothing. Development simulation (development and test only) reproduces the frontend's demo flow and is never trusted in production.

### 14.1 Routes

| Method and path | FE call (`services/premium`) | Body | Success |
|---|---|---|---|
| `GET /api/premium/entitlement` | `getEntitlement` | — | 200 `PremiumEntitlement` |
| `POST /api/premium/super-likes/purchase` | `purchaseSuperLikePack(packId)` | `{ packId, purchaseKey? }` | 200 `PremiumEntitlement` |
| `POST /api/premium/boost/activate` | `activateBoost(optionId)` | `{ optionId }` | 200 `PremiumEntitlement` |
| `POST /api/premium/subscribe` | `subscribe(planId)` | `{ planId }` | 200 `PremiumEntitlement` |

- All four need an access token (§3.9) and a registered profile (409 `profile_not_registered`). The caller is always the token's account.
- Only the named fields are read; every other body field is dropped (`price`, `count`, `quantity`, `tier`, `superLikesRemaining`, `boostExpiresAt`, `callingEnabled`, `userId`, …).
- The three actions share a per-account limit: **20 per hour** (provisional; `PREMIUM_RATE_LIMIT_MAX`, `PREMIUM_RATE_LIMIT_WINDOW_MS`), 429 beyond.
- `GET /api/matching/super-likes/balance` (§9) is unchanged.

`purchaseKey` (AD-59) is an optional, backend-only idempotency key: 1–64 characters of `[A-Za-z0-9_-]`, scoped to the caller.
- A repeated or concurrent request with the same key applies the credit at most once and answers the current entitlement.
- The same key with a **different** pack answers 409 `purchase_key_conflict`.
- Without a key, every request is a separate purchase, applied exactly once.

### 14.2 Catalog (D22, AD-63)

| Kind | IDs | Server-side value |
|---|---|---|
| Super Like pack | `pack_5`, `pack_15`, `pack_25` | 5, 15, 25 Super Likes |
| Boost | `boost_15`, `boost_30`, `boost_60` | 15, 30, 60 minutes |
| Plan | `plan_1m`, `plan_3m`, `plan_12m` | no duration (expiry is unresolved, AD-55) |

The catalog has **no prices**. Prices, labels and features are frontend display text. IDs are matched as the catalog's own properties only (`__proto__`, `toString` and other inherited names are unknown). A missing or unknown ID answers **400 before the payment mode is examined**, so it is rejected even while payment is disabled.

### 14.3 `PremiumEntitlement` (FE `PremiumEntitlement`)

```json
{ "tier": "free", "superLikesRemaining": 3, "boostStatus": "inactive", "boostExpiresAt": null, "callingEnabled": false }
```

| Field | Rule |
|---|---|
| `tier` | `premium` when the member has a **trusted** subscription (§14.6), else `free` |
| `superLikesRemaining` | The Super Like ledger balance (§9), with the AD-61 safeguard |
| `boostStatus` | No trusted Boost → `inactive`; trusted Boost with expiry later than the server's current time → `active`; otherwise `expired` (at the exact expiry instant: `expired`) |
| `boostExpiresAt` | The trusted Boost's expiry (ISO), kept after it passes; `null` when there is none |
| `callingEnabled` | `true` exactly when `tier` is `premium` (AD-56). Calling itself does not exist |

Exactly these five fields: no provenance, plan or option ID, version, record ID or provider data.

### 14.4 Modes (B13, AD-60, AD-62)

Pure gate, strict inputs (non-production = `NODE_ENV` exactly `development` or `test`):

| Case | Non-production | `PAYMENT_PROVIDER_ENABLED` | URL and key | `PAYMENT_DEV_SIMULATION` | Mode |
|---|---|---|---|---|---|
| P1 | yes | false | — | false | `unavailable` |
| P2 | yes | false | — | true | `dev_simulation` |
| P3 | no | false | — | false | `unavailable` |
| P4 | no | false | — | true | `unavailable` |
| P5 | yes | true | set | false | `real` |
| P6 | yes | true | set | true | `real` |
| P7 | no | true | set | false | `real` |
| P8 | no | true | set | true | `real` |
| P9 | any | true | missing | any | `unavailable` |

**Start-up rules:**
- `PAYMENT_DEV_SIMULATION=true` with `NODE_ENV=production` → refused (configuration).
- Mode `real` in production → **refused** (no implementation exists, AD-60). In development and test it starts, and the actions answer 503 and write nothing.
- In production, a Super Like ledger containing **any** `simulated_pack_purchase` entry → **refused** (AD-61).

### 14.5 Actions

| Action | `unavailable`, or `real` (no implementation) | `dev_simulation` |
|---|---|---|
| purchase | 503 | Ledger credit of the pack's count (reason `simulated_pack_purchase`), in one transaction |
| activate Boost | 503 | Boost = that option, from now, for its minutes; **replaces** a running Boost (AD-57) |
| subscribe | 503 | Subscription = that plan, from now, with no expiry; 409 `already_subscribed` if one exists (AD-58) |

A 503 is answered after authentication, validation and the registration check, and **before** any entitlement or ledger read or write. No payment, order, receipt or settlement record exists in any mode.

### 14.6 Provenance

- **Subscription and Boost** each record whether simulation or a provider created them. In production, a simulated component is read as absent: tier `free`, `callingEnabled: false`, Boost `inactive`, `isPro: false`.
- **Super Likes (AD-61):**
  - Production refuses to start while any simulated credit exists.
  - After start-up, an account whose ledger contains a simulated credit has its Super Like balance and spending **refused**. The entitlement read, the balance route and Super Likes answer 503 `{ reason: "super_likes_unavailable" }`, and an operational log names the account (no amounts).
  - The balance is never recomputed and no entry is changed.
  - Clean accounts are unaffected.

### 14.7 Errors

| Condition | Status | `errors` |
|---|---|---|
| No or invalid token, revoked session | 401 | — |
| Suspended | 403 | — |
| Missing or unknown ID, or a malformed `purchaseKey` | 400 | field messages |
| Profile not registered | 409 | `{ reason: "profile_not_registered" }` |
| Payment unavailable, or `real` without implementation | **503** | `{ reason: "payment_unavailable" }` |
| Untrusted Super Like history (production) | 503 | `{ reason: "super_likes_unavailable" }` |
| Same `purchaseKey`, different pack | 409 | `{ reason: "purchase_key_conflict" }` |
| Already subscribed | 409 | `{ reason: "already_subscribed" }` |
| The entitlement changed during the request | 409 | `{ reason: "entitlement_changed" }` |
| Rate limit | 429 | — |

### 14.8 `isPro` (B12)

`Conversation.isPro` (§10.2) is the **viewer's own** `callingEnabled`: one entitlement read per conversation list. The other member's entitlement is never read for it.

### 14.9 Not built (AD-55)

Real payments (checkout, callback or webhook, signatures, settlement, refunds); subscription expiry or renewal; recurring free Super Likes or Boosts; Boost ranking in discovery; "See Who Liked You Instantly"; "Incognito Browsing Mode"; Boost history (`boost_triggers` stays not tracked).

---

## 15. Admin and moderation operations (Recovery 9) — **IMPLEMENTED (Recovery 9-A to 9-D); RUNTIME-UNVERIFIED; NOT PRODUCTION-READY**

> **Status after Recovery 9-D (Recovery 9 implementation complete):**
> - **Implemented (Recovery 9-A):** §15.1. One `/api/admin` router (`src/routes/admin.routes.js`) mounts `authenticate`, a sanitized denial log and `requireAdmin` (`src/middlewares/adminAccess.js`), then the per-admin read or write limit (AD-72).
> - **Implemented (Recovery 9-B):** routes 6 to 9 of §15.2 (the report list, report detail, report status transition and audit-log listing), with the shapes, errors and behaviour of §15.6.
> - **Implemented (Recovery 9-C):** routes 2 to 5 of §15.2 (the user list and detail, suspension and reinstatement, and the **read-only** verification queue), with the shapes, errors and behaviour of §15.7.
> - **Implemented (Recovery 9-D):** route 1 of §15.2 (the dashboard), with the shapes, errors and behaviour of §15.8. The route count is **51**.
> - **Runtime-unverified:** none of these routes has run against MongoDB, Express or the declared Zod 4 (`RUNTIME_VERIFICATION.md`).
> - Any other path that passes the guards answers 404 `{ success: false, message: "Route not found", errors: {} }` (the existing 404 envelope, `src/middlewares/errorHandler.js`). There is no audit update or delete route, and **no verification approve, reject or re-upload route** (AD-80).
> - **Not implemented, by decision:** verification approve, reject and re-upload (AD-80); role management; exports; report reopening; moderation-event review; retention (P-13).
> - **Approved:** AD-65 to AD-83 (AD-81 to AD-83 in Recovery 9-D: P-14, P-15 and the final checkpoint).
> - **Pending:** P-02, P-04, P-13, the retention part of P-12, N-3, every retention period and the verification admin-trust policy.
>
> **Status update (2026-10-26):** P-02, P-04 and N-3 were decided on 2026-10-22. AD-90 (P-02): **conditional, not cleared for production**; the emergency-demotion operator and rehearsal date are unresolved. AD-91 (P-04): **not approved**; admin actions without step-up authentication remain a **production blocker**, and no step-up flow is built. AD-92 (N-3): approved with conditions. Still pending: P-13, the retention part of P-12, every retention period and the verification admin-trust policy.
> - **Frontend integration:** the open items are listed in §15.9; the frontend is unchanged.

> Design proposal (revision 2, after design review). **Routes 6 to 9 exist since Recovery 9-B (§15.6), routes 2 to 5 since Recovery 9-C (§15.7) and route 1 since Recovery 9-D (§15.8).** Reasons and trade-offs: `docs/reports/RECOVERY_9_DESIGN_REQUEST.md`. Recommended resolutions and their status: `IMPLEMENTATION_DECISIONS.md`, "Recovery 9: proposed" (P-01 to P-18, all pending). Where a pending decision is named, the behaviour shown is its recommended resolution.

### 15.1 Authorization (all routes) — implemented (Recovery 9-A)

Every route is under `/api/admin`, on one router that mounts `authenticate`, then `requireAdmin` (R9-T1). The role and account state are read from the database on every request.

| Caller | Status | Envelope |
|---|---|---|
| No or invalid token, revoked or expired session | 401 | `{ success: false, message: "Authentication required", errors: {} }` (existing) |
| Active member without `ADMIN` | 403 | `message: "You are not allowed to do this"`, `errors: {}` (existing) |
| Suspended account (admin or not) | 403 | `message: "This account is suspended."` (existing) |
| Active `ADMIN` | the route | — |

- No admin route reads a role, actor, timestamp, status history or audit field from the request.
- No route creates, changes or removes a role (§4.1).
- Emergency demotion is an operator procedure, not a route (design request §7.1).
- Denied requests are logged with the user ID, route template, reason code and request ID only (R9-T15).

### 15.2 Routes (all nine implemented: 6 to 9 in Recovery 9-B, 2 to 5 in 9-C, 1 in 9-D)

| # | Method and path | FE call | Body / query | Success |
|---|---|---|---|---|
| 1 | `GET /api/admin/dashboard` | `adminService.getDashboard()` | — | 200 `AdminDashboardSnapshot` — **implemented (R9-D)** |
| 2 | `GET /api/admin/users` | `listUsers(filters)` | `query?`, `verificationStatus?`, `accountStatus?`, `page`, `limit` | 200 paginated `AdminUserRecord[]`: registered `USER` accounts, `active` or `suspended`, newest registration first — **implemented (R9-C)** |
| 3 | `GET /api/admin/users/:userId` | — (MP §25) | — | 200 `AdminUserRecord` — **implemented (R9-C)** |
| 4 | `PATCH /api/admin/users/:userId/status` | `suspendUser`, `reinstateUser` | `{ accountStatus: "suspended" \| "active" }` | 200 `AdminUserRecord` — **implemented (R9-C)** |
| 5 | `GET /api/admin/verification/queue` | `getVerificationQueue()` | `page`, `limit` | 200 paginated `VerificationQueueItem[]`, **read-only** (P-08); `[]` when no trusted record is in `manual_review`; never fabricated — **implemented (R9-C)** |
| — | approve / re-upload | `approveVerification`, `rejectVerification` | — | **No route** (404) until an admin-trust policy is approved (AD-51, P-08) |
| 6 | `GET /api/admin/reports` | — (MP §25, AD-43) | `status` (required), `order` = `desc` \| `asc`, `page`, `limit` | 200 paginated `AdminReportSummary[]` — **implemented (R9-B)** |
| 7 | `GET /api/admin/reports/:reportId` | — | — | 200 `AdminReportDetail`, only after its `report.details_released` entry commits (AD-77) — **implemented (R9-B)** |
| 8 | `PATCH /api/admin/reports/:reportId/status` | — | `{ to, expectedStatus, resolution?, internalNote? }` | 200 `AdminReportDetail` — **implemented (R9-B)** |
| 9 | `GET /api/admin/audit-logs` | — (MP §25) | `action?`, `actorId?`, `targetType?`, `targetId?`, `subjectUserId?`, `before?` (entry ID), `limit` | 200 `{ items: AuditRecord[], nextBefore }` — **implemented (R9-B)** |

With all nine routes the count is **51**. Recovery 9B's settings routes are not included.

### 15.3 Proposed shapes

> `AdminUserRecord` and `VerificationQueueItem` are implemented as written here since Recovery 9-C (§15.7); `AdminReportSummary`, `AdminReportDetail` and `AuditRecord` since Recovery 9-B (§15.6). `AdminDashboardSnapshot` is implemented since Recovery 9-D (§15.8).

- **`AdminDashboardSnapshot`** = `{ primaryKpis, memberKpis, engagementKpis, recentActivity }`, exactly the frontend type.
  - `AdminKpi` = `{ id, label, value: string, hint?, supported }`.
  - Unsupported KPIs: `value: "—"`, `hint: "Not tracked"`, `supported: false`. The frontend's `value` is a required `string` (P-14; revises B11).
  - `recentActivity` items are the frontend `AuditLogEntry` `{ id, action, memberName, category, timestampLabel, status }`, at most 10 (P-15). "High Priority", "Settled", "Monetization" and "Engagement" are never produced.
- **`AdminUserRecord`** has the frontend keys exactly, with **least-privilege values** (P-09):
  - `member.age` as members would see it: `null` when hidden (AD-26);
  - `member.primaryPhoto` only where `canViewProfileOf(admin, member)` already allows it, else `null`;
  - `maskedEmail: null` (C7);
  - `maskedPhone` masked.

  The `null`s do not match the frontend types (`number` and `string`), a recorded frontend-integration item. Field sources: `FRONTEND_BACKEND_FIELD_MAPPING.md` §10.
- **`VerificationQueueItem`** is the frontend type, derived per D14. `attemptCount` is `null` (not tracked).
- **`AdminReportSummary`** (backend only) = `{ id, targetType, status, target: { id, fullName }, hasEvidence, createdAt, statusChangedAt }`. **No reporter (AD-76, N-2), reason, evidence, resolution or note.** Implemented in Recovery 9-B.
- **`AdminReportDetail`** = the summary plus `{ reporter: { id, fullName }, reason, evidence: { messageText, messageSentAt } | null, targetMessageId, conversationId, resolution, internalNote, updatedAt }`. Implemented in Recovery 9-B.
- **`AuditRecord`** = `{ id, actorId, action, targetType, targetId, subjectUserId, change: { from, to } | null, requestId, outcome, createdAt }`. Never the acting session. Implemented in Recovery 9-B.

### 15.4 Proposed errors (envelope unchanged: `{ success: false, message, errors }`)

> Implemented for routes 2 to 9 (§15.6, §15.7), including `self_action` and `admin_target` (AD-79). `dashboard_unavailable` is implemented since Recovery 9-D (§15.8).

| Condition | Status | `errors` |
|---|---|---|
| Invalid ID, filter, `limit`, `to` or `accountStatus`; missing `expectedStatus`; missing `resolution` for `RESOLVED` / `REJECTED` (P-05); text over 2000 characters | 400 | field messages |
| Unknown or `deleted` account; unknown report | 404 | — |
| Transition not in the graph | 409 | `{ reason: "invalid_transition" }` (existing) |
| `expectedStatus` differs from the current status | 409 | `{ reason: "report_state_changed" }` (existing) |
| Account status changed concurrently | 409 | `{ reason: "account_status_changed" }` |
| Target is an `ADMIN` account / the caller | 409 | `{ reason: "admin_target" }` / `{ reason: "self_action" }` (P-03) |
| Audit entry cannot be written: the mutation is not committed, and evidence is not returned | 503 | `{ reason: "audit_unavailable" }` (P-10, P-11) |
| A KPI query fails or times out | 503 | `{ reason: "dashboard_unavailable" }` |
| Admin rate limit (provisional, P-18) | 429 | — |

No error carries a reason, note, evidence, message text, phone number or stack.

### 15.5 Proposed behaviour (summary)

- **Report transition:** the AD-43 graph, in one transaction: the actor lock write and re-read (R9-T2), a conditional update on `expectedStatus`, the audit insert. It changes only the report (P-06).
- **Details release (AD-77, replacing the proposed evidence release):** one transaction (the actor lock write and re-read, read the report, insert `report.details_released`); the details are returned only after commit, whether or not the report has evidence. Lists never carry the reporter, the reason or evidence.
- **Status change:** one transaction: the actor lock write and re-read (R9-T2), a conditional update, all sessions revoked on suspension (reason `admin`), the audit insert. Sockets are disconnected after commit. A no-op answers 200 without an audit entry (R9-T8). Reinstatement restores `active` only (P-07).
- **Member-facing behaviour is unchanged,** including §7 (privacy), §12 (reports; evidence never shown to members) and §13 (verification trust).
- **Not built:**
  - verification approve and re-upload (P-08);
  - report reopening;
  - moderation-event review;
  - exports;
  - role management;
  - notifications;
  - automatic retention (P-13).

### 15.6 Moderation routes as implemented (Recovery 9-B; AD-66, AD-67, AD-75 to AD-78)

All four routes are on the guarded router of §15.1, after `authenticate`, the denial log, `requireAdmin` and the per-admin limit: `GET` uses the read budget, `PATCH` the write budget (AD-72). Every one of them then runs inside the admin transaction guard (AD-73): the acting admin's `adminLock` is written and the account re-read in the transaction, so a demotion or suspension committed earlier refuses the request (401 or 403 as in §15.1), and the answer leaves the service only after that transaction has committed. Request input is validated (`src/validators/adminRules.js`); unknown fields are dropped; no actor, timestamp, reporter, target, evidence or audit field is ever taken from the request.

| Route | Input | Answer | Audit entries (same transaction) |
|---|---|---|---|
| `GET /api/admin/reports` | `status` (required: `OPEN`, `UNDER_REVIEW`, `RESOLVED`, `REJECTED`), `order` (`desc` default, `asc`), `page` (1 to 1000), `limit` (1 to 50, default 20) | 200 paginated `AdminReportSummary[]`, by creation time | none |
| `GET /api/admin/reports/:reportId` | `reportId` (object ID) | 200 `AdminReportDetail` | one `report.details_released` (`change: null`) |
| `PATCH /api/admin/reports/:reportId/status` | `to` (`UNDER_REVIEW`, `RESOLVED`, `REJECTED`), `expectedStatus` (required), `resolution` (required, non-blank, to close), `internalNote` (optional); text trimmed, at most 2000 characters, no control characters | 200 `AdminReportDetail` of the updated report | one `report.status_changed` (`change: { from: expectedStatus, to }`), then one `report.details_released`, because the answer is the report's details |
| `GET /api/admin/audit-logs` | `action`, `targetType`, `actorId`, `targetId`, `subjectUserId`, `before` (entry ID cursor), `limit` (1 to 50, default 20) | 200 `{ items: AuditRecord[], nextBefore }`, newest first | none |

- **Names (AD-75):** `target.fullName` and `reporter.fullName` are the profile's full name, or `null` without a profile. Nothing else of a member is returned: no age, date of birth, photo, phone number, token, provider field or internal field (`openKey`, locks).
- **Audit entries** hold IDs and enumerated values only (AD-69): never the reason, the evidence, the resolution, the note, a name or a phone number.
- **Errors:** 400 field messages for invalid input, a missing `expectedStatus` or a missing resolution to close; 404 for an unknown report; 409 `{ reason: "invalid_transition" }` for a step outside the AD-43 graph from `expectedStatus`; 409 `{ reason: "report_state_changed" }` when the report is no longer in `expectedStatus` (a stale view or a concurrent transition); 503 `{ reason: "audit_unavailable" }` when an audit entry cannot be written, in which case nothing is committed and no detail is returned; 429 over the admin limit.
- **No sanction (AD-67):** a transition changes only the report: no account status, session, block or match changes.
- **Not built:** routes 1 to 5, report reopening, moderation-event review, exports, retention (P-13; every retention period is undecided).

### 15.7 User administration as implemented (Recovery 9-C; AD-68, AD-69, AD-73, AD-75, AD-79, AD-80)

The four routes are on the guarded router of §15.1. `GET` uses the per-admin read budget, `PATCH` the write budget (AD-72). Every one of them runs inside the admin transaction guard (AD-73), so a demotion or suspension of the acting administrator committed earlier refuses the request, and the answer leaves the service only after the guard's transaction commits.

**Which accounts (the admin user set):** role `USER`, registration completed, status `active` or `suspended`. Administrators, unregistered and `deleted` accounts are never listed, and their detail answers 404.

| Route | Input | Answer | Audit (same transaction) |
|---|---|---|---|
| `GET /api/admin/users` | `query` (trimmed, at most 60 characters, no control characters; matched literally and case-insensitively against the full name or city), `verificationStatus` (`verified`, `pending`, `retry_required`, `manual_review`, `unverified`), `accountStatus` (`active`, `suspended`), `page` (1 to 1000), `limit` (1 to 50, default 20) | 200 paginated `AdminUserRecord[]`, newest registration first | none |
| `GET /api/admin/users/:userId` | `userId` (object ID) | 200 `AdminUserRecord` | none |
| `PATCH /api/admin/users/:userId/status` | `{ accountStatus: "suspended" \| "active" }`; nothing else is read | 200 `AdminUserRecord` after the change | `user.suspended` (`{ from: "active", to: "suspended" }`) or `user.reinstated` (`{ from: "suspended", to: "active" }`); none for a no-op |
| `GET /api/admin/verification/queue` | `page`, `limit` | 200 paginated `VerificationQueueItem[]`, longest wait first | none |

**`AdminUserRecord`** is the frontend type (`services/admin/users/types.ts`) with least-privilege values (AD-75; `FRONTEND_BACKEND_FIELD_MAPPING.md` §10.2):
- `member.age` is the age members would see: `null` when the member hides it (AD-26). `member.primaryPhoto` is the primary photo's URL only where `visibility.canViewProfileOf` allows this administrator, else `null`; a suspended member therefore has none. `member.isVerified` is trusted verification only (§13.6).
- `maskedEmail` is `null` (no email exists, C7). `maskedPhone` is `"<country code> <first five digits>•••••"`; the full number is never returned.
- `tier` is `"Premium"` only for a trusted subscription (§14). `verificationStatus` is the C1 mapping of the effective record (AD-51); a record the trust rule reads as absent counts as `unverified`.
- `joinedLabel` is `"Since <Mon YYYY>"` (UTC month) from the registration time.
- Never returned: the date of birth, the full phone number, tokens, provider references or evidence, `adminLock` or other locks, and audit internals.
- `member.age`, `member.primaryPhoto` and `maskedEmail` may be `null`, which the frontend types do not allow: a recorded frontend-integration item.

**Suspension and reinstatement** (AD-68, AD-79):
- In order: the caller's own account answers 409 `{ reason: "self_action" }`; any `ADMIN` account answers 409 `{ reason: "admin_target" }` (both before anything is written, whatever the requested status); an account outside the admin set answers 404; an account already in the requested status answers 200 with its record and writes nothing (no entry, no revocation, no disconnect; R9-T8).
- Otherwise, in one transaction: the status update, conditional on the account still being a `USER` in the expected status (409 `{ reason: "account_status_changed" }` if it changed meanwhile); on suspension, the revocation of **every** session of the account (reason `admin`); the audit entry. If any of these fails, nothing is committed; an audit failure answers 503 `{ reason: "audit_unavailable" }`.
- Only after the commit, on suspension, the account's sockets are disconnected (best effort; a failure is logged and does not undo the suspension).
- Reinstatement sets `active` only. Revoked sessions stay revoked; the member signs in again.
- The status checks at sign-in, refresh, every request and every socket event are unchanged and remain the backstop for anything in flight. No user sanction is applied automatically by any other route (AD-67).

**`VerificationQueueItem`** (read-only; AD-80, D14):
- The records the trust rule accepts (AD-51: in production, provider evidence only) that are in `manual_review`, oldest `stateChangedAt` first. **Empty when there is none;** nothing is ever manufactured.
- `id` is the member's **account ID**; accounts are never matched by name. `applicantName` is the profile's full name and `ageCityLabel` is `"<age> • <city>"` with the member-visible age (the city alone when hidden); both are `null` without a profile.
- `verificationType` is the provider name on the record, else `"Not available"`. `status` is always `"Ready for Approval"` (D14). `attemptCount` is `null`: attempts are not tracked. `waitLabel` is the time since the record entered `manual_review`.
- Reading the queue changes nothing. There is **no** approve, reject or re-upload route, and none will exist until a verification admin-trust policy is approved.

**Errors:** 400 field messages for invalid input; 404 for an account outside the admin set; 409 `self_action`, `admin_target` or `account_status_changed`; 503 `audit_unavailable`; 429 over the admin limit; 401 or 403 for the caller as in §15.1.

### 15.8 Dashboard as implemented (Recovery 9-D; AD-73, AD-75, AD-81, AD-82)

`GET /api/admin/dashboard`, on the guarded router of §15.1, with the per-admin **read** budget (AD-72). It takes no input: any query parameter is dropped. It runs inside the admin transaction guard (AD-73) and **writes nothing**, not even an audit entry.

**Answer:** 200 `AdminDashboardSnapshot` = `{ primaryKpis, memberKpis, engagementKpis, recentActivity }` (the frontend type, `services/admin/types.ts`).

**KPIs** (AD-81): the frontend's twelve IDs and labels, in its order. Each is `{ id, label, value, hint, supported }`; `supported` is a backend addition the frontend type does not declare.
- `value` is the live count formatted with thousands separators (`"1,234"`). There is no cache.
- **Untracked** (`gateway_retries`, `boost_triggers`, `mod_queue_sla`): `value: "—"`, `hint: "Not tracked"`, `supported: false`; never `null`, zero or an estimate.
- Hints are definitions only: no trend, ratio, forecast or urgency.
- "Today" is the calendar day in Asia/Kolkata (00:00 to 24:00 IST); "24 h" is a rolling window ending now.

| KPI | Counts | Hint |
|---|---|---|
| `verification_backlog` | the records the read-only queue (§15.7) lists: `manual_review` records the trust rule accepts (AD-51) | Verification records awaiting manual review |
| `open_safety_reports` | reports `OPEN` or `UNDER_REVIEW` | Reports open or under review |
| `moderation_alerts` | moderation events with status `OPEN` (one per held message; there is no review workflow, AD-42) | Held messages recorded by automated moderation |
| `total_members` | the admin user set of §15.7 (registered `USER` accounts, `active` or `suspended`), with the list's own filter | Registered members, active or suspended |
| `new_today` | the same accounts registered within today (IST) | Registered since 00:00 IST |
| `active_users` | distinct accounts with a session whose `lastUsedAt` is in the last 24 h. **Approximate:** `lastUsedAt` changes at sign-in and refresh only, and expired sessions are deleted | Approximate: accounts that signed in or refreshed a session in the last 24 h |
| `online_now` | distinct accounts with an open socket **in this server process** (the presence service). Aggregate only: no member is identified. Not a cluster-wide count (AD-46) | This server process only |
| `messages_sent` | messages created in the last 24 h whose moderation is `unmoderated` or `clear`; **held messages are excluded** | Messages sent in the last 24 h; held messages excluded |
| `super_likes` | Super Like ledger entries (reason `super_like`) created in the last 24 h | Super Likes sent in the last 24 h |

Every count is one indexed count query with `maxTimeMS` 5000 (`active_users` is a distinct-account aggregation). Indexes: `users { registrationCompletedAt: 1 }`, `sessions { lastUsedAt: 1 }`, `messages { createdAt: 1, moderation: 1 }`, and the existing `verifications { state, stateChangedAt }`, `reports { status, createdAt }`, `moderationevents { status, createdAt }` and `superlikeledgerentries { reason, createdAt }`.

**Recent activity** (AD-82): at most 10 `AuditLogEntry` rows `{ id, action, memberName, category, timestampLabel, status }`, newest first, merged from five sources of at most 10 rows each:

| Source | `action` | `category` | `status` | `memberName` |
|---|---|---|---|---|
| a registration (the admin user set) | New User Registered | User Lifecycle | Success | the member |
| a trusted verification reaching `verified` | Verification Completed | Trust & Safety | Verified | the member |
| a report that is still `OPEN` or `UNDER_REVIEW` | Safety Report Filed | Moderation | Active (the report is open) | the **reported** member |
| a suspension (audit entry) | Account Suspended | Trust & Safety | Suspended | the member |
| a reinstatement (audit entry) | Account Reinstated | Trust & Safety | Success | the member |

- `memberName` is the first name and last initial (`"Vikram M."`; a one-word name stays as it is; `""` without a profile).
- **The reporter is never shown,** and no report reason, evidence, resolution or note is read. A closed report leaves the feed.
- `id` is an opaque row key (an HMAC under a per-process key): it carries no account, report or audit ID and changes when the server restarts.
- `timestampLabel` is the relative time ("8 mins ago").
- Never produced: "High Priority", "Settled", "Monetization", "Engagement", or any payment or Boost row.

**Errors:** 401 or 403 for the caller (§15.1); 429 over the read limit; **503 `{ reason: "dashboard_unavailable" }`** when any query fails or exceeds its time limit, with no partial snapshot.

### 15.9 Frontend integration items (recorded; the frontend is unchanged)

The backend follows the approved privacy and trust rules; it does not bend them to fit the frontend types. These items must be resolved in the frontend at integration:

| Item | Frontend today | Backend |
|---|---|---|
| Admin services are mocks | `adminService` and `adminUsersService` are `mock*` objects; no HTTP client calls `/api/admin` | the nine routes of §15.2 |
| Admin route guard | the `(admin)` route group has no client-side role check; the layout renders for anyone | every `/api/admin` request is authorized on the server (§15.1); a non-admin gets 401 or 403 |
| Pagination envelope | `listUsers()` and `getVerificationQueue()` resolve to plain arrays and are called without paging | paginated envelopes `{ success, message, data, pagination: { page, limit, hasMore } }`; `limit` at most 50. The Users page KPI cards, computed from the list, would count one page only |
| Nullable fields | `AdminUserRecord.member.age: number`, `member.primaryPhoto: string`, `maskedEmail: string`; `VerificationQueueItem.applicantName`, `ageCityLabel: string`, `attemptCount: number` | `null` when the member hides the age, when the visibility rule hides the photo, always for the email (none exists), without a profile, and always for the attempt count (not tracked) |
| Extra KPI field | `AdminKpi` has no `supported` | `supported` is added; untracked KPIs answer `"—"` |
| Verification actions | `approveVerification` / `rejectVerification` buttons in the queue | **no routes** (AD-80) until a verification admin-trust policy is approved; the buttons must not be wired |
| Queue matching | the queue action finds the member by `u.fullName === item.applicantName` | the queue item `id` **is** the account ID; members must be matched by ID, never by name (two members can share a name) |
| Report and audit screens | none | routes 6 to 9 have no frontend |
| Dashboard extras | "Export Report" button, "Cluster BOM-01 • Healthy" header | not backed |

---

## 16. Member settings (Recovery 9B) — **IMPLEMENTED; RUNTIME-UNVERIFIED**

Decisions AD-19 (most restrictive wins), AD-34 (presence), AD-70 (the counters), AD-71 and AD-85 (the Online Activity Indicator), AD-84 (route surface), AD-86 and AD-94 to AD-96 (refused switches), AD-87 (no presence push), AD-88 (sessions), AD-89 (pause), AD-93 (Display Exact Age). Only the settings features whose semantics are approved are served. Every route requires an access token, acts on the caller's own account only (`req.auth`; no route takes another member's ID), and requires a completed registration, as the blocked list does (409 `{ reason: "profile_not_registered" }`). The app-wide rate limit applies.

### 16.1 Routes

| Method and path | Body | Success |
|---|---|---|
| `GET /api/settings/summary` | — | 200 `{ blockedCount, reportedCount }` |
| `GET /api/settings/privacy` | — | 200 `{ onlineActivityIndicator, displayExactAge }` |
| `PATCH /api/settings/privacy` | `{ onlineActivityIndicator?: boolean, displayExactAge?: boolean }`, at least one | 200 `{ onlineActivityIndicator, displayExactAge }` |
| `POST /api/settings/pause` | none, or `{ paused?: boolean }` | 200 `{ paused }` |
| `GET /api/settings/sessions` | — | 200, `data` is `DeviceSession[]` |
| `DELETE /api/settings/sessions/:sessionId` | — | 200, `data` is `DeviceSession[]` (the list after the revocation); 404 `"Session not found"` |

### 16.2 The counters (AD-70)

- `blockedCount`: the blocks the caller made, exactly the set `GET /api/users/blocked` lists (§12). Being blocked is never counted.
- `reportedCount`: the caller's **own** reports that are still open (`OPEN` or `UNDER_REVIEW`). Reports filed **about** the caller are never counted and never revealed (AD-40).
- Both are counts on existing indexes whose first field is the caller (`blocks { blockerId, createdAt }`, `reports { reporterId, createdAt }`): only the caller's own records are read.

### 16.3 The Online Activity Indicator (AD-19, AD-34, AD-71, AD-85, AD-87)

- Stored in `UserSettings.privacy.onlineActivityIndicator` (created on the first change).
- **Reads as `true` until the member changes it:** an absent setting imposes no restriction (§7), so presence for a member who never touched it is exactly what it was before Recovery 9B.
- `false` hides the member's online status from every other member, combined with the profile's `showOnlineStatus`, **the more restrictive winning**: the member is shown `offline` in conversation summaries and cards, is never kept by discovery's `onlineOnly`, and no `presence:update` is sent about them (§11.6). Nothing else changes: the member still appears in discovery, conversations and cards.
- **Limitation (AD-87):** switching the indicator off or on sends no `presence:update`. While a member is hidden, their presence audience is empty, so no offline update is sent when they later disconnect either: a viewer who saw them online before the switch keeps that state until the viewer's next refresh. Same as the profile's `showOnlineStatus` since Recovery 5.
- There is no admin view of a member's setting or presence (AD-71); the admin dashboard's `online_now` stays an aggregate count.

### 16.4 Display Exact Age (AD-19, AD-26, AD-93)

- Stored in `UserSettings.privacy.displayExactAge`. **Reads as `true` until changed**: unset imposes no additional restriction, and the profile's `showExactAge` continues to govern.
- `false` hides the member's exact age from every other member, combined with `showExactAge`, **the more restrictive winning** (`effectivePrivacy`): `age` is `null` on discovery cards, member detail, the matches and liked-you lists, and in the admin user records and verification queue, which show the age exactly as members see it (AD-75).
- With an age filter active, discovery leaves out a member whose age is hidden by either switch, so repeated searches cannot reveal it (AD-26). Without an age filter the member appears normally, with `age: null`.
- Nothing else changes: presence, intention, distance and discovery visibility are unaffected.

### 16.5 Sessions (AD-88, D12)

- `DeviceSession` is the frontend's type: `{ id, deviceLabel, location, isCurrent }`, and nothing else (no dates, no token hash, no raw User-Agent).
- The list holds the caller's sessions that are **not revoked and not expired**. The current session (the one whose access token made the request) comes first and is the only one with `isCurrent: true`; the others follow, most recently used first (`lastUsedAt`, which changes at sign-in and refresh). At most 50 sessions are returned (provisional bound); the current session is always included.
- `deviceLabel` is derived from the User-Agent stored at sign-in, through a fixed list of names: "`<browser>` on `<system>`" (for example "Chrome on macOS"), "Browser on `<system>`", or "Unknown device". The raw User-Agent is never returned.
- `location` is always `""`: no geolocation is performed and no provider is added.
- `DELETE /api/settings/sessions/:sessionId` revokes that one session with reason `user`, only if it is the caller's own, not revoked and not expired. The conditional update names both the session and the account, so no other member's session can be touched. Any other ID (another member's, already revoked, expired, or unknown) answers the same 404, revealing nothing. A malformed ID is 400. After the revocation the session's sockets are disconnected (AD-32). The caller may revoke their current session too; the frontend offers this only for other sessions, and signing out of the current one remains `POST /api/auth/logout`, which also clears the refresh cookie.
- `data` is the `DeviceSession[]` array itself, as `logOutSession(sessionId)` and `SettingsSnapshot.sessions` expect and as every list in this API returns it. The list is not paginated: it is bounded by the 50-session limit, so it carries no `pagination`.

### 16.6 Pause (AD-89, D17)

- Stored in `UserSettings.paused`. **A member without a stored value is not paused**, so no existing member is hidden and no migration is needed.
- `POST /api/settings/pause` with no body (the frontend's `pauseProfile()` sends none) or `{ paused: true }` pauses; `{ paused: false }` resumes. Pausing or resuming changes no other setting and no profile privacy switch.
- A paused member is **not visible in discovery** (`effectivePrivacy`: visible only when `visibleInDiscovery` and not paused). This applies wherever "visible in discovery" decides something:
  - discovery search, `onlineOnly`, the text query and `featured` leave the member out;
  - member detail and the member's photos (§6.4, §8.4) remain visible only to a match or to a member the paused member has liked;
  - like, Super Like and pass (§9.1) are refused (404) unless the paused member has liked the caller.
- Existing matches, conversations, the liked-you list and presence are unchanged. Resuming restores discovery only where the profile's `visibleInDiscovery` allows it.
- There is no read route for the pause state (the frontend has none); `POST` answers the stored state.

### 16.7 Validation and what is not served

- Each switch in the privacy patch must be `true` or `false`; at least one approved switch is required; anything else is 400.
- `intentAndDietaryPrivacy` (AD-95, deferred), `approximateProximity` (AD-94) and `culturalHeritageAndHometown` (AD-96) are **refused** with 400 `"This setting is not available yet"`, not silently dropped (AD-86). Any other unknown field is dropped.
- `paused` must be `true` or `false` when present; the session ID must be a 24-character hexadecimal ID.
- **Not served:** the frontend's `getSettings()` snapshot as a whole (`AccountSummary.fullName`, `maskedPhoneNumber`, `isDigilockerVerified`, the three refused switches, `NotificationSettings`), `updateNotifications`, `requestDeletion` and `requestDataExport`. They need decisions first (`docs/reports/RECOVERY_9B_DECISION_REGISTER.md`). At integration the frontend composes its settings screen from §16.1 and the existing routes; it receives no placeholder values.

## 17. Deletion request (batch LC-3) — **IMPLEMENTED; RUNTIME-UNVERIFIED; NON-DESTRUCTIVE**

Decisions AD-97 to AD-102. A member asks for their account to be deleted. The request is recorded, the account becomes unavailable to other members, every session is signed out, and a purge-eligibility time is scheduled. **Nothing is deleted.** No purge, scheduler, export, redaction, retention enforcement or legal hold exists; nothing reads `scheduledPurgeAt`.

### 17.1 Routes

Mounted before `/api/settings`. "Pending" means the route also admits an account with a pending request (restricted mode, AD-99); every other route in the API answers such an account 409 `{ reason: "deletion_pending" }`.

| Method and path | Admits pending | Body | Success |
|---|---|---|---|
| `GET /api/settings/deletion` | yes | — | 200 `{ status: "none" }` or `{ status: "pending", requestedAt, scheduledPurgeAt }` |
| `POST /api/settings/deletion/request-code` | no | none | 200 `{ requestId, expiresInSeconds, maskedPhoneNumber }`; 409 `deletion_already_pending` |
| `POST /api/settings/deletion` | no | `{ requestId, code }` | 201 `{ status: "pending", requestedAt, scheduledPurgeAt }`; 409 `deletion_already_pending` |
| `POST /api/settings/deletion/cancel-code` | yes | none | 200 `{ requestId, expiresInSeconds, maskedPhoneNumber }`; 409 `no_pending_deletion` |
| `POST /api/settings/deletion/cancel` | yes | `{ requestId, code }` | 200 `{ status: "cancelled", cancelledAt }`; 409 `no_pending_deletion` |

`POST /api/auth/logout` needs no authentication and works in restricted mode. `POST /api/auth/refresh` refuses a pending account (409 `deletion_pending`), so a restricted session ends when its access token expires; the member signs in again with a sign-in code. Over Socket.IO a pending account is refused at the handshake and on every event with the existing `unauthenticated` code; no new socket error code is introduced.

### 17.2 Who

A registered `USER` account: 409 `profile_not_registered` before registration; 403 `{ reason: "admin_account" }` for an administrator. A suspended account cannot sign in or authenticate (403), so it has no path while suspended. No exception and no admin-initiated path exists (AD-100). The service refuses a suspended account again (403) as a backstop.

### 17.3 Codes (AD-97, AD-103, AD-104)

- Each code is sent to the **account's own stored number**. A `phoneNumber` or `countryCode` in any of these bodies is refused with 400; it is never used.
- Codes are bound to a purpose (`sign_in`, `deletion_request`, `deletion_cancel`). A deletion code is also bound to the **account** it was issued for. A code is accepted only for its own purpose, number and account; anything else answers as an expired code (410) and counts no attempt. A deletion code cannot sign in (`POST /api/auth/verify-otp` answers 410) and is not resent by `POST /api/auth/resend-otp` (410); a new one is requested from its own route.
- **Isolation by purpose (AD-104).**
  - At most one active code per number **and purpose**.
  - A new code invalidates only the same purpose's earlier code. A public sign-in request never invalidates a deletion or cancellation code, and never uses up their allowance.
  - Limits:
    - **sign-in**: the existing 30-second cooldown and the per-number caps (`OTP_MAX_SENDS_PER_PHONE_PER_HOUR` / `_PER_DAY`, default 5 and 10), counting sign-in sends only;
    - **each deletion purpose**: the same cooldown and the same five-per-hour and ten-per-day values, counted **per account and purpose**.
  - A number can therefore receive up to three purposes' allowances, where previously it had one.
  - Unchanged: five-minute validity, and five wrong attempts lock a code (429). Simultaneous requests for one number and purpose leave one active code; the others answer 429.
- **Templates (AD-103).** Each purpose has its own provider template:
  - `SMS_TEMPLATE_ID` for sign-in (unchanged);
  - `SMS_TEMPLATE_ID_DELETION_REQUEST`;
  - `SMS_TEMPLATE_ID_DELETION_CANCEL`.

  While SMS is enabled, a code request whose purpose has no template answers **503 and sends nothing**: no code is stored and no earlier code is invalidated. There is **no fallback** to the sign-in template. The template wording and its registration with the provider need staging and provider access; **real delivery is not verified**.
- A code is consumed before the change is written. If the write then fails, nothing changed and a new code is needed.

### 17.4 The request (AD-98, AD-102)

- One transaction:
  1. the `AccountDeletionRequest` (`pending`, `requestedAt`, `scheduledPurgeAt` = `requestedAt` + 30 days);
  2. its history entry (`requested`);
  3. `User.deletionPendingAt`, conditional on a plain, active account not already pending;
  4. the revocation of **every** session, the current one included (reason `user`).
- After the commit, and only then, the account's sockets are disconnected.
- `scheduledPurgeAt` is a scheduled **eligibility** time (AD-98): when a purge would become eligible. It is not a promise that a purge exists or will run at that instant.
- One pending request per account (partial unique index). A second request answers 409 `deletion_already_pending` and writes nothing.

### 17.5 While pending

- **Restricted mode (AD-99).** The member may sign in. Signing in never cancels. Their sessions can use only the three "pending" routes above and logout.
- **Other members (AD-102).** The account is unavailable wherever an inactive account already is:
  - discovery, cards and member detail and photos (404);
  - like and pass targets (404);
  - matches and liked-you lists;
  - conversations: the other member's list omits the conversation, and sends answer 404;
  - presence audiences.
- **Administrators.** The account stays in the admin user set (list and detail). Report, queue and moderation views are unchanged. Suspension and reinstatement work as before and are **independent** of the request: neither creates nor cancels it.
- **Nothing is deleted.** Messages, matches, likes, blocks, reports, evidence, moderation events, audit entries, photos and the profile all stay (AD-100).

### 17.6 Cancellation (AD-99)

- Explicit, with a fresh `deletion_cancel` code. One transaction:
  1. `pending` → `cancelled` (with `cancelledAt`);
  2. its history entry (`cancelled`);
  3. `deletionPendingAt` cleared. `accountStatus` is never touched.
- Member-facing availability returns, with every record intact.
- **Sessions revoked by the request stay revoked.** The current restricted session becomes an ordinary session.
- A later request is a new record.

### 17.7 History (AD-101)

`AccountDeletionEvent` records one entry per state change, in the same transaction:
- the request ID;
- the account ID;
- the event (`requested` | `cancelled`);
- the confirming session's ID;
- the time.

It holds no phone number, code or free text. It is insert-only: the model refuses every update and delete. It is separate from `AdminAuditLog`. No retention period is chosen (P-12, L-20), and there is no read route.

### 17.8 Not served, and frontend integration (deferred; frontend files are off-limits)

- `requestDeletion()` sends no data. The frontend needs a code step: `request-code`, then the `POST` with `{ requestId, code }`.
- There is no status or cancellation screen, and no handling of 409 `deletion_pending` or of being signed out right after the request.
- The frontend copy says data "will be purged **within** 30 days" (card, dialog and toast). Under AD-98, 30 days is a **waiting period** before eligibility, so the copy is inaccurate and must change at integration.
- The `Conversation` type has no field to show "pending deletion"; the conversation simply disappears for the other member.
- The admin views show no pending marker: `AdminUserRecord` has no such field.
- No purge, export (`requestDataExport()` is still unserved) or scheduler exists.
