# API security & integration guideline

This document is the integration contract for the ERP API. The live, generated
endpoint inventory lives in the dashboard: **Settings → (sidebar) API Reference**
(`/api-docs`), backed by `GET /api/v1/integrations/api-docs` (auth +
`settings.manage`). Documentation that exposes the full endpoint surface is
never anonymously readable.

## 1. Versioning

- Canonical base: `{APP_URL}/api/v1`. Every future breaking change ships as
  `v2`, `v3`, … next to it; old versions are removed at their own pace.
- The unversioned `{APP_URL}/api` remains an exact legacy alias (same code
  paths) so existing integrations keep working. New integrations use `/v1`.
- The frontend points `NEXT_PUBLIC_API_URL` at `…/api/v1`.

## 2. Authentication

- `POST /api/v1/login` → `{ access_token, user }` (Sanctum personal token).
- Every protected call: `Authorization: Bearer <access_token>`.
- **Tokens are short-lived**: 60 minutes (`config/sanctum.php` → `expiration`).
  On `401` the client re-authenticates; there is no silent sliding window.
- **Least-privilege keys**: a token is issued with only the user's permission
  keys as Sanctum abilities (`'*'` only for admins). Enforcement stays with
  the `perm:` middleware; abilities exist so per-token scopes can be cut down
  later without re-issuing.
- Logout (`POST /api/v1/logout`) revokes exactly the token in use.
- 2FA (TOTP) is enforced when enabled; trusted-device cookie shortens the
  challenge to once per device.

## 3. Authorization on every call

- The entire closed surface sits under `middleware('auth:sanctum')` — there is
  no "unauthenticated by default" controller ambiguity.
- Per-route permissions: `perm:<module>.<action>` (e.g. `crm.manage`) —
  403 when the user lacks it.
- Object-level access: single-record routes are branch-scoped
  (`branch:` middleware + controller `authorizeBranchOf`) — records belonging
  to another branch answer 404/403, not 200.
- Public endpoints (`/public/*`) are enumerated, throttled and read-only or
  flow-specific; they never list internal data wholesale.

## 4. Rate limiting

- Global burst guard: 240 requests/minute per IP (`config/security.php`);
  exceeding twice briefly auto-blocks the IP for 60 minutes.
- Tighter per-endpoint caps: login 10/min, password reset 5/min,
  public read 30/min, public submit 10/min, uploads bounded.
- 429 responses carry `Retry-After`; the frontend surfaces the wait.
- Malicious-payload scanner (SQLi/XSS patterns) rejects 400 and scores the
  IP; repeated attempts block it.

## 5. Transport (HTTPS only)

- Enabled automatically in production (`FORCE_HTTPS=true` or `APP_URL`
  `https://…`); off locally so `http://localhost` installs keep working.
- Under HTTPS enforcement, plain-HTTP API calls answer **426 Upgrade
  Required**; web pages are 301-redirected to the secure URL.
- All cookies are Secure / HttpOnly / SameSite (`EnsureSecureCookies`).

## 6. Input validation & response hygiene

- Every controller validates with Laravel validators → `422
  { message, errors }`.
- Intrusion-pattern input is rejected before controllers run.
- User listings return explicit column sets (never lazy `get()` dumps) and
  sensitive model fields are `$hidden` (password, TOTP secrets, tokens).
- Third-party API keys (Google Places, SMTP, WhatsApp, SMS, Pusher) are stored
  server-side in `settings` and only ever surfaced as
  `configured`/masked-hint values — never raw.
- No secrets are passed in URLs. Signed URLs, where used, are temporary and
  single-purpose. Public records use opaque tokens in paths.

## 7. Auth failure logging

- Failed logins, 2FA mismatches and unauthenticated hits on protected routes
  are logged (`Log::warning` + the `security_logs` table with IP/endpoint
  payload). Correlate by IP over time; never render these details back to the
  client beyond the standard error messages.
- New-device logins email the account owner (`DeviceTracker`).

## 8. Errors

All `/api/*` responses are JSON, always: 400 rejected payload, 401
unauthenticated, 403 forbidden (permission/branch/license), 404 unknown or
out-of-scope record, 422 validation, 426 HTTPS required, 429 rate limited.

## 9. Integration quick start

```bash
BASE="https://your-erp.example.com/api/v1"

# 1. authenticate
TOKEN=$(curl -s -X POST "$BASE/login" -H 'Content-Type: application/json' \
  -d '{"email":"user@example.com","password":"secret"}' | jq -r .access_token)

# 2. call anything in your permission scope
curl -s "$BASE/sales-invoices" -H "Authorization: Bearer $TOKEN"

# 3. consult the live inventory (settings.manage users)
curl -s "$BASE/integrations/api-docs" -H "Authorization: Bearer $TOKEN"
```

Empty realm checklist for integrators: assume 60-minute tokens, keep HTTPS,
respect `Retry-After`, and treat 403/404 as scope boundaries rather than bugs.
