# Production Security Checklist

This document outlines the security hardening implemented in the Shopify AI App Builder.

## Critical Security Updates

### 1. Session Secret (REQUIRED)
**Status**: ✅ Implemented

The application now requires `USER_SESSION_SECRET` to be set in production. The default fallback has been removed.

**Action Required**:
```bash
# Generate a secure session secret
openssl rand -hex 32
```

Add to your `.env`:
```env
USER_SESSION_SECRET=your-generated-secret-here
```

### 2. Cookie Security (Updated)
**Status**: ✅ Implemented

Cookies are now **secure by default**. Set `COOKIE_SECURE=0` only if you must run over HTTP (not recommended).

### 3. Admin Authentication Hardening (Implemented)
**Status**: ✅ Implemented

- Admin passwords are now bcrypt-hashed at startup
- Rate limiting: 5 attempts per minute per IP
- Account lockout after failed attempts
- Generic error messages (no username enumeration)

## Authentication Security

### 4. Login Rate Limiting (Implemented)
**Status**: ✅ Implemented

- User login: 10 attempts per minute per email:IP combination
- Admin login: 5 attempts per minute per IP
- Account lockout: 15 minutes after 5+ failed attempts

### 5. Password Policy Enhancement (Implemented)
**Status**: ✅ Implemented

Passwords must now have:
- Minimum 12 characters
- Uppercase letter
- Lowercase letter
- Number
- Special character

### 6. Account Lockout (Implemented)
**Status**: ✅ Implemented

Accounts are automatically locked for 15 minutes after 5 failed login attempts.

## AI Prompt Security

### 7. Prompt Injection Protection (Implemented)
**Status**: ✅ Implemented

All user input to AI prompts is sanitized with:
- Injection pattern detection and filtering
- Template escape prevention
- Length limits (10,000 characters)
- Special character removal

### 8. AI Output Sanitization (Implemented)
**Status**: ✅ Implemented

AI responses are sanitized to prevent:
- API key exposure
- Password leakage
- Sensitive credential leakage

## Input Validation

### 9. Git Action Validation (Implemented)
**Status**: ✅ Implemented

Git operations now validate actions against a whitelist:
- `pull`, `push`, `sync`, `status`, `log`, `fetch`
- `commit`, `checkout`, `branch`, `init`, `clone`
- `add`, `reset`, `restore`

### 10. Git Commit Message Sanitization (Implemented)
**Status**: ✅ Implemented

Commit messages are sanitized to prevent:
- Newline injection
- Git control character injection
- Message length limits (500 characters)

### 11. Enhanced HTML Escaping (Implemented)
**Status**: ✅ Implemented

HTML escaping now includes:
- Backtick (`) → `&#96;`
- Forward slash (/) → `&#47;`

### 12. Host Header Validation (Implemented)
**Status**: ✅ Implemented

Host headers are validated to prevent Host header injection attacks.

## Rate Limiting & DoS Protection

### 13. API Rate Limiting (Implemented)
**Status**: ✅ Implemented

All authenticated API endpoints include:
- Rate limit headers: `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset`
- Automatic 429 responses with `Retry-After` header
- 100 requests per minute per user

### 14. Enhanced 429 Responses (Implemented)
**Status**: ✅ Implemented

Rate-limited responses now include:
- `Retry-After` header
- `X-RateLimit-*` headers
- Helpful error messages

## Bot Detection

### 15. Honeypot Fields (Implemented)
**Status**: ✅ Implemented

Hidden honeypot fields added to:
- Login form (`#website` field)
- Registration form (`#website` field)

### 16. Request Timing Analysis (Implemented)
**Status**: ✅ Implemented

All responses include:
- `X-Request-Time` header for timing analysis
- Fast request detection for bot identification

### 17. User-Agent Validation (Implemented)
**Status**: ✅ Implemented

Suspicious user agents are flagged:
- Bots, crawlers, spiders
- Common automation tools (curl, wget, python, etc.)

## File Upload Security

### 18. MIME Type Whitelisting (Implemented)
**Status**: ✅ Implemented

Allowed file types:
- Images: PNG, JPEG, GIF, SVG, WebP
- Documents: PDF, plain text, Markdown, CSV, JSON, XML
- Code: CSS, JavaScript, HTML

### 19. Magic Byte Verification (Implemented)
**Status**: ✅ Implemented

Image uploads are verified by checking magic bytes/signatures.

### 20. Safe File Extension Handling (Implemented)
**Status**: ✅ Implemented

File extensions are sanitized to prevent executable uploads.

## CSRF Protection

### 21. CSRF Token Generation (Implemented)
**Status**: ✅ Implemented

- CSRF tokens generated per user session
- Tokens expire after 1 hour
- Endpoint: `GET /api/csrf`

### 22. CSRF Validation Middleware (Implemented)
**Status**: ✅ Implemented

State-changing endpoints validate CSRF tokens via:
- `X-CSRF-Token` header

## Logging & Monitoring

### 23. Security Event Logging (Implemented)
**Status**: ✅ Implemented

Security events logged:
- Failed login attempts
- Account lockouts
- Rate limit triggers
- Honeypot triggers
- CSRF validation failures

## Environment Variables Summary

| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `USER_SESSION_SECRET` | Yes (prod) | - | Session encryption key |
| `COOKIE_SECURE` | No | `1` | Enable secure cookies |
| `ADMIN_LOGIN_RATE_LIMIT` | No | `5` | Admin login attempts/min |
| `USER_LOGIN_RATE_LIMIT` | No | `10` | User login attempts/min |
| `API_RATE_LIMIT` | No | `100` | API requests/min |
| `LOGIN_LOCKOUT_MS` | No | `900000` | Lockout duration (ms) |
| `MAX_PROMPT_LENGTH` | No | `10000` | Max prompt length |

## Testing Checklist

Before deploying to production, verify:

- [ ] `USER_SESSION_SECRET` is set and secure
- [ ] `COOKIE_SECURE=1` in production
- [ ] SSL/TLS is enabled
- [ ] Admin password is strong (12+ chars)
- [ ] Rate limiting is working (test with multiple rapid requests)
- [ ] Account lockout triggers after failed attempts
- [ ] Honeypot field rejects bots
- [ ] CSRF tokens work on state-changing endpoints
- [ ] File uploads reject disallowed types
- [ ] AI prompts reject injection attempts

## Security Headers Added

All responses include:
- `X-RateLimit-Limit`
- `X-RateLimit-Remaining`
- `X-RateLimit-Reset`
- `X-Request-Time`
- `X-Content-Type-Options: nosniff`

## Migration Guide

### For Existing Deployments

1. **Generate new session secret**:
   ```bash
   openssl rand -hex 32
   ```

2. **Update `.env`** with new security variables:
   ```env
   USER_SESSION_SECRET=<generated-secret>
   COOKIE_SECURE=1
   ADMIN_LOGIN_RATE_LIMIT=5
   ```

3. **Restart the application**

4. **Users will need to re-authenticate** (session secrets changed)

### For New Deployments

Follow the standard deployment process. The security defaults are production-ready.

## Reporting Security Issues

If you discover a security vulnerability, please report it responsibly:
- Do NOT disclose publicly
- Contact the development team securely
- Allow time for remediation before disclosure
