# JWT Lifecycle Policy

**Document Version**: 1.0  
**Last Updated**: 2025-10-03  
**Owners**: Platform Security Guild & Identity Engineering

The Lilith authentication service issues JSON Web Tokens (JWT) for every
authenticated session. This policy defines the authoritative lifecycle
requirements for issuing, validating, refreshing, rotating, and revoking tokens
across the platform.

## Token Issuance

- Signing algorithm: `RS512` with hardware-backed keys (Vault/HSM).
- Issuer: `https://auth.lilith.local`; Audience: `https://api.lilith.local`
  (multi-service audiences enumerated below).
- Access token Time-To-Live (TTL): **900 seconds (15 minutes)**.
- Refresh token TTL: **30 days** with adaptive shortening on risk signals.
- Mandatory claims: `iss`, `aud`, `sub`, `exp`, `iat`, `jti`, `sessionId`,
  `roles`, `permissions`, device telemetry (`ipAddress`, `userAgent`, optional
  `deviceId`).
- Every issuance records a security event and audit trail entry referencing the
  calling client and session fingerprint.

### Algorithm Rotation

- Signing keys rotate every 24 hours with 12-hour overlap.
- JWKS endpoint publishes both current and previous keys; consumers must support
  kid-based rollover.
- Emergency rotation path documented in
  `docs/runbooks/security/jwt-key-rotation.md`.

## Access Token Validation

- Verifiers must check signature, issuer, audience, expiration, and `jti` replay
  cache.
- `JWTSecurityManager.validateAccessToken` enforces replay detection, device/IP
  drift detection, and rotation hints (`requiresRotation` flag) when <5 minutes
  to expiry or anomalies observed.
- Suspicious validations fire `SUSPICIOUS_ACTIVITY` events and can blacklist
  offending IPs.

### Access Token TTL and Grace

- Access token TTL: **900 seconds**.
- Grace window: tokens within 300 seconds of expiry trigger proactive refresh on
  next API call.
- Blacklist TTL: revoked access tokens remain in-memory blacklist for **900
  seconds**.

## Refresh Token Rotation

- Rotation Strategy: **One-time use refresh tokens**.
- Each refresh response invalidates the presented token and issues a new one
  with a fresh `sessionId`.
- Device binding: SHA-256 fingerprint of `ipAddress:userAgent:deviceId`. Drift
  triggers revocation and security event.
- Max usage before forced re-authentication: 5 refreshes per rolling day.
- Stored metadata: `issuedAt`, `expiresAt`, `usageCount`, `lastUsed`,
  `deviceFingerprint`, `isRevoked`.

### Refresh Token TTL

- Standard TTL: **30 days** (2,592,000 seconds).
- High-risk refresh tokens (flagged devices/IPs) are reduced to 7 days
  automatically.
- Cleanup job purges expired/ revoked tokens every 60 seconds.

## Revocation & Blacklist

- Revocation Reasons: `user-initiated`, `admin-force`, `suspicious-activity`,
  `access-policy-update`.
- Revocation cascades: when a refresh token is revoked, associated access tokens
  are blacklisted immediately.
- `JWTSecurityManager.revokeRefreshToken` and `revokeAllUserTokens` guarantee
  audit entries and security events.
- Blacklisted tokens persist for **15 minutes** to cover clock skew.
- Revocation ledger retained for **365 days** for compliance.

### Session Termination

- Logout endpoint revokes active refresh tokens, clears session store, and
  records `TOKEN_REVOKED` event.
- Compromised-session flow (`/v1/auth/session/revoke`) revokes all user tokens
  and triggers downstream notifications.

## Signing Keys & Algorithms

- All signing keys stored encrypted at rest and never leave HSM/Vault.
- Hash: SHA-256 for device fingerprints; random source: `crypto.randomBytes`.
- Allowed algorithms: `RS512` (primary) and `ES512` (fallback). `HS256`/`HS512`
  reserved for local development only.
- Key rotation automation updates JWKS and invalidates caches within 60 seconds.

## Monitoring & Alerting

- Security events emitted for every issuance, validation, rotation, and
  revocation.
- High-severity events trigger PagerDuty and auto-blacklist suspicious IPs.
- Metrics: `auth_tokens_active`, `auth_refresh_tokens_active`,
  `auth_revocations_total`, `auth_security_events_total`.

## Policy Artefacts

- Canonical machine-readable schema:
  [`docs/schemas/jwt-lifecycle.schema.json`](../schemas/jwt-lifecycle.schema.json).
- Compliance enforced via Playwright spec
  `tests/security.jwt-lifecycle.spec.ts`.
- Implementations must align with `services/auth/src/jwt-security.ts`;
  deviations require security review.
