> ## Documentation Index
> Fetch the complete documentation index at: https://docs.pcm.game/llms.txt
> Use this file to discover all available pages before exploring further.

# Sprint 13: Core Hardening & Security

> Implementation of Lobby Transition Guards, Control Plane Presence Sweeper, Multi-Stage Build Hardening, and Ingress Policy Enforcement.

# Sprint 13: Core Hardening & Security

Sprint 13 focuses on **hardening system security, locking down API ingress, and eliminating operational vulnerabilities** across both the backend and frontend components. We transition the platform from rapid feature prototyping to production-grade resilience and strict zero-trust execution.

***

## 🛡 Context & Required Rules for AI Agents

When working on this sprint, agents must adhere to the following strict technical directives:

1. **Atomic Transactions**:
   * All state transitions and database changes must execute inside isolated transactions (`db.runTransaction` or Prisma `$transaction`).
   * Never write to Firestore first and Prisma second if the Prisma update could throw an error; keep database mutations failure-safe and trace-able.
2. **Zero-Trust Network Ingress**:
   * Web application traffic is strictly limited to authorized hosts.
   * Decouple all public-facing API and backend resource identifier strings into secure, platform-native environment variables.
3. **Minimized Execution Attack Surface**:
   * Docker production artifacts must be built with minimal footprints and step down from root privileges immediately before process initiation.

***

## 🗺 Sprint 13 Roadmap

### \[x] Phase 1: LOBBY Transition Guards (Task 13.2.1)

* **Objective**: Prevent actions outside correct phases and block duplicate actions or race conditions.
* **Tasks**:
  * Implemented the **XOR Action Rule** inside `backend/src/routes/debate.js` for `POST /play-card` and `POST /vote` to ensure players can play cards OR vote once per phase—never both, and never twice.
  * Enforced strict state checking: requests are rejected with `400 Bad Request` if the table state is not actively in `DEBATE_PHASE`.

### \[x] Phase 2: Presence Sweep & Disconnection Cleanup (Task 13.2.2)

* **Objective**: Identify disconnected players during debates, transition abandoned lobbies, and safely penalize disconnected users.
* **Tasks**:
  * Upgraded the control plane sweeper (`POST /debate/sweep`) inside `backend/index.js` to inspect active lobbies and cross-reference human players' states in the `PlayerPresence` Firestore collection.
  * Engineered the **Anti-Penalty-Evasion Order of Operations**: First resolve the user profile, second perform the Prisma database transaction to safely deduct 50 ELO and 15 native quadrant currency, and third execute the Firestore write batch to transition the lobby state and purge the air-gapped `secure_data/solution` document.

### \[x] Phase 3: Multi-Stage Production Build Hardening (Task 13.4.1)

* **Objective**: Optimize backend containers for security, size, and privilege isolation.
* **Tasks**:
  * Built a multi-stage Dockerfile leveraging `node:22-alpine` split into `builder` and `runner` phases.
  * Frozen dependencies using `npm ci --only=production --ignore-scripts` to eliminate vulnerability vectors from transitive post-install hooks.
  * Structured manual copying of both `node_modules/.prisma` and `node_modules/@prisma` to circumvent blocked post-install schema engine generation hooks.
  * Stepped down execution from root to user `node` and purged all local scripts, tests, and configuration utilities.

### \[x] Phase 4: Ingress Policy Enforcement & Client Decoupling (Task 13.1.2)

* **Objective**: Deprecate open CORS access and extract hardcoded third-party secrets from client builds.
* **Tasks**:
  * Replaced wildcard CORS with a custom origin-checking validation middleware restricting access to `http://localhost:3000` and `process.env.PRODUCTION_FRONTEND_URL`.
  * Configured a safe bypass for originless calls (such as internal cron schedules, serverless webhooks, and headless tasks) while maintaining strict cross-origin restrictions on browser-initiated queries.
  * Extracted hardcoded configuration keys (`authDomain`, `projectId`, and `storageBucket`) in `frontend/lib/firebase.ts` to `NEXT_PUBLIC_*` environment variables.

***

## 📡 E2E Verification & Security Audits

1. **Syntax Integrity & Compilation**:
   ```bash theme={null}
   node --check backend/index.js
   ```
   * **Result**: Passed cleanly with zero syntax warnings or run-time script load errors.

2. **Clean Container Isolation**:
   * The production Docker image size was trimmed down significantly by removing test suites, local scripts, and build-time compiler engines.
