# Fix User ID Header Spoofing Plan

## Problem
`src/routes/battlegroundV2.js` uses client-supplied `x-user-id` header instead of the verified `req.user.id` from JWT authentication.

**Impact:** Any authenticated user can impersonate any other user by setting the `x-user-id` header.

**Exploit Example:**
```bash
# Authenticated user "attacker" impersonates user "victim"
curl -X POST /api/battleground/duels/challenge \
  -H "Authorization: Bearer <attacker-jwt>" \
  -H "x-user-id: <victim-user-id>" \
  -d '{"targetId": "...", "duelType": "calls"}'
# Creates duel as victim, not attacker
```

## Severity
**HIGH** - Allows user impersonation within authenticated context.

## Root Cause
`battlegroundV2.js` was written using a different auth pattern (header-based) that bypasses the JWT verification done by `requireAuth` middleware.

```javascript
// INSECURE (current)
const userId = req.headers['x-user-id'];

// SECURE (required)
const userId = req.user.id;
```

## Affected Code
**File:** `src/routes/battlegroundV2.js`
**Lines:** 31, 65, 84, 103, 122, 159, 208, 259, 278, 316

All 10 occurrences need to be fixed.

## Solution
Replace all `req.headers['x-user-id']` with `req.user.id`.

Since `requireAuth` is already applied to this route in `index.js`, `req.user` is always populated with verified user data. No fallback needed.

### Before:
```javascript
router.post('/duels/challenge', async (req, res) => {
  try {
    const userId = req.headers['x-user-id'];
    if (!userId) {
      return res.status(401).json({ success: false, error: 'User ID required' });
    }
    // ...
```

### After:
```javascript
router.post('/duels/challenge', async (req, res) => {
  try {
    const userId = req.user.id;  // Already verified by requireAuth middleware
    // No null check needed - requireAuth guarantees req.user exists
    // ...
```

## Implementation Steps
- [ ] Phase 1: Replace all 10 occurrences of `req.headers['x-user-id']` with `req.user.id`
- [ ] Phase 2: Remove the unnecessary `if (!userId)` checks (auth middleware handles this)
- [ ] Phase 3: Test duel creation, acceptance, decline, and history endpoints
- [ ] Phase 4: Verify spoofing no longer works

## Files to Modify
| File | Changes |
|------|---------|
| `src/routes/battlegroundV2.js` | Replace 10 header reads with `req.user.id` |

## Database Migration
None required.

## API Endpoints Affected
All `/api/battleground/*` V2 endpoints:
- `POST /duels/challenge`
- `POST /duels/:id/accept`
- `POST /duels/:id/decline`
- `GET /duels/active`
- `GET /duels/history`
- `GET /challenges`
- `POST /challenges`
- `POST /challenges/:id/progress`
- `GET /leaderboard/:period`
- `GET /stats`

## Success Criteria
1. All endpoints use `req.user.id` instead of header
2. Spoofing test fails:
   ```bash
   # This should NOT work after fix - should use JWT user, not header
   curl -X POST /api/battleground/duels/challenge \
     -H "Authorization: Bearer <user-a-jwt>" \
     -H "x-user-id: <user-b-id>" \
     -d '{"targetId": "...", "duelType": "calls"}'
   # Duel should be created by user-a, not user-b
   ```
3. Normal duel flow still works

## Notes for Builder

### Quick Fix Pattern
```javascript
// Find:
const userId = req.headers['x-user-id'];
if (!userId) {
  return res.status(401).json({ success: false, error: 'User ID required' });
}

// Replace with:
const userId = req.user.id;
```

The `requireAuth` middleware guarantees `req.user` exists with:
- `id` - Verified UUID from Supabase JWT
- `email` - User's email
- `displayName` - Derived from email

### Lines to Fix
1. Line 31: `router.post('/duels/challenge'...`
2. Line 65: `router.post('/duels/:id/accept'...`
3. Line 84: `router.post('/duels/:id/decline'...`
4. Line 103: `router.get('/duels/active'...`
5. Line 122: `router.get('/duels/history'...`
6. Line 159: `router.get('/challenges'...`
7. Line 208: `router.post('/challenges'...`
8. Line 259: `router.post('/challenges/:id/progress'...`
9. Line 278: `router.get('/leaderboard/:period'...`
10. Line 316: `router.get('/stats'...`

## Notes for QA
1. Test with two different user accounts
2. Verify User A cannot create duels as User B
3. Verify duel history shows correct user's duels
4. Check Battleground UI still works normally

## Why This Matters
- **Data integrity** - Actions attributed to wrong users
- **XP manipulation** - Could steal XP from other users via duels
- **Trust violation** - Users could see others' challenge history
- **Audit trail corruption** - Logs show wrong user IDs

## Related Issues
The `'default-user'` fallback pattern in other files is a code smell but NOT a security issue because:
1. Those routes use `req.user?.id` (verified from JWT)
2. The fallback only triggers if somehow `req.user` isn't set
3. With `requireAuth`, `req.user` is always set or request is rejected

However, the `'default-user'` pattern should be removed in a future cleanup - it pollutes data if auth ever fails silently.
