API
Every route the KuentaGYM backend serves — passkey auth, state sync,
push, pairing, admin — as one hand-written
OpenAPI spec. The same file lives
in the repository
at api/openapi.yaml, next to the one server file it documents.
OpenAPI 3.1.0 KuentaGYM v1.3.8 38 endpoints AGPL-3.0-or-later
Overview
Passkey (WebAuthn) auth + per-user state storage for KuentaGYM. One Node file, no framework, JSON-file storage, HMAC-signed session cookies.
/Same origin as the KuentaGYM web app (the normal deployment)https://kuentagym.example.comYour self-hosted instanceAuthentication
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 <token> instead.
Sessions
The cookie/bearer value is <payload>.<hmac> where the payload is <uid>:<expiry-ms>:<session-version>, 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 viaGET /api/config(guest mode never talks to this API at all).ADMIN_UIDS=<uid>,<uid>— user ids treated as admins (a"admin": trueflag on the user record indb.jsonworks 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 byGET /api/admin/audit.
Conventions
- Every response body is JSON with
Cache-Control: no-store. - Errors are always
{"error": "<human-readable message>"}. - Unknown method+path pairs return
404 {"error":"not found"}; an unhandled exception returns500 {"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), is400 {"error":"invalid json"}on every route that reads one; an empty body counts as{}. A body over 5 MiB is413 {"error":"body too large"}; the rest of the upload is discarded so the answer reaches the client. - CORS: the request's
Originis reflected inAccess-Control-Allow-OriginwithoutAllow-Credentials— cross-origin callers can only ever authenticate with a Bearer token, never with the cookie.
Meta
Health and public configuration
GET
/api/healthpublic
Health check
Always public. Also reports how many user accounts exist.
Public — no authentication required.
Responses
GET
/api/configpublic
Public instance configuration
The flags the login screen needs before anyone is signed in. Both reflect environment variables on the server (INVITE_ONLY, ALLOW_GUEST).
Public — no authentication required.
Responses
Auth
Passkey (WebAuthn) registration and login, sessions
GET
/api/me
Who am I?
Resolves the current session to a user.
Requires a session — the cookie set at sign-in, or Authorization: Bearer <token> from mobile-app pairing.
Responses
{"error":"not signed in"}
POST
/api/register/optionspublic
Start passkey registration (WebAuthn ceremony, step 1)
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.
Public — no authentication required.
Request body (JSON)
{
"name": "Ada",
"code": "3F9C21A07B54D688"
}
Responses
name missing/empty.{"error":"name required"}
{"error":"a valid invite code is required"}
POST
/api/register/verifypublic
Finish passkey registration (WebAuthn ceremony, step 2)
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.
Public — no authentication required.
Request body (JSON)
Responses
Set-Cookie
{"error":"challenge expired — try again"}
{"error":"invite code is no longer valid — ask for a new one"}
{"error":"credential already registered"}
POST
/api/login/optionspublic
Start passkey login (WebAuthn ceremony, step 1)
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.
Public — no authentication required.
Responses
POST
/api/login/verifypublic
Finish passkey login (WebAuthn ceremony, step 2)
Verifies the assertion (verifyAuthenticationResponse), updates the signature counter, and signs the caller in (sets the session cookie). CSRF-exempt.
Public — no authentication required.
Request body (JSON)
Responses
Set-Cookie
{"error":"not verified"}
{"error":"this account has been disabled"}
{"error":"unknown passkey — create a profile first"}
{"error":"user missing"}
POST
/api/logoutpublic
Sign out (this device)
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.
Public — no authentication required.
Responses
Set-Cookie
POST
/api/logout/all
Sign out everywhere
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.
Requires a session — the cookie set at sign-in, or Authorization: Bearer <token> from mobile-app pairing.
Responses
Set-Cookie
{"error":"not signed in"}
Pairing
Mobile-app pairing (code from a signed-in browser tab)
POST
/api/pair/create
Mint a pairing code for the mobile app
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.
Requires a session — the cookie set at sign-in, or Authorization: Bearer <token> from mobile-app pairing.
Responses
{"error":"not signed in"}
POST
/api/pair/redeempublic
Redeem a pairing code for a Bearer token
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 <token> from then on. CSRF-exempt.
Public — no authentication required.
Request body (JSON)
{
"code": "K7WQ2MZP"
}
Responses
{"error":"invalid or expired code"}
Data
Per-user state sync (the whole app state as one JSON blob)
GET
/api/data
Pull the account's app state
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).
Requires a session — the cookie set at sign-in, or Authorization: Bearer <token> from mobile-app pairing.
Responses
{"error":"not signed in"}
PUT
/api/data
Push the account's app state
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.
Requires a session — the cookie set at sign-in, or Authorization: Bearer <token> from mobile-app pairing.
Request body (JSON)
Responses
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.{"error":"state required"} · {"error":"invalid state"}
{"error":"not signed in"}
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.
Push
Web Push (VAPID) subscriptions, rest-timer and test pushes
GET
/api/push/public-keypublic
VAPID public key
The instance's Web-Push application server key (generated once at first boot), for PushManager.subscribe({applicationServerKey}). Public.
Public — no authentication required.
Responses
POST
/api/push/subscribe
Register a Web-Push subscription
Stores the browser's PushSubscription for this account. Only endpoint and the two protocol keys are kept. The endpoint must be a public https:// URL — private/loopback/link-local addresses are refused (here and again at send time, against DNS rebinding). At most 20 subscriptions per user; the oldest are dropped first. Re-subscribing an existing endpoint replaces it and keeps its original created — the client re-sends its subscription on every signed-in boot, so a row the instance lost comes back on its own.
Requires a session — the cookie set at sign-in, or Authorization: Bearer <token> from mobile-app pairing.
Request body (JSON)
Responses
{"error":"invalid subscription"} · {"error":"endpoint must not point at a private address"}
{"error":"not signed in"}
GET
/api/push/status
Does the server hold this subscription?
Whether the caller's account has a stored subscription with exactly this endpoint. The browser's PushManager.getSubscription() says nothing about the server's side — a row pruned after a dead send (404/410/403) leaves the browser subscribed to nowhere — so the client asks here before showing the notifications switch as on, and re-registers when the answer is no.
Requires a session — the cookie set at sign-in, or Authorization: Bearer <token> from mobile-app pairing.
Query parameters
Responses
{"error":"not signed in"}
POST
/api/push/unsubscribe
Remove a Web-Push subscription
Removes the caller's subscription with the given endpoint. Idempotent.
Requires a session — the cookie set at sign-in, or Authorization: Bearer <token> from mobile-app pairing.
Request body (JSON)
Responses
{"error":"not signed in"}
POST
/api/push/test
Send a test notification
Sends a test push to all of the caller's subscriptions (localized with the lang in their synced state). Returns 200 even if delivery to individual endpoints fails — dead endpoints (404/410, and 403 for a subscription made against a VAPID key the instance no longer has) are pruned as a side effect.
Requires a session — the cookie set at sign-in, or Authorization: Bearer <token> from mobile-app pairing.
Responses
{"error":"not signed in"}
POST
/api/push/rest-timer
Schedule a server-side rest-timer push
Schedules one push after seconds (a number or numeric string ≥ 1, clamped to 3600). One pending timer per device — deviceId, the same token the subscription was registered with; a new call from the same device replaces it, and the push goes only to that device's subscriptions. Without a deviceId there is one timer per account and the push goes to every subscription, as before. The client schedules this on rest start/extend and cancels on skip or on-screen completion — the push only actually fires when the tab was backgrounded/suspended and never got to cancel it. Timers live in memory: an API restart drops them.
Requires a session — the cookie set at sign-in, or Authorization: Bearer <token> from mobile-app pairing.
Request body (JSON)
POST /api/push/subscribe. Optional.
{
"seconds": 90,
"deviceId": "3f9c1d2e7b0a4c6d9e8f1a2b3c4d5e6f"
}
Responses
seconds missing, not numeric, or below 1. Nothing is scheduled.{"error":"seconds required"}
{"error":"not signed in"}
POST
/api/push/rest-timer/cancel
Cancel the pending rest-timer push
Cancels the caller's scheduled rest-timer push, if any. With a deviceId only that device's timer; without one, every pending timer of the account. Idempotent.
Requires a session — the cookie set at sign-in, or Authorization: Bearer <token> from mobile-app pairing.
Request body (JSON) (optional)
Responses
{"error":"not signed in"}
Activity
Live-workout presence heartbeat
POST
/api/activity
Live-workout presence heartbeat
The client pings this every ~20 s while a workout is on screen; the admin dashboard reads who is training right now. Purely ephemeral, in-memory, never persisted; entries expire ~70 s after the last ping. {"active": false} drops the caller's entry immediately.
Requires a session — the cookie set at sign-in, or Authorization: Bearer <token> from mobile-app pairing.
Request body (JSON)
{
"active": true,
"name": "Push Day",
"exIdx": 2,
"exTotal": 5,
"setsDone": 7,
"setsTotal": 16,
"startedAt": 1756500000000
}
Responses
{"error":"not signed in"}
Admin
Admin dashboard — requires an admin session (ADMIN_UIDS or admin:true)
GET
/api/admin/usersadmin
List all users
One row per user with workout counts, last sync, push status and live presence. workouts counts only the entries the drill-down can show. Admin only.
Admin only — a signed-in session whose user is an admin (ADMIN_UIDS or admin:true), as the session cookie or a Bearer token.
Responses
{"error":"not signed in"}
{"error":"forbidden"}
GET
/api/admin/useradmin
One user in detail
Drill-down — full workout history (newest first) and body-weight log for one user. Admin only. Anything in routines, bodyweight or workouts that is not an object is left out, and a list that is not an array reads as empty: PUT /api/data drops those entries now, but a state file written before it did still has them and this route has to answer for it.
Admin only — a signed-in session whose user is an admin (ADMIN_UIDS or admin:true), as the session cookie or a Bearer token.
Query parameters
Responses
{"error":"not signed in"}
{"error":"forbidden"}
{"error":"no such user"}
POST
/api/admin/user/disableadmin
Disable or re-enable a user
Sets the disabled flag. A disabled account is locked out everywhere at once (every existing session stops resolving) and dropped from live presence. Admins cannot be disabled. Audited.
Admin only — a signed-in session whose user is an admin (ADMIN_UIDS or admin:true), as the session cookie or a Bearer token.
Request body (JSON)
Responses
{"error":"cannot disable an admin"}
{"error":"not signed in"}
{"error":"forbidden"}
{"error":"no such user"}
GET
/api/admin/invitesadmin
List invite codes
All invite codes, with the redeeming user's name resolved for display.
Admin only — a signed-in session whose user is an admin (ADMIN_UIDS or admin:true), as the session cookie or a Bearer token.
Responses
{"error":"not signed in"}
{"error":"forbidden"}
POST
/api/admin/invites/newadmin
Mint an invite code
Creates a fresh single-use invite code (16 hex chars = 64 bits — the code itself is the thing that isn't worth guessing; rate limiting is the reverse proxy's job). Audited.
Admin only — a signed-in session whose user is an admin (ADMIN_UIDS or admin:true), as the session cookie or a Bearer token.
Request body (JSON) (optional)
Responses
{"error":"not signed in"}
{"error":"forbidden"}
POST
/api/admin/invites/revokeadmin
Revoke an unused invite code
Deletes an unused code. A code that was already redeemed cannot be revoked.
Admin only — a signed-in session whose user is an admin (ADMIN_UIDS or admin:true), as the session cookie or a Bearer token.
Request body (JSON)
Responses
{"error":"already used — cannot revoke"}
{"error":"not signed in"}
{"error":"forbidden"}
{"error":"no such code"}
GET
/api/admin/auditadmin
Read the activity log
The audit log (sign-ins, failed attempts, admin actions), newest first, paged by event id (before cursor — offset paging would repeat rows as new events land). Retention (AUDIT_MAX events / AUDIT_DAYS days) is applied on read as well as on the hourly compaction. When AUDIT_LOG is off the route still answers, with enabled: false and whatever was logged before.
Admin only — a signed-in session whose user is an admin (ADMIN_UIDS or admin:true), as the session cookie or a Bearer token.
Query parameters
nextBefore).
fail keeps only failed events; any other value keeps events whose name starts with <cat>. (in practice auth or admin).
Responses
{"error":"not signed in"}
{"error":"forbidden"}
POST
/api/admin/audit/clearadmin
Clear the activity log
Deletes the log file. The clear is itself the first event of the fresh log, and event ids are never reset — a wipe always leaves a visible id gap.
Admin only — a signed-in session whose user is an admin (ADMIN_UIDS or admin:true), as the session cookie or a Bearer token.
Responses
{"error":"not signed in"}
{"error":"forbidden"}
Schemas
The named shapes the endpoints above link to. The State blob
is representative, not enforced — the server stores it opaquely and the app
grows it over time.
Error
Ok
SessionUser
The caller's identity, as returned by /api/me and the sign-in routes.
WebAuthnRegistrationOptions
PublicKeyCredentialCreationOptionsJSON — pass to startRegistration() (@simplewebauthn/browser) or decode for navigator.credentials.create().
Resident keys are required; attestation is none.
WebAuthnRegistrationCredential
RegistrationResponseJSON — the value startRegistration() resolves with (the created credential plus the authenticator's attestation response), sent back verbatim.
WebAuthnAuthenticationOptions
PublicKeyCredentialRequestOptionsJSON — pass to startAuthentication().
allowCredentials is empty: the browser offers the user's discoverable passkeys itself.
WebAuthnAuthenticationCredential
AuthenticationResponseJSON — the value startAuthentication() resolves with, sent back verbatim.
State
The whole app state as one blob.
The server treats it as opaque (it only strips active on save and reads a few fields for reminders and the admin dashboard) — the schema below is representative, not enforced (except workouts and routines, which must be arrays (or null) when present), and grows with the app. Concurrent writes are caught by the server's revision (_rev, see PUT /api/data); the client merges the two documents and decides by _ts which side's settings win.
week.
time (HH:MM, in tz) it sends one push if a routine is planned and nothing was logged yet.
Workout
One completed workout (representative shape).
unit.
Routine
A workout template (representative shape).
BodyweightEntry
unit.
PushSubscription
The browser's PushSubscription.toJSON() — only these fields are stored.
AdminUserRow
_ts (ms).
Presence
Live-workout snapshot (from /api/activity heartbeats).
AdminUserDetail
Invite
VitalsField
One numeric field of one metric for one day, aggregated over the samples that carried it.
A counter's day is its sum; a rate's is its avg; a gauge's is its last. Both are stored so the rule that picks one is a display decision rather than a storage one.
VitalsDay
One day for one metric, keyed by the date the phone wrote (HAE stamps every sample with its own local offset, so the server never re-derives the day from its own clock).
GET /api/vitals/hours answers one metric and one day, because 24 buckets × every metric × every day is not something a grid of cards should download.
qty, Avg, asleep, systolic…
VitalsMetric
AuditEvent
One line of the audit log.
auth.register.ok|fail|denied, auth.login.ok|fail, auth.logout, auth.logout.all, auth.pair.create|ok|fail, admin.denied, admin.user.disable|enable, admin.invite.create|revoke, admin.audit.clear.
full) or just the network, /24 or /48 (net).