Raw view: Cursor Rule: API Security

No invisible, zero-width, or bidi-control characters detected.

---
description: Security requirements for any change touching authentication, authorization, sessions, tokens, API routes, webhooks, file uploads, or code that handles untrusted input. Apply before editing or reviewing such code.
alwaysApply: false
---

# API security rules

Apply these whenever a change touches a route handler, middleware, server action, webhook, auth flow, or any function that receives data from outside the process.

## Input

- Validate every inbound payload (body, query, params, headers you rely on) with `{{VALIDATION_LIB}}` at the top of the handler, before any other logic. Reject unknown fields (`.strict()` or equivalent).
- Treat path and query parameters as untrusted strings even when typed. Parse IDs, bound numbers, and enforce max lengths on strings.
- Never build SQL, shell commands, file paths, HTML, or regexes by string concatenation with user input. Use `{{DB_CLIENT}}` parameterized queries, `path.resolve` plus a root check for files, and a template engine with auto-escaping for HTML.
- Deserialize only JSON. No `eval`, `new Function`, `vm.runInContext`, or YAML/pickle-style loaders on inbound data.
- File uploads: enforce size limits, verify content type by sniffing bytes rather than trusting the header, store under a generated name, and never serve uploads from the application origin.

## Authentication and sessions

- All authentication goes through `{{AUTH_MODULE}}`. Do not add a second way to verify a credential or token.
- Sessions and tokens are read on the server from `HttpOnly; Secure; SameSite=Lax` (or `Strict`) cookies. Never from `localStorage`, never from a query string.
- Compare secrets and tokens with a constant-time function (`crypto.timingSafeEqual`), never `===`.
- Hash passwords with the existing `argon2id` (or `bcrypt`) helper; never MD5, SHA-1, or unsalted SHA-256. Do not lower the cost parameters.
- Tokens: short-lived access tokens, server-side revocable refresh tokens, `aud` and `iss` checked on every verify, algorithm pinned (`alg: RS256` or `EdDSA`; reject `none`).
- Log out must invalidate the session server-side, not only clear the cookie.

## Authorization

- Every handler that returns or mutates a resource checks that the authenticated principal may access that specific resource (object-level check), not only that they are logged in. Look up by `(id, ownerId)` or check ownership after fetch, before responding.
- Authorization happens in the handler or a shared `authorize(user, action, resource)` helper, never only in the UI.
- Default deny: a new route is unauthenticated only if it is explicitly listed in the public-routes allowlist in `{{AUTH_MODULE}}`.
- Admin and role checks use the server-side role claim, never a client-supplied flag.

## Output and headers

- Return the minimum fields needed; map database rows to response DTOs. Never return password hashes, tokens, internal IDs of other tenants, or stack traces.
- Error responses are generic (`401 Unauthorized`, `403 Forbidden`, `404 Not Found`). Use 404 instead of 403 when revealing existence of a resource is itself a leak. Log the detail server-side with a correlation ID.
- Set `Cache-Control: no-store` on authenticated responses.
- CORS: explicit origin allowlist; never `*` with credentials.
- Rate limit login, signup, password reset, and any endpoint that sends email or SMS.

## Webhooks and outbound

- Verify webhook signatures (HMAC over the raw body with the provider's secret, constant-time compare) before parsing. Reject timestamps older than five minutes.
- Outbound requests to user-supplied URLs must resolve the host and reject private, loopback, link-local, and metadata ranges (SSRF). Follow no more than three redirects and re-check each hop.

## Secrets

- Read secrets only from the validated env module. Never hardcode, never log, never include in error messages or test fixtures.
- If a secret appears in a diff or a log, stop and flag it; do not just remove the line.

## Before finishing

List in your summary, for each handler you touched: what validates input, what checks authentication, what checks object-level authorization, and what the error responses are. State "none" explicitly where a check is intentionally absent.