# Security Baseline — {{projectName}}

> **Scope:** Security requirements and practices | **Loaded On-Demand**

---

## Security Principles

{{#if securityPrinciples}}
{{#each securityPrinciples}}
- {{this}}
{{/each}}
{{else}}
- **Never trust user input** — Validate, sanitize, verify
- **Defense in depth** — Multiple layers of security
- **Least privilege** — Minimal access required
- **Fail secure** — Error states don't expose data
- **Security by design** — Built in, not bolted on
{{/if}}

---

## Authentication

### Password Requirements
{{#if passwordPolicy}}
{{passwordPolicy}}
{{else}}
- Minimum 12 characters
- Require: uppercase, lowercase, number, special char
- Check against common password lists
- No personal information (name, email)
{{/if}}

### Session Management
{{#if sessionManagement}}
{{sessionManagement}}
{{else}}
- JWT tokens with short expiration (15 minutes)
- Refresh tokens with longer expiration (7 days)
- httpOnly, secure, SameSite cookies
- Invalidate on logout
- Rotate tokens periodically
{{/if}}

### Multi-Factor Authentication
{{#if mfa}}
{{mfa}}
{{else}}
- Require MFA for admin accounts
- Support TOTP (Google Authenticator)
- Backup codes for recovery
{{/if}}

---

## Authorization

### Access Control
{{#if accessControl}}
{{accessControl}}
{{else}}
- Role-Based Access Control (RBAC)
- Check permissions at every layer (API, service, data)
- Default deny: explicit allow only
- Audit all authorization decisions
{{/if}}

### Role Hierarchy
{{#if roles}}
{{#each roles}}
- **{{this.name}}:** {{this.description}}
{{/each}}
{{else}}
- **guest** — Unauthenticated access
- **user** — Authenticated, basic access
- **admin** — Full system access
- **superadmin** — Emergency access, audit only
{{/if}}

---

## Input Validation

### Validation Rules
{{#if inputValidation}}
{{inputValidation}}
{{else}}
- Validate all inputs at API boundary
- Use schema validation (Zod/Joi/Yup)
- Whitelist allowed values (don't blacklist)
- Sanitize HTML (DOMPurify)
- Truncate excessively long inputs
{{/if}}

### SQL Injection Prevention
{{#if sqlPrevention}}
{{sqlPrevention}}
{{else}}
- Use parameterized queries only
- Never concatenate SQL strings
- Use ORM-provided query builders
- Enable query logging in development
{{/if}}

### XSS Prevention
{{#if xssPrevention}}
{{xssPrevention}}
{{else}}
- Escape all user-generated content
- Use CSP headers (Content-Security-Policy)
- Set `httpOnly` cookies
- Validate and sanitize file uploads
{{/if}}

---

## Data Protection

### Encryption at Rest
{{#if encryptionAtRest}}
{{encryptionAtRest}}
{{else}}
- Database: {{encryption.db}}
- File storage: {{encryption.files}}
- Secrets: {{encryption.secrets}}
- Backup: {{encryption.backup}}
{{/if}}

### Encryption in Transit
{{#if encryptionInTransit}}
{{encryptionInTransit}}
{{else}}
- HTTPS only (TLS 1.3+)
- HSTS headers enabled
- Secure cipher suites only
{{/if}}

### PII Handling
{{#if piiHandling}}
{{piiHandling}}
{{else}}
- Identify all PII in code (comment: # PII)
- Encrypt sensitive fields in database
- Log PII only when necessary
- Mask PII in logs (email: u***@example.com)
{{/if}}

---

## API Security

### Rate Limiting
{{#if rateLimiting}}
{{rateLimiting}}
{{else}}
- Per-IP limits for anonymous: 100/min
- Per-user limits: 1000/min
- Per-endpoint limits for expensive operations
- Track with Redis, expire after window
{{/if}}

### API Key Management
{{#if apiKeyManagement}}
{{apiKeyManagement}}
{{else}}
- Rotate API keys quarterly
- Include key owner in key metadata
- Revoke immediately on leak
- Monitor usage patterns
{{/if}}

### CORS Configuration
{{#if cors}}
{{cors}}
{{else}}
- Whitelist allowed origins only
- Don't use `*` in production
- Expose only necessary headers
- Max age: 1 hour
{{/if}}

---

## Dependencies

### Supply Chain Security
{{#if supplyChain}}
{{supplyChain}}
{{else}}
- Lock dependency versions
- Run `npm audit` in CI
- Use Dependabot or Renovate
- Review PR from dependabots
- Pin action versions in GitHub Actions
{{/if}}

### Vulnerability Scanning
{{#if vulnScanning}}
{{vulnScanning}}
{{else}}
- SAST: {{sastTool}} in CI
- SCA: {{scaTool}} for dependencies
- DAST: {{dastTool}} on staging
- Container scan: {{containerScanTool}}
{{/if}}

---

## Secrets Management

### Secrets Policy
{{#if secretsPolicy}}
{{secretsPolicy}}
{{else}}
- Never commit secrets to git
- Use environment variables or vault
- Rotate secrets quarterly
- Different secrets per environment
{{/if}}

### Secrets Storage
{{#if secretsStorage}}
{{secretsStorage}}
{{else}}
- Development: `.env` (gitignored)
- Production: {{secretsManager}}
- CI/CD: {{ciSecrets}}
{{/if}}

---

## Logging & Monitoring

### Security Logging
{{#if securityLogging}}
{{securityLogging}}
{{else}}
Log all security events:
- Failed authentication
- Authorization failures
- Rate limit violations
- Admin actions
- Data exports
- Configuration changes

Include:
- Timestamp
- User ID (if available)
- IP address
- Action
- Result
{{/if}}

### Alerting
{{#if alerting}}
{{alerting}}
{{else}}
Alert on:
- > 10 failed auth attempts / 5 min / IP
- > 100 failed auth attempts / 5 min globally
- New admin account created
- Database backup accessed
- Unusual data export volume
{{/if}}

---

## Compliance

{{#if compliance}}
{{#each compliance}}
### {{this.framework}}
{{this.requirements}}
{{/each}}
{{/if}}

---

## Security Checklist

Before deploying:
{{#if deploymentChecklist}}
{{#each deploymentChecklist}}
- [ ] {{this}}
{{/each}}
{{else}}
- [ ] All dependencies audited
- [ ] No secrets in code
- [ ] HTTPS enabled
- [ ] CORS configured
- [ ] Rate limiting enabled
- [ ] Input validation on all endpoints
- [ ] Authentication required for sensitive operations
- [ ] Authorization checks on all endpoints
- [ ] Security headers configured
- [ ] Logging enabled
- [ ] Error handling doesn't leak info
- [ ] File upload validation
- [ ] Database encryption enabled
{{/if}}

---

## Incident Response

{{#if incidentResponse}}
{{incidentResponse}}
{{else}}
### Breach Response
1. **Detect** — Monitoring/alerts fire
2. **Contain** — Isolate affected systems
3. **Investigate** — Determine scope and impact
4. **Remediate** — Patch vulnerabilities
5. **Recover** — Restore from backups if needed
6. **Post-mortem** — Document and improve
{{/if}}

---

> **Token Budget:** ~1000 tokens max
> **Loaded On-Demand** — Only when working on security
