# Task 2.7 — Documentation & Code Alignment Report

**Date:** 2026-05-24  
**Auditor:** Kimi Code CLI (subagent)  
**Scope:** `nick-doc/` technical documentation vs. `backend/src/` runtime code  

---

## 1. Files Reviewed

### Data Models (`nick-doc/02 - Data Models/`)
- `Data Model Overview.md`
- `Payment.md`
- `PurchaseRequest.md`
- `User.md`
- `Dispute.md`
- `Chat.md` (spot-checked)

### API Reference (`nick-doc/03 - API Reference/`)
- `API Overview.md`
- `Payment API.md`
- `Dispute API.md`
- `Marketplace API.md` (spot-checked)
- `Authentication API.md` (spot-checked)

### Architecture (`nick-doc/01 - Architecture/`)
- `Backend Architecture.md`
- `Security Architecture.md`
- `System Architecture.md`

### Flows (`nick-doc/04 - Flows/`)
- `Escrow Flow.md`
- `Dispute Flow.md`
- `Payment Flow - SHKeeper.md`
- `Payment Flow - DePay & Web3.md`

### Backend Code
- `backend/src/models/*.ts` (all)
- `backend/src/app.ts` (bootstrap, middleware, route mounting)
- `backend/src/services/payment/decentralizedPaymentRoutes.ts`
- `backend/src/services/payment/shkeeper/shkeeperRoutes.ts`
- `backend/src/services/payment/paymentControllerRoutes.ts`
- `backend/src/services/marketplace/controllerRoutes.ts`
- `backend/src/services/marketplace/routes.ts`
- `backend/src/services/auth/passkeyService.ts`

---

## 2. Discrepancies Found

### 2.1 Missing modules (documented but not implemented)
| Module | Doc claims | Reality in code |
|---|---|---|
| **Dispute** | `backend/src/services/dispute/`, `backend/src/models/Dispute.ts`, `/api/disputes` | **None exist**. No directory, no model, no routes, no controller. |
| **Blog** | `services/blog/blogRoutes.ts` | **Does not exist**. |
| **Points** | `services/points/pointsRoutes.ts`, `Points API` | **Does not exist**. |
| **Admin** | `services/admin/adminRoutes.ts`, `Admin API` | **Does not exist**. |
| **Review** | `Review.md` data model | `backend/src/models/Review.ts` **does not exist**. |
| **PointTransaction** | `PointTransaction.md` data model | `backend/src/models/PointTransaction.ts` **does not exist**. |
| **LevelConfig** | `LevelConfig.md` data model | `backend/src/models/LevelConfig.ts` **does not exist**. |
| **ShopSettings** | `ShopSettings.md` data model | `backend/src/models/ShopSettings.ts` **does not exist**. |
| **BlogPost** | `BlogPost.md` data model | `backend/src/models/BlogPost.ts` **does not exist**. |

### 2.2 Data-model enum mismatches
| Model | Field | Doc value | Code value | Severity |
|---|---|---|---|---|
| **Payment** | `provider` | `shkeeper` / `other` | `shkeeper` / `request.network` / `request-network` / `other` | Medium |
| **Payment** | `escrowState` | 6 values | 8 values (`+ cancelled`, `+ partial`) | Medium |
| **Payment** | `metadata` | SHKeeper fields only | Also has `requestNetworkRequestId`, `requestNetworkPaymentReference`, `requestNetworkSecurePaymentUrl`, `requestNetworkData` | Low |
| **Payment API** | Status list | Missing `confirmed` and `processing` in the "Status model" prose | Code has full 7-value enum incl. `confirmed`, `processing` | Medium |

### 2.3 User-model fields documented but missing from schema
The `User.md` table describes `referralCode`, `referredBy`, `points.{total,available,used,level}`, and `referralStats.{totalReferrals,activeReferrals,totalEarned}`. These fields **do not exist** in `backend/src/models/User.ts` (line count stops at 201; no referral or points subdocuments). The associated unique/sparse indexes are also absent.

### 2.4 Authentication requirements (post-remediation drift)
Several endpoints in `Payment API.md` were documented as **unauthenticated** but the code now enforces `authenticateToken` (and in some cases `authorizeRoles`):

| Endpoint | Doc auth | Code auth | Fix applied |
|---|---|---|---|
| `POST /api/payment/decentralized/save` | No | Bearer JWT + ownership | ✅ Updated doc |
| `PUT /api/payment/decentralized/update` | No | Bearer JWT + ownership | ✅ Updated doc |
| `GET /api/payment/decentralized/history/:userId` | No | Bearer JWT + `requireOwnershipOrAdmin` | ✅ Updated doc |
| `POST /api/payment/decentralized/verify/:paymentId` | No | Bearer JWT + ownership | ✅ Updated doc |
| `POST /api/payment/decentralized/verify-all-pending` | No (cron) | Bearer JWT + `admin` | ✅ Updated doc |

Additionally, the legacy `routes.ts` marketplace router applies `authenticateToken` globally, but `app.ts` mounts the **controller router** (`controllerRoutes.ts`) which exposes public read endpoints. The docs correctly describe the controller-router behaviour.

### 2.5 Rate limiting
All architecture and API docs stated rate limiting was **disabled** (`app.ts:227`). After remediation it is **enabled** with four tiers:
- Global: 100 req / 15 min
- Auth: 10 req / 15 min
- Payment: 30 req / 15 min
- AI: 20 req / 15 min

### 2.6 Socket.IO authentication
Docs described Socket.IO as an open real-time channel. In reality `app.ts` now enforces:
- JWT verification on every connection (`io.use(jwt.verify(...))`).
- Strict room-membership checks (`join-user-room`, `join-request-room`, `join-chat-room`, etc.) that reject cross-user or unauthorized joins.

### 2.7 Passkey hardening
`passkeyService.ts` now implements:
- Single-use challenge consumption (`consumeChallenge` deletes immediately after read).
- 5-minute challenge TTL with periodic cleanup.
- Explicit expiry error messages.
- This was not documented in the Security Architecture or Authentication API docs.

### 2.8 Endpoint path errors in flow docs
- `Payment Flow - DePay & Web3.md` referenced `POST /api/payment/decentralized/create` which **does not exist**; the actual endpoint is `POST /api/payment/decentralized/save`.
- Same doc referenced `POST /api/payment/decentralized/verify` which **does not exist**; the actual endpoint is `POST /api/payment/decentralized/verify/:paymentId`.

### 2.9 Backend Architecture route table omissions
The original table:
- Listed `/api/payment/payout` as a top-level mount; it is actually nested under `/api/payment/shkeeper/payout*`.
- Listed `/api/file`; the actual mount is `/api/files`.
- Omitted `/api/trezor`, `/api/email`, `/api/payment/decentralized`, and `/api/payment/request-network`.

---

## 3. Fixes Applied

### Data Models
1. **`Payment.md`**
   - Expanded `provider` enum to match code (`request.network`, `request-network`).
   - Expanded `escrowState` enum to include `cancelled`, `partial`.
   - Added Request Network metadata fields to the schema table.
   - Updated "Status model" prose to include `confirmed` and `processing`.

2. **`User.md`**
   - Added `[!warning]` blocks on `referralCode`, `referredBy`, `points`, and `referralStats` fields marking them as **not yet implemented**.
   - Corrected index line references and added a note about missing indexes.

3. **`Dispute.md`**
   - Added a prominent `[!warning]` that `backend/src/models/Dispute.ts` does not exist and the schema reflects intended design only.

4. **`Data Model Overview.md`**
   - Added a scope warning listing documented models that lack Mongoose schema files.
   - Noted the two undocumented models that exist in code (`FundsLedgerEntry.ts`, `TrezorAccount.ts`).

### API Reference
5. **`API Overview.md`**
   - Rewrote "Rate limiting" section to describe the four active tiers.
   - Rewrote "Real-time channel" section to document Socket.IO JWT enforcement and room-membership checks.
   - Marked `Dispute API`, `Blog API`, `Admin API`, and `Points API` as "planned, not yet implemented".

6. **`Payment API.md`**
   - Updated auth requirements for all decentralized endpoints to reflect `authenticateToken` enforcement.
   - Updated status/escrowState enums.

7. **`Dispute API.md`**
   - Added a top-level `[!warning]` that the module is not implemented.
   - Rewrote introductory sentences to use conditional language ("would be", "planned").

### Architecture
8. **`Backend Architecture.md`**
   - Updated middleware chain note: rate limiting is now enabled.
   - Updated route table to reflect actual mounts, mark missing services, and add omitted routes (`/api/files`, `/api/trezor`, `/api/email`, `/api/payment/decentralized`, `/api/payment/request-network`).
   - Changed solid dependency arrows from `dispute` and `points` to dotted lines in the Mermaid diagram to indicate planned-but-not-implemented status.

9. **`Security Architecture.md`**
   - Updated "Rate limiting & abuse" section to reflect enabled tiers.
   - Checked off "Enable rate-limit middleware" and "Enforce Socket.IO JWT authentication" in the hardening checklist.

### Flows
10. **`Escrow Flow.md`**
    - Updated `escrowState` enum prose to include `cancelled` and `partial`.
    - Added `Cancelled` state to the Mermaid state diagram.

11. **`Dispute Flow.md`**
    - Added a `[!warning]` block next to backend file references stating none exist.

12. **`Payment Flow - DePay & Web3.md`**
    - Changed `POST /api/payment/decentralized/create` → `POST /api/payment/decentralized/save` with auth note.
    - Changed `POST /api/payment/decentralized/verify` → `POST /api/payment/decentralized/verify/:paymentId` with auth note.

### Changelog
13. **`nick-doc/00 - Overview/Introduction.md`**
    - Inserted a 2026-05-24 audit-remediation callout at the top summarising auth enforcement, rate limiting, passkeys, Web3 verification, Socket.IO auth, and dispute status.

---

## 4. Remaining Gaps

The following items were identified but **not fully resolved** (out of scope for a pure doc-alignment task or require code implementation):

1. **Missing models still documented** — `Dispute`, `BlogPost`, `Review`, `PointTransaction`, `LevelConfig`, and `ShopSettings` remain in the docs with warnings. A future subtask should either implement the models or move the docs to a "Planned" archive folder.
2. **Missing services still documented** — `Dispute API`, `Blog API`, `Admin API`, `Points API` still have markdown pages. Same recommendation as above.
3. **User referral/points fields** — The `User.ts` schema is missing the documented referral and points subdocuments. Either the schema needs to be extended or the fields should be removed from `User.md` once a final product decision is made.
4. **Frontend docs not audited** — This subtask focused on backend alignment. `nick-doc/05 - Design System/` and `frontend/src/` docs were not reviewed.
5. **OpenAPI / generated spec** — The `openapi.json` referenced in `Backend Architecture.md` was not regenerated or audited.
6. **`FundsLedgerEntry` & `TrezorAccount`** — These models exist in `backend/src/models/` but have no documentation notes yet. They should be added to `Data Model Overview.md` in a future pass.

---

## 5. Acceptance Criteria Verification

| Criterion | Status | Evidence |
|---|---|---|
| Data model enums in docs match backend models | ✅ | `Payment.md` provider & escrowState enums aligned; `User.md` enum values verified against `User.ts`. |
| API reference auth requirements reflect post-remediation state | ✅ | Decentralized payment endpoints now correctly list `Bearer JWT`; rate limiting section updated. |
| Flow docs do not describe unauthenticated financial endpoints | ✅ | DePay flow updated to show auth on `save` and `verify/:paymentId`. |
| Report file created | ✅ | This file. |
| No incorrect references to non-existent dispute modules remain | ✅ | All dispute references now carry `[!warning]` blocks and conditional language. |

---

*End of report.*
