# Security Core

## Authentication & Authorization

- **JWT Handling:** Never store sensitive data in JWT payloads. Always set httpOnly and Secure flags for session cookies.
- **Role-Based Access (RBAC):** Every API endpoint must have an explicit permission check. Default to Deny All.
- **Session Management:** Enforce token expiration and rotation. Revoke all sessions on password change or account compromise.
- **Multi-Factor Authentication:** Require MFA for privileged operations (admin actions, payment changes, account recovery).

## Input Validation & Sanitization

- **The Golden Rule:** All external input (params, body, query) is malicious until proven otherwise.
- **Schema Validation:** Use a validation library (like Zod or Joi) to enforce types before the controller logic runs.
- **SQL Injection:** Never use string interpolation for queries. Always use parameterized queries or an ORM.
- **XSS Prevention:** Sanitize and escape all user-generated content before rendering. Use Content-Security-Policy headers.
- **File Uploads:** Validate file type by content (magic bytes), not just extension. Enforce size limits. Store uploads outside the webroot.

## Data Protection

- **Sensitive Fields:** Mask PII (emails, phone numbers) in logs.
- **Secrets:** Never hardcode keys. Reference process.env only. If a secret is missing, the app must fail-fast and throw an error.
- **Encryption at Rest:** Encrypt sensitive database fields (PII, payment data) using application-level encryption, not just disk-level.
- **Encryption in Transit:** Enforce TLS everywhere. Reject plaintext HTTP connections. Pin certificates for internal service-to-service calls where feasible.
- **Data Retention:** Do not store data longer than required. Implement automated purge policies for logs, sessions, and user data per compliance requirements.

## Error Handling

- **No Leaks:** Never return stack traces or raw DB errors to the client. Use generic messages like "Internal Server Error" for 500s.
- **Logging:** Log the event for the admin, but give the result to the user.
- **Fail Secure:** When a security check throws an exception, treat it as a denial, not a pass. Errors in auth logic must default to "access denied."

## AI Agent Security

- **Prompt Injection:** Treat all user-supplied text that will be passed to an LLM as untrusted input. Never concatenate raw user input into system prompts without sanitization and clear delimiter boundaries.
- **Tool Authorization:** AI agents with tool access (file system, database, APIs) must operate under the principle of least privilege. Scope tool permissions narrowly and require explicit allowlists for destructive actions.
- **Output Validation:** Never trust LLM output as safe. Validate, sanitize, and constrain AI-generated content before executing it as code, inserting it into a database, or rendering it to users.
- **Data Exfiltration via AI:** Prevent sensitive data from being included in prompts sent to external LLM APIs. Strip PII, secrets, and internal system details before any external AI call.
- **Autonomous Action Limits:** AI agents must not perform irreversible actions (deleting data, sending communications, deploying code) without human approval or a confirmed authorization chain.
- **Audit Trail:** Log all AI agent actions including prompts sent, tools invoked, and outputs received. These logs must be tamper-evident and retained for incident investigation.

## Insider Threat Mitigation

- **Least Privilege:** Grant the minimum permissions required for each role. Review and prune access quarterly. No standing admin access -- use just-in-time elevation.
- **Separation of Duties:** No single person should be able to deploy code, approve their own PR, and access production data. Require independent review for sensitive operations.
- **Audit Logging:** Log all access to sensitive resources (database queries, file downloads, admin panel actions) with user identity, timestamp, and action detail. Logs must be immutable and stored separately from application data.
- **Offboarding:** Revoke all access (code repos, cloud accounts, secrets, VPN, SSO) within hours of departure. Rotate any shared secrets the departing person had access to.
- **Code Review for Security:** All changes touching auth, payments, permissions, or data access require review from a second engineer. No self-merging for sensitive paths.

## Supply Chain Security

- **Dependency Pinning:** Use lockfiles (package-lock.json, pubspec.lock, etc.) and commit them. Never use floating version ranges for production dependencies.
- **Vulnerability Scanning:** Run automated dependency audits (npm audit, snyk, etc.) in CI. Block merges that introduce known critical or high vulnerabilities.
- **Typosquatting:** Verify package names carefully before adding new dependencies. Prefer well-known, actively maintained packages with verified publishers.
- **Build Integrity:** CI/CD pipelines should run in isolated, reproducible environments. Do not install arbitrary packages or run unreviewed scripts during builds.
- **Third-Party Code Review:** Evaluate third-party libraries for maintenance status, known vulnerabilities, and excessive permissions before adoption.

## API Security

- **Rate Limiting:** Enforce rate limits on all public-facing endpoints, especially authentication, password reset, and search. Use progressive backoff for repeated failures.
- **CORS:** Restrict allowed origins to known domains. Never use wildcard (*) origins with credentialed requests.
- **SSRF Prevention:** Validate and restrict outbound requests from the server. Block requests to internal IP ranges (10.x, 172.16.x, 192.168.x, 169.254.x, localhost). Use an allowlist for external service URLs where possible.
- **API Key Management:** Rotate API keys on a regular schedule. Scope keys to the minimum required permissions. Immediately revoke compromised keys.
- **Webhook Security:** Verify webhook signatures before processing payloads. Use shared secrets and HMAC validation. Reject replayed requests using timestamp checks.

## Secure Defaults & Zero Trust

- **Assume Breach:** Design systems so that compromise of one component does not grant access to all others. Segment networks, databases, and services.
- **Default Deny:** Firewalls, network policies, and IAM rules should deny all traffic and access by default. Only explicitly allow what is needed.
- **Infrastructure as Code:** Define security configurations (firewall rules, IAM policies, secrets access) in version-controlled IaC. Manual console changes should be detected and flagged.
- **Dependency on External Services:** Treat all third-party services as potentially compromised. Validate responses, enforce timeouts, and have fallback behavior for outages.
