Files
HealthLog/src/lib/whoop/oauth-state.ts
T
Marc-André Bombeck 2258cbb489 feat(whoop): WHOOP v2 API client, response classifier, credential resolution
Add the WHOOP integration data layer on copy-of-Withings rails:

- client.ts: hand-rolled fetch over safeFetch (no SDK) — OAuth authorize
  URL / code exchange / rotating-refresh, the four v2 collection fetchers
  (recovery, sleep, cycle, workout) with next_token pagination, single
  body-measurement + profile reads, and the field->Measurement mappers
  (RECOVERY_SCORE/HRV_RMSSD/RESTING_HEART_RATE/OXYGEN_SATURATION/
  SKIN_TEMPERATURE, per-stage SLEEP_DURATION ms->min, SLEEP_NEED/SLEEP_*,
  DAY_STRAIN/ENERGY_EXPENDITURE_KJ, source=WHOOP). Day strain maps to
  DAY_STRAIN and RMSSD to HRV_RMSSD so the device-native values never
  share a bucket with the COMPUTED STRAIN_SCORE / SDNN proxies.
- response-classifier.ts: HTTP-status-driven success/transient/
  reauth_required/persistent verdicts + WhoopApiError, mirroring the
  Withings reason-tag classifier.
- credentials.ts: per-user BYO-key resolution, decrypting the client
  id/secret from the User columns.
- oauth-state.ts: opaque-nonce mint helper + cookie/TTL constants.
- mapping.md: field->Measurement reference, kept in sync with the mappers.

Unit tests cover the classifier, pagination, every fetcher, the mappers
(ms->min, kJ->kcal factor, stage mapping, unscored-record handling), and
credential resolution against mocked WHOOP JSON. No routes / OAuth flow /
sync workers / migration yet.
2026-06-04 01:05:06 +02:00

35 lines
1.4 KiB
TypeScript

/**
* v1.11.0 — shared constants + mint helper for the WHOOP OAuth state nonce
* ledger. Mirrors `src/lib/withings/oauth-state.ts`.
*
* The nonce is random + opaque; a short-lived `WhoopOAuthState` row carries
* the `(nonce → userId)` mapping so the user id never leaks into request logs
* or network captures via the OAuth `state` param. The connect route, the
* callback route, and the cleanup cron all read these constants so the
* contract has one source of truth and the unit tests can pin it without
* importing either route file.
*/
import { randomBytes } from "node:crypto";
/**
* Cookie name carrying the in-flight state nonce. httpOnly + Secure +
* sameSite:lax at the connect route (mirrors the Withings cookie shape).
*/
export const WHOOP_OAUTH_STATE_COOKIE = "whoop_state" as const;
/**
* 10-minute TTL on the state row. Matches the cookie `maxAge`. Long enough to
* cover a user approving the WHOOP consent prompt; short enough that an
* abandoned handshake doesn't strand a row for hours.
*/
export const WHOOP_OAUTH_STATE_TTL_MS = 10 * 60 * 1000;
/**
* Mint a fresh state nonce. 16 random bytes → 22 base64url chars without
* padding — 128 bits of entropy, aligned with the OAuth 2.0 §10.10
* "at least 128 bits" recommendation.
*/
export function mintWhoopOAuthStateNonce(): string {
return randomBytes(16).toString("base64url");
}