# TORAZ Backend — Recovery Implementation Plan

**Batch:** Recovery 0 (inventory only)
**Date:** 2026-10-07
**Status:** Proposal awaiting review. Nothing in this plan has been built.

This plan covers Recovery 1 to Recovery 12 as defined in the recovery roadmap (R03) and the recovery master prompt (R01 §8). It adds what those documents leave open: the order in which gaps must be settled, the dependencies between batches, and what can be tested where.

Source abbreviations, status labels and gap IDs are defined in [`RECOVERY_BASELINE.md`](./RECOVERY_BASELINE.md) and [`RECOVERY_GAPS.md`](./RECOVERY_GAPS.md).

Everything described as a file, model, route or dependency below is **[RECONSTRUCT]**: a proposal for new code, not a description of the lost code.

---

## 1. Rules that apply to every batch

From R01 §1, §9, §10 and your instructions.

1. One batch at a time. Each batch starts by inspecting the files already present, builds only its own scope, and stops.
2. No frontend file is modified, created or integrated. The frontend checksum manifest is re-verified at the end of every batch and the result is reported.
3. No business rule is invented. An ASK gap is either answered, or its written fallback is explicitly approved, before the code that depends on it is written.
4. Every DEFAULT assumption used in a batch is listed by gap ID in that batch's report.
5. New code is never described as recovered. Documents never describe code that has not been inspected.
6. A test is reported as passed only with the command that was run and its actual result. A test that could not run is reported as "not executed", with the reason.
7. No secret, credential or real phone number appears in code, documents, tests or the Postman collection.
8. Third-party integrations stay disabled. No provider is called.
9. Historical prompts, if supplied, inform gaps only. They do not override the recovery package.

---

## 2. Proposed technical baseline

The surviving record fixes the stack but leaves these choices open (gap D23). They need one confirmation, because the choice of module system is expensive to change later.

| Choice | Proposal | Reason |
|---|---|---|
| Node.js | `>=22` | Version 22.22.0 is what this workspace has. MP §1 asks for a maintained LTS release. |
| Package manager | npm | MP §1 |
| Module system | CommonJS throughout | MP §1 allows either but not a mixture. CommonJS is the lower-risk fit for the test tooling. |
| Validation | Zod | The frontend's rules are already written in Zod, so they carry over rule for rule (MP §28). |
| Tokens | `jsonwebtoken`; access and refresh secrets as in MP §9; refresh token in an HttpOnly cookie, stored hashed against a `Session`, rotated on use | MP §9; R06 |
| Uploads | `multer` memory storage, `sharp` re-encode, hand-written signature check for JPEG, PNG and WEBP | R01 §5. Three formats do not justify another dependency. |
| HTTP security | `helmet`, `cors`, `express-rate-limit`, `cookie-parser`; in-house guards for NoSQL operators and parameter pollution | MP §26, including its rule against unnecessary or unmaintained packages |
| Logging | Small in-house structured logger with field redaction | MP §26: no OTP, token or message content in logs |
| Tests | Built-in `node:test`; `supertest`, `mongodb-memory-server` (as a replica set, for transactions) and `socket.io-client` as development dependencies | Fewest packages; pure tests run with nothing installed |
| Lint | ESLint, flat config | MP §43 |
| Rate-limit and presence state | In process memory | Suits a single VPS process; recorded as a limit if more than one process is ever run |

Runtime dependencies come to twelve: `express`, `mongoose`, `socket.io`, `jsonwebtoken`, `dotenv`, `zod`, `helmet`, `cors`, `express-rate-limit`, `cookie-parser`, `multer`, `sharp`. Exact versions are whatever is current at the first successful install, then pinned by the lockfile. No version is claimed until that install has run.

Transactions need a replica set. MongoDB Atlas provides one; a bare local server does not. Code will use transactions where the deployment supports them and rely on unique indexes as the backstop, as R01 §5 puts it ("transaction-safe where supported").

**Superseded 2026-10-09 (decisions AD-30, AD-31):** transactions are no longer optional. The like/Match, Super Like and registration operations always run in transactions, unique indexes stay as a second guard, and the server refuses to start unless MongoDB is a replica set or sharded cluster. A bare local server must be run as a one-member replica set (README, "MongoDB must be a replica set").

---

## 3. Proposed layout

Follows R04. Folders appear only when a batch puts a file in them.

```text
backend/
├── src/
│   ├── config/        central configuration and startup validation
│   ├── controllers/   thin; no business rules
│   ├── middlewares/   authenticate, requireAdmin, validate, rate limits, errors
│   ├── models/        Mongoose schemas
│   ├── routes/        one file per module; no queries here
│   ├── services/      business rules
│   ├── validators/    Zod schemas, shared by routes and tests
│   ├── sockets/       Socket.IO authentication and handlers
│   ├── adapters/      SMS, verification, moderation, payment
│   ├── jobs/          due-account purge; externally scheduled
│   ├── utils/         errors, envelope, canonical pair, serializers
│   ├── app.js
│   └── server.js
├── tests/
├── uploads/.gitkeep
├── docs/
├── .env.example
├── .gitignore
├── package.json
└── README.md
```

---

## 4. Plan decisions that need your approval

These are the places where this plan adds to, or departs from, the roadmap.

| ID | Proposal | Why |
|---|---|---|
| P1 | The three design documents (`FRONTEND_BACKEND_FIELD_MAPPING.md`, `API_CONTRACT.md`, `DATABASE_DESIGN.md`) grow by one module section per batch, written and checked against the frontend **before** that batch's models and routes. They are finalized in Recovery 10. | MP §2 requires these before any model. R03 does not assign them to a batch. This satisfies both. |
| P2 | `IMPLEMENTATION_DECISIONS.md` is created at the start of Recovery 1 as a copy of R02, then extended with every gap answer you give. It becomes the single decisions ledger. | Resolves C10 and gives your answers a permanent home. |
| P3 | The `Block` model and the read-only blocking policy are built in Recovery 4, not Recovery 6. The block, unblock and list routes, reports and moderation events stay in Recovery 6. | R01 requires "blocking-aware eligibility" in Recovery 4, but the roadmap introduces blocking in Recovery 6. Discovery and likes cannot be correct without the policy. |
| P4 | Every batch ends by sending you a ZIP of the whole `backend/` tree. | Gap E4. The workspace is temporary. |
| P5 | Every provisional number (rate limits, image dimensions, presence window) is a named configuration value, and each batch report carries one table of the provisional values it introduced. | Keeps unconfirmed numbers visible and changeable in one place. |

---

## 5. Dependencies between batches

Several early batches need something a later batch owns. The approach is the same each time: the early batch calls one narrow service function; the owning batch completes it; the earlier batch's tests are re-run.

| Needed in | Thing | Owned by | Until the owner lands |
|---|---|---|---|
| R2 | Account status check in `authenticate` | R9 sets suspension and deletion | R2 already rejects any status other than active |
| R2 | `requireAdmin` | R9 adds admin routes | Middleware built and tested in R2 |
| R3, R4 | Settings privacy and pause | R9 `UserSettings` | One visibility policy module reads profile privacy only |
| R4, R5 | Blocking policy | R6 | Brought forward to R4 (P3) |
| R4 | `isOnline` and the `onlineOnly` filter | R5 socket presence | Presence service backed by a last-seen timestamp; R5 adds live connections |
| R4 | `isVerified` on cards | R7 | Reads the verification record; nobody can be verified before R7 exists |
| R4 | Conversation created with the match | R5 | R4 leaves one marked hook inside the match transaction; R5 fills it |
| R5 | `isPro` on conversations | R8 entitlement | `false` |
| R5 | Moderation events for flagged messages | R6 | Adapter is disabled, so every message is `clear` and no event is needed |

---

## 6. The batches

Each batch lists its scope, the gaps to settle before coding, what it would create, and the tests it calls for. Test tiers (T0–T5) are defined in §8.

### Recovery 1 — Foundation

- **Scope (R01 §8):** package configuration, central config with startup validation, database connection, Express app and server, security middleware, error handling, response envelope, health route, base utilities, test infrastructure.
- **Settle first:** D23 (this plan's §2), E1 (registry access), E4 (where work is kept), C10 (P2).
- **Would create:** `package.json`, `.env.example` (placeholders only), `.gitignore`, `src/config`, `src/app.js`, `src/server.js`, error classes, envelope helpers, request ID, body-size limits, strict CORS from `FRONTEND_URL`, base rate limiter, `GET /api/health`, test harness, `docs/IMPLEMENTATION_DECISIONS.md`.
- **Tests:** config validation fails fast when required values are missing and never prints secrets; provider credentials required only when the provider is enabled (MP §31); envelope and error shape; health exposes nothing sensitive; oversized body rejected; CORS allows only the configured origin; malformed ObjectId handled. Tiers T0–T2, lint.
- **Exit:** the server starts, the health route answers, and tests run — or each of those is reported "not executed" with E1 as the reason.

### Recovery 2 — Authentication

- **Scope:** `User`, `OtpRequest`, `Session`; OTP service; SMS adapter; JWT; refresh rotation; `authenticate`; validators; the six auth routes.
- **Settle first:** D13 (first admin). Defaults in use: C3, C5, C6, D7, D20. C4 is already settled. E2 decides whether database tests run.
- **Would create:** the three models with unique phone index and expiry handling; OTP generated with a cryptographic source, stored hashed, single use; resend cooldown 30 s; validity 5 min; SMS adapter that is inert unless enabled; session listing and revocation primitives for later use.
- **Tests (MP §34):** request, verify, invalid code, expired code, attempt limit, resend cooldown, non-enumerating responses, no OTP in logs or production responses; refresh rotation, reuse of a rotated token, logout, revoked session, expired access token, bad signature, suspended and deleted accounts, wrong role; concurrent refresh. Tiers T0–T3, T5.

### Recovery 3 — Profile and photos

- **Scope:** `Profile`, registration, edit, profile privacy, derived completion; `Photo`, upload pipeline, secure serving, ownership, primary-photo logic.
- **Settle first:** nothing is an ASK. Defaults in use: C2, D1, D4, D5, D6. C9 is already settled. C8 (privacy precedence) should be answered by now if possible, because serializers are written here; otherwise its fallback applies and is revisited in Recovery 9.
- **Would create:** one canonical profile schema used by both registration and edit, mirroring all 49 frontend fields; server-side copy of the option lists; completion derived from required fields; photo upload with field name `photo`, signature, size and dimension checks, re-encoding, UUID filenames under a per-account directory; first photo becomes primary, deleting the primary promotes the next, setting a primary clears the others atomically; authenticated image route.
- **Tests:** full registration, duplicate registration, each required field, invalid enum, invalid date, under-18, array limits, oversized input, another user's profile untouchable, hidden fields absent from public output; wrong signature, wrong extension, oversized file, malformed image, executable, path traversal, ownership, primary-photo transitions, concurrent uploads at the photo limit. Tiers T0–T3, T5.

### Recovery 4 — Discovery and matching

- **Scope:** discovery, filters, blocking-aware eligibility, likes, Super Likes, `Match`, canonical pair, ledger, concurrency safeguards.
- **Settle first:** **B7** (compatibility rule), **B6** (unknown distance), **B2** (pass and revoke), **B3** (initial grant). These four are product rules; this batch does not start until each is answered or its fallback approved. Defaults in use: D2, D10, D19. P3 applies.
- **Would create:** `Like` with a unique index on the ordered pair; `Match` with a unique index on the canonical pair; `SuperLikeLedgerEntry` with balance derived from entries; `Block` and the read-only policy (P3); eligibility pipeline (self, account status, registered, visibility, blocks both ways, compatibility, filters); the six frontend filters only; escaped search over first name, city and profession; pagination; member-card serializer.
- **Tests:** pagination, filter validation, self-exclusion, blocked both ways, hidden and paused profiles, private fields absent, no coordinates in any response, regex metacharacters in search; self-like, duplicate like, blocked like, mutual like creates exactly one match; Super Like with and without balance. Concurrency: simultaneous duplicate likes, simultaneous mutual likes, simultaneous Super Likes against a balance of one. Tiers T0–T3, T5.

### Recovery 5 — Messaging and Socket.IO

**Decided 2026-10-09 (AD-32 to AD-36):** handshake token in the Socket.IO `auth` payload with per-event rechecks; disabled moderation adapter with a production start-up refusal; live presence (15-minute `recently_active`); read-up-to with separate delivery; the seven-event contract in `API_CONTRACT.md` §11; Conversation created in the Match transaction; single instance. Where the plan below differs, those decisions win.


- **Scope:** `Conversation`, `Message`, messaging service, the four REST routes, Socket.IO authentication, presence, room authorization, send and read flows, moderation adapter hook.
- **Settle first:** nothing is an ASK. Defaults in use: B5, B12, D3, D8, D11. The Socket.IO event contract (D11) is written into `API_CONTRACT.md` and shown to you before handlers are coded, since no surviving source constrains it.
- **Would create:** conversation created inside the match transaction; cursor-paginated message history; send path in the order MP §17 gives (authenticate, membership, allowed to communicate, block check, moderate, save, emit); idempotent mark-read; socket handshake using the access token; join only after a membership check; per-socket event rate limit; no message content in logs.
- **Tests:** non-member read and send refused, sender taken from the token not the body, blocked send refused, mark-read by a non-participant refused and repeat calls harmless, pagination order; socket without token, with expired token, joining another pair's room, delivery only to participants. Tiers T0–T4.

### Recovery 6 — Safety

- **Scope:** block routes, `Report`, `ModerationEvent`, completion of the central safety policy, report rate limiting, admin report hooks.
- **Settle first:** **B4** (report rate limit), **D9** (effect of a block on existing matches and conversations). Default in use: D18.
- **Would create:** block, unblock and list routes; report creation for user, profile and message targets with participant check for messages; report statuses from MP §21; moderation event creation for non-clear outcomes; policy applied uniformly to discovery, profile view, likes, Super Likes, matches, conversations, sending and sockets.
- **Tests:** block then every interaction path refused in both directions, unblock restores, self-block refused, report of a message by a non-participant refused, users cannot change report status, rate limit reached, moderation event written. Earlier batches' tests re-run. Tiers T0–T4.

### Recovery 7 — Verification

- **Scope:** the corrected provider-gating design.
- **Settle first:** nothing is an ASK. Defaults in use: B10, B13, C1, D21.
- **Would create:** `Verification` holding the frontend's state values and no raw identity or biometric payload; a pure gate function returning `real`, `dev_simulation` or `unavailable`; adapter interface; status, start, liveness and retry routes; 503 when unavailable; simulation refused in production regardless of flags.
- **Tests:** the gate's full truth table as pure tests (T1, runnable with nothing installed); disabled provider never verifies anyone; a client-supplied `verified: true` changes nothing; simulation blocked when `NODE_ENV=production`; provider reference never serialized to members. Tiers T0–T3.

### Recovery 8 — Premium and payment-disabled architecture

- **Scope:** entitlements, Super Like balance integration, Boost, calling entitlement, payment adapter, disabled behaviour, simulation gating.
- **Settle first:** nothing is an ASK. Defaults in use: B13, D22. D22 lists four product questions (recurring grants, subscription expiry, Boost ordering, plan benefits) that are recorded, not built.
- **Would create:** entitlement model and service; server-side catalog of pack, boost and plan IDs; entitlement read assembling tier, ledger balance, Boost status with server-side expiry, and calling flag; purchase, Boost and subscribe routes that return the disabled response and change nothing unless simulation is explicitly on outside production.
- **Tests:** disabled payment grants nothing on all three routes; unknown catalog ID refused; client-sent balance or tier ignored; simulation refused in production; Boost reads as expired after its time; `isPro` follows the viewer's entitlement; concurrent ledger writes. Tiers T0–T3, T5.

### Recovery 9 — Settings, deletion and admin

- **Scope:** `UserSettings`, sessions, account deletion, purge request, purge job, admin dashboard, users, suspend and reinstate, verification management, reports, audit logs.
- **Settle first:** **C8** (privacy precedence), **B8** (purge scope), **D16** (deletion window), **D15** (data export). Defaults in use: B11, B14, C7, D12, D14, D17. D13 must be settled to test any admin route.
- **Would create:** settings snapshot and the two patch routes; session list and per-session logout; pause; `AccountDeletionRequest` with requested time, scheduled purge time, status and purge metadata; idempotent purge job run as a command by an external scheduler; `AdminAuditLog`; the seven admin routes from MP §25 plus verification queue and report management; dashboard returning 12 KPIs, nine computed and three marked unsupported; recent activity built only from account, verification and report records.
- **Tests:** another user's session cannot be revoked; pause hides from discovery and resume restores stored privacy; deletion request hides the profile and revokes sessions; purge removes photo files and records, removes the verification record, tombstones messages in place, and a second run changes nothing; every admin route refuses a missing token, a normal user and a suspended admin; suspension signs the user out; each admin write produces an audit record; no fabricated KPI or activity row. Tiers T0–T3, T5.

### Recovery 10 — Documentation and Postman

- **Scope:** `API.md`, `ROUTE_INVENTORY.md`, `SECURITY_AUDIT.md` draft, `DEPLOYMENT.md`, final design documents, README, Postman collection.
- **Settle first:** nothing. Defaults in use: B1, B9.
- **Method (R06):** routes are extracted from the route files by script; the inventory and its count are generated from that output; the count is compared with 56 and any difference reported. The Postman collection (v2.1, collection-level bearer token, token and ID capture, multipart upload with field `photo`, no refresh-token variable) is generated from the same inventory, then cross-checked in both directions: every route has a request, every request has a route.
- **Reported:** actual route count, positive requests, negative requests, total, unmatched routes, unmatched requests.

### Recovery 11 — Validation

- **Scope:** no feature changes unless a real failure requires a fix.
- **Runs, where the environment permits:** install, syntax check, lint, pure tests, HTTP tests, database tests, Socket.IO tests, concurrency tests, application start, secret and authorization sweep from MP §38.
- **Depends on:** E1 and E2. If they are still open, this batch states plainly which parts of R01 §11 remain unvalidated, and the backend is not described as complete.

### Recovery 12 — Final package

- **Scope:** final audit, final route inventory, final Postman cross-check, final README, Git commit and tag, ZIP archive, backup.
- **Settle first:** E4, if not already settled.

---

## 7. Gap-to-batch matrix

| Batch | ASK gaps that gate it | DEFAULT gaps it uses |
|---|---|---|
| R1 | E1, E4, C10 | D23 |
| R2 | D13, E2 | C3, C5, C6, D7, D20 |
| R3 | (C8 preferred) | C2, D1, D4, D5, D6 |
| R4 | B2, B3, B6, B7 | D2, D10, D19 |
| R5 | — | B5, B12, D3, D8, D11 |
| R6 | B4, D9 | D18 |
| R7 | — | B10, B13, C1, D21 |
| R8 | — | B13, D22 |
| R9 | B8, C8, D15, D16 | B11, B14, C7, D12, D14, D17 |
| R10 | — | B1, B9 |
| R11 | E1, E2 | — |
| R12 | E4 | — |

Recovery 4 and Recovery 9 carry the most product decisions. Answering their ASK items early avoids a stop at the start of each.

---

## 8. Test tiers and what this workspace can run

| Tier | What | Needs | Runnable here today |
|---|---|---|---|
| T0 | `node --check` on every source file | Node only | Yes |
| T1 | Pure unit tests with `node:test`: canonical pair, verification gate, completion, masking, cursor encoding, catalog lookup | Node only | Yes |
| T2 | HTTP tests through the Express app | npm packages | **No** (E1) |
| T3 | Database tests: persistence, unique indexes, transactions | npm packages and a MongoDB binary | **No** (E1, E2) |
| T4 | Socket.IO tests | npm packages | **No** (E1) |
| T5 | Concurrency tests | T3 | **No** (E1, E2) |
| Lint | ESLint | npm packages | **No** (E1) |

Validator tests fall in T2 rather than T1 because Zod is an npm package.

With E1 and E2 resolved, all tiers are expected to run in this workspace; that expectation is itself unverified until the first install in Recovery 1.

If they are not resolved, the alternatives are to run T2–T5 on your own machine or the VPS and send back the output, or to accept a backend validated at T0–T1 only, which R01 §11 does not count as complete.

---

## 9. What each batch report will contain

In this order, per R01 §9:

1. Files inspected.
2. Files created and modified.
3. Commands executed, with their results.
4. Tests executed with results; tests not executed with the reason.
5. Gap IDs relied on, and any provisional values introduced (P5).
6. Frontend integrity check result.
7. Known issues and blockers.
8. STOP.

---

## 10. Out of scope for the whole recovery

- Any frontend change, including replacing mock services (R01 §10).
- Live SMS, verification, moderation or payment providers.
- Notifications, voice and video calling, data-export generation, recommendation scoring, IP geolocation, email: none exists in the approved record as a backend requirement. A gap answer (for example D15) can change that.
- Deployment to a server. Deployment is documented, not performed.
