From 88139fb981c97c6c0629492ad20351a0fd0cad4f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc-Andr=C3=A9=20Bombeck?= Date: Sun, 14 Jun 2026 20:10:35 +0200 Subject: [PATCH] feat(integrations): add Oura Cloud v2 OAuth sync MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Connect an Oura account over the Cloud v2 API: an authorization-code OAuth flow (shared app from OURA_CLIENT_ID / OURA_CLIENT_SECRET) on the same signed state machinery as Polar. Unlike Polar, Oura issues refresh tokens; the sync refreshes reactively on a 401, rotating and re-encrypting both tokens, and a 403 stays a hard reauth rather than a refresh. An hourly poll-cohort job maps daily readiness to RECOVERY_SCORE, sleep to per-stage durations plus efficiency / HRV / resting heart rate / respiratory rate, and daily activity to steps and active energy — all tagged source OURA, idempotent on (userId, type, source, externalId). Readiness flows through the canonical recovery ladder above the computed proxy. Settings gains a connect / disconnect card. Tokens are never logged or returned; every egress goes through safeFetch. --- .env.production.example | 11 + docker-compose.yml | 15 +- messages/de.json | 20 + messages/en.json | 20 + messages/es.json | 20 + messages/fr.json | 20 + messages/it.json | 20 + messages/pl.json | 20 + scripts/env-manifest.json | 16 + src/app/api/oura/callback/route.ts | 96 ++++ src/app/api/oura/connect/route.ts | 60 +++ src/app/api/oura/disconnect/route.ts | 39 ++ .../api/oura/status/__tests__/route.test.ts | 75 +++ src/app/api/oura/status/route.ts | 42 ++ .../__tests__/integrations-section.test.tsx | 8 +- .../settings/integrations-section.tsx | 14 +- .../settings/integrations/oura-card.tsx | 18 + src/lib/jobs/reminder-worker.ts | 31 +- src/lib/jobs/reminder/oura-sync.ts | 62 +++ src/lib/oura/__tests__/client.test.ts | 177 +++++++ src/lib/oura/__tests__/sync.test.ts | 172 +++++++ src/lib/oura/client.ts | 432 ++++++++++++++++++ src/lib/oura/credentials.ts | 50 ++ src/lib/oura/response-classifier.ts | 113 +++++ src/lib/oura/sync.ts | 235 ++++++++++ src/lib/query-keys/integrations.ts | 6 +- 26 files changed, 1764 insertions(+), 28 deletions(-) create mode 100644 src/app/api/oura/callback/route.ts create mode 100644 src/app/api/oura/connect/route.ts create mode 100644 src/app/api/oura/disconnect/route.ts create mode 100644 src/app/api/oura/status/__tests__/route.test.ts create mode 100644 src/app/api/oura/status/route.ts create mode 100644 src/components/settings/integrations/oura-card.tsx create mode 100644 src/lib/jobs/reminder/oura-sync.ts create mode 100644 src/lib/oura/__tests__/client.test.ts create mode 100644 src/lib/oura/__tests__/sync.test.ts create mode 100644 src/lib/oura/client.ts create mode 100644 src/lib/oura/credentials.ts create mode 100644 src/lib/oura/response-classifier.ts create mode 100644 src/lib/oura/sync.ts diff --git a/.env.production.example b/.env.production.example index e7ae7cd05..d53e7acd1 100644 --- a/.env.production.example +++ b/.env.production.example @@ -62,6 +62,17 @@ API_TOKEN_HMAC_KEY="" # POLAR_CLIENT_SECRET="" # POLAR_REDIRECT_URI="" +# ----------------------------------------------------------------------------- +# Oura Cloud v2 -- optional integration (full OAuth, shared app from env) +# ----------------------------------------------------------------------------- +# Register an app at https://cloud.ouraring.com/oauth/applications and set its +# redirect URI to `${NEXT_PUBLIC_APP_URL}/api/oura/callback`. Both vars together +# enable the Oura connect button. Oura uses refresh tokens; the sync refreshes +# reactively on a 401. OURA_REDIRECT_URI overrides the derived callback. +# OURA_CLIENT_ID="" +# OURA_CLIENT_SECRET="" +# OURA_REDIRECT_URI="" + # ----------------------------------------------------------------------------- # APNs -- iOS push (optional, all-or-none) diff --git a/docker-compose.yml b/docker-compose.yml index 19d20d0e5..57e84f8b5 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -77,15 +77,18 @@ services: # container (the `environment:` block is a whitelist). WHOOP_WEBHOOK_SECRET: "${WHOOP_WEBHOOK_SECRET:-}" WHOOP_REDIRECT_URI: "${WHOOP_REDIRECT_URI:-}" - # v1.17.0 (F4) — Polar AccessLink OAuth (shared app from env). The pair - # together enables the connect button; an unset pair leaves the - # integration disabled. The optional POLAR_REDIRECT_URI overrides the - # derived `${NEXT_PUBLIC_APP_URL}/api/polar/callback`. Listed here so - # operator values in .env reach the container (the `environment:` block is - # a whitelist). + # v1.17.0 (F4) — Polar AccessLink + Oura Cloud OAuth (shared app from + # env). Both pairs together enable each connect button; an unset pair + # leaves that integration disabled. The optional *_REDIRECT_URI overrides + # the derived `${NEXT_PUBLIC_APP_URL}/api/{polar,oura}/callback`. Listed + # here so operator values in .env reach the container (the `environment:` + # block is a whitelist). POLAR_CLIENT_ID: "${POLAR_CLIENT_ID:-}" POLAR_CLIENT_SECRET: "${POLAR_CLIENT_SECRET:-}" POLAR_REDIRECT_URI: "${POLAR_REDIRECT_URI:-}" + OURA_CLIENT_ID: "${OURA_CLIENT_ID:-}" + OURA_CLIENT_SECRET: "${OURA_CLIENT_SECRET:-}" + OURA_REDIRECT_URI: "${OURA_REDIRECT_URI:-}" # Deploy-result webhook (optional). DEPLOY_WEBHOOK_SECRET authenticates # POST /api/internal/deploy-webhook; DEPLOY_LOGS_URL is the # deployment-dashboard URL (e.g. the Coolify UI) linked in diff --git a/messages/de.json b/messages/de.json index d9b73d58e..10e7a54a8 100644 --- a/messages/de.json +++ b/messages/de.json @@ -4605,6 +4605,26 @@ "token": "Der Token-Austausch mit Polar ist fehlgeschlagen. Bitte starte die Verbindung erneut.", "rate_limited": "Zu viele Verbindungsversuche. Warte einen Moment und versuche es erneut.", "generic": "Unbekannter Fehler bei der Verbindung. Bitte starte die Verbindung erneut." + }, + "oura": "Oura", + "ouraDescription": "Verbinde dein Oura-Konto, um Readiness, Schlafphasen, HRV und Tagesaktivität zu synchronisieren.", + "ouraHelp": "Melde dich bei Oura an, um den Zugriff zu erlauben. Daten werden stündlich im Hintergrund abgerufen.", + "ouraUnavailable": "Oura ist auf diesem Server nicht konfiguriert. Bitte deinen Administrator, die Oura-OAuth-Zugangsdaten zu hinterlegen.", + "ouraConnect": "Oura verbinden", + "ouraDisconnect": "Trennen", + "ouraDisconnectTitle": "Oura trennen?", + "ouraDisconnectDescription": "Künftige Synchronisierungen stoppen. Bereits importierte Werte bleiben in deinem Verlauf.", + "ouraOauthConnected": "Oura verbunden — die erste Synchronisierung startet im Hintergrund.", + "ouraOauthFailed": "Oura-Verbindung fehlgeschlagen", + "ouraOauthError": { + "csrf1": "Die Sicherheitsprüfung ist fehlgeschlagen, weil das Browser-Cookie fehlte. Bitte starte die Verbindung im selben Browser erneut.", + "state": "Die Antwort von Oura passte zu keiner offenen Verbindungsanfrage. Bitte starte die Verbindung erneut.", + "cross_user": "Die Antwort gehört zu einer Anfrage eines anderen Kontos. Bitte starte die Verbindung aus deinem eigenen Konto erneut.", + "nocode": "Oura hat keinen Autorisierungscode zurückgegeben. Versuche es erneut und erlaube den Zugriff im Oura-Dialog.", + "nocreds": "Oura ist auf diesem Server nicht konfiguriert. Bitte deinen Administrator, die Oura-OAuth-Zugangsdaten zu hinterlegen.", + "token": "Der Token-Austausch mit Oura ist fehlgeschlagen. Bitte starte die Verbindung erneut.", + "rate_limited": "Zu viele Verbindungsversuche. Warte einen Moment und versuche es erneut.", + "generic": "Unbekannter Fehler bei der Verbindung. Bitte starte die Verbindung erneut." } }, "admin": { diff --git a/messages/en.json b/messages/en.json index d568a1e36..94ef0a035 100644 --- a/messages/en.json +++ b/messages/en.json @@ -4605,6 +4605,26 @@ "token": "The token exchange with Polar failed. Please start the connection again.", "rate_limited": "Too many connection attempts. Wait a moment and try again.", "generic": "Unknown error while connecting. Please start the connection again." + }, + "oura": "Oura", + "ouraDescription": "Connect your Oura account to sync readiness, sleep stages, HRV, and daily activity.", + "ouraHelp": "Sign in with Oura to grant access. Data is pulled in the background once an hour.", + "ouraUnavailable": "Oura is not configured on this server. Ask your administrator to add the Oura OAuth credentials.", + "ouraConnect": "Connect Oura", + "ouraDisconnect": "Disconnect", + "ouraDisconnectTitle": "Disconnect Oura?", + "ouraDisconnectDescription": "Future syncs stop. Readings already imported stay in your history.", + "ouraOauthConnected": "Oura connected — the first sync starts in the background.", + "ouraOauthFailed": "Oura connection failed", + "ouraOauthError": { + "csrf1": "The security check failed because the browser cookie was missing. Please start the connection again in the same browser.", + "state": "The response from Oura did not match any open connection request. Please start the connection again.", + "cross_user": "The response belongs to a request from a different account. Please restart the connection from your own account.", + "nocode": "Oura did not return an authorization code. Try again and allow access in the Oura dialog.", + "nocreds": "Oura is not configured on this server. Ask your administrator to add the Oura OAuth credentials.", + "token": "The token exchange with Oura failed. Please start the connection again.", + "rate_limited": "Too many connection attempts. Wait a moment and try again.", + "generic": "Unknown error while connecting. Please start the connection again." } }, "admin": { diff --git a/messages/es.json b/messages/es.json index c485b3e0a..03f1fa659 100644 --- a/messages/es.json +++ b/messages/es.json @@ -4605,6 +4605,26 @@ "token": "El intercambio de token con Polar falló. Inicia la conexión de nuevo.", "rate_limited": "Demasiados intentos de conexión. Espera un momento e inténtalo de nuevo.", "generic": "Error desconocido al conectar. Inicia la conexión de nuevo." + }, + "oura": "Oura", + "ouraDescription": "Conecta tu cuenta de Oura para sincronizar readiness, fases de sueño, VFC y actividad diaria.", + "ouraHelp": "Inicia sesión en Oura para conceder acceso. Los datos se obtienen en segundo plano una vez por hora.", + "ouraUnavailable": "Oura no está configurado en este servidor. Pide a tu administrador que añada las credenciales OAuth de Oura.", + "ouraConnect": "Conectar Oura", + "ouraDisconnect": "Desconectar", + "ouraDisconnectTitle": "¿Desconectar Oura?", + "ouraDisconnectDescription": "Las sincronizaciones futuras se detienen. Las lecturas ya importadas permanecen en tu historial.", + "ouraOauthConnected": "Oura conectado: la primera sincronización empieza en segundo plano.", + "ouraOauthFailed": "Error al conectar con Oura", + "ouraOauthError": { + "csrf1": "La verificación de seguridad falló porque faltaba la cookie del navegador. Inicia la conexión de nuevo en el mismo navegador.", + "state": "La respuesta de Oura no coincidió con ninguna solicitud de conexión abierta. Inicia la conexión de nuevo.", + "cross_user": "La respuesta pertenece a una solicitud de otra cuenta. Reinicia la conexión desde tu propia cuenta.", + "nocode": "Oura no devolvió un código de autorización. Inténtalo de nuevo y permite el acceso en el diálogo de Oura.", + "nocreds": "Oura no está configurado en este servidor. Pide a tu administrador que añada las credenciales OAuth de Oura.", + "token": "El intercambio de token con Oura falló. Inicia la conexión de nuevo.", + "rate_limited": "Demasiados intentos de conexión. Espera un momento e inténtalo de nuevo.", + "generic": "Error desconocido al conectar. Inicia la conexión de nuevo." } }, "admin": { diff --git a/messages/fr.json b/messages/fr.json index c8ff71cb9..fa15939e6 100644 --- a/messages/fr.json +++ b/messages/fr.json @@ -4605,6 +4605,26 @@ "token": "L'échange de jeton avec Polar a échoué. Veuillez relancer la connexion.", "rate_limited": "Trop de tentatives de connexion. Patientez un instant et réessayez.", "generic": "Erreur inconnue lors de la connexion. Veuillez relancer la connexion." + }, + "oura": "Oura", + "ouraDescription": "Connectez votre compte Oura pour synchroniser le readiness, les phases de sommeil, la VFC et l'activité quotidienne.", + "ouraHelp": "Connectez-vous à Oura pour accorder l'accès. Les données sont récupérées en arrière-plan une fois par heure.", + "ouraUnavailable": "Oura n'est pas configuré sur ce serveur. Demandez à votre administrateur d'ajouter les identifiants OAuth Oura.", + "ouraConnect": "Connecter Oura", + "ouraDisconnect": "Déconnecter", + "ouraDisconnectTitle": "Déconnecter Oura ?", + "ouraDisconnectDescription": "Les synchronisations futures s'arrêtent. Les mesures déjà importées restent dans votre historique.", + "ouraOauthConnected": "Oura connecté — la première synchronisation démarre en arrière-plan.", + "ouraOauthFailed": "Échec de la connexion à Oura", + "ouraOauthError": { + "csrf1": "La vérification de sécurité a échoué car le cookie du navigateur était absent. Veuillez relancer la connexion dans le même navigateur.", + "state": "La réponse d'Oura ne correspondait à aucune demande de connexion en cours. Veuillez relancer la connexion.", + "cross_user": "La réponse appartient à une demande d'un autre compte. Veuillez relancer la connexion depuis votre propre compte.", + "nocode": "Oura n'a pas renvoyé de code d'autorisation. Réessayez et autorisez l'accès dans la fenêtre Oura.", + "nocreds": "Oura n'est pas configuré sur ce serveur. Demandez à votre administrateur d'ajouter les identifiants OAuth Oura.", + "token": "L'échange de jeton avec Oura a échoué. Veuillez relancer la connexion.", + "rate_limited": "Trop de tentatives de connexion. Patientez un instant et réessayez.", + "generic": "Erreur inconnue lors de la connexion. Veuillez relancer la connexion." } }, "admin": { diff --git a/messages/it.json b/messages/it.json index 89dfad67b..85749d220 100644 --- a/messages/it.json +++ b/messages/it.json @@ -4605,6 +4605,26 @@ "token": "Lo scambio del token con Polar è fallito. Riavvia la connessione.", "rate_limited": "Troppi tentativi di connessione. Attendi un momento e riprova.", "generic": "Errore sconosciuto durante la connessione. Riavvia la connessione." + }, + "oura": "Oura", + "ouraDescription": "Collega il tuo account Oura per sincronizzare readiness, fasi del sonno, HRV e attività giornaliera.", + "ouraHelp": "Accedi a Oura per concedere l'accesso. I dati vengono recuperati in background una volta all'ora.", + "ouraUnavailable": "Oura non è configurato su questo server. Chiedi al tuo amministratore di aggiungere le credenziali OAuth di Oura.", + "ouraConnect": "Collega Oura", + "ouraDisconnect": "Disconnetti", + "ouraDisconnectTitle": "Disconnettere Oura?", + "ouraDisconnectDescription": "Le sincronizzazioni future si interrompono. Le letture già importate restano nella tua cronologia.", + "ouraOauthConnected": "Oura collegato — la prima sincronizzazione parte in background.", + "ouraOauthFailed": "Connessione a Oura non riuscita", + "ouraOauthError": { + "csrf1": "Il controllo di sicurezza è fallito perché il cookie del browser era assente. Riavvia la connessione nello stesso browser.", + "state": "La risposta di Oura non corrispondeva a nessuna richiesta di connessione aperta. Riavvia la connessione.", + "cross_user": "La risposta appartiene a una richiesta di un altro account. Riavvia la connessione dal tuo account.", + "nocode": "Oura non ha restituito un codice di autorizzazione. Riprova e concedi l'accesso nella finestra di Oura.", + "nocreds": "Oura non è configurato su questo server. Chiedi al tuo amministratore di aggiungere le credenziali OAuth di Oura.", + "token": "Lo scambio del token con Oura è fallito. Riavvia la connessione.", + "rate_limited": "Troppi tentativi di connessione. Attendi un momento e riprova.", + "generic": "Errore sconosciuto durante la connessione. Riavvia la connessione." } }, "admin": { diff --git a/messages/pl.json b/messages/pl.json index 8889d3b71..a06d81682 100644 --- a/messages/pl.json +++ b/messages/pl.json @@ -4605,6 +4605,26 @@ "token": "Wymiana tokena z Polar nie powiodła się. Rozpocznij połączenie ponownie.", "rate_limited": "Zbyt wiele prób połączenia. Poczekaj chwilę i spróbuj ponownie.", "generic": "Nieznany błąd podczas łączenia. Rozpocznij połączenie ponownie." + }, + "oura": "Oura", + "ouraDescription": "Połącz konto Oura, aby synchronizować readiness, fazy snu, HRV i aktywność dzienną.", + "ouraHelp": "Zaloguj się w Oura, aby przyznać dostęp. Dane są pobierane w tle raz na godzinę.", + "ouraUnavailable": "Oura nie jest skonfigurowana na tym serwerze. Poproś administratora o dodanie danych OAuth Oura.", + "ouraConnect": "Połącz Oura", + "ouraDisconnect": "Rozłącz", + "ouraDisconnectTitle": "Rozłączyć Oura?", + "ouraDisconnectDescription": "Przyszłe synchronizacje zostaną zatrzymane. Już zaimportowane odczyty pozostaną w historii.", + "ouraOauthConnected": "Oura połączona — pierwsza synchronizacja startuje w tle.", + "ouraOauthFailed": "Połączenie z Oura nie powiodło się", + "ouraOauthError": { + "csrf1": "Kontrola bezpieczeństwa nie powiodła się, ponieważ brakowało pliku cookie przeglądarki. Rozpocznij połączenie ponownie w tej samej przeglądarce.", + "state": "Odpowiedź z Oura nie pasowała do żadnego otwartego żądania połączenia. Rozpocznij połączenie ponownie.", + "cross_user": "Odpowiedź należy do żądania z innego konta. Rozpocznij połączenie ponownie z własnego konta.", + "nocode": "Oura nie zwróciła kodu autoryzacji. Spróbuj ponownie i zezwól na dostęp w oknie Oura.", + "nocreds": "Oura nie jest skonfigurowana na tym serwerze. Poproś administratora o dodanie danych OAuth Oura.", + "token": "Wymiana tokena z Oura nie powiodła się. Rozpocznij połączenie ponownie.", + "rate_limited": "Zbyt wiele prób połączenia. Poczekaj chwilę i spróbuj ponownie.", + "generic": "Nieznany błąd podczas łączenia. Rozpocznij połączenie ponownie." } }, "admin": { diff --git a/scripts/env-manifest.json b/scripts/env-manifest.json index 10ba0c0cc..6b3d72f90 100644 --- a/scripts/env-manifest.json +++ b/scripts/env-manifest.json @@ -70,6 +70,22 @@ } ] }, + { + "name": "Oura OAuth", + "description": "Required to enable the Oura Cloud v2 integration. App boots without these but the Oura connect button stays disabled. Register an app at https://cloud.ouraring.com/oauth/applications and set the redirect URI to ${NEXT_PUBLIC_APP_URL}/api/oura/callback.", + "required": false, + "allOrNone": true, + "variables": [ + { + "name": "OURA_CLIENT_ID", + "purpose": "Oura Cloud OAuth client id." + }, + { + "name": "OURA_CLIENT_SECRET", + "purpose": "Oura Cloud OAuth client secret." + } + ] + }, { "name": "APNs (iOS push)", "description": "All four core APNS_* vars together. Missing any disables APNs silently — the v1.4.40 AP-2 gap that motivated this manifest. allOrNone trips the synthetic required row whenever 1-3 of the 4 are set.", diff --git a/src/app/api/oura/callback/route.ts b/src/app/api/oura/callback/route.ts new file mode 100644 index 000000000..e30899161 --- /dev/null +++ b/src/app/api/oura/callback/route.ts @@ -0,0 +1,96 @@ +import { prisma } from "@/lib/db"; +import { apiHandler } from "@/lib/api-handler"; +import { getSession } from "@/lib/auth/session"; +import { annotate, getEvent } from "@/lib/logging/context"; +import { auditLog } from "@/lib/auth/audit"; +import { encrypt } from "@/lib/crypto"; +import { exchangeCode, getOuraCredentials } from "@/lib/oura/client"; +import { + oauthStateCookieName, + stateMatchesCookie, + verifySignedState, +} from "@/lib/oauth/signed-state"; +import { markReconnected } from "@/lib/integrations/status"; +import { NextRequest, NextResponse } from "next/server"; + +/** + * v1.17.0 (F4) — OAuth callback from Oura. + * + * Identity + CSRF mirror the Polar callback: the `state` param is a stateless + * HMAC-signed token, enforced as a byte-exact double-submit against the + * httpOnly cookie AND verified for signature / expiry / `oura` provider + * binding. The `userId` is read from inside the verified token, cross-checked + * against the web session when present. + * + * On success: exchange the code, persist the encrypted access + refresh token + * on `User`, clear any prior reauth state, and redirect back to Settings. + */ +const ERR = (reason: string) => + NextResponse.redirect( + new URL( + `/settings/integrations?oura=error&reason=${reason}`, + process.env.NEXT_PUBLIC_APP_URL!, + ), + ); + +export const GET = apiHandler(async (request: NextRequest) => { + annotate({ action: { name: "oura.callback" } }); + + const { searchParams } = new URL(request.url); + const code = searchParams.get("code"); + const state = searchParams.get("state"); + const cookieState = request.cookies.get(oauthStateCookieName("oura"))?.value; + + if (!stateMatchesCookie(state, cookieState)) { + annotate({ meta: { reason: "csrf1" } }); + return ERR("csrf1"); + } + + const verified = verifySignedState("oura", state); + if (!verified) { + annotate({ meta: { reason: "state" } }); + return ERR("state"); + } + const userId = verified.userId; + + const evt = getEvent(); + if (evt) evt.setAuth({ user_id: userId, auth_method: "session" }); + + const sessionData = await getSession(); + if (sessionData && sessionData.user.id !== userId) { + annotate({ meta: { reason: "cross_user" } }); + return ERR("cross_user"); + } + + if (!code) return ERR("nocode"); + + try { + const creds = getOuraCredentials(); + if (!creds) return ERR("nocreds"); + + const tokens = await exchangeCode(code, creds); + + await prisma.user.update({ + where: { id: userId }, + data: { + ouraAccessTokenEncrypted: encrypt(tokens.access_token), + ouraRefreshTokenEncrypted: encrypt(tokens.refresh_token), + }, + }); + + await auditLog("oura.connect", { userId }); + await markReconnected(userId, "oura"); + + const response = NextResponse.redirect( + new URL( + "/settings/integrations?oura=connected", + process.env.NEXT_PUBLIC_APP_URL!, + ), + ); + response.cookies.delete(oauthStateCookieName("oura")); + return response; + } catch (err) { + getEvent()?.setError(err); + return ERR("token"); + } +}); diff --git a/src/app/api/oura/connect/route.ts b/src/app/api/oura/connect/route.ts new file mode 100644 index 000000000..fd67aa350 --- /dev/null +++ b/src/app/api/oura/connect/route.ts @@ -0,0 +1,60 @@ +import { apiHandler, requireAuth } from "@/lib/api-handler"; +import { apiError } from "@/lib/api-response"; +import { annotate } from "@/lib/logging/context"; +import { shouldEmitSecureCookie } from "@/lib/auth/secure-cookie"; +import { checkRateLimit } from "@/lib/rate-limit"; +import { getAuthorizationUrl, getOuraCredentials } from "@/lib/oura/client"; +import { + OAUTH_STATE_TTL_MS, + mintSignedState, + oauthStateCookieName, +} from "@/lib/oauth/signed-state"; +import { NextResponse } from "next/server"; + +/** + * v1.17.0 (F4) — redirect the user to the Oura consent screen. + * + * Full OAuth from env (`OURA_CLIENT_ID` / `OURA_CLIENT_SECRET`). CSRF via the + * stateless signed state (`src/lib/oauth/signed-state.ts`): the same token is + * the `state` URL param AND an httpOnly cookie. Rate-limited per user. + */ +const CONNECT_RATE_LIMIT = 10; +const CONNECT_WINDOW_MS = 60_000; + +export const GET = apiHandler(async () => { + const { user } = await requireAuth(); + annotate({ action: { name: "oura.connect" } }); + + const rl = await checkRateLimit( + `oura:connect:${user.id}`, + CONNECT_RATE_LIMIT, + CONNECT_WINDOW_MS, + ); + if (!rl.allowed) { + annotate({ action: { name: "oura.connect.rate_limited" } }); + return NextResponse.redirect( + new URL( + "/settings/integrations?oura=error&reason=rate_limited", + process.env.NEXT_PUBLIC_APP_URL!, + ), + ); + } + + const creds = getOuraCredentials(); + if (!creds) { + return apiError("Oura integration is not configured on this server.", 400); + } + + const state = mintSignedState("oura", user.id); + const url = getAuthorizationUrl(state, creds); + + const response = NextResponse.redirect(url); + response.cookies.set(oauthStateCookieName("oura"), state, { + httpOnly: true, + secure: shouldEmitSecureCookie(), + sameSite: "lax", + maxAge: Math.floor(OAUTH_STATE_TTL_MS / 1000), + path: "/", + }); + return response; +}); diff --git a/src/app/api/oura/disconnect/route.ts b/src/app/api/oura/disconnect/route.ts new file mode 100644 index 000000000..6eb47e33a --- /dev/null +++ b/src/app/api/oura/disconnect/route.ts @@ -0,0 +1,39 @@ +import { prisma } from "@/lib/db"; +import { apiHandler, requireAuth } from "@/lib/api-handler"; +import { auditLog } from "@/lib/auth/audit"; +import { apiSuccess, apiError } from "@/lib/api-response"; +import { annotate } from "@/lib/logging/context"; +import { markDisconnected } from "@/lib/integrations/status"; + +/** + * v1.17.0 (F4) — disconnect Oura for the current user. + * + * Clears the stored access + refresh token on `User` and parks the integration + * status at `disconnected`. Imported `source = OURA` measurements are left + * intact; a reconnect resumes sync. + */ +export const POST = apiHandler(async () => { + const { user } = await requireAuth(); + annotate({ action: { name: "oura.disconnect" } }); + + const dbUser = await prisma.user.findUnique({ + where: { id: user.id }, + select: { ouraAccessTokenEncrypted: true }, + }); + if (!dbUser?.ouraAccessTokenEncrypted) { + return apiError("No Oura connection", 404); + } + + await prisma.user.update({ + where: { id: user.id }, + data: { + ouraAccessTokenEncrypted: null, + ouraRefreshTokenEncrypted: null, + }, + }); + + await auditLog("oura.disconnect", { userId: user.id }); + await markDisconnected(user.id, "oura"); + + return apiSuccess({ disconnected: true }); +}); diff --git a/src/app/api/oura/status/__tests__/route.test.ts b/src/app/api/oura/status/__tests__/route.test.ts new file mode 100644 index 000000000..b62b1d884 --- /dev/null +++ b/src/app/api/oura/status/__tests__/route.test.ts @@ -0,0 +1,75 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; + +vi.mock("@/lib/api-handler", () => ({ + apiHandler: unknown>(fn: T) => fn, + requireAuth: vi.fn(async () => ({ user: { id: "u1" } })), +})); + +vi.mock("@/lib/db", () => ({ + prisma: { user: { findUnique: vi.fn() } }, +})); + +vi.mock("@/lib/logging/context", () => ({ annotate: vi.fn() })); + +vi.mock("@/lib/api-response", () => ({ + apiSuccess: (data: unknown) => ({ data, error: null }), +})); + +vi.mock("@/lib/oura/client", () => ({ + getOuraCredentials: vi.fn(() => ({ clientId: "c", clientSecret: "s" })), +})); + +vi.mock("@/lib/integrations/status", () => ({ + getIntegrationStatus: vi.fn(async () => ({ + integration: "oura", + state: "error_reauth", + lastSuccessAt: null, + lastAttemptAt: "2026-06-10T00:00:00.000Z", + lastError: "http_401", + consecutiveFailuresByKind: null, + })), +})); + +import { GET } from "../route"; +import { prisma } from "@/lib/db"; +import { getOuraCredentials } from "@/lib/oura/client"; + +const userFind = prisma.user.findUnique as ReturnType; +const credsMock = getOuraCredentials as ReturnType; + +type Body = { + connected: boolean; + available: boolean; + state?: string; + lastError?: string | null; +}; +const call = () => + (GET as unknown as () => Promise<{ data: Body }>)().then((r) => r.data); + +describe("GET /api/oura/status", () => { + beforeEach(() => { + vi.clearAllMocks(); + credsMock.mockReturnValue({ clientId: "c", clientSecret: "s" }); + }); + + it("reports not-connected but available", async () => { + userFind.mockResolvedValue({ ouraAccessTokenEncrypted: null }); + const res = await call(); + expect(res.connected).toBe(false); + expect(res.available).toBe(true); + }); + + it("surfaces the ledger reauth state when connected", async () => { + userFind.mockResolvedValue({ ouraAccessTokenEncrypted: "enc" }); + const res = await call(); + expect(res.connected).toBe(true); + expect(res.state).toBe("error_reauth"); + expect(res.lastError).toBe("http_401"); + }); + + it("never returns the token", async () => { + userFind.mockResolvedValue({ ouraAccessTokenEncrypted: "enc-secret" }); + const res = (await call()) as Record; + expect(JSON.stringify(res)).not.toContain("enc-secret"); + }); +}); diff --git a/src/app/api/oura/status/route.ts b/src/app/api/oura/status/route.ts new file mode 100644 index 000000000..d5dcb6484 --- /dev/null +++ b/src/app/api/oura/status/route.ts @@ -0,0 +1,42 @@ +import { prisma } from "@/lib/db"; +import { apiHandler, requireAuth } from "@/lib/api-handler"; +import { annotate } from "@/lib/logging/context"; +import { apiSuccess } from "@/lib/api-response"; +import { getOuraCredentials } from "@/lib/oura/client"; +import { getIntegrationStatus } from "@/lib/integrations/status"; + +/** + * v1.17.0 (F4) — Oura connection status for the current user. + * + * `available` reports whether the server has the shared OAuth app configured. + * `connected` is whether a token is stored. The ledger snapshot comes off the + * shared `oura` IntegrationKey. The access / refresh tokens are NEVER returned. + */ +export const GET = apiHandler(async () => { + const { user } = await requireAuth(); + annotate({ action: { name: "oura.status" } }); + + const dbUser = await prisma.user.findUnique({ + where: { id: user.id }, + select: { ouraAccessTokenEncrypted: true }, + }); + + const available = !!getOuraCredentials(); + const connected = !!dbUser?.ouraAccessTokenEncrypted; + + if (!connected) { + return apiSuccess({ connected: false, configured: false, available }); + } + + const status = await getIntegrationStatus(user.id, "oura"); + + return apiSuccess({ + connected: true, + configured: true, + available, + state: status.state, + lastSuccessAt: status.lastSuccessAt, + lastAttemptAt: status.lastAttemptAt, + lastError: status.lastError, + }); +}); diff --git a/src/components/settings/__tests__/integrations-section.test.tsx b/src/components/settings/__tests__/integrations-section.test.tsx index 9d6344867..8381da09e 100644 --- a/src/components/settings/__tests__/integrations-section.test.tsx +++ b/src/components/settings/__tests__/integrations-section.test.tsx @@ -131,10 +131,10 @@ describe("IntegrationsSection — single-status-display contract (A5)", () => { }); const html = render(); - // Exactly one pill per card → 5 pills total (Withings, WHOOP, - // Fitbit / Google Health, Polar, Nightscout). The moodLog integration was - // removed; Polar (F4) was added in v1.17.0. - expect(count(html, 'data-testid="integration-status-pill"')).toBe(5); + // Exactly one pill per card → 6 pills total (Withings, WHOOP, + // Fitbit / Google Health, Polar, Oura, Nightscout). The moodLog integration + // was removed; Polar + Oura (F4) were added in v1.17.0. + expect(count(html, 'data-testid="integration-status-pill"')).toBe(6); // The redundant banner from v1.4.15 is gone. expect(html).not.toContain('data-testid="integration-status-banner"'); // Card-body "letzter Sync" repetition is gone — no diff --git a/src/components/settings/integrations-section.tsx b/src/components/settings/integrations-section.tsx index 89fb1116e..148a806ca 100644 --- a/src/components/settings/integrations-section.tsx +++ b/src/components/settings/integrations-section.tsx @@ -8,6 +8,7 @@ import { toast } from "sonner"; import { FitbitCard } from "@/components/settings/integrations/fitbit-card"; import { NightscoutCard } from "@/components/settings/integrations/nightscout-card"; +import { OuraCard } from "@/components/settings/integrations/oura-card"; import { PolarCard } from "@/components/settings/integrations/polar-card"; import { pickStatus, @@ -92,15 +93,15 @@ export function IntegrationsSection() { }, [withingsOauthOutcome, router, queryClient, t]); // v1.17.0 (F4) — generic OAuth-callback toast for the env-based providers. - // The Polar callback redirects back with `?polar=connected` or - // `?polar=error&reason=`; surface the outcome as a toast and scrub the - // one-shot params so a reload doesn't replay it. + // The Polar / Oura callbacks redirect back with `?=connected` or + // `?=error&reason=`; surface the outcome as a toast and scrub + // the one-shot params so a reload doesn't replay it. const [oauthOutcome] = useState< - { provider: "polar"; kind: "connected" } | { provider: "polar"; kind: "error"; reason: string } | null + { provider: "polar" | "oura"; kind: "connected" } | { provider: "polar" | "oura"; kind: "error"; reason: string } | null >(() => { if (typeof window === "undefined") return null; const params = new URLSearchParams(window.location.search); - for (const provider of ["polar"] as const) { + for (const provider of ["polar", "oura"] as const) { const v = params.get(provider); if (v === "connected") return { provider, kind: "connected" }; if (v === "error") { @@ -117,7 +118,7 @@ export function IntegrationsSection() { url.searchParams.delete(provider); url.searchParams.delete("reason"); router.replace(`${url.pathname}${url.search}`, { scroll: false }); - const key = queryKeys.polar(); + const key = provider === "polar" ? queryKeys.polar() : queryKeys.oura(); if (oauthOutcome.kind === "connected") { toast.success(t(`settings.${provider}OauthConnected`)); queryClient.invalidateQueries({ queryKey: key }); @@ -179,6 +180,7 @@ export function IntegrationsSection() { + ); diff --git a/src/components/settings/integrations/oura-card.tsx b/src/components/settings/integrations/oura-card.tsx new file mode 100644 index 000000000..dfcd92166 --- /dev/null +++ b/src/components/settings/integrations/oura-card.tsx @@ -0,0 +1,18 @@ +"use client"; + +// v1.17.0 (F4) — Oura Cloud integration card. Thin wrapper over the shared +// env-based OAuth card. + +import { OAuthProviderCard } from "@/components/settings/integrations/oauth-provider-card"; +import { queryKeys } from "@/lib/query-keys"; + +export function OuraCard({ enabled = true }: { enabled?: boolean }) { + return ( + + ); +} diff --git a/src/lib/jobs/reminder-worker.ts b/src/lib/jobs/reminder-worker.ts index ecf91a553..57aa681f0 100644 --- a/src/lib/jobs/reminder-worker.ts +++ b/src/lib/jobs/reminder-worker.ts @@ -264,6 +264,7 @@ import { handleNightscoutSync, } from "./reminder/nightscout-sync"; import { PolarSyncPayload, handlePolarSync } from "./reminder/polar-sync"; +import { OuraSyncPayload, handleOuraSync } from "./reminder/oura-sync"; import { handleMedicationInventoryExpire, handleIntakeAutoSkip, @@ -402,13 +403,16 @@ const FITBIT_OAUTH_STATE_CLEANUP_CRON = "24 3 * * *"; const NIGHTSCOUT_SYNC_QUEUE = "nightscout-sync"; const NIGHTSCOUT_SYNC_CRON = "11 * * * *"; // every hour at :11 -// v1.17.0 (F4) — Polar OAuth poll sync. Poll-only (one hourly tick re-walks -// every connected user). :13 staggers off the other hourly sync ticks (WHOOP -// :05, Fitbit :08, Nightscout :11) so the polls don't pile up on one boss poll. -// The queue MUST be registered in `allQueues` below or pg-boss never provisions -// it and the schedule silently no-ops (the v1.4.37 dead-queue class). +// v1.17.0 (F4) — Polar + Oura OAuth poll sync. Poll-only (one hourly tick per +// provider re-walks every connected user). :13 / :15 stagger off the other +// hourly sync ticks (WHOOP :05, Fitbit :08, Nightscout :11) so the polls don't +// pile up on one boss poll. The queues MUST be registered in `allQueues` below +// or pg-boss never provisions them and the schedule silently no-ops (the +// v1.4.37 dead-queue class). const POLAR_SYNC_QUEUE = "polar-sync"; const POLAR_SYNC_CRON = "13 * * * *"; // every hour at :13 +const OURA_SYNC_QUEUE = "oura-sync"; +const OURA_SYNC_CRON = "15 * * * *"; // every hour at :15 // v1.15.19 — daily duplicate dose-slot dedup discovery tick. The boot-time // pass only ran on worker restart, so a cross-source duplicate slot created // between deploys (a pending REMINDER row plus a standalone API/WEB row on @@ -630,9 +634,10 @@ export async function startReminderWorker() { // MUST be registered here or pg-boss never provisions it and the schedule // below silently no-ops (the v1.4.37 dead-queue class). NIGHTSCOUT_SYNC_QUEUE, - // v1.17.0 (F4) — Polar OAuth poll sync. Registered here or pg-boss never - // provisions it and the hourly schedule below silently no-ops. + // v1.17.0 (F4) — Polar + Oura OAuth poll sync. Registered here or pg-boss + // never provisions them and the hourly schedule below silently no-ops. POLAR_SYNC_QUEUE, + OURA_SYNC_QUEUE, OFFHOST_BACKUP_QUEUE, RESTORE_DRILL_QUEUE, HOST_METRIC_QUEUE, @@ -856,8 +861,9 @@ export async function startReminderWorker() { // v1.17.0 — hourly Nightscout CGM poll (:11, staggered off the other sync // ticks). [NIGHTSCOUT_SYNC_QUEUE, NIGHTSCOUT_SYNC_CRON], - // v1.17.0 (F4) — hourly Polar (:13) OAuth poll. + // v1.17.0 (F4) — hourly Polar (:13) + Oura (:15) OAuth polls. [POLAR_SYNC_QUEUE, POLAR_SYNC_CRON], + [OURA_SYNC_QUEUE, OURA_SYNC_CRON], [OFFHOST_BACKUP_QUEUE, OFFHOST_BACKUP_CRON], [RESTORE_DRILL_QUEUE, RESTORE_DRILL_CRON], [HOST_METRIC_QUEUE, HOST_METRIC_CRON], @@ -1058,14 +1064,19 @@ export async function startReminderWorker() { { localConcurrency: 1 }, handleNightscoutSync, ); - // v1.17.0 (F4) — Polar OAuth poll-cohort sync. The hourly cron tick (no - // `userId`) re-walks every connected user; one user's revoked grant is + // v1.17.0 (F4) — Polar + Oura OAuth poll-cohort sync. The hourly cron tick + // (no `userId`) re-walks every connected user; one user's revoked grant is // warned, not fatal. await boss.work( POLAR_SYNC_QUEUE, { localConcurrency: 1 }, handlePolarSync, ); + await boss.work( + OURA_SYNC_QUEUE, + { localConcurrency: 1 }, + handleOuraSync, + ); await boss.work( GENERAL_STATUS_QUEUE, { localConcurrency: 1 }, diff --git a/src/lib/jobs/reminder/oura-sync.ts b/src/lib/jobs/reminder/oura-sync.ts new file mode 100644 index 000000000..b722b89ad --- /dev/null +++ b/src/lib/jobs/reminder/oura-sync.ts @@ -0,0 +1,62 @@ +/** + * v1.17.0 (F4) — Oura poll-cohort sync handler. + * + * Poll-only: one hourly cron tick (no `userId`) iterates every user with a + * stored Oura token and re-syncs each via `syncUserOura`. One user's revoked + * grant / outage is warned and the pass continues. The queue name, cron + * schedule, and boss.work registration live in reminder-worker.ts. + */ +import { type Job } from "pg-boss"; + +import { recordError } from "@/lib/jobs/worker-status"; +import { withBackgroundEvent } from "@/lib/logging/background"; +import { syncUserOura } from "@/lib/oura/sync"; +import { getWorkerPrisma } from "./shared"; + +export interface OuraSyncPayload { + userId?: string; +} + +export async function handleOuraSync(jobs: Job[]) { + await withBackgroundEvent("job.oura_sync", async (evt) => { + const prisma = getWorkerPrisma(); + try { + const targets: Array<{ userId: string }> = []; + for (const job of jobs) { + if (job.data?.userId) targets.push({ userId: job.data.userId }); + } + if (targets.length === 0) { + const users = await prisma.user.findMany({ + where: { ouraAccessTokenEncrypted: { not: null } }, + select: { id: true }, + }); + targets.push(...users.map((u) => ({ userId: u.id }))); + } + if (targets.length === 0) return; + + let usersSynced = 0; + let measurementsImported = 0; + for (const { userId } of targets) { + try { + measurementsImported += await syncUserOura(userId); + usersSynced++; + } catch (err) { + evt.addWarning(`job.oura_sync failed for user ${userId}: ${err}`); + } + } + + evt.setBackground({ + task_name: "job.oura_sync", + result: { + users_synced: usersSynced, + total: targets.length, + measurements_imported: measurementsImported, + }, + }); + } catch (err) { + evt.setError(err); + recordError(); + throw err; + } + }); +} diff --git a/src/lib/oura/__tests__/client.test.ts b/src/lib/oura/__tests__/client.test.ts new file mode 100644 index 000000000..39a626a2f --- /dev/null +++ b/src/lib/oura/__tests__/client.test.ts @@ -0,0 +1,177 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { + OURA_OAUTH_SCOPE, + exchangeCode, + fetchReadiness, + getAuthorizationUrl, + getOuraCredentials, + mapDailyActivity, + mapReadiness, + mapSleep, + refreshAccessToken, + type OuraDailyActivity, + type OuraReadiness, + type OuraSleep, +} from "../client"; +import { OuraApiError } from "../response-classifier"; + +const CREDS = { clientId: "cid", clientSecret: "csecret" }; + +function installFetchMock(pages: Array<{ status: number; body?: unknown }>) { + let i = 0; + const fetchMock = vi.fn(async (...args: [string, RequestInit?]) => { + void args; + const page = pages[Math.min(i, pages.length - 1)]!; + i += 1; + return { status: page.status, json: async () => page.body ?? null }; + }); + vi.stubGlobal("fetch", fetchMock); + return fetchMock; +} + +beforeEach(() => { + process.env.OURA_CLIENT_ID = "env-cid"; + process.env.OURA_CLIENT_SECRET = "env-secret"; + process.env.NEXT_PUBLIC_APP_URL = "https://app.example"; + delete process.env.OURA_REDIRECT_URI; +}); + +afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +describe("getOuraCredentials", () => { + it("reads env", () => { + expect(getOuraCredentials()).toEqual({ + clientId: "env-cid", + clientSecret: "env-secret", + }); + }); + it("null when unconfigured", () => { + delete process.env.OURA_CLIENT_SECRET; + expect(getOuraCredentials()).toBeNull(); + }); +}); + +describe("getAuthorizationUrl", () => { + it("builds the Oura authorize URL", () => { + const url = getAuthorizationUrl("signed", CREDS); + expect(url).toContain("cloud.ouraring.com/oauth/authorize"); + expect(url).toContain("scope=daily+personal"); + expect(url).toContain("state=signed"); + }); +}); + +describe("exchangeCode / refreshAccessToken", () => { + it("exchanges a code for an access + refresh token", async () => { + installFetchMock([ + { + status: 200, + body: { access_token: "a", refresh_token: "r", expires_in: 86400 }, + }, + ]); + const t = await exchangeCode("code", CREDS); + expect(t.access_token).toBe("a"); + expect(t.refresh_token).toBe("r"); + }); + + it("rotates tokens on refresh", async () => { + const fetchMock = installFetchMock([ + { + status: 200, + body: { access_token: "a2", refresh_token: "r2", expires_in: 86400 }, + }, + ]); + const t = await refreshAccessToken("r1", CREDS); + expect(t.refresh_token).toBe("r2"); + const [, init] = fetchMock.mock.calls[0]!; + expect(init!.body).toContain("grant_type=refresh_token"); + }); + + it("throws OuraApiError on a 400 invalid_grant", async () => { + installFetchMock([{ status: 400, body: { error: "invalid_grant" } }]); + await expect(refreshAccessToken("dead", CREDS)).rejects.toBeInstanceOf( + OuraApiError, + ); + }); +}); + +describe("fetchReadiness pagination", () => { + it("walks next_token across pages", async () => { + installFetchMock([ + { + status: 200, + body: { data: [{ id: "1", day: "2026-06-09", score: 70 }], next_token: "abc" }, + }, + { + status: 200, + body: { data: [{ id: "2", day: "2026-06-10", score: 80 }], next_token: null }, + }, + ]); + const r = await fetchReadiness("tok", { + startDate: "2026-06-01", + endDate: "2026-06-10", + }); + expect(r).toHaveLength(2); + }); +}); + +describe("mapReadiness", () => { + it("maps score -> RECOVERY_SCORE", () => { + const r: OuraReadiness = { id: "1", day: "2026-06-10", score: 84 }; + const mapped = mapReadiness(r); + expect(mapped).toHaveLength(1); + expect(mapped[0]).toMatchObject({ type: "RECOVERY_SCORE", value: 84, fieldTag: "recovery" }); + }); + it("skips a record with no score", () => { + expect(mapReadiness({ id: "1", day: "2026-06-10", score: null })).toEqual([]); + }); +}); + +describe("mapSleep", () => { + it("maps stages s->min, efficiency, hrv, rhr, breath", () => { + const s: OuraSleep = { + id: "1", + day: "2026-06-10", + light_sleep_duration: 3600, + deep_sleep_duration: 1800, + rem_sleep_duration: 5400, + awake_time: 600, + efficiency: 91, + average_hrv: 48, + lowest_heart_rate: 49, + average_breath: 14.5, + }; + const mapped = mapSleep(s); + expect(mapped.find((m) => m.sleepStage === "CORE")?.value).toBe(60); + expect(mapped.find((m) => m.sleepStage === "AWAKE")?.value).toBe(10); + expect(mapped.find((m) => m.type === "SLEEP_EFFICIENCY")?.value).toBe(91); + expect(mapped.find((m) => m.type === "HRV_RMSSD")?.value).toBe(48); + expect(mapped.find((m) => m.type === "RESTING_HEART_RATE")?.value).toBe(49); + expect(mapped.find((m) => m.type === "RESPIRATORY_RATE")?.value).toBe(14.5); + }); +}); + +describe("mapDailyActivity", () => { + it("maps steps and active energy", () => { + const a: OuraDailyActivity = { + id: "1", + day: "2026-06-10", + steps: 9001, + active_calories: 412, + }; + const mapped = mapDailyActivity(a); + expect(mapped.find((m) => m.type === "ACTIVITY_STEPS")?.value).toBe(9001); + expect(mapped.find((m) => m.type === "ACTIVE_ENERGY_BURNED")?.value).toBe( + 412, + ); + }); +}); + +describe("OURA_OAUTH_SCOPE", () => { + it("requests daily + personal", () => { + expect(OURA_OAUTH_SCOPE).toBe("daily personal"); + }); +}); diff --git a/src/lib/oura/__tests__/sync.test.ts b/src/lib/oura/__tests__/sync.test.ts new file mode 100644 index 000000000..e242401d5 --- /dev/null +++ b/src/lib/oura/__tests__/sync.test.ts @@ -0,0 +1,172 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +const { + getConnMock, + storeTokensMock, + getCredsMock, + fetchReadinessMock, + fetchSleepMock, + fetchActivityMock, + refreshMock, + upsertMock, + recordSuccessMock, + recordFailureMock, + recomputeMock, + invalidateMock, +} = vi.hoisted(() => ({ + getConnMock: vi.fn(), + storeTokensMock: vi.fn(), + getCredsMock: vi.fn(), + fetchReadinessMock: vi.fn(), + fetchSleepMock: vi.fn(), + fetchActivityMock: vi.fn(), + refreshMock: vi.fn(), + upsertMock: vi.fn(), + recordSuccessMock: vi.fn(), + recordFailureMock: vi.fn(), + recomputeMock: vi.fn(), + invalidateMock: vi.fn(), +})); + +vi.mock("../credentials", () => ({ + getOuraConnection: getConnMock, + storeOuraTokens: storeTokensMock, +})); + +vi.mock("@/lib/db", () => ({ + prisma: { measurement: { upsert: upsertMock } }, +})); + +vi.mock("@/lib/integrations/status", () => ({ + recordSyncSuccess: recordSuccessMock, + recordSyncFailure: recordFailureMock, +})); + +vi.mock("@/lib/rollups/measurement-rollups", () => ({ + collapseToTypeDayKeys: (rows: Array<{ type: string; measuredAt: Date }>) => + rows.map((r) => ({ type: r.type, measuredAt: r.measuredAt })), + recomputeBucketsForMeasurement: recomputeMock, +})); + +vi.mock("@/lib/insights/comprehensive-generate", () => ({ + invalidateStatusInsightsForTypes: invalidateMock, +})); + +vi.mock("../client", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + getOuraCredentials: getCredsMock, + fetchReadiness: fetchReadinessMock, + fetchSleep: fetchSleepMock, + fetchDailyActivity: fetchActivityMock, + refreshAccessToken: refreshMock, + }; +}); + +import { syncUserOura } from "../sync"; +import { OuraApiError } from "../response-classifier"; + +const CONN = { accessToken: "acc", refreshToken: "ref" }; + +beforeEach(() => { + getConnMock.mockReset(); + storeTokensMock.mockReset().mockResolvedValue(undefined); + getCredsMock.mockReset().mockReturnValue({ clientId: "c", clientSecret: "s" }); + fetchReadinessMock.mockReset().mockResolvedValue([]); + fetchSleepMock.mockReset().mockResolvedValue([]); + fetchActivityMock.mockReset().mockResolvedValue([]); + refreshMock.mockReset(); + upsertMock.mockReset().mockResolvedValue({}); + recordSuccessMock.mockReset().mockResolvedValue(undefined); + recordFailureMock.mockReset().mockResolvedValue(undefined); + recomputeMock.mockReset().mockResolvedValue(undefined); + invalidateMock.mockReset().mockResolvedValue(undefined); +}); + +afterEach(() => vi.clearAllMocks()); + +function err401() { + return new OuraApiError({ + verb: "fetchReadiness", + classification: "reauth_required", + httpStatus: 401, + reason: "http_401", + }); +} + +describe("syncUserOura", () => { + it("no-ops cleanly when unconnected", async () => { + getConnMock.mockResolvedValue(null); + expect(await syncUserOura("u1")).toBe(0); + expect(recordSuccessMock).not.toHaveBeenCalled(); + }); + + it("writes a readiness RECOVERY_SCORE with source OURA", async () => { + getConnMock.mockResolvedValue(CONN); + fetchReadinessMock.mockResolvedValue([ + { id: "x", day: "2026-06-10", score: 84 }, + ]); + const imported = await syncUserOura("u1"); + expect(imported).toBe(1); + const arg = upsertMock.mock.calls[0]![0]; + expect(arg.where.userId_type_source_externalId).toMatchObject({ + type: "RECOVERY_SCORE", + source: "OURA", + externalId: "readiness:2026-06-10:recovery", + }); + expect(arg.create.value).toBe(84); + expect(recordSuccessMock).toHaveBeenCalledWith("u1", "oura"); + }); + + it("refreshes the token on a 401 and retries once", async () => { + getConnMock.mockResolvedValue(CONN); + // First call (with old token) 401s; after refresh the retry succeeds. + fetchReadinessMock + .mockRejectedValueOnce(err401()) + .mockResolvedValueOnce([{ id: "x", day: "2026-06-10", score: 70 }]); + refreshMock.mockResolvedValue({ + access_token: "newAcc", + refresh_token: "newRef", + expires_in: 86400, + }); + const imported = await syncUserOura("u1"); + expect(refreshMock).toHaveBeenCalledWith("ref", expect.anything()); + expect(storeTokensMock).toHaveBeenCalledWith("u1", "newAcc", "newRef"); + expect(imported).toBe(1); + expect(recordSuccessMock).toHaveBeenCalledWith("u1", "oura"); + }); + + it("records reauth_required when the refresh itself fails", async () => { + getConnMock.mockResolvedValue(CONN); + fetchReadinessMock.mockRejectedValue(err401()); + refreshMock.mockRejectedValue( + new OuraApiError({ + verb: "refreshAccessToken", + classification: "reauth_required", + httpStatus: 400, + reason: "http_400", + upstreamError: "invalid_grant", + }), + ); + await expect(syncUserOura("u1")).rejects.toBeInstanceOf(OuraApiError); + expect(recordFailureMock).toHaveBeenCalledWith( + expect.objectContaining({ integration: "oura", kind: "reauth_required" }), + ); + expect(recordSuccessMock).not.toHaveBeenCalled(); + }); + + it("does NOT refresh on a 403 (not an expiry case)", async () => { + getConnMock.mockResolvedValue(CONN); + fetchReadinessMock.mockRejectedValue( + new OuraApiError({ + verb: "fetchReadiness", + classification: "reauth_required", + httpStatus: 403, + reason: "http_403", + }), + ); + await expect(syncUserOura("u1")).rejects.toBeInstanceOf(OuraApiError); + expect(refreshMock).not.toHaveBeenCalled(); + }); +}); diff --git a/src/lib/oura/client.ts b/src/lib/oura/client.ts new file mode 100644 index 000000000..96ca16c84 --- /dev/null +++ b/src/lib/oura/client.ts @@ -0,0 +1,432 @@ +/** + * v1.17.0 (F4) — Oura Cloud API v2 client for OAuth + data fetching. + * Docs: https://cloud.ouraring.com/v2/docs (re-verify at build). + * + * Mirrors the WHOOP / Polar client structure: hand-rolled fetch over + * `safeFetch` (no SDK), an OAuth handshake (`getAuthorizationUrl` / + * `exchangeCode` / `refreshAccessToken`), typed v2 collection fetchers with + * `next_token` pagination, and a single source-of-truth field→Measurement + * mapping. + * + * Oura specifics: standard authorization-code OAuth WITH refresh tokens (the + * sync layer refreshes on 401, persisting BOTH rotated tokens). The token + * endpoint takes client_id/secret in the body. Collections are read by + * `start_date` / `end_date` (YYYY-MM-DD) and page via `next_token`. + */ +import { getEvent } from "@/lib/logging/context"; +import { safeFetch } from "@/lib/safe-fetch"; +import { OuraApiError, classifyOuraResponse } from "./response-classifier"; + +const OURA_API_BASE = "https://api.ouraring.com"; +const OURA_OAUTH_AUTH_URL = "https://cloud.ouraring.com/oauth/authorize"; +const OURA_OAUTH_TOKEN_URL = "https://api.ouraring.com/oauth/token"; + +export interface OuraCredentials { + clientId: string; + clientSecret: string; +} + +/** Env-configured shared OAuth credentials (F4 = full OAuth from env). */ +export function getOuraCredentials(): OuraCredentials | null { + const clientId = process.env.OURA_CLIENT_ID; + const clientSecret = process.env.OURA_CLIENT_SECRET; + if (!clientId || !clientSecret) return null; + return { clientId, clientSecret }; +} + +export function getOuraRedirectUri(): string { + return ( + process.env.OURA_REDIRECT_URI || + `${process.env.NEXT_PUBLIC_APP_URL}/api/oura/callback` + ); +} + +/** `daily` covers sleep / readiness / activity; `personal` is profile info. */ +export const OURA_OAUTH_SCOPE = "daily personal" as const; + +export function getAuthorizationUrl( + state: string, + creds: OuraCredentials, +): string { + const params = new URLSearchParams({ + response_type: "code", + client_id: creds.clientId, + redirect_uri: getOuraRedirectUri(), + scope: OURA_OAUTH_SCOPE, + state, + }); + return `${OURA_OAUTH_AUTH_URL}?${params}`; +} + +export interface OuraTokenResponse { + access_token: string; + refresh_token: string; + expires_in: number; + token_type?: string; + scope?: string; +} + +async function postToken( + params: URLSearchParams, + verb: string, +): Promise { + const start = performance.now(); + const res = await safeFetch(OURA_OAUTH_TOKEN_URL, { + method: "POST", + headers: { + "Content-Type": "application/x-www-form-urlencoded", + Accept: "application/json", + }, + body: params.toString(), + }); + const json = await res.json().catch(() => null); + const verdict = classifyOuraResponse(res.status); + getEvent()?.addExternalCall({ + service: "oura", + method: verb, + duration_ms: Math.round(performance.now() - start), + status: res.status, + error: verdict.classification === "success" ? undefined : verdict.reason, + }); + if (verdict.classification !== "success") { + throw new OuraApiError({ + verb, + classification: verdict.classification, + httpStatus: verdict.httpStatus, + reason: verdict.reason, + upstreamError: + typeof json?.error === "string" ? json.error : undefined, + }); + } + return json as OuraTokenResponse; +} + +export async function exchangeCode( + code: string, + creds: OuraCredentials, +): Promise { + return postToken( + new URLSearchParams({ + grant_type: "authorization_code", + code, + redirect_uri: getOuraRedirectUri(), + client_id: creds.clientId, + client_secret: creds.clientSecret, + }), + "exchangeCode", + ); +} + +export async function refreshAccessToken( + refreshToken: string, + creds: OuraCredentials, +): Promise { + return postToken( + new URLSearchParams({ + grant_type: "refresh_token", + refresh_token: refreshToken, + client_id: creds.clientId, + client_secret: creds.clientSecret, + }), + "refreshAccessToken", + ); +} + +// ─── Collection reads (v2) ───────────────────────────────────── + +/** v2 paginated envelope: `{ data, next_token }`. */ +export interface OuraCollection { + data: T[]; + next_token?: string | null; +} + +export interface OuraSleep { + id: string; + day: string; + bedtime_end?: string; + total_sleep_duration?: number | null; + time_in_bed?: number | null; + efficiency?: number | null; + rem_sleep_duration?: number | null; + deep_sleep_duration?: number | null; + light_sleep_duration?: number | null; + awake_time?: number | null; + average_heart_rate?: number | null; + lowest_heart_rate?: number | null; + average_hrv?: number | null; + average_breath?: number | null; +} + +export interface OuraReadiness { + id: string; + day: string; + timestamp?: string; + score?: number | null; +} + +export interface OuraDailyActivity { + id: string; + day: string; + timestamp?: string; + steps?: number | null; + active_calories?: number | null; + total_calories?: number | null; +} + +interface DateRangeQuery { + startDate: string; // YYYY-MM-DD + endDate: string; // YYYY-MM-DD + maxPages?: number; +} + +async function fetchCollection( + path: string, + accessToken: string, + verb: string, + query: DateRangeQuery, +): Promise { + const records: T[] = []; + let nextToken: string | null | undefined; + let pageCount = 0; + const maxPages = query.maxPages ?? 100; + + do { + const params = new URLSearchParams({ + start_date: query.startDate, + end_date: query.endDate, + }); + if (nextToken) params.set("next_token", nextToken); + + const pageStart = performance.now(); + const res = await safeFetch(`${OURA_API_BASE}${path}?${params}`, { + method: "GET", + headers: { + Authorization: `Bearer ${accessToken}`, + Accept: "application/json", + }, + }); + const json = (await res.json().catch(() => null)) as + | OuraCollection + | null; + const verdict = classifyOuraResponse(res.status); + getEvent()?.addExternalCall({ + service: "oura", + method: `${verb}(page=${pageCount})`, + duration_ms: Math.round(performance.now() - pageStart), + status: res.status, + error: + verdict.classification === "success" ? undefined : verdict.reason, + }); + if (verdict.classification !== "success") { + throw new OuraApiError({ + verb, + classification: verdict.classification, + httpStatus: verdict.httpStatus, + reason: verdict.reason, + }); + } + for (const r of json?.data ?? []) records.push(r); + nextToken = json?.next_token ?? null; + pageCount += 1; + } while (nextToken && pageCount < maxPages); + + return records; +} + +export function fetchSleep( + accessToken: string, + query: DateRangeQuery, +): Promise { + return fetchCollection( + "/v2/usercollection/sleep", + accessToken, + "fetchSleep", + query, + ); +} + +export function fetchReadiness( + accessToken: string, + query: DateRangeQuery, +): Promise { + return fetchCollection( + "/v2/usercollection/daily_readiness", + accessToken, + "fetchReadiness", + query, + ); +} + +export function fetchDailyActivity( + accessToken: string, + query: DateRangeQuery, +): Promise { + return fetchCollection( + "/v2/usercollection/daily_activity", + accessToken, + "fetchDailyActivity", + query, + ); +} + +// ─── Field → Measurement mapping ─────────────────────────────── + +const SEC_TO_MIN = 1 / 60; + +function round2(n: number): number { + return parseFloat(n.toFixed(2)); +} + +export interface MappedMeasurement { + type: string; + value: number; + unit: string; + measuredAt: Date; + fieldTag: string; + sleepStage?: "CORE" | "DEEP" | "REM" | "AWAKE"; +} + +function dayAnchor(day: string, bedtimeEnd?: string): Date | null { + // Prefer the precise wake instant when present; else anchor the day at UTC + // midnight. The recovery resolver reads the local day key off this stamp. + const candidate = bedtimeEnd ?? `${day}T00:00:00.000Z`; + const d = new Date(candidate); + return Number.isNaN(d.getTime()) ? null : d; +} + +/** Map one Oura readiness record: `score` → `RECOVERY_SCORE` (source OURA, + * feeding the recovery ladder below WHOOP). */ +export function mapReadiness(r: OuraReadiness): MappedMeasurement[] { + if (typeof r.score !== "number") return []; + const measuredAt = dayAnchor(r.day, r.timestamp); + if (!measuredAt) return []; + return [ + { + type: "RECOVERY_SCORE", + value: round2(r.score), + unit: "score", + measuredAt, + fieldTag: "recovery", + }, + ]; +} + +/** Map one Oura sleep record: per-stage durations (s→min), efficiency, HRV, + * RHR (lowest_heart_rate), respiratory rate. */ +export function mapSleep(s: OuraSleep): MappedMeasurement[] { + const measuredAt = dayAnchor(s.day, s.bedtime_end); + if (!measuredAt) return []; + const out: MappedMeasurement[] = []; + + const stages: Array<[number | null | undefined, MappedMeasurement["sleepStage"], string]> = [ + [s.light_sleep_duration, "CORE", "sleep_core"], + [s.deep_sleep_duration, "DEEP", "sleep_deep"], + [s.rem_sleep_duration, "REM", "sleep_rem"], + [s.awake_time, "AWAKE", "sleep_awake"], + ]; + for (const [sec, stage, fieldTag] of stages) { + if (typeof sec === "number" && sec >= 0) { + out.push({ + type: "SLEEP_DURATION", + value: round2(sec * SEC_TO_MIN), + unit: "minutes", + measuredAt, + fieldTag, + sleepStage: stage, + }); + } + } + if (typeof s.efficiency === "number") { + out.push({ + type: "SLEEP_EFFICIENCY", + value: round2(s.efficiency), + unit: "%", + measuredAt, + fieldTag: "sleep_eff", + }); + } + if (typeof s.average_hrv === "number" && s.average_hrv > 0) { + out.push({ + type: "HRV_RMSSD", + value: round2(s.average_hrv), + unit: "ms", + measuredAt, + fieldTag: "hrv_rmssd", + }); + } + if (typeof s.lowest_heart_rate === "number" && s.lowest_heart_rate > 0) { + out.push({ + type: "RESTING_HEART_RATE", + value: Math.round(s.lowest_heart_rate), + unit: "bpm", + measuredAt, + fieldTag: "rhr", + }); + } + if (typeof s.average_breath === "number" && s.average_breath > 0) { + out.push({ + type: "RESPIRATORY_RATE", + value: round2(s.average_breath), + unit: "breaths/min", + measuredAt, + fieldTag: "resp_rate", + }); + } + return out; +} + +/** Map one Oura daily-activity record: steps + active energy. */ +export function mapDailyActivity(a: OuraDailyActivity): MappedMeasurement[] { + const measuredAt = dayAnchor(a.day, a.timestamp); + if (!measuredAt) return []; + const out: MappedMeasurement[] = []; + if (typeof a.steps === "number" && a.steps >= 0) { + out.push({ + type: "ACTIVITY_STEPS", + value: Math.round(a.steps), + unit: "steps", + measuredAt, + fieldTag: "steps", + }); + } + if (typeof a.active_calories === "number" && a.active_calories >= 0) { + out.push({ + type: "ACTIVE_ENERGY_BURNED", + value: round2(a.active_calories), + unit: "kcal", + measuredAt, + fieldTag: "active_energy", + }); + } + return out; +} + +export const OURA_FIELD_MAP: Record< + string, + { type: string; unit: string; note?: string } +> = { + "daily_readiness.score": { + type: "RECOVERY_SCORE", + unit: "score", + note: "0-100 readiness; feeds recovery ladder below WHOOP", + }, + "sleep.{light,deep,rem}_sleep_duration": { + type: "SLEEP_DURATION", + unit: "minutes", + note: "s->min, one row per stage", + }, + "sleep.awake_time": { + type: "SLEEP_DURATION", + unit: "minutes", + note: "AWAKE stage", + }, + "sleep.efficiency": { type: "SLEEP_EFFICIENCY", unit: "%" }, + "sleep.average_hrv": { type: "HRV_RMSSD", unit: "ms" }, + "sleep.lowest_heart_rate": { type: "RESTING_HEART_RATE", unit: "bpm" }, + "sleep.average_breath": { type: "RESPIRATORY_RATE", unit: "breaths/min" }, + "daily_activity.steps": { type: "ACTIVITY_STEPS", unit: "steps" }, + "daily_activity.active_calories": { + type: "ACTIVE_ENERGY_BURNED", + unit: "kcal", + }, +}; diff --git a/src/lib/oura/credentials.ts b/src/lib/oura/credentials.ts new file mode 100644 index 000000000..ecf9b4200 --- /dev/null +++ b/src/lib/oura/credentials.ts @@ -0,0 +1,50 @@ +/** + * v1.17.0 (F4) — per-user Oura token accessors. + * + * Oura uses a single shared OAuth app (env client id/secret via + * `getOuraCredentials`). Per-user state is the granted access + refresh token, + * stored encrypted on `User`. The merged schema carries NO token-expiry column, + * so the sync layer refreshes REACTIVELY on a 401 rather than proactively on an + * expiry timestamp (and persists both rotated tokens). + */ +import { prisma } from "@/lib/db"; +import { decrypt, encrypt } from "@/lib/crypto"; + +export interface OuraConnection { + accessToken: string; + refreshToken: string; +} + +export async function getOuraConnection( + userId: string, +): Promise { + const user = await prisma.user.findUnique({ + where: { id: userId }, + select: { + ouraAccessTokenEncrypted: true, + ouraRefreshTokenEncrypted: true, + }, + }); + if (!user?.ouraAccessTokenEncrypted || !user?.ouraRefreshTokenEncrypted) { + return null; + } + return { + accessToken: decrypt(user.ouraAccessTokenEncrypted), + refreshToken: decrypt(user.ouraRefreshTokenEncrypted), + }; +} + +/** Persist a rotated token pair after a successful refresh. */ +export async function storeOuraTokens( + userId: string, + accessToken: string, + refreshToken: string, +): Promise { + await prisma.user.update({ + where: { id: userId }, + data: { + ouraAccessTokenEncrypted: encrypt(accessToken), + ouraRefreshTokenEncrypted: encrypt(refreshToken), + }, + }); +} diff --git a/src/lib/oura/response-classifier.ts b/src/lib/oura/response-classifier.ts new file mode 100644 index 000000000..0f3e39ea8 --- /dev/null +++ b/src/lib/oura/response-classifier.ts @@ -0,0 +1,113 @@ +/** + * v1.17.0 (F4) — off-response classifier for Oura Cloud API v2 replies. + * Mirrors the WHOOP / Polar classifiers: HTTP-status-driven. + * + * - `success` → HTTP 2xx + * - `transient` → 429 (rate-limited), 5xx, 3xx, unknown. + * - `reauth_required` → 401 / 403 — token rejected / grant revoked. + * - `persistent` → any other 4xx — malformed request / contract drift. + */ + +export type OuraClassification = + | "success" + | "transient" + | "reauth_required" + | "persistent"; + +export interface ClassifiedOuraResponse { + classification: OuraClassification; + httpStatus: number | undefined; + reason: string; +} + +export function classifyOuraResponse( + httpStatus: number, +): ClassifiedOuraResponse { + if (httpStatus >= 200 && httpStatus < 300) { + return { classification: "success", httpStatus, reason: "ok" }; + } + if (httpStatus === 429) { + return { classification: "transient", httpStatus, reason: "http_429" }; + } + if (httpStatus === 401 || httpStatus === 403) { + return { + classification: "reauth_required", + httpStatus, + reason: `http_${httpStatus}`, + }; + } + if (httpStatus >= 400 && httpStatus < 500) { + return { + classification: "persistent", + httpStatus, + reason: `http_${httpStatus}`, + }; + } + if (httpStatus >= 500 && httpStatus < 600) { + return { + classification: "transient", + httpStatus, + reason: `http_${httpStatus}`, + }; + } + return { + classification: "transient", + httpStatus, + reason: `http_${httpStatus}_unknown`, + }; +} + +export class OuraApiError extends Error { + readonly classification: OuraClassification; + readonly httpStatus: number | undefined; + readonly reason: string; + readonly verb: string; + readonly upstreamError: string | undefined; + + constructor(opts: { + verb: string; + classification: OuraClassification; + httpStatus: number | undefined; + reason: string; + upstreamError?: string; + }) { + const statusLabel = + typeof opts.httpStatus === "number" ? opts.httpStatus : "?"; + const errSegment = opts.upstreamError ? ` - ${opts.upstreamError}` : ""; + const raw = `Oura ${opts.verb} error: ${statusLabel}${errSegment}`; + super(raw.slice(0, 1024)); + this.name = "OuraApiError"; + this.verb = opts.verb; + this.classification = opts.classification; + this.httpStatus = opts.httpStatus; + this.reason = opts.reason; + this.upstreamError = opts.upstreamError; + } +} + +/** + * True when a caught error is an OAuth `invalid_grant` on the token endpoint — + * the canonical revoked-refresh-token signal. Lifts a 400 carrying + * `invalid_grant` from `persistent` to `reauth_required` so the connection + * surfaces the reconnect prompt. + */ +export function isInvalidGrant(err: unknown): boolean { + if (err instanceof OuraApiError) { + if (err.httpStatus !== 400) return false; + if (err.upstreamError === "invalid_grant") return true; + return /\binvalid_grant\b/.test(err.message); + } + const msg = err instanceof Error ? err.message : String(err); + return /Oura\s+\w+\s+error:\s*400\b[\s\S]*\binvalid_grant\b/.test(msg); +} + +export function classifyOuraError(err: unknown): OuraClassification { + if (isInvalidGrant(err)) return "reauth_required"; + if (err instanceof OuraApiError) return err.classification; + const msg = err instanceof Error ? err.message : String(err); + const m = /Oura\s+\w+\s+error:\s*(\d+)/.exec(msg); + if (!m) return "transient"; + const status = Number.parseInt(m[1]!, 10); + if (!Number.isFinite(status)) return "transient"; + return classifyOuraResponse(status).classification; +} diff --git a/src/lib/oura/sync.ts b/src/lib/oura/sync.ts new file mode 100644 index 000000000..cfdafba35 --- /dev/null +++ b/src/lib/oura/sync.ts @@ -0,0 +1,235 @@ +/** + * v1.17.0 (F4) — Oura Cloud v2 sync. + * + * Pulls daily readiness (→ RECOVERY_SCORE), sleep (per-stage durations, + * efficiency, HRV, RHR, respiratory rate), and daily activity (steps + active + * energy) for one connected user, mapping each into `Measurement` rows tagged + * `source = OURA`. + * + * Token model: Oura uses refresh tokens. The merged schema has no expiry + * column, so the sync refreshes REACTIVELY — the first read that 401s triggers + * one refresh (persisting BOTH rotated tokens) and a single retry. A failed + * refresh (`invalid_grant`) records `reauth_required` on the `oura` ledger. + * + * Idempotency: `externalId = ::`, upsert keyed on + * `(userId, type, source = OURA, externalId)`. Oura finalises a day's scores + * after the night, so the `update` branch overwrites in place (re-score). + * + * The measurement-write tail mirrors the shared WHOOP / Nightscout sync tail. + */ +import { prisma } from "@/lib/db"; +import type { MeasurementType } from "@/generated/prisma/client"; +import { getEvent } from "@/lib/logging/context"; +import { + recordSyncFailure, + recordSyncSuccess, + type FailureKind, +} from "@/lib/integrations/status"; +import { + collapseToTypeDayKeys, + recomputeBucketsForMeasurement, +} from "@/lib/rollups/measurement-rollups"; +import { invalidateStatusInsightsForTypes } from "@/lib/insights/comprehensive-generate"; +import { + fetchDailyActivity, + fetchReadiness, + fetchSleep, + getOuraCredentials, + mapDailyActivity, + mapReadiness, + mapSleep, + refreshAccessToken, + type MappedMeasurement, +} from "./client"; +import { getOuraConnection, storeOuraTokens } from "./credentials"; +import { OuraApiError, classifyOuraError } from "./response-classifier"; + +/** Default lookback window (days) for an incremental sync. Oura finalises a + * night's scores hours after wake; 7 days re-fetches a handful of records (the + * upserts are idempotent) and closes any catch-up gap. */ +export const OURA_SYNC_LOOKBACK_DAYS = 7; + +export function classifyOuraFailure(err: unknown): FailureKind { + const c = classifyOuraError(err); + if (c === "reauth_required") return "reauth_required"; + if (c === "persistent") return "persistent"; + return "transient"; +} + +function ymd(d: Date): string { + return d.toISOString().slice(0, 10); +} + +export interface OuraMeasurementUpsert { + type: string; + value: number; + unit: string; + measuredAt: Date; + externalId: string; + sleepStage?: "CORE" | "DEEP" | "REM" | "AWAKE" | null; +} + +function toUpsert( + mapped: MappedMeasurement[], + resourcePrefix: string, +): OuraMeasurementUpsert[] { + return mapped.map((m) => ({ + type: m.type, + value: m.value, + unit: m.unit, + measuredAt: m.measuredAt, + externalId: `${resourcePrefix}:${ymd(m.measuredAt)}:${m.fieldTag}`, + sleepStage: m.sleepStage ?? null, + })); +} + +/** + * Fetch all three Oura collections for a user with a single reactive + * refresh-on-401 retry. Returns the raw mapped readings (not yet upserted). + * Throws a classified `OuraApiError` on a hard failure so the caller records + * the ledger entry. + */ +async function fetchAll( + userId: string, + accessToken: string, + refreshToken: string, + lookbackDays: number, +): Promise { + const now = new Date(); + const start = new Date(now.getTime() - lookbackDays * 24 * 60 * 60 * 1000); + const query = { startDate: ymd(start), endDate: ymd(now) }; + + const run = async (token: string): Promise => { + const [readiness, sleeps, activities] = await Promise.all([ + fetchReadiness(token, query), + fetchSleep(token, query), + fetchDailyActivity(token, query), + ]); + const out: OuraMeasurementUpsert[] = []; + for (const r of readiness) out.push(...toUpsert(mapReadiness(r), "readiness")); + for (const s of sleeps) out.push(...toUpsert(mapSleep(s), "sleep")); + for (const a of activities) out.push(...toUpsert(mapDailyActivity(a), "activity")); + return out; + }; + + try { + return await run(accessToken); + } catch (err) { + // Reactive refresh: a 401 means the access token expired. Refresh once + // (rotating both tokens) and retry. A 403 / other error is NOT a refresh + // case — rethrow so the caller classifies it. + if (!(err instanceof OuraApiError) || err.httpStatus !== 401) throw err; + + const creds = getOuraCredentials(); + if (!creds) throw err; + + const rotated = await refreshAccessToken(refreshToken, creds); + await storeOuraTokens(userId, rotated.access_token, rotated.refresh_token); + return run(rotated.access_token); + } +} + +/** + * Sync one user's Oura data. Returns the count of measurement rows written. + * A user with no Oura connection is a clean no-op (returns 0, touches no + * status row). + */ +export async function syncUserOura( + userId: string, + opts: { lookbackDays?: number } = {}, +): Promise { + const conn = await getOuraConnection(userId); + if (!conn) return 0; + + let readings: OuraMeasurementUpsert[]; + try { + readings = await fetchAll( + userId, + conn.accessToken, + conn.refreshToken, + opts.lookbackDays ?? OURA_SYNC_LOOKBACK_DAYS, + ); + } catch (err) { + await recordSyncFailure({ + userId, + integration: "oura", + kind: classifyOuraFailure(err), + message: err instanceof Error ? err.message : String(err), + errorCode: + err instanceof OuraApiError && err.httpStatus != null + ? String(err.httpStatus) + : undefined, + }); + throw err; + } + + const imported = await upsertOuraMeasurements(userId, readings); + await recordSyncSuccess(userId, "oura"); + return imported; +} + +export async function upsertOuraMeasurements( + userId: string, + readings: OuraMeasurementUpsert[], +): Promise { + if (readings.length === 0) return 0; + + let imported = 0; + const touched: Array<{ type: MeasurementType; measuredAt: Date }> = []; + + for (const r of readings) { + const type = r.type as MeasurementType; + try { + await prisma.measurement.upsert({ + where: { + userId_type_source_externalId: { + userId, + type, + source: "OURA", + externalId: r.externalId, + }, + }, + create: { + userId, + type, + source: "OURA", + value: r.value, + unit: r.unit, + measuredAt: r.measuredAt, + externalId: r.externalId, + sleepStage: r.sleepStage ?? null, + }, + update: { + value: r.value, + unit: r.unit, + measuredAt: r.measuredAt, + sleepStage: r.sleepStage ?? null, + syncVersion: { increment: 1 }, + }, + }); + touched.push({ type, measuredAt: r.measuredAt }); + imported++; + } catch (err) { + getEvent()?.addWarning(`oura: failed to upsert measurement: ${err}`); + } + } + + try { + const keys = collapseToTypeDayKeys(touched); + for (const k of keys) { + await recomputeBucketsForMeasurement(userId, k.type, k.measuredAt); + } + invalidateStatusInsightsForTypes( + userId, + keys.map((k) => k.type), + ).catch((err) => { + getEvent()?.addWarning( + `oura: status-insight invalidate failed for ${userId}: ${err}`, + ); + }); + } catch (err) { + getEvent()?.addWarning(`oura: rollup recompute failed for ${userId}: ${err}`); + } + + return imported; +} diff --git a/src/lib/query-keys/integrations.ts b/src/lib/query-keys/integrations.ts index 97d90909d..17c459337 100644 --- a/src/lib/query-keys/integrations.ts +++ b/src/lib/query-keys/integrations.ts @@ -34,11 +34,13 @@ export const integrationKeys = { nightscout: () => ["nightscout"] as const, nightscoutStatus: () => ["nightscout", "status"] as const, - // v1.17.0 (F4) — Polar OAuth integration card. Self-contained status read - // (not the consolidated /api/integrations/status envelope), so the + // v1.17.0 (F4) — Polar + Oura OAuth integration cards. Self-contained status + // reads (not the consolidated /api/integrations/status envelope), so the // connect/disconnect mutations invalidate these single keys. polar: () => ["polar"] as const, polarStatus: () => ["polar", "status"] as const, + oura: () => ["oura"] as const, + ouraStatus: () => ["oura", "status"] as const, moodlogStatus: () => ["moodlog-status"] as const, integrationsStatus: () => ["integrations", "status"] as const,