# ADR-0004: JWT access + rotating refresh tokens with family reuse-detection

**Status:** Accepted

## Context

Demeter serves a web dashboard, a mobile app, and IoT/integration clients. We
need stateless request auth that scales horizontally, secure long-lived sessions
on mobile, detection of stolen-token replay, and a separate credential type for
machine clients — without storing raw secrets at rest.

## Decision

- **Access tokens:** short-lived **JWTs** validated statelessly on each request
  (no DB hit for the common path). Declared as the `BearerAuth` scheme.
- **Refresh tokens:** long-lived, **rotated on every use**, stored only as
  hashes in `demeter_refresh_tokens`. Each token carries a `family` id; if a
  already-rotated (revoked) token is presented, the **entire family is revoked**
  — a strong signal the token was stolen and replayed.
- **Passwordless:** single-use, email-scoped magic links
  (`demeter_magic_links`), consumed atomically (marked used only if currently
  unused and unexpired).
- **Machine clients:** API keys stored as hashes with a visible prefix + scoped
  permissions (`demeter_api_keys`).
- **Sessions:** device sessions with a per-user concurrency cap that evicts the
  oldest session when exceeded (`demeter_sessions`).
- **Secrets at rest:** passwords (hashed), refresh tokens (hashed), API keys
  (hashed) — never stored in plaintext. This is the application's
  "encryption-at-rest" posture for credentials; volume-level encryption is a
  deployment control (§29.19).

## Consequences

- **+** Stateless hot path; refresh/reuse-detection limits the blast radius of a
  stolen refresh token to one detection cycle.
- **+** Distinct, least-privilege credential type for IoT/integrations.
- **+** No recoverable secrets in the database.
- **−** Refresh rotation requires careful client handling (store the newest
  token, retry once on 401); family revocation can log a user out of all devices
  if reuse is (correctly) detected.
- **−** OAuth verification must be real but deterministic in tests — addressed
  by [ADR-0005](0005-injectable-external-providers.md).
