diff --git a/src/app/api/google-health/credentials/route.ts b/src/app/api/google-health/credentials/route.ts index e7d11e867..d7edaa328 100644 --- a/src/app/api/google-health/credentials/route.ts +++ b/src/app/api/google-health/credentials/route.ts @@ -6,21 +6,10 @@ import { apiSuccess, apiError, safeJson } from "@/lib/api-response"; import { annotate } from "@/lib/logging/context"; import { encrypt } from "@/lib/crypto"; import { markDisconnected } from "@/lib/integrations/status"; +import { googleHealthCredentialsSchema } from "@/lib/validations/google-health"; import { NextRequest } from "next/server"; import { z } from "zod/v4"; -/** - * Per-user Google Health BYO-key credentials. Each self-hoster registers their - * own Google Cloud OAuth client (the Restricted-scope brand verification + CASA - * assessment is per-OAuth-client, so a single shared app is unworkable for a - * multi-operator product) and pastes the client id/secret into Settings. Stored - * encrypted on `User`. - */ -const googleHealthCredentialsSchema = z.object({ - clientId: z.string().min(1).max(200), - clientSecret: z.string().min(1).max(200), -}); - /** * Check whether the user has Google Health BYO-key credentials stored * (v1.26.0). diff --git a/src/lib/openapi/routes/devices.ts b/src/lib/openapi/routes/devices.ts index 361b31b51..d3534737c 100644 --- a/src/lib/openapi/routes/devices.ts +++ b/src/lib/openapi/routes/devices.ts @@ -92,4 +92,51 @@ export const devicePaths: NonNullable = { }, }, }, + "/api/devices/{id}": { + delete: { + tags: ["Devices"], + summary: "Revoke a device and everything bound to it", + description: + "Deletes the device and, in one transaction, revokes every refresh and access token bound to it — the cleanup a native client runs when it rotates its own registration. The counts come back so the caller can log what the cascade actually killed. Scoped to the caller's own devices: an id belonging to somebody else is indistinguishable from one that does not exist. This is a second URL for `DELETE /api/auth/me/devices/{id}`; the two share one transactional helper and behave identically, and the duplication exists so the native rotation loop has a path that is not the settings-surface one. Auth via cookie or Bearer.", + parameters: [ + { + name: "id", + in: "path", + required: true, + schema: { type: "string" }, + description: "Device id.", + }, + ], + responses: { + "200": { + description: "The device and its tokens were revoked.", + content: { + "application/json": { + schema: dataEnvelope( + z.object({ + id: z.string(), + revoked: z.literal(true), + refreshTokensRevoked: z + .number() + .int() + .describe("Refresh tokens the cascade revoked."), + accessTokensRevoked: z + .number() + .int() + .describe("Access tokens the cascade revoked."), + }), + "DeviceRevokeResponse", + ), + }, + }, + }, + "404": { + description: + "No such device for this caller — also the answer for one already revoked, so a retry after a successful revoke is a 404 rather than an idempotent 200.", + content: { "application/json": { schema: errorEnvelope } }, + }, + ...stdResponses, + }, + }, + }, }; diff --git a/src/lib/openapi/routes/index.ts b/src/lib/openapi/routes/index.ts index 4d91aadcf..b24badb48 100644 --- a/src/lib/openapi/routes/index.ts +++ b/src/lib/openapi/routes/index.ts @@ -72,6 +72,7 @@ import { notificationChannelPaths } from "./notifications"; import { nutrientPaths } from "./nutrients"; import { onboardingPaths } from "./onboarding"; import { profilePaths } from "./profile"; +import { recordSettingsPaths } from "./record-settings"; import { settingsPaths } from "./settings"; import { syncPaths } from "./sync"; import { workoutPaths } from "./workouts"; @@ -137,6 +138,11 @@ export const openApiPaths: NonNullable = { // load-bearing). ...notificationChannelPaths, ...mcpPaths, + // The managed record's own configuration tree. Kept out of the sharing module + // because it is the one surface fenced by `requireGuardianAuth`, and its 403 + // therefore has to be the shared refusal sentence rather than the neighbouring + // module's local wording (appended, spread order is load-bearing). + ...recordSettingsPaths, }; export const openApiComponents: NonNullable = { diff --git a/src/lib/openapi/routes/integrations.ts b/src/lib/openapi/routes/integrations.ts index 9b257147b..7b52b18ff 100644 --- a/src/lib/openapi/routes/integrations.ts +++ b/src/lib/openapi/routes/integrations.ts @@ -1,15 +1,42 @@ /** - * OpenAPI route table — third-party integration config (HealthKit) and the - * per-provider connection surfaces (Nightscout / WHOOP / Withings). + * OpenAPI route table — third-party integrations. + * + * Three families live here: + * + * * the HealthKit config the iOS client drives, + * * the per-provider surfaces under `/api//*` — credentials, + * status, disconnect, sync and the token probe, for Fitbit, Google Health, + * Nightscout, Oura, Polar, Strava, WHOOP and Withings, + * * the cross-provider surfaces under `/api/integrations/*` — the + * consolidated status envelope, the park-resume endpoints and the + * connection probes for the four providers that have one there. + * + * The same verb name does NOT mean the same contract across providers, and the + * descriptions say so per path rather than smoothing it over. Three divergences + * are worth knowing before reading further: + * + * * A disconnect is 404-on-repeat for six providers and an idempotent 200 for + * two. Which is which is stated on each path. + * * `/api//test` answers `{ ok, latencyMs }`; the same-named + * `/api/integrations//test` answers `{ ok, lastSyncedAt, + * latencyMs }`, and the Google Health one additionally accepts a body that + * changes the response shape entirely. + * * `GET /api/withings/status` refreshes and re-persists the OAuth token as a + * side effect. No other status read writes anything. * * Part of the OpenAPI route table; aggregated in `./index.ts`. - * Response DTOs are declared here mirroring the route handler under - * `src/app/api/integrations/healthkit/route.ts`; the request schema - * mirrors the handler's `patchSchema`. + * Response DTOs are declared here mirroring the route handlers; request schemas + * come from `src/lib/validations/*` so the wire contract stays single-source. */ import { z } from "zod/v4"; import type { ZodOpenApiObject } from "zod-openapi"; +import { fitbitCredentialsSchema } from "@/lib/validations/fitbit"; +import { googleHealthCredentialsSchema } from "@/lib/validations/google-health"; +import { ouraCredentialsSchema } from "@/lib/validations/oura"; +import { polarCredentialsSchema } from "@/lib/validations/polar"; +import { stravaCredentialsSchema } from "@/lib/validations/strava"; import { whoopCredentialsSchema } from "@/lib/validations/whoop"; +import { withingsCredentialsSchema } from "@/lib/validations/withings"; import { dataEnvelope, errorEnvelope, stdResponses } from "./shared"; // Mirror the route's `directionEnum` — per-metric sync direction. @@ -465,6 +492,432 @@ const withingsStatusResponse = z "Withings connection status. When no connection row exists the body is exactly `{ connected: false, configured }` — every other field is absent, not null. Note that this read is not side-effect free: a token within 60 s of expiry is refreshed and re-persisted before the response is built, so a GET here can rotate the stored token.", }); +// ── Shapes shared across the provider surfaces ─────────────────────── + +/** Every credentials GET answers exactly this, and never the values. */ +const credentialsPresenceResponse = z + .object({ + hasCredentials: z + .boolean() + .describe( + "Both the client id and the client secret are stored. Neither value is ever returned by any endpoint.", + ), + }) + .meta({ + id: "CredentialsPresenceResponse", + description: + "Presence check for a provider's per-user BYO-key credentials. Presence only — the stored id and secret are write-only.", + }); + +// The BYO-key request bodies. Five providers trim their inputs and two do not +// (Fitbit / Google Health / Withings take the string verbatim); the difference +// is real and is stated per schema rather than averaged away. +const fitbitCredentialsRequest = fitbitCredentialsSchema.meta({ + id: "FitbitCredentialsRequest", + description: + "Per-user Fitbit BYO-key credentials, 1–200 characters each, stored encrypted at rest and never read back. NOT trimmed: a trailing space or newline from the developer portal's copy button is stored verbatim and reaches Fitbit as part of the id.", +}); + +const googleHealthCredentialsRequest = googleHealthCredentialsSchema.meta({ + id: "GoogleHealthCredentialsRequest", + description: + "Per-user Google Health BYO-key credentials — each self-hoster registers their own Google Cloud OAuth client, because the Restricted-scope brand verification and CASA assessment are per-client. 1–200 characters each, stored encrypted, never read back. NOT trimmed.", +}); + +const ouraCredentialsRequest = ouraCredentialsSchema.meta({ + id: "OuraCredentialsRequest", + description: + "Per-user Oura BYO-key credentials. Trimmed on the way in, because a trailing space from the portal's copy button reaches Oura verbatim and answers as 'unknown client'. Stored encrypted, never read back. Leaving these unset is valid: the integration then falls back to the operator's shared env app.", +}); + +const polarCredentialsRequest = polarCredentialsSchema.meta({ + id: "PolarCredentialsRequest", + description: + "Per-user Polar AccessLink BYO-key credentials. Trimmed on the way in. Stored encrypted, never read back. Leaving these unset falls back to the operator's shared env app.", +}); + +const stravaCredentialsRequest = stravaCredentialsSchema.meta({ + id: "StravaCredentialsRequest", + description: + "Per-user Strava BYO-key credentials. Strava caps every newly-created API app at athlete capacity 1, so one shared app cannot serve several self-hosters and each registers their own. Trimmed on the way in. Stored encrypted, never read back. Leaving these unset falls back to the operator's shared env app.", +}); + +const withingsCredentialsRequest = withingsCredentialsSchema.meta({ + id: "WithingsCredentialsRequest", + description: + "Per-user Withings BYO-key credentials, 1–200 characters each, stored encrypted at rest and never read back. NOT trimmed.", +}); + +const updatedAck = z.object({ updated: z.literal(true) }); +const deletedAck = z.object({ deleted: z.literal(true) }); +const disconnectedAck = z.object({ disconnected: z.literal(true) }); + +/** Body refusals shared by every `safeJson(request, { maxBytes: 64 * 1024 })`. */ +const jsonBody64k = { + "400": { + description: "Body is not parseable JSON.", + content: { "application/json": { schema: errorEnvelope } }, + }, + "413": { + description: "Body exceeds 64 KiB.", + content: { "application/json": { schema: errorEnvelope } }, + }, + "415": { + description: "Content-Type is not `application/json`.", + content: { "application/json": { schema: errorEnvelope } }, + }, +}; + +const credentialsRejected422 = { + "422": { + description: + "`clientId` and `clientSecret` are both required and each must be 1–200 characters. The envelope carries a single fixed message, not per-field issues.", + content: { "application/json": { schema: errorEnvelope } }, + }, +}; + +/** + * The token probe under `/api//test` (Nightscout / Oura / Polar / + * Strava). Bare success — no `lastSyncedAt`, which is the difference from the + * same-named probe under `/api/integrations//test`. + */ +const providerProbeResponse = z + .object({ + ok: z.literal(true), + latencyMs: z + .number() + .int() + .describe("Round-trip time of the probe request, in milliseconds."), + }) + .meta({ + id: "ProviderProbeResponse", + description: + "A probe that reached the provider with the stored grant. Only ever returned on success — a failed probe is an error status, never `ok: false`.", + }); + +/** + * The probe under `/api/integrations//test` (Fitbit / Google Health / + * WHOOP / Withings). Same idea, one field more. + */ +const integrationProbeResponse = z + .object({ + ok: z.literal(true), + lastSyncedAt: z.iso + .datetime({ offset: true }) + .nullable() + .describe( + "The connection row's last successful sync; null when it has never synced. Present here and absent from the `/api//test` family — the one shape difference between the two probe families.", + ), + latencyMs: z.number().int(), + }) + .meta({ + id: "IntegrationProbeResponse", + description: + "A probe that reached the provider with a freshly-resolved access token, plus the connection's last sync instant.", + }); + +/** + * The 502 both probe families answer, with the error-code set they share. + * + * The set is identical across Fitbit / Google Health / Oura / Polar / Strava / + * WHOOP / Withings. Two providers add one code of their own and say so on their + * own path: Nightscout adds `url_not_public`, Withings adds + * `upstream_invalid_json`. + */ +const probeFailure502 = { + "502": { + description: + "The probe did not complete. `meta.errorCode` names the class: `credentials_rejected` (the provider answered 401/403 — the stored grant is gone), `rate_limited` (the PROVIDER answered 429, which is not this endpoint's own limiter), `upstream_error` (5xx), `timeout` (no answer within 5 s), `connection_failed` (everything else). The message is fixed per class; the upstream body never reaches the client.", + content: { "application/json": { schema: errorEnvelope } }, + }, +}; + +const probeNotConfigured422 = { + "422": { + description: + "No usable connection for this provider — nothing stored, or the stored grant could no longer be resolved into an access token. `meta.errorCode` = `not_configured`.", + content: { "application/json": { schema: errorEnvelope } }, + }, +}; + +const selfRateLimited429 = { + "429": { + description: + "More than 5 requests in 60 s from this user. `meta.errorCode` = `rate_limited_self` — this is the local limiter, distinct from a `rate_limited` 502 which is the provider's.", + content: { "application/json": { schema: errorEnvelope } }, + }, +}; + +/** + * The manual-sync body. Every sync route parses it the same way and the parse + * is deliberately forgiving: a missing body, an unparseable body and a body + * without the key all mean the same thing — an incremental run. Only a literal + * `true` selects the full-history walk. + */ +const syncTriggerRequest = z + .object({ + fullSync: z + .boolean() + .optional() + .describe( + "`true` walks full history; anything else (including a malformed body, which is swallowed rather than refused) runs the incremental sync.", + ), + }) + .meta({ + id: "SyncTriggerRequest", + description: + "Optional flag-only body for a manual sync. Note that this body is NOT validated: a parse failure silently degrades to `fullSync: false` rather than answering 422, so a client typo reads as a successful incremental run.", + }); + +const syncTriggerOutcome = z + .object({ + imported: z + .number() + .int() + .describe("Rows that reached the database this run."), + failed: z.boolean().describe("True when any part of the run did not land."), + outcome: z + .enum(["empty", "failed", "partial", "success"]) + .describe( + 'Server-resolved tone, never derived from the HTTP status: a run where everything was refused still answers 200 with `outcome: "failed"`.', + ), + fullSync: z.boolean().describe("Echo of the flag this run used."), + }) + .meta({ + id: "SyncTriggerOutcome", + description: + "The result of a manual sync trigger, with the flag echoed back so a client can tell an incremental run from a full one in the response alone.", + }); + +const googleHealthSyncOutcome = syncTriggerOutcome + .extend({ + runId: z + .string() + .optional() + .describe("Truncated to 128 chars. Absent when the run produced none."), + state: z + .enum([ + "in_progress", + "complete", + "partial", + "zero", + "truncated", + "failed", + "interrupted", + ]) + .optional(), + resources: z + .array(googleHealthResourceOutcome) + .max(16) + .optional() + .describe( + "Per-collection outcome, capped at 16 entries and re-sanitised on the way out exactly as the status endpoint does.", + ), + }) + .meta({ + id: "GoogleHealthSyncOutcome", + description: + "The Google Health manual-sync result: the shared outcome plus the run identity and the per-collection breakdown.", + }); + +const resumeResponse = z + .object({ + resumed: z.literal(true), + wasParked: z + .boolean() + .describe( + "Whether the ledger was actually parked before this call. False means the call changed nothing — render it as a no-op rather than a 'resumed' confirmation.", + ), + }) + .meta({ + id: "IntegrationResumeResponse", + description: + "The result of clearing a park. Idempotent: a second call answers 200 with `wasParked: false` and writes no further audit row.", + }); + +/** + * The connection-row status shape Fitbit and Google Health share. WHOOP's is + * the same minus nothing and plus nothing, but it is declared separately above + * because it predates this batch and iOS reads it by its own component name. + */ +function connectionStatusShape() { + return { + connected: z.boolean().describe("A connection row exists."), + configured: z + .boolean() + .describe("Per-user BYO-key client id AND secret are both stored."), + lastSyncedAt: z.iso.datetime({ offset: true }).nullable().optional(), + connectedAt: z.iso.datetime({ offset: true }).optional(), + tokenExpired: z + .boolean() + .optional() + .describe( + "Read straight off the row — this endpoint does not refresh; the sync path refreshes lazily.", + ), + tokenExpiresAt: z.iso.datetime({ offset: true }).optional(), + backfillCompleted: z + .boolean() + .optional() + .describe("The history backfill has walked every collection."), + scope: z + .string() + .nullable() + .optional() + .describe( + "OAuth scope string granted at authorisation. Null on a legacy connection that predates scope tracking.", + ), + }; +} + +const fitbitStatusResponse = z.object(connectionStatusShape()).meta({ + id: "FitbitStatusResponse", + description: + "Fitbit connection status. When no connection row exists the body is exactly `{ connected: false, configured }` — every other field is absent, not null. Pure read.", +}); + +const googleHealthStatusResponse = z + .object({ + ...connectionStatusShape(), + needsReauth: z + .boolean() + .optional() + .describe( + "The stored refresh token was rejected with `invalid_grant` — Google expires it after 7 days while the OAuth client is in Testing publishing mode, and a user-revoked grant lands here too. Distinct from `parked` and from `disconnected`: the connection still exists, it just cannot mint a token until the user reconnects. Only Google Health has this field.", + ), + }) + .meta({ + id: "GoogleHealthStatusResponse", + description: + "Google Health connection status. When no connection row exists the body is exactly `{ connected: false, configured }` — every other field is absent, not null. Pure read.", + }); + +/** + * Oura / Polar / Strava share one status shape. They differ from the + * connection-row providers in that `configured` MIRRORS `connected` rather than + * reporting credentials: there is no "credentials saved but disconnected" state + * on these three, and `hasOwnCredentials` is the field that reports the BYO + * pair instead. + */ +const oauthProviderStatusResponse = z + .object({ + connected: z.boolean().describe("An access token is stored."), + configured: z + .boolean() + .describe( + "Mirrors `connected` exactly on these three providers. It is NOT a credentials marker — read `hasOwnCredentials` for that.", + ), + available: z + .boolean() + .describe( + "Usable OAuth client credentials resolve for this user: the per-user BYO pair first, then the operator's shared env app. False means the connect button cannot work at all.", + ), + hasOwnCredentials: z + .boolean() + .describe("The user has stored their own BYO client id and secret."), + state: integrationLedgerState.optional(), + lastSuccessAt: z.iso.datetime({ offset: true }).nullable().optional(), + lastAttemptAt: z.iso.datetime({ offset: true }).nullable().optional(), + lastError: z.string().nullable().optional(), + syncHealth: syncHealth.optional(), + }) + .meta({ + id: "OAuthProviderStatusResponse", + description: + "Connection status for an OAuth provider whose grant lives on the user row (Oura / Polar / Strava). When no token is stored the body is exactly `{ connected: false, configured: false, available, hasOwnCredentials }` — the ledger fields are absent, not null. Tokens and client secrets are never returned. Pure read.", + }); + +// ── The consolidated envelope (`GET /api/integrations/status`) ─────── + +const consecutiveFailuresByKind = z + .object({ + transient: z.number().int(), + reauth_required: z.number().int(), + persistent: z.number().int(), + }) + .nullable() + .describe( + "Per-kind consecutive-failure counters, or null when the row has never written a bucket payload. Compare against the top-level `threshold` to know how close the provider is to the operator alert.", + ); + +const integrationEnvelopeEntry = z + .object({ + integration: z + .enum([ + "withings", + "whoop", + "fitbit", + "google-health", + "polar", + "oura", + "strava", + "nightscout", + ]) + .describe("Which provider this entry describes."), + state: integrationLedgerState, + lastSuccessAt: z.iso.datetime({ offset: true }).nullable(), + lastAttemptAt: z.iso.datetime({ offset: true }).nullable(), + lastError: z.string().nullable(), + consecutiveFailuresByKind, + syncHealth, + metricFreshness: z + .array(metricFreshnessEntry) + .describe( + "Per-metric-type freshness for this provider's data. Empty when the provider has delivered nothing, and also empty when the freshness read itself failed — the endpoint degrades to no data rather than failing the whole envelope, so an empty list is not proof of no data.", + ), + connected: z.boolean(), + configured: z.boolean(), + connectedAt: z.iso.datetime({ offset: true }).nullable().optional(), + legacyLastSyncedAt: z.iso + .datetime({ offset: true }) + .nullable() + .optional() + .describe( + "The connection row's own last-sync instant, for legacy connections established before the ledger existed. Not present on the three user-row OAuth providers or on Nightscout.", + ), + tokenExpiresAt: z.iso.datetime({ offset: true }).nullable().optional(), + tokenExpired: z + .boolean() + .nullable() + .optional() + .describe("Null — not false — when there is no connection to judge."), + backfillCompleted: z.boolean().nullable().optional(), + scope: z.string().nullable().optional().describe("Withings only."), + hasActivityScope: z.boolean().optional().describe("Withings only."), + needsReauth: z.boolean().optional().describe("Google Health only."), + available: z.boolean().optional().describe("Oura / Polar / Strava only."), + hasOwnCredentials: z + .boolean() + .optional() + .describe("Oura / Polar / Strava only."), + hasToken: z.boolean().optional().describe("Nightscout only."), + allowPrivateHost: z.boolean().optional().describe("Nightscout only."), + }) + .meta({ + id: "IntegrationStatusEntry", + description: + "One provider's entry in the consolidated envelope: the ledger core and the liveness verdict, which every entry carries, plus the extras that provider has. The optional fields are not optional per request — each is present exactly for the providers named in its description and absent for the rest, so branch on `integration`, not on presence.", + }); + +const integrationStatusEnvelope = z + .object({ + threshold: z + .number() + .int() + .describe( + "Consecutive persistent failures at which the operator is alerted. Operator-level, configurable via env.", + ), + integrations: z + .array(integrationEnvelopeEntry) + .describe( + "All eight providers, always, in the fixed order withings, whoop, fitbit, google-health, polar, oura, strava, nightscout. A provider the user has never touched still appears, with `connected: false` and a synthesised `connected` ledger state — absence from this list never means anything, because nothing is ever absent from it.", + ), + }) + .meta({ + id: "IntegrationStatusEnvelope", + description: + "The one read behind the integrations settings surface. It carries every field the per-provider status routes carry, so a client has the choice of eight round-trips or this one; the per-provider routes remain for callers that want a single provider.", + }); + export const integrationPaths: NonNullable = { "/api/integrations/healthkit": { get: { @@ -875,4 +1328,1124 @@ export const integrationPaths: NonNullable = { }, }, }, + "/api/withings/credentials": { + get: { + tags: ["Integrations"], + summary: "Check whether Withings BYO-key credentials are stored", + description: "Presence only. Auth via cookie or Bearer.", + responses: { + "200": { + description: "Credential presence.", + content: { + "application/json": { + schema: dataEnvelope( + credentialsPresenceResponse, + "WithingsCredentialsStatusEnvelope", + ), + }, + }, + }, + ...stdResponses, + }, + }, + put: { + tags: ["Integrations"], + summary: "Store the caller's Withings BYO-key credentials", + description: + "Replaces both values; there is no partial update. Auth via cookie or Bearer.", + requestBody: { + required: true, + content: { + "application/json": { schema: withingsCredentialsRequest }, + }, + }, + responses: { + "200": { + description: "Credentials stored.", + content: { + "application/json": { + schema: dataEnvelope( + updatedAck, + "WithingsCredentialsUpdateEnvelope", + ), + }, + }, + }, + ...jsonBody64k, + ...stdResponses, + ...credentialsRejected422, + }, + }, + delete: { + tags: ["Integrations"], + summary: "Delete the caller's Withings credentials and connection", + description: + "Deletes the connection row (with its encrypted OAuth tokens) and clears both credential columns. Idempotent — a missing connection row is a benign no-op, so a repeat call still answers 200. Unlike every sibling provider's credential DELETE, this one writes NO audit row and does NOT park the `withings` ledger: the ledger keeps whatever state it last held, so a client should not read `state` as proof of a live connection after this call. Auth via cookie or Bearer.", + responses: { + "200": { + description: "Credentials and connection removed.", + content: { + "application/json": { + schema: dataEnvelope( + deletedAck, + "WithingsCredentialsDeleteEnvelope", + ), + }, + }, + }, + ...stdResponses, + }, + }, + }, + "/api/withings/sync": { + post: { + tags: ["Integrations"], + summary: "Trigger a Withings sync", + description: + "Incremental by default; `{ fullSync: true }` walks full history. NOT rate-limited — the only manual sync in this group without a limiter, alongside WHOOP's. Auth via cookie or Bearer.", + requestBody: { + required: false, + content: { "application/json": { schema: syncTriggerRequest } }, + }, + responses: { + "200": { + description: "Sync run complete.", + content: { + "application/json": { + schema: dataEnvelope( + syncTriggerOutcome, + "WithingsSyncTriggerEnvelope", + ), + }, + }, + }, + "413": { + description: "Body exceeds 64 KiB.", + content: { "application/json": { schema: errorEnvelope } }, + }, + ...stdResponses, + }, + }, + }, + "/api/whoop/sync": { + post: { + tags: ["Integrations"], + summary: "Trigger a WHOOP sync", + description: + "Incremental by default; `{ fullSync: true }` walks full history. NOT rate-limited — the only manual sync in this group without a limiter, alongside Withings'. Auth via cookie or Bearer.", + requestBody: { + required: false, + content: { "application/json": { schema: syncTriggerRequest } }, + }, + responses: { + "200": { + description: "Sync run complete.", + content: { + "application/json": { + schema: dataEnvelope( + syncTriggerOutcome, + "WhoopSyncTriggerEnvelope", + ), + }, + }, + }, + "413": { + description: "Body exceeds 64 KiB.", + content: { "application/json": { schema: errorEnvelope } }, + }, + ...stdResponses, + }, + }, + }, + "/api/whoop/connect/ticket": { + post: { + tags: ["Integrations"], + summary: "Mint a one-time WHOOP connect ticket", + description: + "Bearer-capable by design: a native client with no browser session mints a ticket here, then opens `GET /api/whoop/connect?ticket=` in an in-app web session to run the WHOOP OAuth handshake. THE RESPONSE CARRIES THE RAW TICKET — only its hash is stored, so it cannot be retrieved again; it is short-lived and single-use. No body. Rate-limited 10 requests / 60 s per user. Auth via cookie or Bearer.", + responses: { + "200": { + description: + "Ticket minted. The `ticket` field is the only copy of the credential.", + content: { + "application/json": { + schema: dataEnvelope( + z.object({ + ticket: z + .string() + .describe( + "Opaque one-time connect ticket, returned exactly once. Treat as a secret: pass it only as the `ticket` query parameter of the connect URL, and never log it.", + ), + }), + "WhoopConnectTicketEnvelope", + ), + }, + }, + }, + "400": { + description: + "No WHOOP client id and secret are stored for this user, so a ticket could not complete the handshake. Store the credentials first. Note that this is 400, not the 422 the probe endpoints answer for the same condition.", + content: { "application/json": { schema: errorEnvelope } }, + }, + ...stdResponses, + "429": { + description: "More than 10 ticket mints in 60 s from this user.", + content: { "application/json": { schema: errorEnvelope } }, + }, + }, + }, + }, + "/api/fitbit/credentials": { + get: { + tags: ["Integrations"], + summary: "Check whether Fitbit BYO-key credentials are stored", + description: "Presence only. Auth via cookie or Bearer.", + responses: { + "200": { + description: "Credential presence.", + content: { + "application/json": { + schema: dataEnvelope( + credentialsPresenceResponse, + "FitbitCredentialsStatusEnvelope", + ), + }, + }, + }, + ...stdResponses, + }, + }, + put: { + tags: ["Integrations"], + summary: "Store the caller's Fitbit BYO-key credentials", + description: + "Replaces both values; there is no partial update. Auth via cookie or Bearer.", + requestBody: { + required: true, + content: { "application/json": { schema: fitbitCredentialsRequest } }, + }, + responses: { + "200": { + description: "Credentials stored.", + content: { + "application/json": { + schema: dataEnvelope( + updatedAck, + "FitbitCredentialsUpdateEnvelope", + ), + }, + }, + }, + ...jsonBody64k, + ...stdResponses, + ...credentialsRejected422, + }, + }, + delete: { + tags: ["Integrations"], + summary: "Delete the caller's Fitbit credentials and connection", + description: + "Deletes the connection row, clears both credential columns, audits the teardown and parks the `fitbit` ledger at `disconnected`. Idempotent — a missing connection row is a benign no-op, so a repeat call still answers 200. Auth via cookie or Bearer.", + responses: { + "200": { + description: "Credentials and connection removed.", + content: { + "application/json": { + schema: dataEnvelope( + deletedAck, + "FitbitCredentialsDeleteEnvelope", + ), + }, + }, + }, + ...stdResponses, + }, + }, + }, + "/api/fitbit/status": { + get: { + tags: ["Integrations"], + summary: "Read the caller's Fitbit connection status", + description: + "Reports the BYO-key marker plus the connection row's last sync, token expiry, granted scope and backfill progress. Pure read — no refresh, no ledger write. Auth via cookie or Bearer.", + responses: { + "200": { + description: "Connection status.", + content: { + "application/json": { + schema: dataEnvelope( + fitbitStatusResponse, + "FitbitStatusEnvelope", + ), + }, + }, + }, + ...stdResponses, + }, + }, + }, + "/api/fitbit/disconnect": { + post: { + tags: ["Integrations"], + summary: "Disconnect the caller's Fitbit account", + description: + "Deletes the connection row, audits the teardown and parks the `fitbit` ledger at `disconnected`. There is nothing to unsubscribe upstream — the integration polls. The BYO-key credentials are deliberately LEFT IN PLACE so a reconnect does not force the user to re-paste them; use the credentials DELETE to remove those too. No body. Auth via cookie or Bearer.", + responses: { + "200": { + description: "The connection was removed.", + content: { + "application/json": { + schema: dataEnvelope(disconnectedAck, "FitbitDisconnectEnvelope"), + }, + }, + }, + "404": { + description: + "No Fitbit connection to remove. NOT an idempotent no-op: a second disconnect answers 404 rather than 200.", + content: { "application/json": { schema: errorEnvelope } }, + }, + ...stdResponses, + }, + }, + }, + "/api/fitbit/sync": { + post: { + tags: ["Integrations"], + summary: "Trigger a Fitbit sync", + description: + "Incremental by default; `{ fullSync: true }` walks full history across four paginated resources. Two limiters apply: 5 requests / 60 s for any run, and additionally 1 per hour for a full one, because the classic Web API budget is 150 requests per hour per user. Auth via cookie or Bearer.", + requestBody: { + required: false, + content: { "application/json": { schema: syncTriggerRequest } }, + }, + responses: { + "200": { + description: "Sync run complete.", + content: { + "application/json": { + schema: dataEnvelope( + syncTriggerOutcome, + "FitbitSyncTriggerEnvelope", + ), + }, + }, + }, + "413": { + description: "Body exceeds 64 KiB.", + content: { "application/json": { schema: errorEnvelope } }, + }, + ...stdResponses, + "429": { + description: + "Either limiter tripped: more than 5 syncs in 60 s, or a second full sync within the hour. `meta.errorCode` = `rate_limited_self` for both; the message distinguishes them.", + content: { "application/json": { schema: errorEnvelope } }, + }, + }, + }, + }, + "/api/google-health/credentials": { + get: { + tags: ["Integrations"], + summary: "Check whether Google Health BYO-key credentials are stored", + description: "Presence only. Auth via cookie or Bearer.", + responses: { + "200": { + description: "Credential presence.", + content: { + "application/json": { + schema: dataEnvelope( + credentialsPresenceResponse, + "GoogleHealthCredentialsStatusEnvelope", + ), + }, + }, + }, + ...stdResponses, + }, + }, + put: { + tags: ["Integrations"], + summary: "Store the caller's Google Health BYO-key credentials", + description: + "Replaces both values; there is no partial update. Auth via cookie or Bearer.", + requestBody: { + required: true, + content: { + "application/json": { schema: googleHealthCredentialsRequest }, + }, + }, + responses: { + "200": { + description: "Credentials stored.", + content: { + "application/json": { + schema: dataEnvelope( + updatedAck, + "GoogleHealthCredentialsUpdateEnvelope", + ), + }, + }, + }, + ...jsonBody64k, + ...stdResponses, + ...credentialsRejected422, + }, + }, + delete: { + tags: ["Integrations"], + summary: "Delete the caller's Google Health credentials and connection", + description: + "Deletes the connection row, clears both credential columns, audits the teardown and parks the `google-health` ledger at `disconnected`. Idempotent — a missing connection row is a benign no-op, so a repeat call still answers 200. Auth via cookie or Bearer.", + responses: { + "200": { + description: "Credentials and connection removed.", + content: { + "application/json": { + schema: dataEnvelope( + deletedAck, + "GoogleHealthCredentialsDeleteEnvelope", + ), + }, + }, + }, + ...stdResponses, + }, + }, + }, + "/api/google-health/status": { + get: { + tags: ["Integrations"], + summary: "Read the caller's Google Health connection status", + description: + "Reports the BYO-key marker plus the connection row's last sync, token expiry, granted scope, backfill progress and the `needsReauth` soft-disconnect flag. Pure read — no refresh, no ledger write. Auth via cookie or Bearer.", + responses: { + "200": { + description: "Connection status.", + content: { + "application/json": { + schema: dataEnvelope( + googleHealthStatusResponse, + "GoogleHealthStatusEnvelope", + ), + }, + }, + }, + ...stdResponses, + }, + }, + }, + "/api/google-health/disconnect": { + post: { + tags: ["Integrations"], + summary: "Disconnect the caller's Google Health account", + description: + "Deletes the connection row, audits the teardown and parks the `google-health` ledger at `disconnected`. Deleting the encrypted token pair is the effective revocation; there is no subscription to tear down. The BYO-key credentials are deliberately LEFT IN PLACE. No body. Auth via cookie or Bearer.", + responses: { + "200": { + description: "The connection was removed.", + content: { + "application/json": { + schema: dataEnvelope( + disconnectedAck, + "GoogleHealthDisconnectEnvelope", + ), + }, + }, + }, + "404": { + description: + "No Google Health connection to remove. NOT an idempotent no-op: a second disconnect answers 404 rather than 200.", + content: { "application/json": { schema: errorEnvelope } }, + }, + ...stdResponses, + }, + }, + }, + "/api/google-health/sync": { + post: { + tags: ["Integrations"], + summary: "Trigger a Google Health sync", + description: + 'Incremental by default; `{ fullSync: true }` walks full history across every data type, each capped at 1000 pages. Two limiters apply: 5 requests / 60 s for any run, and additionally 1 per hour for a full one. Unlike every sibling sync, this one can answer 502: a run that failed AND wrote nothing is an error, while a run that failed after writing some resources is a 200 with `outcome: "partial"` — the honest half of the result is not thrown away. Auth via cookie or Bearer.', + requestBody: { + required: false, + content: { "application/json": { schema: syncTriggerRequest } }, + }, + responses: { + "200": { + description: + "Sync run complete, wholly or partly. Carries the per-collection breakdown.", + content: { + "application/json": { + schema: dataEnvelope( + googleHealthSyncOutcome, + "GoogleHealthSyncTriggerEnvelope", + ), + }, + }, + }, + "413": { + description: "Body exceeds 64 KiB.", + content: { "application/json": { schema: errorEnvelope } }, + }, + "502": { + description: + "The run failed and wrote nothing. A run that wrote something before failing answers 200 instead.", + content: { "application/json": { schema: errorEnvelope } }, + }, + ...stdResponses, + "429": { + description: + "Either limiter tripped: more than 5 syncs in 60 s, or a second full sync within the hour. `meta.errorCode` = `rate_limited_self`.", + content: { "application/json": { schema: errorEnvelope } }, + }, + }, + }, + }, + "/api/oura/credentials": { + get: { + tags: ["Integrations"], + summary: "Check whether Oura BYO-key credentials are stored", + description: + "Presence only. `false` is not a misconfiguration: with no BYO pair the integration falls back to the operator's shared env app. Auth via cookie or Bearer.", + responses: { + "200": { + description: "Credential presence.", + content: { + "application/json": { + schema: dataEnvelope( + credentialsPresenceResponse, + "OuraCredentialsStatusEnvelope", + ), + }, + }, + }, + ...stdResponses, + }, + }, + put: { + tags: ["Integrations"], + summary: "Store the caller's Oura BYO-key credentials", + description: + "Replaces both values; there is no partial update. Auth via cookie or Bearer.", + requestBody: { + required: true, + content: { "application/json": { schema: ouraCredentialsRequest } }, + }, + responses: { + "200": { + description: "Credentials stored.", + content: { + "application/json": { + schema: dataEnvelope(updatedAck, "OuraCredentialsUpdateEnvelope"), + }, + }, + }, + ...jsonBody64k, + ...stdResponses, + ...credentialsRejected422, + }, + }, + delete: { + tags: ["Integrations"], + summary: "Delete the caller's Oura credentials and connection", + description: + "Clears the stored access and refresh tokens as well as the BYO pair — a token minted against a deleted app is orphaned, so the grant goes with the keys. Always answers 200. The audit row and the ledger park are written only when a token was actually present, so tearing down an unconnected credential pair leaves no audit trail. Auth via cookie or Bearer.", + responses: { + "200": { + description: "Credentials and any connection removed.", + content: { + "application/json": { + schema: dataEnvelope(deletedAck, "OuraCredentialsDeleteEnvelope"), + }, + }, + }, + ...stdResponses, + }, + }, + }, + "/api/oura/status": { + get: { + tags: ["Integrations"], + summary: "Read the caller's Oura connection status", + description: + "Reports whether usable credentials resolve at all, whether the user brought their own, and the ledger snapshot plus liveness verdict when a token is stored. Tokens and the client secret are never returned. Pure read. Auth via cookie or Bearer.", + responses: { + "200": { + description: "Connection status.", + content: { + "application/json": { + schema: dataEnvelope( + oauthProviderStatusResponse, + "OuraStatusEnvelope", + ), + }, + }, + }, + ...stdResponses, + }, + }, + }, + "/api/oura/disconnect": { + post: { + tags: ["Integrations"], + summary: "Disconnect the caller's Oura account", + description: + "Clears the stored access and refresh tokens, audits the teardown and parks the `oura` ledger at `disconnected`. The BYO-key credentials are left in place. Imported readings stay; a reconnect resumes sync. No body. Rate-limited 20 requests / 60 s per user. Auth via cookie or Bearer.", + responses: { + "200": { + description: "The connection was cleared.", + content: { + "application/json": { + schema: dataEnvelope(disconnectedAck, "OuraDisconnectEnvelope"), + }, + }, + }, + "404": { + description: + "No Oura token stored. NOT an idempotent no-op: a second disconnect answers 404 rather than 200.", + content: { "application/json": { schema: errorEnvelope } }, + }, + ...stdResponses, + }, + }, + }, + "/api/oura/test": { + post: { + tags: ["Integrations"], + summary: "Probe the caller's Oura grant", + description: + "Fetches the personal-info record, the cheapest authenticated Oura call, to confirm the stored grant still works. No body, nothing written. Rate-limited 5 requests / 60 s per user. Auth via cookie or Bearer.", + responses: { + "200": { + description: "The probe reached Oura.", + content: { + "application/json": { + schema: dataEnvelope(providerProbeResponse, "OuraTestEnvelope"), + }, + }, + }, + ...probeFailure502, + ...stdResponses, + ...probeNotConfigured422, + ...selfRateLimited429, + }, + }, + }, + "/api/polar/credentials": { + get: { + tags: ["Integrations"], + summary: "Check whether Polar BYO-key credentials are stored", + description: + "Presence only. `false` is not a misconfiguration: with no BYO pair the integration falls back to the operator's shared env app. Auth via cookie or Bearer.", + responses: { + "200": { + description: "Credential presence.", + content: { + "application/json": { + schema: dataEnvelope( + credentialsPresenceResponse, + "PolarCredentialsStatusEnvelope", + ), + }, + }, + }, + ...stdResponses, + }, + }, + put: { + tags: ["Integrations"], + summary: "Store the caller's Polar BYO-key credentials", + description: + "Replaces both values; there is no partial update. Audits the write — the only credentials PUT in this group that does. Auth via cookie or Bearer.", + requestBody: { + required: true, + content: { "application/json": { schema: polarCredentialsRequest } }, + }, + responses: { + "200": { + description: "Credentials stored.", + content: { + "application/json": { + schema: dataEnvelope( + updatedAck, + "PolarCredentialsUpdateEnvelope", + ), + }, + }, + }, + ...jsonBody64k, + ...stdResponses, + ...credentialsRejected422, + }, + }, + delete: { + tags: ["Integrations"], + summary: "Delete the caller's Polar credentials and connection", + description: + "Clears the stored access token and member id as well as the BYO pair — a token minted under a deleted AccessLink app is orphaned, so the grant goes with the keys. Always answers 200, and unlike Oura's and Strava's equivalents it audits and parks the ledger unconditionally, whether or not a token was present. Auth via cookie or Bearer.", + responses: { + "200": { + description: "Credentials and any connection removed.", + content: { + "application/json": { + schema: dataEnvelope( + deletedAck, + "PolarCredentialsDeleteEnvelope", + ), + }, + }, + }, + ...stdResponses, + }, + }, + }, + "/api/polar/status": { + get: { + tags: ["Integrations"], + summary: "Read the caller's Polar connection status", + description: + "Reports whether usable credentials resolve at all, whether the user brought their own, and the ledger snapshot plus liveness verdict when a token is stored. The access token, member id and client secret are never returned. Pure read. Auth via cookie or Bearer.", + responses: { + "200": { + description: "Connection status.", + content: { + "application/json": { + schema: dataEnvelope( + oauthProviderStatusResponse, + "PolarStatusEnvelope", + ), + }, + }, + }, + ...stdResponses, + }, + }, + }, + "/api/polar/disconnect": { + post: { + tags: ["Integrations"], + summary: "Disconnect the caller's Polar account", + description: + "Clears the stored token and member id, audits the teardown and parks the `polar` ledger at `disconnected`. The BYO-key credentials are left in place. Imported readings stay. No body. Rate-limited 20 requests / 60 s per user. Auth via cookie or Bearer.", + responses: { + "200": { + description: "The connection was cleared.", + content: { + "application/json": { + schema: dataEnvelope(disconnectedAck, "PolarDisconnectEnvelope"), + }, + }, + }, + "404": { + description: + "No Polar token stored. NOT an idempotent no-op: a second disconnect answers 404 rather than 200.", + content: { "application/json": { schema: errorEnvelope } }, + }, + ...stdResponses, + }, + }, + }, + "/api/polar/test": { + post: { + tags: ["Integrations"], + summary: "Probe the caller's Polar grant", + description: + "Fetches the registered AccessLink user record, the cheapest authenticated Polar call, to confirm the stored grant still works. No body, nothing written. Rate-limited 5 requests / 60 s per user. Auth via cookie or Bearer.", + responses: { + "200": { + description: "The probe reached Polar.", + content: { + "application/json": { + schema: dataEnvelope(providerProbeResponse, "PolarTestEnvelope"), + }, + }, + }, + ...probeFailure502, + ...stdResponses, + ...probeNotConfigured422, + ...selfRateLimited429, + }, + }, + }, + "/api/strava/credentials": { + get: { + tags: ["Integrations"], + summary: "Check whether Strava BYO-key credentials are stored", + description: + "Presence only. `false` is not a misconfiguration: with no BYO pair the integration falls back to the operator's shared env app. Auth via cookie or Bearer.", + responses: { + "200": { + description: "Credential presence.", + content: { + "application/json": { + schema: dataEnvelope( + credentialsPresenceResponse, + "StravaCredentialsStatusEnvelope", + ), + }, + }, + }, + ...stdResponses, + }, + }, + put: { + tags: ["Integrations"], + summary: "Store the caller's Strava BYO-key credentials", + description: + "Replaces both values; there is no partial update. Auth via cookie or Bearer.", + requestBody: { + required: true, + content: { "application/json": { schema: stravaCredentialsRequest } }, + }, + responses: { + "200": { + description: "Credentials stored.", + content: { + "application/json": { + schema: dataEnvelope( + updatedAck, + "StravaCredentialsUpdateEnvelope", + ), + }, + }, + }, + ...jsonBody64k, + ...stdResponses, + ...credentialsRejected422, + }, + }, + delete: { + tags: ["Integrations"], + summary: "Delete the caller's Strava credentials and connection", + description: + "Clears the stored access token, refresh token and athlete id as well as the BYO pair. Always answers 200. The audit row and the ledger park are written only when a token was actually present. Note that this path does NOT deauthorize at Strava — only `POST /api/strava/disconnect` does, so removing the credentials here leaves the app authorised on the user's Strava account. Auth via cookie or Bearer.", + responses: { + "200": { + description: "Credentials and any connection removed.", + content: { + "application/json": { + schema: dataEnvelope( + deletedAck, + "StravaCredentialsDeleteEnvelope", + ), + }, + }, + }, + ...stdResponses, + }, + }, + }, + "/api/strava/status": { + get: { + tags: ["Integrations"], + summary: "Read the caller's Strava connection status", + description: + "Reports whether usable credentials resolve at all, whether the user brought their own, and the ledger snapshot plus liveness verdict when a token is stored. Tokens and the client secret are never returned. Pure read. Auth via cookie or Bearer.", + responses: { + "200": { + description: "Connection status.", + content: { + "application/json": { + schema: dataEnvelope( + oauthProviderStatusResponse, + "StravaStatusEnvelope", + ), + }, + }, + }, + ...stdResponses, + }, + }, + }, + "/api/strava/disconnect": { + post: { + tags: ["Integrations"], + summary: "Disconnect the caller's Strava account", + description: + "Best-effort deauthorizes at Strava, then clears the stored tokens and athlete id, audits the teardown and parks the `strava` ledger at `disconnected`. A Strava-side outage does not block the local teardown, so a 200 here does not prove the app was deauthorised upstream. Imported workouts stay. No body. Rate-limited 20 requests / 60 s per user. Auth via cookie or Bearer.", + responses: { + "200": { + description: "The connection was cleared locally.", + content: { + "application/json": { + schema: dataEnvelope(disconnectedAck, "StravaDisconnectEnvelope"), + }, + }, + }, + "404": { + description: + "No Strava connection. NOT an idempotent no-op: a second disconnect answers 404 rather than 200.", + content: { "application/json": { schema: errorEnvelope } }, + }, + ...stdResponses, + }, + }, + }, + "/api/strava/test": { + post: { + tags: ["Integrations"], + summary: "Probe the caller's Strava grant", + description: + "Fetches the authenticated athlete, the cheapest authenticated Strava call, to confirm the stored grant still works. No body, nothing written. Rate-limited 5 requests / 60 s per user. Auth via cookie or Bearer.", + responses: { + "200": { + description: "The probe reached Strava.", + content: { + "application/json": { + schema: dataEnvelope(providerProbeResponse, "StravaTestEnvelope"), + }, + }, + }, + ...probeFailure502, + ...stdResponses, + ...probeNotConfigured422, + ...selfRateLimited429, + }, + }, + }, + "/api/integrations/status": { + get: { + tags: ["Integrations"], + summary: "Read every integration's status in one call", + description: + "The consolidated envelope behind the integrations settings surface: all eight providers, always, in a fixed order, each with the ledger core, the server-resolved liveness verdict and its own extras. Prefer this over eight per-provider round-trips. Pure read. Auth via cookie or Bearer.", + responses: { + "200": { + description: "All eight provider entries plus the alert threshold.", + content: { + "application/json": { + schema: dataEnvelope( + integrationStatusEnvelope, + "IntegrationStatusEnvelopeResponse", + ), + }, + }, + }, + ...stdResponses, + }, + }, + }, + "/api/integrations/fitbit/resume": { + post: { + tags: ["Integrations"], + summary: "Clear a parked Fitbit integration", + description: + "A provider whose persistent-failure streak has run for more than 24 h is parked, and the sync entry point short-circuits until somebody clears it. This clears it; the next cron tick attempts again. No body, no upstream call. Rate-limited 5 requests / 60 s per user. Auth via cookie or Bearer.", + responses: { + "200": { + description: "Park cleared, or nothing to clear.", + content: { + "application/json": { + schema: dataEnvelope(resumeResponse, "FitbitResumeEnvelope"), + }, + }, + }, + ...stdResponses, + ...selfRateLimited429, + }, + }, + }, + "/api/integrations/fitbit/test": { + post: { + tags: ["Integrations"], + summary: "Probe the caller's Fitbit connection", + description: + "Resolves a valid access token (refreshing if needed) and fetches the profile endpoint. Returns the connection's `lastSyncedAt` alongside the probe result — the shape difference from the `/api//test` family. No body, nothing written beyond whatever the token refresh persists. Rate-limited 5 requests / 60 s per user. Auth via cookie or Bearer.", + responses: { + "200": { + description: "The probe reached Fitbit.", + content: { + "application/json": { + schema: dataEnvelope( + integrationProbeResponse, + "FitbitIntegrationTestEnvelope", + ), + }, + }, + }, + ...probeFailure502, + ...stdResponses, + ...probeNotConfigured422, + ...selfRateLimited429, + }, + }, + }, + "/api/integrations/google-health/resume": { + post: { + tags: ["Integrations"], + summary: "Clear a parked Google Health integration", + description: + "Identical contract to the Fitbit / WHOOP / Withings resume endpoints — same body (none), same response, same limiter. Auth via cookie or Bearer.", + responses: { + "200": { + description: "Park cleared, or nothing to clear.", + content: { + "application/json": { + schema: dataEnvelope( + resumeResponse, + "GoogleHealthResumeEnvelope", + ), + }, + }, + }, + ...stdResponses, + ...selfRateLimited429, + }, + }, + }, + "/api/integrations/google-health/test": { + post: { + tags: ["Integrations"], + summary: "Probe the caller's Google Health connection", + description: + 'Two endpoints in one, selected by the body. With no body (or any body other than the one below) it behaves like its Fitbit / WHOOP / Withings siblings: fetch the profile endpoint and answer `{ ok, lastSyncedAt, latencyMs }`. With `{ "probe": "structure" }` it instead walks one page or window per Google Health data type and answers a per-type diagnostic map — a completely different response shape under the same status code, so a client MUST branch on what it sent. The structure map reduces every leaf to its type name and never carries a value, a timestamp or an identifier, so the output is safe to paste into a public support thread. Rate-limited 5 requests / 60 s per user. Auth via cookie or Bearer.', + requestBody: { + required: false, + content: { + "application/json": { + schema: z + .object({ + probe: z + .literal("structure") + .optional() + .describe( + 'Send `"structure"` for the per-data-type diagnostic. Anything else, including a malformed body, runs the plain connection check — the body is not validated and a typo is silently ignored rather than refused.', + ), + }) + .meta({ id: "GoogleHealthTestRequest" }), + }, + }, + }, + responses: { + "200": { + description: + "Either the plain probe result or the structure map, depending on the body sent.", + content: { + "application/json": { + schema: dataEnvelope( + z.union([ + integrationProbeResponse, + z + .object({ + probe: z.literal("structure"), + probedAt: z.iso.datetime({ offset: true }), + types: z + .record(z.string(), z.unknown()) + .describe( + "One entry per Google Health data type. A successful entry carries `{ ok: true, count, structure }` plus, where the client learned it, `requestShape` (which documented request form Google accepted) and `envelopeKeys` (raw first-page key names, present only when the parse yielded zero points — the one signal separating 'nothing returned' from 'returned under a key this reader does not know'). A failed entry carries `{ ok: false, httpStatus, classification, detail }`. `structure` is the first data point with every leaf replaced by its type name.", + ), + }) + .meta({ id: "GoogleHealthStructureProbeResponse" }), + ]), + "GoogleHealthIntegrationTestEnvelope", + ), + }, + }, + }, + "413": { + description: "Body exceeds 64 KiB.", + content: { "application/json": { schema: errorEnvelope } }, + }, + ...probeFailure502, + ...stdResponses, + ...probeNotConfigured422, + ...selfRateLimited429, + }, + }, + }, + "/api/integrations/whoop/resume": { + post: { + tags: ["Integrations"], + summary: "Clear a parked WHOOP integration", + description: + "Identical contract to the Fitbit / Google Health / Withings resume endpoints — same body (none), same response, same limiter. Auth via cookie or Bearer.", + responses: { + "200": { + description: "Park cleared, or nothing to clear.", + content: { + "application/json": { + schema: dataEnvelope(resumeResponse, "WhoopResumeEnvelope"), + }, + }, + }, + ...stdResponses, + ...selfRateLimited429, + }, + }, + }, + "/api/integrations/whoop/test": { + post: { + tags: ["Integrations"], + summary: "Probe the caller's WHOOP connection", + description: + "Resolves a valid access token (refreshing if needed) and fetches the basic-profile endpoint. Returns the connection's `lastSyncedAt` alongside the probe result. No body. Rate-limited 5 requests / 60 s per user. Auth via cookie or Bearer.", + responses: { + "200": { + description: "The probe reached WHOOP.", + content: { + "application/json": { + schema: dataEnvelope( + integrationProbeResponse, + "WhoopIntegrationTestEnvelope", + ), + }, + }, + }, + ...probeFailure502, + ...stdResponses, + ...probeNotConfigured422, + ...selfRateLimited429, + }, + }, + }, + "/api/integrations/withings/resume": { + post: { + tags: ["Integrations"], + summary: "Clear a parked Withings integration", + description: + "Identical contract to the Fitbit / Google Health / WHOOP resume endpoints — same body (none), same response, same limiter. For Withings the park is typically reached through a run of contract-mismatch errors rather than an expired grant. Auth via cookie or Bearer.", + responses: { + "200": { + description: "Park cleared, or nothing to clear.", + content: { + "application/json": { + schema: dataEnvelope(resumeResponse, "WithingsResumeEnvelope"), + }, + }, + }, + ...stdResponses, + ...selfRateLimited429, + }, + }, + }, + "/api/integrations/withings/test": { + post: { + tags: ["Integrations"], + summary: "Probe the caller's Withings connection", + description: + "Resolves a valid access token and asks for one recent measure. Withings signals API-level failure with HTTP 200 and a status code in the JSON body, so this probe inspects the body as well as the status — a 200 from Withings can still be a `credentials_rejected` 502 from here. No body. Rate-limited 5 requests / 60 s per user. Auth via cookie or Bearer.", + responses: { + "200": { + description: "The probe reached Withings and the body reported OK.", + content: { + "application/json": { + schema: dataEnvelope( + integrationProbeResponse, + "WithingsIntegrationTestEnvelope", + ), + }, + }, + }, + ...stdResponses, + ...probeNotConfigured422, + ...selfRateLimited429, + "502": { + description: + "The probe did not complete. The shared codes apply (`credentials_rejected`, `rate_limited`, `upstream_error`, `timeout`, `connection_failed`) and this path adds one of its own: `upstream_invalid_json`, when Withings answered 200 with a body that would not parse. Withings' in-body status codes are mapped onto the same shared set, so a body-level rejection is indistinguishable from an HTTP-level one by errorCode alone.", + content: { "application/json": { schema: errorEnvelope } }, + }, + }, + }, + }, }; diff --git a/src/lib/openapi/routes/record-settings.ts b/src/lib/openapi/routes/record-settings.ts new file mode 100644 index 000000000..acfd2e1b4 --- /dev/null +++ b/src/lib/openapi/routes/record-settings.ts @@ -0,0 +1,453 @@ +/** + * OpenAPI route table — the managed record's own configuration. + * + * A Guardian acting on a managed record reads and writes that record's + * settings here, never through `/api/auth/me`: the actor's identity payload + * stays the actor's while the browser is pointed at somebody else's record, and + * conflating the two is how a Guardian's own locale ends up written onto a + * child's profile. Every response names the record it describes for the same + * reason. + * + * These paths carry `recordRefusal()` rather than the local `sharingRefusal` + * the grant-lifecycle module uses, and the difference is load-bearing: this is + * the one tree in the application fenced by `requireGuardianAuth`, so + * `src/__tests__/openapi-sharing-denial.test.ts` holds every operation here to + * the byte-identical shared refusal sentence. Copying the neighbouring + * module's wording into this one fails that guard. + * + * Part of the OpenAPI route table; aggregated in `./index.ts`. The PATCH + * bodies come from `src/lib/record-settings/configuration.ts` — the same strict + * objects the handler parses — so a published field the route would 422 cannot + * drift into the contract. + */ +import type { ZodOpenApiObject } from "zod-openapi"; +import { z } from "zod/v4"; + +import { METRIC_BOUNDS } from "@/lib/analytics/effective-range"; +import { MANAGED_RECORD_SETTINGS_PATCH_SCHEMAS } from "@/lib/record-settings"; +import { + dataEnvelope, + errorEnvelope, + recordRefusal, + stdResponses, +} from "./shared"; + +const thresholdMetricEnum = z + .enum(Object.keys(METRIC_BOUNDS) as [string, ...string[]]) + .describe("A metric that carries a user-overridable traffic-light range."); + +const settingsFamilyEnum = z + .enum([ + "profile", + "modules", + "notifications", + "thresholds", + "coach", + "insights", + ]) + .describe( + "The closed set of configuration families a Guardian may read and write on a managed record. Identity, credentials, delivery channels, Coach memories and provider connections are absent by construction — no family accepts them, so every future field fails closed until one deliberately does.", + ); + +const recordSettingsResponse = z + .object({ + record: z.object({ + id: z.string(), + displayName: z + .string() + .describe("Empty string when the record has no display name set."), + locale: z.string().nullable(), + timezone: z.string(), + kind: z + .literal("managed") + .describe( + "Always `managed`. The endpoint exists only for managed records; there is no owner-record arm.", + ), + }), + }) + .meta({ + id: "RecordSettingsResponse", + description: + "The active managed record's configuration identity. Deliberately a distinct DTO rather than another actor field on `/api/auth/me`.", + }); + +const recordSettingsIntegrationsResponse = z + .object({ + recordId: z.string(), + integrations: z + .array( + z.object({ + integration: z.enum([ + "withings", + "whoop", + "fitbit", + "nightscout", + "polar", + "oura", + "google-health", + "strava", + ]), + state: z.enum([ + "connected", + "error_transient", + "error_reauth", + "disconnected", + "parked", + ]), + lastSuccessAt: z.iso.datetime({ offset: true }).nullable(), + lastAttemptAt: z.iso.datetime({ offset: true }).nullable(), + }), + ) + .describe( + "All eight providers, always, in the fixed order withings, whoop, fitbit, nightscout, polar, oura, google-health, strava. Note the order differs from the owner's own `/api/integrations/status` envelope.", + ), + }) + .meta({ + id: "RecordSettingsIntegrationsResponse", + description: + "Whether the managed record's integrations are connected, and nothing else. Deliberately no control and no credential projection — OAuth and provider state cannot safely carry a record selector, so a Guardian can see that a pipe exists but cannot connect, disconnect, probe or resume it from here. A provider with no real credential reads `disconnected` even when its ledger row says otherwise, because a synthesised healthy ledger is not proof of a connection.", + }); + +// ── The six family DTOs ────────────────────────────────────────────── + +const profileSettings = z + .object({ + displayName: z.string().nullable(), + heightCm: z.number().nullable(), + dateOfBirth: z.iso + .date() + .nullable() + .describe("Calendar date (`YYYY-MM-DD`), not an instant."), + gender: z.enum(["MALE", "FEMALE", "OTHER"]).nullable(), + locale: z.enum(["de", "en", "es", "fr", "it", "pl"]).nullable(), + timezone: z.string(), + unitPreference: z.enum(["metric", "imperial"]), + timeFormat: z.enum(["AUTO", "H12", "H24"]), + dateFormat: z.enum(["AUTO", "DMY", "MDY", "YMD"]), + }) + .meta({ id: "RecordProfileSettings" }); + +const moduleSettings = z + .object({ + modulePreferences: z + .record(z.string(), z.boolean()) + .describe( + "Every directly-owned module key, always present, with the registry default filled in for keys the record has never persisted — so a Guardian administers the whole supported surface rather than only what happens to be stored.", + ), + }) + .meta({ id: "RecordModuleSettings" }); + +const notificationSettings = z + .object({ + moodReminderEnabled: z.boolean(), + notificationPreferences: z.object({ + medication: z.object({ + lowStockRunwayDays: z.number().int().nullable(), + reorderLeadDays: z.number().int(), + }), + mood: z.object({ reminderHour: z.number().int() }), + }), + }) + .meta({ + id: "RecordNotificationSettings", + description: + "Reminder timing and low-stock thresholds only. Delivery ownership is the actor's personal choice and is not here: a Guardian cannot route a managed record's notifications to their own phone or channel.", + }); + +const trafficRange = z.object({ + greenMin: z.number(), + greenMax: z.number(), + orangeMin: z.number(), + orangeMax: z.number(), +}); + +const thresholdSettings = z + .object({ + overrides: z + .record( + thresholdMetricEnum, + z.object({ min: z.number(), max: z.number() }), + ) + .describe( + "Only the metrics the record has actually overridden. A metric absent here uses the computed default.", + ), + effective: z + .record( + thresholdMetricEnum, + z.object({ + range: trafficRange + .nullable() + .describe("Resolved range: the override if set, else the default."), + isOverride: z.boolean(), + default: trafficRange + .nullable() + .describe( + "The unmodified computed default, so a client can show the diff. Null when no default can be computed — a weight range needs a height, an age-banded range needs a date of birth.", + ), + bounds: z.object({ + min: z.number(), + max: z.number(), + unit: z.string(), + }), + }), + ) + .describe( + "Every threshold metric, always, whether overridden or not — this is the resolved view a client renders without recomputing anything.", + ), + }) + .meta({ id: "RecordThresholdSettings" }); + +const coachSettings = z + .object({ + disableCoach: z.boolean(), + preferences: z.object({ + tone: z.string(), + verbosity: z.string(), + excludeMetrics: z.array(z.string()), + defaultWindow: z.string(), + dataClusters: z + .array(z.string()) + .optional() + .describe("Absent when the record has never set it."), + }), + }) + .meta({ + id: "RecordCoachSettings", + description: + "The Coach kill switch and the prompt-tuning subset a Guardian may set. A write to `preferences` also mirrors `excludeMetrics` onto the record's insights exclusion list, so the two cannot drift apart.", + }); + +const insightsSettings = z + .object({ + layout: z.object({ + version: z.number().int(), + sections: z.array( + z.object({ + id: z.string(), + visible: z.boolean(), + order: z.number().int(), + }), + ), + tiles: z.array( + z.object({ + id: z.string(), + visible: z.boolean(), + order: z.number().int(), + }), + ), + }), + }) + .meta({ + id: "RecordInsightsSettings", + description: + "The resolved insights layout. Unknown and legacy tile ids are normalised or dropped on read, and a newly-shipped tile is merged in default-visible, so the response is always the full current tile set rather than whatever was last persisted.", + }); + +const recordSettingsFamilyResponse = z + .object({ + recordId: z.string(), + family: settingsFamilyEnum, + settings: z + .union([ + profileSettings, + moduleSettings, + notificationSettings, + thresholdSettings, + coachSettings, + insightsSettings, + ]) + .describe( + "The DTO for the family in the path. Which variant arrives is determined entirely by `{family}`, so branch on `family` rather than probing the shape — OpenAPI cannot express the dependency between a path parameter and a response variant.", + ), + }) + .meta({ + id: "RecordSettingsFamilyResponse", + description: + "One family's settings for one managed record. Both the GET and the PATCH answer this same shape; the PATCH echo is the post-write state.", + }); + +const recordSettingsPatchRequest = z + .union([ + MANAGED_RECORD_SETTINGS_PATCH_SCHEMAS.profile.meta({ + id: "RecordProfileSettingsPatch", + description: + "Partial profile edit. Every key is optional and an omitted key is untouched; a `null` on a nullable field clears it. Strict — an unknown key is a 422, which is what keeps the allowlist an allowlist.", + }), + MANAGED_RECORD_SETTINGS_PATCH_SCHEMAS.modules.meta({ + id: "RecordModuleSettingsPatch", + description: + "Partial module toggle. Merged onto the record's current preferences; omitted keys keep their value.", + }), + MANAGED_RECORD_SETTINGS_PATCH_SCHEMAS.notifications.meta({ + id: "RecordNotificationSettingsPatch", + description: + "Reminder timing and low-stock thresholds. No delivery-channel field exists here by design.", + }), + MANAGED_RECORD_SETTINGS_PATCH_SCHEMAS.thresholds.meta({ + id: "RecordThresholdSettingsPatch", + description: + "Per-metric range overrides, merged onto the stored set. Each range must sit inside the metric's physiological bounds with `min` strictly below `max`. There is no clear arm: sending a metric replaces its override, and omitting it keeps the stored one.", + }), + MANAGED_RECORD_SETTINGS_PATCH_SCHEMAS.coach.meta({ + id: "RecordCoachSettingsPatch", + description: + "The Coach kill switch and the prompt-tuning subset. `preferences` is merged onto the stored preferences, not replaced wholesale.", + }), + MANAGED_RECORD_SETTINGS_PATCH_SCHEMAS.insights.meta({ + id: "RecordInsightsSettingsPatch", + description: + "The full insights layout. Unlike the other five families this one is a replacement rather than a merge.", + }), + ]) + .meta({ + id: "RecordSettingsPatchRequest", + description: + "The body for the family named in the path. Only that family's variant is accepted — sending the profile body to `/thresholds` is a 422, because every variant is strict. OpenAPI cannot tie the variant to the path parameter, so the union is the honest publication of six separate contracts sharing one URL shape.", + }); + +const familyParameter = { + name: "family", + in: "path" as const, + required: true, + schema: { + type: "string" as const, + enum: [ + "profile", + "modules", + "notifications", + "thresholds", + "coach", + "insights", + ], + }, + description: + "Which configuration family to read or write. An unrecognised value is a 404 — and note that the family check runs BEFORE authentication, so an unknown family answers 404 to an unauthenticated caller where a known one would answer 401.", +}; + +export const recordSettingsPaths: NonNullable = { + "/api/record-settings": { + get: { + tags: ["Account sharing"], + summary: "Read the active managed record's identity", + description: + "The record the session is currently acting on, named explicitly. This is not `/api/auth/me` with a different scope: that endpoint keeps reporting the actor throughout, and this one reports the record, so a client rendering a managed surface has an unambiguous source for each. Cookie session or Bearer, but only while acting on a managed record the caller guards.", + responses: { + ...recordRefusal(), + "200": { + description: "The active managed record.", + content: { + "application/json": { + schema: dataEnvelope( + recordSettingsResponse, + "RecordSettingsEnvelope", + ), + }, + }, + }, + ...stdResponses, + }, + }, + }, + "/api/record-settings/integrations": { + get: { + tags: ["Account sharing"], + summary: "Read the managed record's integration connection states", + description: + "Disclosure only: whether each of the record's integrations is connected and when it last succeeded. There is deliberately no control arm and no credential projection anywhere under this path — a Guardian cannot connect, disconnect, probe or resume a managed record's provider, because an OAuth flow cannot safely carry a record selector. Cookie session or Bearer, while acting on a managed record the caller guards.", + responses: { + ...recordRefusal(), + "200": { + description: "Connection state per provider.", + content: { + "application/json": { + schema: dataEnvelope( + recordSettingsIntegrationsResponse, + "RecordSettingsIntegrationsEnvelope", + ), + }, + }, + }, + ...stdResponses, + }, + }, + }, + "/api/record-settings/{family}": { + get: { + tags: ["Account sharing"], + summary: "Read one configuration family of the managed record", + description: + "Returns the named family's resolved settings for the record the session is acting on. Cookie session or Bearer, while acting on a managed record the caller guards.", + parameters: [familyParameter], + responses: { + ...recordRefusal(), + "200": { + description: "The family's settings.", + content: { + "application/json": { + schema: dataEnvelope( + recordSettingsFamilyResponse, + "GetRecordSettingsFamilyEnvelope", + ), + }, + }, + }, + "404": { + description: + "Either the path named a family outside the closed set, or the record row itself is gone. The two are not distinguished, and the first is answered before the caller is authenticated at all.", + content: { "application/json": { schema: errorEnvelope } }, + }, + ...stdResponses, + }, + }, + patch: { + tags: ["Account sharing"], + summary: "Update one configuration family of the managed record", + description: + "Applies the family's patch and echoes the post-write state, so a client never needs a follow-up read. Five of the six families MERGE — an omitted key keeps its stored value; `insights` replaces the layout instead. The write is audited against the record with the acting Guardian recorded as the actor, and the changed key names ride the audit row. Body capped at 64 KiB. Cookie session or Bearer, while acting on a managed record the caller guards.", + parameters: [familyParameter], + requestBody: { + required: true, + content: { + "application/json": { schema: recordSettingsPatchRequest }, + }, + }, + responses: { + ...recordRefusal(), + "200": { + description: "The family's settings after the write.", + content: { + "application/json": { + schema: dataEnvelope( + recordSettingsFamilyResponse, + "PatchRecordSettingsFamilyEnvelope", + ), + }, + }, + }, + "400": { + description: "Body is not parseable JSON.", + content: { "application/json": { schema: errorEnvelope } }, + }, + "404": { + description: + "The path named a family outside the closed set. Answered before authentication.", + content: { "application/json": { schema: errorEnvelope } }, + }, + "413": { + description: "Body exceeds 64 KiB.", + content: { "application/json": { schema: errorEnvelope } }, + }, + "415": { + description: "Content-Type is not `application/json`.", + content: { "application/json": { schema: errorEnvelope } }, + }, + ...stdResponses, + "422": { + description: + "Validation failed against the family's strict schema, with every offending issue in the envelope rather than only the first. An unknown key lands here rather than being ignored — that is what makes the field allowlist enforceable.", + content: { "application/json": { schema: errorEnvelope } }, + }, + }, + }, + }, +}; diff --git a/src/lib/record-settings/configuration.ts b/src/lib/record-settings/configuration.ts index d7d2507b2..e2e007132 100644 --- a/src/lib/record-settings/configuration.ts +++ b/src/lib/record-settings/configuration.ts @@ -129,7 +129,13 @@ const managedCoachPreferencesSchema = coachPrefsSchema }) .strict(); -const MANAGED_RECORD_SETTINGS_PATCH_SCHEMAS = { +/** + * One strict patch schema per family. Exported so the OpenAPI registry can + * publish the same objects the handler parses rather than a restatement of + * them — every family is `strict()`, so a published paraphrase that drifted + * would promise a field the route answers 422 for. + */ +export const MANAGED_RECORD_SETTINGS_PATCH_SCHEMAS = { profile: profilePatchSchema, modules: z.object({ modulePreferences: modulePrefsPatchSchema }).strict(), notifications: z diff --git a/src/lib/record-settings/index.ts b/src/lib/record-settings/index.ts index 293842925..f479498fb 100644 --- a/src/lib/record-settings/index.ts +++ b/src/lib/record-settings/index.ts @@ -18,6 +18,7 @@ export { managedModulePreferencesFrom, MANAGED_RECORD_SETTINGS_FIELD_ALLOWLIST, MANAGED_RECORD_SETTINGS_MODULE_DEFAULTS, + MANAGED_RECORD_SETTINGS_PATCH_SCHEMAS, parseManagedRecordSettingsPatch, safeParseManagedRecordSettingsPatch, type ManagedRecordSettingsFamily, diff --git a/src/lib/validations/google-health.ts b/src/lib/validations/google-health.ts new file mode 100644 index 000000000..6d0934a55 --- /dev/null +++ b/src/lib/validations/google-health.ts @@ -0,0 +1,17 @@ +import { z } from "zod/v4"; + +/** + * Per-user Google Health BYO-key credentials. Each self-hoster registers their + * own Google Cloud OAuth client (the Restricted-scope brand verification + CASA + * assessment is per-OAuth-client, so a single shared app is unworkable for a + * multi-operator product) and pastes the client id/secret into Settings. Stored + * encrypted on `User`. + */ +export const googleHealthCredentialsSchema = z.object({ + clientId: z.string().min(1).max(200), + clientSecret: z.string().min(1).max(200), +}); + +export type GoogleHealthCredentialsInput = z.infer< + typeof googleHealthCredentialsSchema +>;