# Runtime Verification Procedure

**Status update (2026-10-26): still NOT EXECUTED.** No run in a suitable environment has happened yet. A hardened gate script, `toraz-runtime-gate.v2.sh` (kept outside the repository; sha256 `4ba82b06ab1c16144179ef6fe68cf23f109efa26b8e49f65841de1eee027993f`), automates sections 3 to 6 and an OTP purpose migration rehearsal for checkpoint `54800a5` on Linux or WSL 2. It has been syntax-checked only and has **never been executed**. This update corrects three figures below (nine frontend-parity tests; one skip that is by design in the unit and full runs; the equipped unit total). Code at later documentation-only commits is identical to `54800a5`.

**Status (2026-10-12): NOT YET EXECUTED.** Every step below needs an environment this reconstruction workspace does not have, so none of it has run. Rechecked on 2026-10-12:

- `registry.npmjs.org` does not resolve, directly or through the proxy (`npm view` times out).
- `fastdl.mongodb.org`, where `mongodb-memory-server` downloads MongoDB, is unreachable.
- There is no `mongod` or `mongosh` binary.
- Docker is installed, but its daemon is not running.

Until this procedure has been run and its results recorded, **no Recovery 1–5 behaviour that needs an installed package, MongoDB or a real socket may be described as runtime-verified.**

The goal is to run the complete suite once, against real packages, a real MongoDB replica set and real Socket.IO. It must record exactly what passed, failed, was skipped or was not executed, and change nothing about the code or tags while doing it.

---

## 1. Prerequisites

| Need | Why | Check |
|---|---|---|
| Node.js **22.x** (`engines: >=22`) and npm 10 | Runtime and test runner (`node --test`, multiple reporters) | `node -v`, `npm -v` |
| Git | Checkpoint integrity, lockfile commit | `git --version` |
| Network access to `registry.npmjs.org` | `npm install` | `npm ping` |
| Network access to `fastdl.mongodb.org`, **or** a local `mongod` 4.4+ binary | `mongodb-memory-server` starts the temporary one-member replica set used by `tests/db` | `curl -I https://fastdl.mongodb.org/` or `mongod --version` |
| Docker (or a separately installed MongoDB 4.4+) | The start-up smoke tests in section 7 against a real replica set and a real standalone server | `docker info` |
| The surviving frontend source, unchanged | Frontend integrity (section 8) and the **9 frontend-parity tests**: 5 in `tests/unit/profile.rules.test.js`, 1 in `tests/unit/verification.units.test.js`, 2 in `tests/unit/premium.units.test.js`, 1 in `tests/unit/admin.dashboard.units.test.js` (corrected 2026-10-26; see section 6 note) | section 8 |
| A platform `sharp` supports (Linux x64/arm64 glibc, macOS, Windows) | Photo pipeline tests | installs with `npm install` |
| About 1.5 GB free disk | `node_modules` plus a MongoDB binary | `df -h` |

**Directory layout.** The frontend-parity tests expect the frontend next to the backend, exactly like this:

```text
<work>/
  backend/                                   the backend repository (from the checkpoint ZIP)
  _frontend_extract/toraz_frontend-master/   the frontend, as extracted from toraz_frontend-master.zip
```

## 2. Obtain and check the checkpoint

> **Update (2026-10-26):** use the latest checkpoint ZIP and check it against its own `.sha256` sidecar. The Recovery 5 names below are the original example and are kept for history.

```bash
mkdir -p ~/toraz-verify && cd ~/toraz-verify
# Copy in the checkpoint ZIP and the frontend ZIP, then:
sha256sum toraz-backend-recovery-5-2026-10-09.zip
#   must be b95d152835664f6a0938889abb6031abbde22271d16184667bb78703b1f80b88
#   (a later review commit ZIP, if used, has its own published hash)
unzip -q toraz-backend-recovery-5-2026-10-09.zip          # creates ./backend
mkdir -p _frontend_extract && unzip -q toraz_frontend-master.zip -d _frontend_extract
cd backend
git fsck --full                                            # must print nothing alarming and exit 0
git status --short                                         # must be empty
git tag -l                                                 # recovery-1 … recovery-5 present
git log --oneline -1
```

Work on a branch, so that no tag or checkpoint moves:

```bash
git switch -c runtime-verification
```

## 3. Review the declared dependencies before installing

Nothing is installed or upgraded blindly. First confirm that every declared range resolves, and note what it resolves to:

```bash
for p in cors dotenv express express-rate-limit helmet jsonwebtoken mongoose multer sharp socket.io zod \
         eslint mongodb-memory-server socket.io-client; do
  range=$(node -p "const j=require('./package.json'); (j.dependencies[process.argv[1]]||j.devDependencies[process.argv[1]])" "$p")
  printf '%-24s %-10s -> %s\n' "$p" "$range" "$(npm view "$p@$range" version 2>/dev/null | tail -1)"
done
```

**If any range resolves to nothing, stop and report it.** Do not edit `package.json` to make it resolve; that is a reviewed change. Known points to confirm:

| Package (declared) | What to confirm | Why it matters |
|---|---|---|
| `zod ^4.4.3` | That 4.4.3 or a later 4.x exists | Validators were run here only under Zod 3.25's bundled 4.0 API, not under a real 4.4 install |
| `express ^5.1.0` + `express-rate-limit ^7.5.0` + `multer ^2.0.2` | Peer ranges accept Express 5 (`npm ls` shows no invalid peer) | Express 5 changed routing and error handling |
| `mongoose ^8.9.0` | Its driver supports MongoDB 4.4–8.x | Start-up requires wire version ≥ 9 (MongoDB 4.4) |
| `mongodb-memory-server ^10.1.0` | Its default MongoDB binary version (7.0.x expected); set `MONGOMS_VERSION` only if the default cannot run on the host | Database tests run on whatever binary it downloads |
| `socket.io ^4.8.1` / `socket.io-client ^4.8.1` | Both resolve to the same minor | The real-socket tests use `emitWithAck` (client 4.6+) |
| `sharp ^0.35.4` | A prebuilt binary exists for the platform | Native module |
| `eslint ^10.1.0` | Flat config (`eslint.config.js`) loads | Lint |
| `dotenv ^16.4.5` | The `quiet` option is harmless in 16.x | Configuration loading |

## 4. Install, create and verify the lockfile

```bash
npm install                      # creates package-lock.json (none exists yet; none was ever invented)
git status --short               # expected: only "?? package-lock.json" (and node_modules is ignored)
npm ls --all > /dev/null         # must exit 0: no missing, extraneous or invalid packages
npm audit --omit=dev || true     # record the output; do not run "npm audit fix" here
git add package-lock.json
git commit -m "Add package-lock.json from the first verified install"

# Reproducibility: the lockfile alone must rebuild the same tree.
rm -rf node_modules
npm ci
npm ls --all > /dev/null
```

The lockfile commit goes on the `runtime-verification` branch. Merging it, and tagging anything, is a separate approved step.

## 5. Static checks

```bash
npm run check        # node --check on every file; expect 0 failed
npm run lint         # ESLint; expect no findings
```

## 6. The test suites

Use `--test-concurrency=1` for the database and socket suites, so that the temporary MongoDB and the ports are not shared between files. Save every result as TAP, which is the evidence:

```bash
mkdir -p verification
run() {  # $1 = name, $2 = glob, rest = extra node flags
  name=$1; glob=$2; shift 2
  node --test "$@" --test-reporter=spec --test-reporter-destination=stdout \
       --test-reporter=tap --test-reporter-destination="verification/$name.tap" "$glob" \
    2>&1 | tee "verification/$name.log"
}
run unit       "tests/unit/**/*.test.js"
run validators "tests/validators/**/*.test.js"
run http       "tests/http/**/*.test.js"
run image      "tests/image/**/*.test.js"
run db         "tests/db/**/*.test.js"      --test-concurrency=1
run socket     "tests/socket/**/*.test.js"  --test-concurrency=1
npm test 2>&1 | tee verification/all.log           # the whole suite in one run, as CI would
```

If the MongoDB binary cannot be downloaded but a local `mongod` 4.4+ exists:

```bash
MONGOMS_SYSTEM_BINARY="$(command -v mongod)" run db "tests/db/**/*.test.js" --test-concurrency=1
```

**Expected totals at this checkpoint (OTP purpose isolation and SMS templates, AD-103 and AD-104).** Two runs of the same working tree, recorded separately because they differ only in whether the frontend is present. Both ran on the restricted reconstruction workspace (Node 22, no npm registry, no MongoDB, a local `sharp` copy), with `node --test "tests/**/*.test.js"`.

| Run | Environment | Tests | Passed | Failed | Skipped (NOT EXECUTED) |
|---|---|---|---|---|---|
| A | Restricted workspace, **frontend present** at `../_frontend_extract/toraz_frontend-master` (section 1 layout) | 2042 | 1424 | 0 | 618 |
| B | Restricted workspace, **backend only** (no frontend next to it) | 2042 | 1415 | 0 | 627 |

**The difference is exactly the 9 frontend-parity tests**: executed and passed in run A, skipped in run B. The other 618 skips are identical in both runs:
- MongoDB: 459 + 3;
- HTTP: 93 + 10;
- Socket.IO: 5;
- Zod: 47;
- **1** store-contract test that needs the Mongoose model: the audit model's append-only middleware, MongoDB backend only.

Syntax check: 315 files checked, 315 ok, 0 failed. Earlier figures, for history: batch LC-3 run A 2009 / 1402 / 607, run B 2009 / 1393 / 616; Recovery 9B integration hardening run A 1941 / 1362 / 579, run B 1941 / 1353 / 588; Recovery 9B sessions and pause run A 1930 / 1356 / 574, run B 1930 / 1347 / 583; Recovery 9B settings run A 1888 / 1333 / 555, run B 1888 / 1324 / 564; Recovery 9-D run A 1845 / 1310 / 535, run B 1845 / 1301 / 544; Recovery 9-C run A 1766 / 1258 / 508, run B 1766 / 1250 / 516; Recovery 9-B run A 1667 / 1191 / 476, run B 1667 / 1183 / 484; Recovery 9-A run A 1560 / 1126 / 434, run B 1560 / 1118 / 442; Recovery 8 run A 1488 / 1067 / 421, run B 1488 / 1059 / 429.

Per suite, run A:

| Suite | Tests | Expected here (run A) | Expected in the equipped environment |
|---|---|---|---|
| unit | 1413 | 1412 pass, 1 skipped (audit model, MongoDB only); run B: 1403 pass, 10 skipped | **1412 pass, 1 skipped by design**: the store-contract audit-model test needs the Mongoose model, so its in-memory instance always skips (it executes in the db suite). Includes the 9 frontend-parity tests if the layout in section 1 is used |
| validators | 50 | 3 pass, 47 skipped (no zod) | 50 pass |
| http | 103 | 103 skipped | 103 pass |
| image | 9 | 9 pass | 9 pass |
| db | 462 | 462 skipped | 462 pass |
| socket | 5 | 5 skipped | 5 pass |
| **all** (`npm test`) | 2042 | 1424 pass, 618 skipped | **2041 pass, 1 skipped by design** (the same audit-model test); backend only (run B): 2032 pass, 10 skipped (that test and the 9 frontend-parity tests) |

The 50 validator tests were also run against the two Zod copies available in this workspace (Zod 3.25.76, and its bundled `zod/v4` API reported as `4.0.0-from-3.25.76`): 50 / 50 each. **That is not the declared `zod@^4.4.3`**, which was not executed.

None of this executes MongoDB, Express/HTTP, the declared Zod 4 or the real Socket.IO packages, and none of it establishes production readiness: it shows only that the syntax is valid and that the in-process tests pass. The in-memory transaction runner is **serializable**, so in-process tests cannot demonstrate MongoDB's snapshot-isolation behaviour (the Recovery 9 `adminLock` guarantee in particular).

*Correction note (2026-10-26):* this section previously listed 8 frontend-parity tests and expected 1413 unit passes in the equipped environment. At checkpoint `54800a5` the correct figures are **9** frontend-parity tests (the ninth, in `tests/unit/admin.dashboard.units.test.js`, arrived in Recovery 9-D, `6b2e8a6`) and **1412 passes plus 1 by-design skip** in the unit suite.

*Correction note (Recovery 8.1):* the Recovery 8 version of this section said "7 frontend-parity tests"; the correct figure is **8**. The Recovery 7 version said 5; the correct figure at Recovery 7 was **6** (5 in profile rules, 1 in verification), checked against the Recovery 7 backup.

**Any test still reported `# SKIP NOT EXECUTED` in the equipped environment means a prerequisite is missing; that is a failed verification, not a pass.** There are exactly two allowed exceptions: the one by-design skip `NOT EXECUTED: needs the Mongoose model (MongoDB backend only)` in the unit and full runs, and, in a backend-only run, the 9 skips `NOT EXECUTED: the frontend source is not present next to the backend`. Count the skips:

```bash
grep -h "# SKIP" verification/*.tap | sed 's/.*# SKIP //' | sort | uniq -c
grep -h -E "^# (tests|pass|fail|skipped|cancelled|todo)" verification/*.tap
```

### What each required area is verified by

| Area | Executed by | Tests |
|---|---|---|
| **MongoDB transactions** (AD-30): like or Super Like, debit, seals, Match and Conversation in one unit; registration and grant | `tests/db/mongo.test.js`, shared suites on a one-member replica set | `matchingFlow` (all, including "simultaneous mutual likes make one Match", which now also asserts exactly one Conversation for that Match; "simultaneous Super Likes …"; "a balance of 1 pays for exactly one …"; "simultaneous registrations grant once"); `storeContract` (transaction contract, conversation duplicate inside a transaction); `profileFlow` |
| **Write skew and the pair lock** (simultaneous A→B and B→A) | same | "simultaneous mutual likes …" (8 rounds with varied timing). On MongoDB this is the first real test of the pair lock; the in-memory model cannot show it |
| **Start-up topology check** (AD-31) | `tests/db/transactionSupport.test.js` | Replica set accepted; standalone `mongod` refused |
| **Messaging on MongoDB** (AD-35, AD-36) | `tests/db/mongo.test.js` (`messagingFlow` on MongoDB) | All 31 messaging flows, including concurrent idempotent sends and concurrent read-up-to |
| **Real Socket.IO** (AD-32, AD-36) | `tests/socket/socketio.test.js` | The handshake refuses a missing, forged or query-string token, with `connect_error` data. Send, push and acknowledgement, with delivery recorded, and rejoin resync. A stranger's join is refused. An oversized packet closes the connection. Logout causes a server-side disconnect (`io server disconnect`) |
| **Safety on MongoDB** (AD-38 to AD-45) | `tests/db/mongo.test.js` (`safetyFlow` and the Block, Report, ModerationEvent and held-message store contract on MongoDB) | Hide and freeze, blocked list, report rules, the partial unique `openKey` index under simultaneous reports, the report limit under simultaneous submissions, evidence, admin transitions, held messages with their events in one transaction |
| **Pair gate (AD-46)** | Not a database property: `tests/unit/safety.races.test.js` and `pairGate.test.js` already run here. On MongoDB, the race outcomes are re-checked indirectly by `safetyFlow` and `matchingFlow`. **No test can show multi-process safety; there is none (single process only)** | — |
| **Verification on MongoDB** (AD-51, AD-52) | `tests/db/mongo.test.js` (`verificationFlow` and the `verificationStore` contract on MongoDB) | The unique `userId` under concurrent first inserts; `findOneAndUpdate` on `version` with `$inc`, including A → B → A; the `evidence` enum; `$in` reads for `isVerified`; every verification flow including the provenance cases |
| **Verification over HTTP** (AD-54) | `tests/http/verification.test.js` | 401 on all four routes; the 503 envelope with the default configuration; 409 and 200 under simulation; hostile bodies ignored; the shared 429 limit |
| **Real verification provider** | none | **Cannot be written: no provider has been chosen** (AD-53). Production refuses to start with the provider enabled |
| **Premium on MongoDB** (AD-61, AD-64) | `tests/db/mongo.test.js` (`premiumFlow`, the `entitlementStore` contract and the ledger `hasReason` / `existsWithReason` contract on MongoDB) | The unique `userId` under concurrent first inserts; `findOneAndUpdate` on `version` with `$inc`; simulated pack credits inside real MongoDB transactions; the unique `(userId, reason, referenceId)` index for purchase keys; the runtime contamination guard on a real ledger; the `subscription` and `boost` enums |
| **Premium over HTTP** (AD-63) | `tests/http/premium.test.js` | 401 on all four routes; the five-field entitlement; the 503 envelope by default; 400 before the mode check; purchase keys, 409 conflicts and `already_subscribed` under simulation; the shared 429 limit |
| **Real payment provider** | none | **Cannot be written: no provider and no payment flow exist** (AD-60). Production refuses to start with the provider enabled |
| **Admin foundation on MongoDB** (Recovery 9-A; AD-69, AD-73) | `tests/db/mongo.test.js` (the Recovery 9-A store contract on MongoDB, including the audit model test) | `AdminAuditLog` insert inside a transaction, which creates the collection on first use (MongoDB 4.4+); an aborted transaction leaving no entry; the (createdAt, _id) cursor; **every update, replace and delete refused by the model middleware**; `touchAdminLock`; `revokeAllForUser` and `reportStore.transition` committing or aborting with the transaction |
| **`adminLock` versus a concurrent demotion** (readiness D-2) | **No test can be written for the in-memory runner** (it is serializable). On a replica set: an admin transaction and a demotion of the same admin interleaved in both orders; the admin transaction must never commit after the demotion, and a `TransientTransactionError` retry must read `USER` and refuse | manual or scripted, two clients |
| **Admin router over HTTP** (Recovery 9-A) | `tests/http/admin.test.js` | 401, 403 (member), 403 suspended admin, 404 for an admin on every path without an endpoint (including audit update and delete methods), and the separate per-admin read and write limits (429) |
| **Admin moderation on MongoDB** (Recovery 9-B; AD-66, AD-76 to AD-78) | `tests/db/mongo.test.js` (`adminModerationFlow` on a one-member replica set) | Report list privacy, paging and order on the `{ status, createdAt }` index; detail with its `report.details_released` entry in the same transaction; every allowed and refused transition; missing resolution; stale `expectedStatus`; simultaneous transitions (exactly one wins on MongoDB's write conflict, not the serializable stand-in); the audit-log listing with filters and the cursor |
| **Admin moderation audit atomicity on MongoDB** (readiness D-3) | no automated test: a forced audit-insert failure and a forced commit failure on a replica set (for example a failpoint or a stopped primary) must leave the report unchanged, write no entry and return no details; `UnknownTransactionCommitResult` must not release details | manual or scripted |
| **Admin user administration on MongoDB** (Recovery 9-C; AD-68, AD-75, AD-79, AD-80) | `tests/db/mongo.test.js` (`adminUsersFlow` and the Recovery 9-C store contract on a one-member replica set) | The `adminUserStore.listIds` aggregation (`$lookup`, escaped `$regex`, the effective-record filter, order, `$skip` / `$limit`) on MongoDB 4.4+; `setAccountStatusIf` with a session; suspension, revocation and audit in one transaction; reinstatement; protected targets; simultaneous suspensions (one change on MongoDB's write conflict, not the serializable stand-in); suspension racing a refresh; the read-only queue on the `{ state, stateChangedAt }` index |
| **Suspension atomicity on MongoDB** (readiness D-3) | no automated test: a forced failure of the status update, the revocation, the audit insert and the commit on a replica set must leave the member active with usable sessions, no entry and no disconnect | manual or scripted |
| **Suspension versus a concurrent sign-in** (design request §7.2 pattern) | no automated test: a sign-in that read the account as active before the suspension committed may still create a session after it; that session must be refused on every request, refresh and socket event (status re-read). Check on a replica set | manual or scripted |
| **Admin dashboard on MongoDB** (Recovery 9-D; AD-81, AD-82) | `tests/db/mongo.test.js` (`adminDashboardFlow` and the Recovery 9-D store contract on a one-member replica set) | Each KPI count on MongoDB with `maxTimeMS`, including the distinct-account aggregation for `active_users`; the IST day and rolling windows; consistency with the member list and the queue; held messages excluded; the recent-activity sources and their limits |
| **KPI query plans and time limits on MongoDB** | no automated test: after `npm run db:indexes`, `explain()` each count (users by `registrationCompletedAt`, sessions by `lastUsedAt`, messages by `{ createdAt, moderation }`, verifications, reports, moderation events, ledger) and confirm an index scan; force a `maxTimeMS` expiry (e.g. a failpoint or a tiny limit on a large collection) and confirm 503 `dashboard_unavailable` with no partial snapshot | manual or scripted |
| **`online_now` with several processes** | none possible here: the count is per process by design (AD-46); confirm in a deployment that only one process serves sockets, or read the KPI as a per-process figure | deployment check |
| **Member settings on MongoDB** (Recovery 9B; AD-70, AD-71) | `tests/db/mongo.test.js` (`settingsFlow` and the Recovery 9B store contract on a one-member replica set) | The `usersettings` upsert on the unique `userId`, including simultaneous first writes (the duplicate-key retry); the block and own-report counts; the indicator in conversation summaries, cards, discovery's `onlineOnly` and the presence audience |
| **Member settings over HTTP** (Recovery 9B) | `tests/http/settings.test.js` | 401 on the three routes; own counters; read and change the indicator; 400 for a non-boolean or an unapproved switch; 409 for an unregistered account; no per-member or admin settings path |
| **Sessions, pause and Display Exact Age on MongoDB** (Recovery 9B; AD-88, AD-89, AD-93) | `tests/db/mongo.test.js` (`settingsFlow` and the Recovery 9B store contract) | `listActiveForUser` and `revokeForUser` filters on real documents; `setPrivacy` / `setPaused` upserts and their simultaneous first writes; **the discovery aggregation's `$lookup` on `usersettings`** (paused members left out, `displayExactAge: false` left out under an age filter, members without a record unchanged); pause in visibility and the like target; the age in cards and admin records |
| **Sessions and pause over HTTP** (Recovery 9B) | `tests/http/settings.test.js` | 401 on all six settings routes; the stored User-Agent becoming `deviceLabel`; `isCurrent` from the access token; 404 for another member's session, 400 for a malformed ID; the revoked session answering 401; pause with no JSON body; the privacy patch with `displayExactAge` and the refused switches |
| **Session revocation ends real sockets** (Recovery 9B) | none yet | `realtime.disconnectSession` after `DELETE /api/settings/sessions/:sessionId` was tested with a recording hub only; a real-Socket.IO test is an addition to approve |
| **Deletion request on MongoDB** (batch LC-3; AD-97 to AD-102) | `tests/db/mongo.test.js` (`deletionFlow` and the LC-3 store contract on a replica set) | The one transaction per change and its rollback; **the partial unique index** (one pending request per account) under concurrent requests; the conditional `deletionPendingAt` and cancel writes; the append-only history model refusing updates and deletes; the discovery aggregation's `'account.deletionPendingAt': null`; purpose-bound codes on real documents |
| **Deletion request over HTTP** (batch LC-3) | `tests/http/deletion.test.js` | 401 on all five routes; the whole request, restricted-mode (409 `deletion_pending` on ordinary routes, including `/api/auth/me`) and cancellation flow; the refused phone number; a wrong code |
| **OTP purpose isolation on MongoDB** (AD-104) | `tests/db/mongo.test.js` (the store contract and `deletionFlow` purpose tests) and `tests/db/otpPurposeMigration.test.js` | One active code per number **and purpose** on the real partial unique index; purpose-scoped invalidation and limits; concurrent code requests; **the migration** on a real collection: the old index built by hand, legacy records backfilled, the new index created, the old one dropped only on request, idempotent |
| **Migration rehearsal** (AD-104) | manual, on a disposable replica set seeded with pre-AD-104 records: `npm run db:migrate-otp-purpose`, `-- --apply`, `-- --apply --drop-old-index`, then `db.otprequests.getIndexes()` | The operator procedure (`DATABASE_DESIGN.md` §12.6) on a real server before any production run |
| **SMS templates per purpose** (AD-103) | manual, staging only: provider sandbox or test numbers, non-production keys from a secret store, one registered template per purpose | Each purpose's message wording; a missing template gives 503 and no message. The provider request format is still a placeholder (Recovery 2) and must be rewritten against the real provider first. **Never enabled in the reconstruction workspace** |
| **Deletion request with real Socket.IO** (batch LC-3) | `tests/socket/socketio.test.js` (one test) | The member's live socket dropped after the commit; a pending account's handshake refused |
| **Presence privacy with real Socket.IO** (Recovery 9B) | none yet | with the indicator off, no `presence:update` about the member reaches a real socket; tested in-process only (the presence audience); a real-socket test is an addition to approve |
| **Admin dashboard over HTTP** (Recovery 9-D) | `tests/http/admin.test.js` | 401 / 403 / 403-suspended; the snapshot shape with `supported`; untracked KPIs `"—"`; query parameters ignored; no audit entry; 503 `dashboard_unavailable` on a failing count; the read budget (429) |
| **Admin user administration over HTTP** (Recovery 9-C) | `tests/http/admin.test.js` | 401 / 403 / 403-suspended on the four endpoints, nothing changed; least-privilege list and detail, no full phone number; 400 on bad filters; suspension cuts the member off at once (401), one entry, no-op 200; reinstatement leaves the old token refused; 409 `self_action` / `admin_target`; 404; empty queue; no approve or reject route (404); read and write budgets (429 changes nothing) |
| **Socket disconnect on suspension with real Socket.IO** | `tests/socket` (none yet for 9-C) | the account room disconnect after commit is tested only with the recording hub (in-process); a real-socket test is an addition to approve separately |
| **Admin moderation over HTTP** (Recovery 9-B) | `tests/http/admin.test.js` | 401 / 403 / 403-suspended on all four endpoints with nothing written; list summaries without the reporter or reason; 400 on bad queries; detail with one audit entry; 503 `audit_unavailable` with no report contents; transition 200 with two entries, 400 / 409 refusals, the actor never from the body; audit listing allowlist and 400 filters; read and write budgets (429 writes nothing) |
| **REST wiring** | `tests/http/*.test.js` | Authentication on every route, envelopes, validation, rate limits, including the messaging and safety routes |
| **Validators under real Zod 4** | `tests/validators/*.test.js` | All schemas |

**Covered only by the in-process gateway tests** (`tests/unit/sockets.gateway.test.js`, which already run here), not yet by a real socket:

- the per-event recheck after a revocation or suspension;
- the token-expiry timer;
- presence pushes;
- the per-socket rate limit;
- the connection cap;
- block effects on sockets: room eviction (`io.in(room).socketsLeave`), refused join/send/read after a block, presence suppression and resumption, and a held message reaching only the sender's sockets (Recovery 6);
- `conversation:join` synchronized with block and unblock through the pair gate (`tests/unit/sockets.join.races.test.js`, Recovery 6.1);
- `conversation:join` delivery state: delivered only after a successful room entry; a failed join leaves no delivery mark and no room membership it created (`tests/unit/sockets.join.delivery.test.js`, Recovery 6.2);
- `conversation:join` room-entry failures, including a join that adds the socket and then fails: cleanup attempted inside the gate, the original error kept (`tests/unit/sockets.join.entry.test.js`, Recovery 6.3). Whether a given real adapter can fail part-way, and whether its `leave` then succeeds, is unknown here. With real Socket.IO, check in a live run that a failing adapter `join` or `leave` behaves as the stand-in assumes (both may be synchronous or return a promise). With real Socket.IO, `socket.join` may complete asynchronously with some adapters; the service awaits it inside the gate, but this has only been tested with the stand-in.

The real-socket tests do exercise the same gateway code. If a real-socket test for any of these is wanted, it is a test addition to approve separately.

## 7. Start-up smoke tests against real MongoDB (Docker)

These check AD-31 and AD-33 against real servers, outside the test runner. Always start **one** Node.js process (`npm start`); never cluster mode or several workers, because the block/delivery guarantee (AD-46) holds only in one process.

```bash
# A one-member replica set and a standalone server
docker run -d --name toraz-rs -p 27017:27017 mongo:7.0 --replSet rs0 --bind_ip_all
docker exec toraz-rs mongosh --quiet --eval \
  'rs.initiate({_id:"rs0",members:[{_id:0,host:"localhost:27017"}]})'
docker run -d --name toraz-standalone -p 27018:27017 mongo:7.0

# A development .env (never commit it; .env is git-ignored)
cp .env.example .env
SECRET1=$(node -e "console.log(require('crypto').randomBytes(48).toString('hex'))")
SECRET2=$(node -e "console.log(require('crypto').randomBytes(48).toString('hex'))")
sed -i "s|^MONGODB_URI=.*|MONGODB_URI=mongodb://localhost:27017/toraz_verify?replicaSet=rs0|" .env
sed -i "s|^JWT_ACCESS_SECRET=.*|JWT_ACCESS_SECRET=$SECRET1|; s|^JWT_REFRESH_SECRET=.*|JWT_REFRESH_SECRET=$SECRET2|" .env
sed -i "s|^OTP_DEV_FIXED_CODE=.*|OTP_DEV_FIXED_CODE=123456|" .env
```

| # | Command | Expected |
|---|---|---|
| 7.1 | `npm start` (Ctrl-C after it is up) | Logs `database supports transactions` with `topology: replicaSet`, the warning `chat moderation is disabled …`, then `listening`. `curl -s http://127.0.0.1:5000/api/health` answers success |
| 7.2 | `MONGODB_URI=mongodb://localhost:27018/toraz_verify npm start; echo "exit $?"` | **Refuses**: `MongoDB does not support transactions: the server is a standalone mongod …` with the fix steps; `exit 1` |
| 7.3 | `NODE_ENV=production COOKIE_SECURE=true FRONTEND_URL=https://app.example.test OTP_DEV_FIXED_CODE= npm start; echo "exit $?"` | **Refuses before connecting**: `Chat moderation is not available: NODE_ENV=production and AI_MODERATION_ENABLED is false …`; `exit 1`. This is required behaviour (AD-33), not a failure. Do not work around it |
| 7.4 | `AI_MODERATION_ENABLED=true AI_MODERATION_URL=https://moderation.example.test AI_MODERATION_API_KEY=placeholder npm start; echo "exit $?"` | **Refuses**: `… this build has no provider implementation`; `exit 1`; neither URL nor key printed |
| 7.4a | `NODE_ENV=production COOKIE_SECURE=true FRONTEND_URL=https://app.example.test VERIFICATION_DEV_SIMULATION=true npm start; echo "exit $?"` | **Refuses at configuration**, before AD-33: `VERIFICATION_DEV_SIMULATION must not be true in production` (B13); `exit 1` |
| 7.4b | The AD-50 refusal (`VERIFICATION_PROVIDER_ENABLED=true` in production) | **Not observable through `npm start` in this build:** with a valid configuration, production always stops first at AD-33 (7.3, 7.4), because no moderation provider exists. Covered by unit tests (`tests/unit/verification.units.test.js`). Once a moderation provider exists, check that it refuses with `Verification cannot start: … no provider implementation`, printing no URL or key |
| 7.4c | `NODE_ENV=production COOKIE_SECURE=true FRONTEND_URL=https://app.example.test PAYMENT_DEV_SIMULATION=true npm start; echo "exit $?"` | **Refuses at configuration**, before AD-33: `PAYMENT_DEV_SIMULATION must not be true in production` (AD-62); `exit 1` |
| 7.4d | The AD-60 refusal (`PAYMENT_PROVIDER_ENABLED=true` in production) and the AD-61 refusal (a production database containing a `simulated_pack_purchase` ledger entry) | **Not observable through `npm start` in this build**, for the same reason as 7.4b: production stops first at AD-33. Covered by unit tests (`tests/unit/premium.units.test.js`) and the server-order project rule. Once a moderation provider exists, check `Payment cannot start: … no provider implementation` (no URL or key printed) and `Super Likes cannot start: the production database contains simulated Super Like credits …`, and that nothing in the database changed |
| 7.4e | `PAYMENT_PROVIDER_ENABLED=true PAYMENT_PROVIDER_URL=https://payments.example.test PAYMENT_PROVIDER_KEY=placeholder npm start` (development) | Starts; logs the payment mode `real` with a warning that no provider is implemented; `POST /api/premium/subscribe` with a valid token answers 503 `payment_unavailable` |
| 7.5 | `npm run db:indexes` | Builds indexes on the replica set, including `conversations.matchId` (unique), the three `messages` indexes, and the Recovery 6 indexes (`blocks.{blockerId, createdAt}`, `reports` partial unique `{reporterId, openKey}`, `moderationevents.messageId` unique), the Recovery 8 indexes (`premiumentitlements.userId` unique, `superlikeledgerentries.{reason, createdAt}`), and the Recovery 9-A `adminauditlogs` indexes (five; AD-74: this step is part of the Recovery 9 deployment and its result must be checked) |

Clean up: `docker rm -f toraz-rs toraz-standalone && rm .env`.

The `example.test` host names and the placeholder key above are deliberately not real; no request is made to them, because start-up stops first.

## 8. Frontend integrity

The manifest is versioned with the backend as `docs/frontend-baseline.sha256`: 178 lines, file SHA-256 `fd553008d5902fc1839dc9fd79348d616f466656b7309936b966b6cf59bbdc2f`. It is a byte-identical copy of the original `.frontend_baseline.sha256`.

```bash
sha256sum docs/frontend-baseline.sha256        # must match the hash above
cd ../_frontend_extract/toraz_frontend-master
sha256sum -c ../../backend/docs/frontend-baseline.sha256 | grep -c ': OK$'   # must print 178
sha256sum -c ../../backend/docs/frontend-baseline.sha256 | grep -v ': OK$'   # must print nothing
find . -type f | wc -l                                                       # must print 178
cd ../../backend
```

## 9. Reporting the result

Write `docs/reports/RUNTIME_VERIFICATION_REPORT.md` with:

1. Environment:
   - OS;
   - Node and npm versions;
   - the resolved version of every package (`npm ls --depth=0`);
   - the MongoDB binary version (`grep -h "MongoDB" verification/db.log` or `mongod --version`);
   - the Docker image digest used in section 7.
2. Checkpoint:
   - ZIP hash;
   - `git rev-parse HEAD`;
   - the lockfile commit.
3. For **each** suite: tests, passed, failed, skipped, cancelled, from the TAP summary lines. Then every failure in full (test name, assertion, stack), and every skip with its reason.
4. Smoke results 7.1–7.5, as observed output.
5. Frontend: the count of OK lines and the file count.
6. A plain statement of what is now runtime-verified and what is not.

Keep the `verification/` folder as evidence (it is not committed unless asked).

**Rules while verifying:**

- A failing test is reported as failing. Neither the test nor the code is changed to make it pass in the same step: fixes are a separate, reviewed change.
- No security control is disabled to make something start (AD-31, AD-33).
- No tag is created or moved, and no checkpoint ZIP is overwritten.
- The frontend is not modified.
