# KuentaGYM HTTP API — hand-written OpenAPI 3.1 spec. # Source of truth: api/server.js (a single framework-free Node file). Every route the # server registers is documented here; if you add a route there, add it here too. # Browsable version: https://gym.dploy.lol/api.html openapi: 3.1.0 info: title: KuentaGYM API version: 1.3.8 summary: Passkey (WebAuthn) auth + per-user state storage for KuentaGYM description: | The backend of [KuentaGYM](https://gym.dploy.lol) — a free, open-source gym & body-weight tracker. One Node file, no framework, JSON-file storage, HMAC-signed session cookies. ### Authentication Sign-in is **passkey only** (WebAuthn, via `@simplewebauthn/server`). A successful `register/verify` or `login/verify` sets the session cookie; every authenticated route then works with that cookie. The paired mobile app has no shared cookie jar, so it redeems a short pairing code (`/api/pair/redeem`) for the *same* signed token and sends it as `Authorization: Bearer ` instead. ### Sessions The cookie/bearer value is `.` where the payload is `::`, signed with a per-instance secret (HMAC-SHA256). Sessions last `SESSION_DAYS` (default 90). `POST /api/logout/all` bumps the user's session version, which invalidates every token ever issued for the account. ### CSRF State-changing browser requests must come from the app's own origin. The server checks `Sec-Fetch-Site` (falling back to `Origin` vs the configured `ORIGIN`); a mismatch is refused with `403 {"error":"cross-origin request refused"}` on any non-GET route. Exempt: the WebAuthn and `pair/redeem` routes (each carries its own one-shot credential in the body) and any request authenticated with a Bearer token. ### Environment-dependent behavior - `INVITE_ONLY=1` — registration requires a valid invite code (minted by an admin). - `ALLOW_GUEST=0` — hides the client-side "continue without account" mode; the server merely reports the flag via `GET /api/config` (guest mode never talks to this API at all). - `ADMIN_UIDS=,` — user ids treated as admins (a `"admin": true` flag on the user record in `db.json` works too). Admins get the `/api/admin/*` routes. - `AUDIT_LOG` (default on), `AUDIT_MAX` (default 5000 events), `AUDIT_DAYS` (default 90), `AUDIT_IP` (`off` | `net` | `full`, default off) — shape the audit log served by `GET /api/admin/audit`. ### Conventions - Every response body is JSON with `Cache-Control: no-store`. - Errors are always `{"error": ""}`. - Unknown method+path pairs return `404 {"error":"not found"}`; an unhandled exception returns `500 {"error":"server error"}`. - Request bodies are parsed as JSON regardless of Content-Type. A body that does not parse, or parses to anything but an object (`null`, a string, an array), is `400 {"error":"invalid json"}` on every route that reads one; an empty body counts as `{}`. A body over 5 MiB is `413 {"error":"body too large"}`; the rest of the upload is discarded so the answer reaches the client. - CORS: the request's `Origin` is reflected in `Access-Control-Allow-Origin` **without** `Allow-Credentials` — cross-origin callers can only ever authenticate with a Bearer token, never with the cookie. license: name: AGPL-3.0-or-later identifier: AGPL-3.0-or-later contact: name: KuentaGYM url: https://git.dploy.lol/dsantillan/kuentagym servers: - url: / description: Same origin as the KuentaGYM web app (the normal deployment) - url: https://kuentagym.example.com description: Your self-hosted instance tags: - name: meta description: Health and public configuration - name: auth description: Passkey (WebAuthn) registration and login, sessions - name: pairing description: Mobile-app pairing (code from a signed-in browser tab) - name: data description: Per-user state sync (the whole app state as one JSON blob) - name: push description: Web Push (VAPID) subscriptions, rest-timer and test pushes - name: activity description: Live-workout presence heartbeat - name: health description: >- Apple Health metrics ingested from an iPhone (Health Auto Export automations) — per profile, write-only for the phone's ingest key - name: music description: >- Música — reading a public Apple Music page for a saved playlist's card, and the live radio station directory. Audio is never proxied by this server: the list carries resolved stream URLs and the phone talks to the station directly. - name: admin description: Admin dashboard — requires an admin session (`ADMIN_UIDS` or `admin:true`) security: - cookieAuth: [] - bearerAuth: [] paths: /api/health: get: tags: [meta] operationId: getHealth summary: Health check description: Always public. Also reports how many user accounts exist. security: [] responses: '200': description: The server is up. content: application/json: schema: type: object properties: ok: { type: boolean, const: true } users: type: integer description: Number of registered user accounts. example: { ok: true, users: 7 } /api/config: get: tags: [meta] operationId: getConfig summary: Public instance configuration description: | The flags the login screen needs before anyone is signed in. Both reflect environment variables on the server (`INVITE_ONLY`, `ALLOW_GUEST`). security: [] responses: '200': description: Instance flags. content: application/json: schema: type: object properties: invite_only: type: boolean description: When true, registration requires a valid invite code. allow_guest: type: boolean description: >- When false, the client hides "continue without account". Guest mode is purely client-side and never calls this API. example: { invite_only: true, allow_guest: false } /api/me: get: tags: [auth] operationId: getMe summary: Who am I? description: Resolves the current session to a user. responses: '200': description: A valid session. content: application/json: schema: type: object properties: user: { $ref: '#/components/schemas/SessionUser' } '401': { $ref: '#/components/responses/Unauthorized' } /api/register/options: post: tags: [auth] operationId: registerOptions summary: 'Start passkey registration (WebAuthn ceremony, step 1)' description: | Returns `PublicKeyCredentialCreationOptions` (from `@simplewebauthn/server`'s `generateRegistrationOptions`) plus a challenge id `cid`. The client passes `options` to `navigator.credentials.create()` (or `@simplewebauthn/browser`'s `startRegistration`) and sends the result to `/api/register/verify` together with the `cid`. Challenges are one-shot and expire after 5 minutes. CSRF-exempt (the challenge is the credential). No session required. security: [] requestBody: required: true content: application/json: schema: type: object required: [name] properties: name: type: string maxLength: 40 description: Display name for the new profile (trimmed, max 40 chars). code: type: string description: >- Invite code — required (and validated) only when the instance runs with INVITE_ONLY. Compared case-insensitively. example: { name: "Ada", code: "3F9C21A07B54D688" } responses: '200': description: Ceremony options. content: application/json: schema: type: object properties: cid: type: string description: One-shot challenge id, echo it back to /api/register/verify. options: $ref: '#/components/schemas/WebAuthnRegistrationOptions' '400': description: '`name` missing/empty.' content: application/json: schema: { $ref: '#/components/schemas/Error' } example: { error: "name required" } '403': description: Instance is invite-only and the code is missing, used, or revoked. content: application/json: schema: { $ref: '#/components/schemas/Error' } example: { error: "a valid invite code is required" } /api/register/verify: post: tags: [auth] operationId: registerVerify summary: 'Finish passkey registration (WebAuthn ceremony, step 2)' description: | Verifies the authenticator's attestation response against the stored challenge (`verifyRegistrationResponse`), creates the user + credential, and signs the caller in (sets the session cookie). On an invite-only instance the invite is re-checked and burned here. CSRF-exempt. security: [] requestBody: required: true content: application/json: schema: type: object required: [cid, credential] properties: cid: type: string description: The challenge id from /api/register/options. credential: $ref: '#/components/schemas/WebAuthnRegistrationCredential' responses: '200': description: Registered and signed in. The session cookie is set. headers: Set-Cookie: description: >- Session cookie (`__Host-gymsid` on HTTPS deployments, `gymsid` over plain http). HttpOnly, SameSite=Lax, Max-Age = SESSION_DAYS. schema: { type: string } content: application/json: schema: type: object properties: user: { $ref: '#/components/schemas/SessionUser' } '400': description: >- Challenge expired/replayed, or the attestation did not verify (wrong origin/RP ID, malformed response…). The message is human-readable. content: application/json: schema: { $ref: '#/components/schemas/Error' } example: { error: "challenge expired — try again" } '403': description: Invite-only and the code became invalid since step 1. content: application/json: schema: { $ref: '#/components/schemas/Error' } example: { error: "invite code is no longer valid — ask for a new one" } '409': description: This credential id is already registered. content: application/json: schema: { $ref: '#/components/schemas/Error' } example: { error: "credential already registered" } /api/login/options: post: tags: [auth] operationId: loginOptions summary: 'Start passkey login (WebAuthn ceremony, step 1)' description: | Returns `PublicKeyCredentialRequestOptions` (`generateAuthenticationOptions` with an empty `allowCredentials` — discoverable credentials / resident keys are required at registration, so the browser offers the user their passkeys itself) plus a one-shot challenge id `cid`. CSRF-exempt. Takes no request body. security: [] responses: '200': description: Ceremony options. content: application/json: schema: type: object properties: cid: { type: string } options: $ref: '#/components/schemas/WebAuthnAuthenticationOptions' /api/login/verify: post: tags: [auth] operationId: loginVerify summary: 'Finish passkey login (WebAuthn ceremony, step 2)' description: | Verifies the assertion (`verifyAuthenticationResponse`), updates the signature counter, and signs the caller in (sets the session cookie). CSRF-exempt. security: [] requestBody: required: true content: application/json: schema: type: object required: [cid, credential] properties: cid: type: string description: The challenge id from /api/login/options. credential: $ref: '#/components/schemas/WebAuthnAuthenticationCredential' responses: '200': description: Signed in. The session cookie is set. headers: Set-Cookie: description: Session cookie (see /api/register/verify). schema: { type: string } content: application/json: schema: type: object properties: user: { $ref: '#/components/schemas/SessionUser' } '400': description: Challenge expired/replayed, or the assertion did not verify. content: application/json: schema: { $ref: '#/components/schemas/Error' } example: { error: "not verified" } '403': description: The account has been disabled by an admin. content: application/json: schema: { $ref: '#/components/schemas/Error' } example: { error: "this account has been disabled" } '404': description: The passkey's credential id is unknown to this instance. content: application/json: schema: { $ref: '#/components/schemas/Error' } example: { error: "unknown passkey — create a profile first" } '500': description: Credential exists but its user record is missing (corrupt db). content: application/json: schema: { $ref: '#/components/schemas/Error' } example: { error: "user missing" } /api/logout: post: tags: [auth] operationId: logout summary: Sign out (this device) description: >- Clears the session cookie. Always succeeds — an invalid or missing session is a no-op. The token itself stays cryptographically valid until it expires; use /api/logout/all to revoke tokens. security: [] responses: '200': description: Cookie cleared. headers: Set-Cookie: description: Expires the session cookie(s). schema: { type: string } content: application/json: schema: { $ref: '#/components/schemas/Ok' } /api/logout/all: post: tags: [auth] operationId: logoutAll summary: Sign out everywhere description: | Bumps the account's session version, which invalidates **every** cookie and Bearer token ever issued for it — on every device, including a copy someone walked off with. Passkeys are untouched; signing back in works immediately. Also clears the caller's own cookie. Unredeemed pairing codes for the account are voided too. responses: '200': description: All sessions revoked. headers: Set-Cookie: description: Expires the caller's session cookie(s). schema: { type: string } content: application/json: schema: { $ref: '#/components/schemas/Ok' } '401': { $ref: '#/components/responses/Unauthorized' } /api/pair/create: post: tags: [pairing] operationId: pairCreate summary: Mint a pairing code for the mobile app description: | Called from an already signed-in browser tab (Settings → "Pair the mobile app"). Returns an 8-character code (alphabet without 0/O/1/I) the phone redeems within 5 minutes via /api/pair/redeem. One-shot. responses: '200': description: A fresh pairing code. content: application/json: schema: type: object properties: code: type: string description: 8 chars from ABCDEFGHJKLMNPQRSTUVWXYZ23456789. example: { code: "K7WQ2MZP" } '401': { $ref: '#/components/responses/Unauthorized' } /api/pair/redeem: post: tags: [pairing] operationId: pairRedeem summary: Redeem a pairing code for a Bearer token description: | Called from the mobile app with the code shown in the browser. No session required — the code *is* the credential (one-shot, 5-minute TTL). Returns the same HMAC-signed session token the cookie would carry; the app sends it as `Authorization: Bearer ` from then on. CSRF-exempt. security: [] requestBody: required: true content: application/json: schema: type: object required: [code] properties: code: type: string description: The pairing code (case-insensitive). example: { code: "K7WQ2MZP" } responses: '200': description: Paired. content: application/json: schema: type: object properties: token: type: string description: Signed session token, valid for SESSION_DAYS. user: { $ref: '#/components/schemas/SessionUser' } '400': description: >- Code unknown, already used, expired — or the account behind it is gone or disabled (deliberately the same message for all of these). content: application/json: schema: { $ref: '#/components/schemas/Error' } example: { error: "invalid or expired code" } /api/data: get: tags: [data] operationId: getData summary: Pull the account's app state description: >- Returns the caller's entire app state as one JSON blob, or `{"state": null}` if nothing has been synced yet, together with `rev`, the server's revision of that document (0 when there is none). A client keeps the `rev` it last read or wrote and sends it back as `baseRev` on the next push, which lets the server refuse a write over a document the client never saw (see the 409 on PUT). responses: '200': description: The stored state, or null, and its revision. content: application/json: schema: type: object properties: state: oneOf: - $ref: '#/components/schemas/State' - type: 'null' rev: type: integer description: Server revision of the stored document; 0 when there is none. '401': { $ref: '#/components/responses/Unauthorized' } put: tags: [data] operationId: putData summary: Push the account's app state description: | Replaces the stored state wholesale (atomic write; there is no merge on the server). The `active` field — an in-progress workout — is stripped before saving: a running session belongs to the device running it. Body limit 5 MiB. With `baseRev` the write is conditional: it goes through only when `baseRev` equals the document's current revision, and answers 409 with the current document otherwise — the client merges the two and pushes again with the revision it was given. Without `baseRev` the write is unconditional (clients from before revisions, and deliberate replaces such as a backup import). The server stamps the new revision into the document as `_rev`; a `_rev` sent by the client is ignored. requestBody: required: true content: application/json: schema: type: object required: [state] properties: state: { $ref: '#/components/schemas/State' } baseRev: oneOf: [{ type: integer }, { type: 'null' }] description: >- The revision this client last read or wrote. Omit or null for an unconditional overwrite. responses: '200': description: Saved. content: application/json: schema: type: object properties: ok: { type: boolean, const: true } ts: oneOf: [{ type: number }, { type: 'null' }] description: Echo of the pushed state's `_ts`, if present. rev: type: integer description: The revision the write produced. '409': description: >- `baseRev` is not the current revision — another client wrote since this one last read. Carries the current document so the client can merge and retry. content: application/json: schema: type: object properties: error: { type: string, const: conflict } rev: { type: integer } state: oneOf: - $ref: '#/components/schemas/State' - type: 'null' '400': description: >- `state` missing or not an object, `state` an array, or `workouts`/`routines` set to anything other than an array or null. Entries inside those two arrays that are not objects (`null`, numbers, nested arrays) are dropped before the write rather than refused, so a client with a damaged copy still syncs. content: application/json: schema: { $ref: '#/components/schemas/Error' } examples: missing: { value: { error: "state required" } } invalid: { value: { error: "invalid state" } } '401': { $ref: '#/components/responses/Unauthorized' } /api/data/rev: get: tags: [Data] summary: Current revision of the caller's profile state description: | The `rev` that `GET /api/data` would return, without the document. Signed-in clients poll this while open and on every return to the foreground and fetch the document only when the number changed. responses: '200': description: The current revision (0 when the profile has no state yet). content: application/json: schema: type: object properties: rev: { type: integer } '401': { $ref: '#/components/responses/Unauthorized' } /api/vitals: get: tags: [health] operationId: vitalsGet summary: The caller's Apple Health metrics, as per-day aggregates description: | What the Salud view renders: one entry per metric, one bucket per day, and every bucket carrying every numeric field HAE sent under the name it used (`qty`, `Min`/`Avg`/`Max`, `systolic`/`diastolic`, `asleep`/`inBed`/`core`/`deep`/`rem`…), already summed and averaged for that day. The server deliberately does not decide what "steps today" means — which field a card shows is a presentation rule (frontend `lib/vitals-view.js`), so a metric HAE adds later needs no change here. A session is always required: the ingest key is write-only, so a key that leaks out of a phone can add to a profile's health file and still cannot read it back. parameters: - name: days in: query schema: { type: integer, minimum: 1, maximum: 400, default: 90 } description: Calendar days to return, including today. responses: '200': description: The stored metrics for the window, oldest day first. content: application/json: schema: type: object properties: ok: { type: boolean } days: { type: integer } key: type: string nullable: true description: The caller's ingest key, or null before one has been created. updatedAt: { type: integer, description: Epoch ms of the last ingest. } last: type: object nullable: true description: What the most recent ingest contained. properties: ts: { type: integer } metrics: { type: integer } points: { type: integer } duplicates: { type: integer } workouts: { type: integer } metrics: type: object additionalProperties: { $ref: '#/components/schemas/VitalsMetric' } workouts: type: array description: Read-only; never folded into the workout history. items: { type: object } example: ok: true days: 30 key: "kghealth_5Z0d…" updatedAt: 1756900000000 metrics: step_count: units: count sources: [Apple Watch] days: [{ day: "2026-09-03", n: 1, lastTs: 1756900000000, hours: 0, f: { qty: { n: 1, sum: 12481, min: 12481, max: 12481, last: 12481, avg: 12481 } } }] heart_rate: units: bpm sources: [Apple Watch] days: [{ day: "2026-09-03", n: 288, lastTs: 1756900000000, f: { Avg: { n: 288, sum: 20000, min: 55, max: 96, last: 72, avg: 69.4 } } }] workouts: [] '401': { $ref: '#/components/responses/Unauthorized' } delete: tags: [health] operationId: vitalsClear summary: Delete the caller's health data, or one metric of it description: | Removes the profile's health file and nothing else: the workout history, the account and the ingest key are untouched, so a phone needs no re-configuring to sync again. With `?metric=` it forgets **one** measurement instead, days and hours included, and leaves every other metric in place — the answer to "these numbers look wrong, start this one over". It is a reset rather than a loss whenever the automation's Date Range is wider than a day: the next sync sends that metric again from Apple Health. A metric the profile does not have answers `200` with `metric: null`, not an error. parameters: - name: metric in: query required: false schema: { type: string } description: >- The metric name exactly as HAE wrote it (`step_count`, `heart_rate`…). Omit it to clear everything. responses: '200': description: Deleted (also when there was nothing stored). content: application/json: schema: type: object properties: { ok: { type: boolean } } '401': { $ref: '#/components/responses/Unauthorized' } /api/vitals/hours: get: tags: [health] operationId: vitalsHours summary: One metric's hours on one day description: | The detail behind a card: the hourly buckets the phone sent for a single metric on a single day, oldest first, each carrying the same per-field aggregates a day does. This is a separate request on purpose. The hours are the bulky part of health data (24 buckets per metric per day), and they are only interesting once somebody taps a card, so a screen listing forty metrics fetches none of them. A day the automation grouped by Day has no hours and comes back as an empty list rather than a fabricated one: the honest answer to "what did the hours look like" for a payload that never carried hours is that the automation does not send them. Set Time Grouping to **Hours** in Health Auto Export to keep them — the day remains the sum of its hours, so nothing is counted twice. Session only, like `GET /api/vitals`: the ingest key is write-only. parameters: - name: metric in: query required: true schema: { type: string } description: The metric name exactly as HAE wrote it (`step_count`, `heart_rate`…). - name: day in: query required: true schema: { type: string, example: "2026-09-03" } description: A calendar day, in the phone's own date, as `YYYY-MM-DD`. responses: '200': description: The hours stored for that metric and day (empty when there are none). content: application/json: schema: type: object properties: ok: { type: boolean } metric: type: string nullable: true description: Echoed when the profile has that metric, null otherwise. day: type: string nullable: true description: Echoed when the day exists for that metric, null otherwise. units: { type: string } hours: type: array items: type: object properties: h: type: string description: "The hour as the phone wrote it: `00`–`23`." n: { type: integer, description: Samples folded into this hour. } ts: { type: integer, description: Epoch ms of the hour's newest sample. } f: type: object additionalProperties: { $ref: '#/components/schemas/VitalsField' } example: ok: true metric: step_count day: "2026-09-03" units: count hours: - h: "08" n: 12 ts: 1756900000000 f: { qty: { n: 12, sum: 512, min: 3, max: 120, last: 44, avg: 42.7 } } - h: "09" n: 12 ts: 1756903600000 f: { qty: { n: 12, sum: 1340, min: 8, max: 310, last: 96, avg: 111.7 } } '401': { $ref: '#/components/responses/Unauthorized' } /api/insights: get: tags: [health] operationId: insightsGet summary: The profile's last second opinion, if the instance has one description: | Whether this instance is configured for a second opinion at all (`configured`, false unless `JEV_API_KEY` or `OPENCODE_API_KEY` is set), what was judged last, whether that judgment is still about the data on screen, and what is left of today's budget. The judgment itself is a small object: one entry per question the server asked, each with the option or level the model chose and the probability it put there. A question it did not answer is `null` — the server never fills a gap with a guess, and the screen says the question went unanswered rather than drawing a zero. parameters: - name: raw in: query schema: { type: string, enum: ['1'] } description: >- Include the gateway's own response body, exactly as it arrived. Debugging detail: the default response leaves it out, because a screen polling this does not need it. responses: '200': description: The state of the feature and the last judgment. content: application/json: schema: type: object properties: ok: { type: boolean } configured: { type: boolean } model: type: string nullable: true description: The model id this instance would ask, null when unconfigured. host: type: string nullable: true description: The gateway's hostname, for the screen to name. Never the key. insight: type: object nullable: true description: The stored judgment, or null before the first ask. freshness: type: object properties: fresh: { type: boolean } reason: type: string nullable: true enum: [none, old, data] description: >- `old` past its six hours, `data` because the profile changed since, `none` because there is no judgment at all. budget: type: object properties: used: { type: integer } remaining: { type: integer } allowed: { type: boolean } waitMs: { type: integer } nextAt: { type: integer, nullable: true } example: ok: true configured: true model: jev-1.13 host: opencode.ai insight: v: 1 at: 1758650400000 model: jev-1.13 answers: readiness: { type: score, value: 2.4, p: 0.58 } deload: { type: noul, p: 0.62, option: 'false' } limiter: { type: choice, option: back, p: 0.55, known: true } freshness: { fresh: true, reason: null } budget: { used: 1, remaining: 11, allowed: true, waitMs: 0, nextAt: null } '401': { $ref: '#/components/responses/Unauthorized' } post: tags: [health] operationId: insightsAsk summary: Ask for a second opinion about this profile description: | Builds a state from the profile's own data — a week of every health metric it has, the sets per body part over four weeks, the last few sessions, **the whole training history per exercise** (sessions, the estimate of the best set then and now, one point per session, and where it has stalled), the weekly load and volume of the last ten weeks, the newest weigh-in, and the Coach intake's goal and limitations note — sends it to Jev (TypeSafe's System One model, through the OpenCode Zen gateway) with four typed questions, and stores the answers. **What leaves the instance is decided server-side and is aggregates only**: no name, no workout titles, no chat, and no identifier of a person. The exceptions are deliberate and small: the Coach intake's `limitations` note, because "bad shoulder" changes the answer, and the **library id of an exercise that has stopped progressing**, because a question about which exercise to change has to name something the app can edit — a library id is a row in a public dataset, not an identifier of anybody. The one piece of the person's own writing that goes is the intake's `limitations` field, because "bad shoulder" changes the answer; the sheet in front of the button lists exactly what will be sent before it is sent. It costs a request, so it is never on a timer: the call is the ask, and the budget (`per profile per day`, plus a ten-minute floor) is enforced here rather than trusted to the client. A profile with no health data and no training still gets an answer — the questions that cannot be answered are simply not asked. responses: '200': description: The judgment, parsed. Every question the model left unanswered is null. content: application/json: schema: type: object properties: ok: { type: boolean } model: { type: string } host: { type: string } insight: { type: object } freshness: { type: object } budget: { type: object } sent: type: object description: Counts, never content — what was just sent, for the screen to show. properties: metrics: { type: array, items: { type: string } } health_days: { type: integer } sessions: { type: integer } last_session_days_ago: { type: integer, nullable: true } body_parts: { type: array, items: { type: string } } includes_limitations: { type: boolean } '400': description: The instance has no key configured — the message names the variable to set. '429': description: Today's budget is spent, or ten minutes have not passed since the last ask. '502': description: The gateway refused or failed; the message carries what it said. '401': { $ref: '#/components/responses/Unauthorized' } /api/radio: get: tags: [music] operationId: radioGet summary: Live radio stations for a genre, with their stream URLs resolved description: | What the **Radio** section of the Música screen draws. Every station arrives with the URL to hand an `