# Security

Author: Nguyen Thi Nguyet Que Created on: May 2, 2026

## Rules

- **Never return tokens in the response body** for `web` platform — use HttpOnly cookies only.
- **Never leak stack traces** — always use `res.error(error)`, never
  `res.json({ error: error.stack })`.
- **Hash tokens before logging** — never log raw access/refresh tokens.
- **Encrypt tokens at rest** — tokens stored in the database must be encrypted.
- **Rate-limit all auth endpoints** — use `createDistributedRateLimit` (Redis-backed).
- **Validate the `X-Platform` header** on every authenticated endpoint (mobile/zalo flows depend on
  it).
- **Parameterized queries only** — no raw string concatenation in SQL.
- **CORS `credentials: true`** with an explicit origin whitelist in production.

---

## Platform authentication

| Platform | Header                     | Token delivery   | Notes                                      |
| -------- | -------------------------- | ---------------- | ------------------------------------------ |
| `web`    | `X-Platform: web`          | HttpOnly cookies | Tokens **never** returned in response body |
| `mobile` | `X-Platform: mobile`       | Response body    | Requires `device_id` in the request        |
| `zalo`   | `X-Platform: zalo_miniapp` | Response body    | Requires Zalo auth flow                    |

Detection priority: query param → header → User-Agent → default (`web`)

---

## Rate limiting example

```typescript
import { createDistributedRateLimit } from '#middlewares/rateLimiter';

// Apply to auth routes
middleware: [
  createDistributedRateLimit({ windowMs: 15 * 60 * 1000, max: 10 }),
  validateLogin,
],
```

---

## Dependency security

```bash
pnpm security:audit   # Audit dependencies for known vulnerabilities
pnpm security:fix     # Auto-fix vulnerabilities
pnpm security:check   # Audit + lint in one step
```
