# Backend Requirements & API Breakdown — KingsPage

This document specifies everything the KingsPage backend must provide: the full API
surface, data model, realtime collaboration infrastructure, and the cross-cutting
handling (auth, security, validation, errors, rate limiting) each route needs.

It is grounded in the current codebase:

- Data shapes: `src/types/index.ts`, `StoredDocument` in `src/lib/document-store.ts`
- Existing API routes: `src/app/api/**` (`auth/login|logout|session`, `documents`,
  `documents/view`, `users`)
- Realtime collab: `src/lib/y-webrtc-provider.ts`, `src/lib/use-yjs-session.ts`,
  `src/lib/y-firestore-provider.ts`, `src/lib/turn-config.ts`, `src/lib/firebase-client.ts`
- Front-end consumers: `document-editor.tsx`, `workbook.tsx`, `presentation-studio.tsx`,
  `document-preview.tsx`, `collaborate-modal.tsx`, `share-modal.tsx`,
  `workspace-content.tsx`, `documents-content.tsx`, `creation-modal.tsx`, `guest-login-modal.tsx`

---

## 1. Current State vs. Required Backend

| Aspect | Current State | Required Backend |
|---|---|---|
| Persistence | Firestore via `firebase-admin` with in-memory/JSON-file fallback (`document-store.ts`, `user-store.ts`) | Firestore as source of truth; keep fallback only for local dev |
| Auth | Demo guest login; HMAC-signed httpOnly cookie (`session.ts`), 3 seed guest users (`data/users.ts`) | Real identity (KingsChat SSO / email+password / OAuth), roles, refresh tokens, email verification, password reset |
| API surface | 6 routes: `auth/login`, `auth/logout`, `auth/session`, `documents`, `documents/view`, `users` | Full REST surface in §4 |
| Realtime collaboration | **Yjs + y-webrtc (WebRTC P2P)**. Signaling server lives in a separate repository. TURN via Metered (`turn-config.ts`). Firestore-based provider kept as an alternative (`y-firestore-provider.ts`) | Production signaling service + auth'd room access + TURN; OR the Firestore provider with locked-down rules |
| View analytics | `POST /api/documents/view` increments `viewCount`/`viewerCount` transactionally, trails recent views | Keep and extend (§4.4) |
| Collaboration UI | Invite / list / change-role / remove all done **client-side** (`collaborate-modal.tsx`, `document-list.tsx`, `document-card.tsx`) — never persisted via an API | Backend endpoints for sharing, roles, revocation, username lookup |
| Exports / conversion | All client-side (jsPDF, html-to-docx, ExcelJS, mammoth, markdown-docx) | Move heavy work server-side (§4.8) |
| Security | `firestore.rules` is `allow read, write: if true` (wide open) | Locked rules + server-side enforcement |
| Ownership enforcement | None on writes; `POST /api/documents` accepts any id | RBAC on every mutating route (§5) |

---

## 2. Architecture

```
Browser
  ├─ Next.js client  ──►  Next.js API routes (BFF)  ──►  Firestore (Admin SDK)
  │                          │ validation (zod)
  │                          │ auth guard / RBAC
  │                          │ rate limiting
  │                          └─ Jobs: exports, conversions, thumbnails
  ├─ y-webrtc client ───────►  Signaling server (WebRTC room broker) ─ other peers (P2P)
  │                            └─ STUN/TURN (Metered) when P2P is blocked
  └─ Firestore client (fallback) ─► Firestore (yjs/{room}/updates subcollection)
```

- **API**: keep Next.js route handlers in `src/app/api/**` (Node runtime).
- **Realtime**: primary path is WebRTC P2P via Yjs with a **separate signaling service**;
  the `YFirestoreProvider` (`src/lib/y-firestore-provider.ts`) is the persistence-backed
  alternative and can be toggled in `src/lib/use-yjs-session.ts`.
- **Validation**: `zod` schemas per route (already a dependency).
- **Errors**: uniform `{ error: { code, message, details? } }` envelope with correct HTTP status.
- **Auth**: extend `src/middleware.ts` to guard `/api/**` and attach `req.user`.

---

## 3. Data Model

### `users`
```
{ id, name, username, email, avatarUrl, role: guest|member|owner|admin,
  isGuest, account, bio, createdAt, lastActiveAt, settings, subscription? }
```
Indexes: `email` (unique), `username` (unique).

### `documents` (mirror `StoredDocument`, `src/lib/document-store.ts:13`)
```
{ id, name, type: document|spreadsheet|presentation|board, shortCode, isDraft,
  content (string | Cell[][]), sheets[{id,name,cells,merged}], thumbnail,
  lastSaved, createdAt, description, summary?,
  collaborators[{id,name,avatarUrl,role,color}], sharedTo[],
  annotations[], versions[], docLocked, docPasswordHash, ownerId,
  category, previewImageUrl,
  viewCount, viewerCount, lastViewedAt, viewHistory[{id,viewerId,viewerName,source,viewedAt}] }
```
- `docPassword` must be **hashed** server-side — never stored plaintext (current
  `StoredDocument` carries it raw).
- Indexes: `ownerId`, `sharedTo` (array-contains), `type`, `shortCode` (unique), `lastSaved` (desc).

### `templates`
```
{ id, type, title, content, thumbnail, category, sortOrder }
```

### `workspaces`
```
{ id, name, slug, ownerId, memberIds[], documentIds[], settings }
```

### `shares`
```
{ code, documentId, createdBy, createdAt, expiresAt?, access: view|edit, revokedAt? }
```

### `yjs/{roomId}` (Firestore-collab fallback, see `y-firestore-provider.ts`)
```
{ roomId }                        ← meta doc: { seeded, t } via claimSeed()
{ roomId }/updates/{clientId}     ← { data (base64 Yjs state), awareness (base64), t }
```

### `activities` / `audit_logs`
```
{ id, actorId, action, documentId?, meta, createdAt }
```

---

## 4. Route Inventory

Legend: 🔒 = auth required · ⚡ = rate-limited.

### 4.1 Authentication & Session

| Method | Route | Purpose | Request | Response | Notes |
|---|---|---|---|---|---|
| POST | `/api/auth/login` | Start session (guest, email/password, SSO callback) | `{ credential \| user \| token }` | `{ user, expiresAt }` + httpOnly cookie | **Exists** — extend beyond guest accounts |
| POST | `/api/auth/logout` | Destroy session | — | `{ ok }` | **Exists** |
| GET | `/api/auth/session` | Validate cookie → current user | — | `{ user } \| { user: null }` | **Exists** |
| POST | `/api/auth/refresh` | Rotate expired token | — | `{ user, expiresAt }` | New |
| POST | `/api/auth/register` | Create account | `{ name, email, password }` | `{ user }` | New |
| POST | `/api/auth/password/forgot` | Send reset email | `{ email }` | `{ ok }` | New |
| POST | `/api/auth/password/reset` | Reset with token | `{ token, password }` | `{ ok }` | New |
| POST | `/api/auth/verify-email` | Confirm email | `{ token }` | `{ ok }` | New |
| POST | `/api/auth/oauth/[provider]/callback` | OAuth/SSO | code | `{ user }` | New |

**Handling**: set/clear the `kingspage_session` httpOnly cookie; never expose tokens to JS;
require `SESSION_SECRET` (see `src/lib/session.ts`); keep the "login as guest" path
working in dev/test only.

### 4.2 Users & Accounts

| Method | Route | Purpose | Request | Response | Notes |
|---|---|---|---|---|---|
| GET | `/api/users` | List users (login picker) | `?limit=&cursor=` | `User[]` | **Exists** — add pagination |
| GET | `/api/users/[id]` | Get profile | — | `User` | **Exists** via `?id=` |
| GET | `/api/users/search` | Username/email autocomplete | `?q=&exclude=` | `User[]` | **New** — powers `collaborate-modal.tsx` recipient input |
| PATCH | `/api/users/[id]` | Update profile | `{ name?, bio?, avatarUrl?, username? }` | `User` | **New** 🔒 |
| POST | `/api/users/[id]/avatar` | Upload avatar | multipart | `{ avatarUrl }` | **New** 🔒 ⚡ |
| GET | `/api/users/[id]/documents` | Docs owned by a user | `?type=&q=` | `Document[]` | **New** |
| DELETE | `/api/users/[id]` | Deactivate account | — | `{ ok }` | **New** 🔒 |

The collaborate modal resolves usernames via `getAccountByUsername` (`src/data/accounts.ts:82`).
That registry must move server-side so arbitrary platform users can be found and invited.

### 4.3 Documents — Core CRUD

| Method | Route | Purpose | Request | Response | Notes |
|---|---|---|---|---|---|
| GET | `/api/documents` | List documents | `?user=&type=&q=&category=&page=&limit=&sort=` | `{ items, total, page, limit }` | **Exists** — upgrade to server-side pagination/filters |
| POST | `/api/documents` | Upsert full document (editor autosave) | `StoredDocument` payload | `{ id, shortCode, persisted }` | **Exists** — primary save route for `document-editor`, `workbook`, `presentation-studio` |
| GET | `/api/documents?id=` | Fetch single document | — | `StoredDocument` | **Exists** |
| GET | `/api/documents?code=` | Resolve short code | — | `StoredDocument` | **Exists** — powers `/s/[code]` |
| PATCH | `/api/documents/[id]` | Partial update (rename, category, lock, summary) | `{ name?, category?, docLocked?, docPassword?, summary? }` | `Document` | **New** 🔒 — wire rename/delete flows |
| DELETE | `/api/documents/[id]` | Hard delete | — | `{ ok }` | **New** 🔒 — owner only (`document-detail-panel` currently no-ops) |
| POST | `/api/documents/[id]/duplicate` | Clone doc + content | — | `Document` | **New** 🔒 |
| POST | `/api/documents/[id]/thumbnail` | Upload generated thumbnail | multipart | `{ thumbnail }` | **New** 🔒 ⚡ |
| GET | `/api/documents/[id]/versions` | Version history | `?page=` | `DocumentVersion[]` | **New** 🔒 |
| POST | `/api/documents/[id]/versions` | Commit a version snapshot | `{ summary }` | `DocumentVersion` | **New** 🔒 |
| POST | `/api/documents/[id]/versions/[version]/restore` | Restore snapshot | — | `Document` | **New** 🔒 |
| GET | `/api/documents/recent` | Recently touched docs | `?limit=` | `Document[]` | **New** — dashboard "Quick Access" |

**Handling:**
- **Authorization** on every route: read if `isAccessibleTo` (`document-store.ts:194`);
  write if `owner`/`editor` role (`canEdit` in `collab.ts:20`). 403 on violation.
- **Save semantics**: idempotent upsert by id; preserve `createdAt`/`shortCode` on re-save;
  return `persisted` for the editor's Offline/Draft/Saved indicator.
- **Password**: store a hash; expose only `docLocked: true` to clients.

### 4.4 Document Views & Analytics

| Method | Route | Purpose | Request | Response | Notes |
|---|---|---|---|---|---|
| POST | `/api/documents/view` | Record a document view | `{ id, viewerId?, viewerName?, source? }` | `{ ok, persisted, viewCount, viewerCount, lastViewedAt }` | **Exists** (`src/app/api/documents/view/route.ts`) — transactionally increments `viewCount`, derives unique `viewerCount`, caps `viewHistory` at 100 |
| GET | `/api/documents/[id]/views` | Read view stats | — | `{ viewCount, viewerCount, lastViewedAt, viewHistory }` | **New** 🔒 |
| GET | `/api/dashboard/stats` | Dashboard metric cards | `?range=` | `{ recentCount, sharedCount, activityCount, deltas }` | **New** 🔒 — replace hardcoded numbers in `dashboard/page.tsx` |

Client-side dedupe already exists in `src/lib/api.ts:124` (60s window per viewer) to avoid
React StrictMode/double-counts; the server should keep the transactional increment.

### 4.5 Sharing, Roles & Collaboration

| Method | Route | Purpose | Request | Response | Notes |
|---|---|---|---|---|---|
| POST | `/api/documents/[id]/share` | Share with users | `{ userIds[], role }` | `{ collaborators, sharedTo }` | **New** 🔒 — backs `collaborate-modal` "Invite" tab |
| PATCH | `/api/documents/[id]/collaborators/[userId]` | Change role | `{ role }` | `Collaborator[]` | **New** 🔒 — owner only; enforce single owner (promotion demotes current owner, mirroring `collaborate-modal.tsx:156`) |
| DELETE | `/api/documents/[id]/collaborators/[userId]` | Revoke access | — | `{ ok }` | **New** 🔒 — owner only; used by "Remove" in `document-list.tsx` / `document-card.tsx` |
| POST | `/api/documents/[id]/annotations` | Create annotation/comment | `Annotation` | `Annotation` | **New** 🔒 — currently only client-side (`document-preview.tsx:249`) |
| PATCH | `/api/documents/[id]/annotations/[annotationId]` | Update status / add comment | `{ status? } \| { comment }` | `Annotation` | **New** 🔒 |
| POST | `/api/documents/[id]/presence` | Presence heartbeat | `{ status }` | `{ ok }` | **New** 🔒 — for the WebRTC/Firestore presence readout |
| GET | `/api/documents/[id]/presence` | Current editors | — | `{ users[], lastSeen }` | **New** 🔒 |

**Realtime model (primary)**: Yjs rooms over WebRTC. The backend's job is not to relay
doc bytes (that is peer-to-peer) but to:
- authenticate who may join room `documentId`,
- hand out the room's signaling endpoint + TURN credentials (see §6),
- keep Firestore as the durable record (editors still `POST /api/documents` for persistence).

### 4.6 Public Share & Short Links

| Method | Route | Purpose | Request | Response | Notes |
|---|---|---|---|---|---|
| GET | `/api/shares/[code]` | Public read payload | — | `{ document, shortCode, shareUrl }` | **New** — `/s/[code]` currently hits `/api/documents?code=` |
| POST | `/api/documents/[id]/share-link` | Create/rotate short code | `{ access }` | `{ code, url }` | **New** 🔒 — uses `generateShortCode()` (`share.ts:6`) |
| DELETE | `/api/shares/[code]` | Revoke link | — | `{ ok }` | **New** 🔒 |
| GET | `/api/shares/[id]/access` | Check access level | — | `{ role }` | **New** — for `/share/[id]` and `/slides/[id]` |

**Handling**: anonymous responses must **strip** `collaborators`, `sharedTo`, `versions`,
`docPassword`, `viewHistory`; enforce `expiresAt`/`revokedAt`; respect `docLocked`
(return a flag, never content).

### 4.7 Templates

| Method | Route | Purpose | Request | Response | Notes |
|---|---|---|---|---|---|
| GET | `/api/templates` | List templates | `?type=` | `Template[]` | **New** — replace hardcoded `src/data/templates.ts` |
| POST | `/api/templates` | Create template (admin) | `Template` | `Template` | **New** 🔒 |
| PATCH | `/api/templates/[id]` | Update (admin) | partial | `Template` | **New** 🔒 |
| DELETE | `/api/templates/[id]` | Delete (admin) | — | `{ ok }` | **New** 🔒 |

### 4.8 Import / Export / Conversion

| Method | Route | Purpose | Request | Response | Notes |
|---|---|---|---|---|---|
| POST | `/api/documents/[id]/export` | Export to file | `{ format: docx\|pdf\|html\|md\|txt\|xlsx\|csv\|pptx }` | binary + content-disposition | **New** — server-side `html-to-docx`, `jsPDF`, `exceljs`, `mammoth`, `markdown-docx`, `pdf-lib` |
| POST | `/api/convert` | Format→format | multipart `{ from, to, file }` | binary | **New** — replaces the simulated `/convert` UI |
| POST | `/api/import/[type]` | Import file into editor payload | `{ type: spreadsheet\|presentation\|pdf, file }` | `{ content, sheets?, slides? }` | **New** ⚡ — PPTX/CSV/XLSX/PDF import feeding the creation modal `sessionStorage` handoff |
| POST | `/api/upload` | Generic file upload (images, media) | multipart | `{ url }` | **New** 🔒 ⚡ — Firebase Storage, persist URL only |

### 4.9 Board / PDF / Slides (document-type persistence)

| Method | Route | Purpose | Request | Response | Notes |
|---|---|---|---|---|---|
| GET/POST | `/api/boards/[id]` | Save/load board strokes | `BoardState` | `BoardState` | **New** 🔒 |
| POST | `/api/boards/[id]/export` | Export as PNG/PDF | `{ format }` | binary | **New** 🔒 |
| POST | `/api/pdf/[id]/upload` | Upload base PDF | multipart | `{ fileUrl }` | **New** 🔒 ⚡ |
| POST | `/api/pdf/[id]/annotations` | Save annotation overlay | `{ pages, annotations }` | `{ ok }` | **New** 🔒 |
| GET | `/api/pdf/[id]/download` | Merged annotated PDF | — | binary | **New** 🔒 |
| GET | `/api/slides/[id]` | Public deck payload | — | `{ slides, settings }` | **New** — for `/slides/[id]` public view |

### 4.10 Global Search

| Method | Route | Purpose | Request | Response | Notes |
|---|---|---|---|---|---|
| GET | `/api/search` | Cross-collection search | `?q=&scope=&page=` | `{ documents, users, templates }` | **New** 🔒 — powers header global search (`AppHeader`, `?q=`) |

### 4.11 Workspaces

| Method | Route | Purpose | Request | Response | Notes |
|---|---|---|---|---|---|
| GET | `/api/workspaces` | List workspaces | — | `Workspace[]` | **New** 🔒 — workspace switcher in `sidebar.tsx` |
| POST | `/api/workspaces` | Create | `{ name }` | `Workspace` | **New** 🔒 |
| PATCH | `/api/workspaces/[id]` | Rename/settings | partial | `Workspace` | **New** 🔒 |

### 4.12 Admin / Billing / Notifications (later phase)

- `GET/PATCH/DELETE /api/admin/users`, `GET /api/admin/stats`
- `GET/POST /api/billing/subscription`, `POST /api/billing/checkout`, `POST /api/billing/webhook`
- `GET /api/notifications`, `POST /api/notifications/[id]/read`

---

## 5. Cross-Cutting Handling (applies to every route)

1. **Auth guard** — middleware verifies `kingspage_session` for all `/api/**` except a
   public allowlist (`auth/login|register|password/*`, `shares`, `s/[code]`, `slides/[id]`,
   `share/[id]`, `convert`). Attach `req.user`.
2. **Authorization (RBAC)** — `owner > editor > viewer`. Reuse `isAccessibleTo`
   (`document-store.ts:194`) and `canEdit` (`collab.ts:20`). 403 on violation.
3. **Input validation** — zod schemas; 400 with field-level errors.
4. **Error envelope** — `{ error: { code, message, details? } }`; map to
   400/401/403/404/409/413/429.
5. **Rate limiting** — per-IP/per-user on login, export/convert, upload, share, search, views.
6. **Pagination** — consistent `?page=&limit=` (or cursor) → `{ items, total, page, limit }`; cap `limit`.
7. **Offline resilience** — keep the memory/JSON fallback (`document-store.ts`) for local
   dev, and the `pendingSync` flush pattern for offline writes; never in production.
8. **File limits** — cap upload sizes, validate MIME, store in Firebase Storage.
9. **Security** — hash `docPassword` and user passwords; sanitize HTML content on write to
   prevent stored XSS in Quill/reveal rendering; escape user content in public views;
   rotate `SESSION_SECRET`; lock down `firestore.rules`.
10. **Audit** — log every mutate (create/delete/share/restore/export/role-change) to `activities`.
11. **CORS/CSP** — same-origin + `NEXT_PUBLIC_PLATFORM_URL`.

### Firestore rules (currently open — must be locked)

`firestore.rules` currently allows everything. Required shape:

```
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    // Authenticated users may read/write only documents they own, collaborate on,
    // or were shared with.
    match /documents/{id} {
      allow read: if isMember(resource.data);
      allow write: if isOwner(resource.data) || isEditor(resource.data);
    }
    // yjs collab room: only authenticated members of the owning document.
    match /yjs/{roomId}/{document=**} {
      allow read, write: if isRoomMember(roomId);
    }
  }
}
```

---

## 6. Realtime Collaboration Infrastructure

### 6.1 Primary: WebRTC (Yjs + y-webrtc)

- **Client**: `YWebRTCProvider` (`src/lib/y-webrtc-provider.ts`) — room name is the
  `documentId`; peers merge edits via Yjs CRDTs; awareness carries presence + cursors.
- **Signaling server**: a **separate repository** (moved out in commit `13ed889`). It
  brokers WebRTC room connections. Local dev runs it with `yarn dev:collab` /
  `yarn signaling` (port 4444). Production must deploy it (Fly/Render/AWS) and point
  `NEXT_PUBLIC_Y_WEBRTC_SIGNALING` at it.
- **TURN**: Metered.ca. Static session credentials via
  `NEXT_PUBLIC_TURN_URL/USERNAME/CREDENTIAL` (`turn-config.ts:13`), optionally upgraded
  at runtime to time-limited credentials via `NEXT_PUBLIC_METERED_API_KEY`
  (`fetchMeteredIceServers`, `turn-config.ts:33`).
- **Backend responsibilities**: authorize room joins, validate the room id belongs to a
  document the user may access, and expose the signaling/TURN config.

### 6.2 Fallback: Firestore-backed Yjs

`YFirestoreProvider` (`src/lib/y-firestore-provider.ts`) stores per-client Yjs state +
awareness under `yjs/{roomId}/updates/{clientId}` (base64, debounced 500 ms) and seeds the
room once via a transaction on `yjs/{roomId}` (`claimSeed`). It is currently commented out
in `use-yjs-session.ts:7` — flipping back requires the locked-down rules in §5 and the
Firestore web config in `src/lib/firebase-client.ts`.

---

## 7. Suggested Build Order

| Phase | Scope |
|---|---|
| **1. Foundations** | zod validation, error envelope, auth guard on `/api/**`, RBAC helpers, rate limiting, locked `firestore.rules`, DB seeds (users, templates) |
| **2. Auth upgrade** | register/login/refresh, password reset, OAuth/SSO; migrate guest sessions |
| **3. Documents core** | `PATCH`/`DELETE`/duplicate/versions/restore on `/api/documents/[id]`; paginated list; wire rename/delete UI |
| **4. Collaboration** | share/invite/roles/revoke, annotations, presence; production signaling + TURN; auth'd room joins |
| **5. Export/Import/Convert** | server-side export matrix, `/api/convert`, PPTX/CSV import, uploads to Storage |
| **6. Platform** | search, dashboard stats, workspaces, templates CRUD, board/PDF persistence |
| **7. Production** | admin, billing, notifications, audit, hardening (XSS, rate limits, backups) |

---

## 8. Environment Variables Required

See `.env.example`. Backend-relevant additions on top of what exists:

- `SESSION_SECRET` — cookie signing (already present).
- `FIREBASE_PROJECT_ID`, `FIREBASE_CLIENT_EMAIL`, `FIREBASE_PRIVATE_KEY` — Admin SDK (prod).
- `NEXT_PUBLIC_FIREBASE_API_KEY/AUTH_DOMAIN/PROJECT_ID`, `NEXT_PUBLIC_FIREBASE_EMULATOR` — client Firestore (fallback collab).
- `NEXT_PUBLIC_Y_WEBRTC_SIGNALING` — comma-separated signaling WS/WSS URLs.
- `NEXT_PUBLIC_TURN_URL`, `NEXT_PUBLIC_TURN_USERNAME`, `NEXT_PUBLIC_TURN_CREDENTIAL` — static TURN.
- `NEXT_PUBLIC_METERED_API_KEY` — optional runtime TURN credentials.
- `GEMINI_API_KEY` — reserved for the AI/Genkit flows (module removed from the app, keep reserved).
- Mail provider keys (password reset, invites, notifications) — to be added.
