API

Every route the openGym 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.

Download openapi.yaml

OpenAPI 3.1.0 openGym v1.3.0 28 endpoints AGPL-3.0-or-later

Overview

Passkey (WebAuthn) auth + per-user state storage for openGym. One Node file, no framework, JSON-file storage, HMAC-signed session cookies.

/Same origin as the openGym web app (the normal deployment)
https://opengym.example.comYour self-hosted instance

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 <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 via GET /api/config (guest mode never talks to this API at all).
  • ADMIN_UIDS=<uid>,<uid> — 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": "<human-readable message>"}.
  • 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; max 5 MiB.
  • 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.

Meta

Health and public configuration

GET /api/healthpublic Health check

Always public. Also reports how many user accounts exist.

Public — no authentication required.

Responses

200 The server is up.{ ok: always true, users: integer }
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

200 Instance flags.{ invite_only: boolean, allow_guest: boolean }

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

200 A valid session.{ user: SessionUser }
401 No session, expired/revoked session, or a disabled account.{"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)

namerequired string (≤ 40 chars) Display name for the new profile (trimmed, max 40 chars).
code string Invite code — required (and validated) only when the instance runs with INVITE_ONLY. Compared case-insensitively.
{
  "name": "Ada",
  "code": "3F9C21A07B54D688"
}

Responses

200 Ceremony options.{ cid: string, options: WebAuthnRegistrationOptions }
400 name missing/empty.{"error":"name required"}
403 Instance is invite-only and the code is missing, used, or revoked.{"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)

cidrequired string The challenge id from /api/register/options.
credentialrequired WebAuthnRegistrationCredential

Responses

200 Registered and signed in. The session cookie is set.{ user: SessionUser } · sets Set-Cookie
400 Challenge expired/replayed, or the attestation did not verify (wrong origin/RP ID, malformed response…). The message is human-readable.{"error":"challenge expired — try again"}
403 Invite-only and the code became invalid since step 1.{"error":"invite code is no longer valid — ask for a new one"}
409 This credential id is already registered.{"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

200 Ceremony options.{ cid: string, options: WebAuthnAuthenticationOptions }
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)

cidrequired string The challenge id from /api/login/options.

Responses

200 Signed in. The session cookie is set.{ user: SessionUser } · sets Set-Cookie
400 Challenge expired/replayed, or the assertion did not verify.{"error":"not verified"}
403 The account has been disabled by an admin.{"error":"this account has been disabled"}
404 The passkey's credential id is unknown to this instance.{"error":"unknown passkey — create a profile first"}
500 Credential exists but its user record is missing (corrupt db).{"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

200 Cookie cleared.Ok · sets 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.

Requires a session — the cookie set at sign-in, or Authorization: Bearer <token> from mobile-app pairing.

Responses

200 All sessions revoked.Ok · sets Set-Cookie
401 No session, expired/revoked session, or a disabled account.{"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

200 A fresh pairing code.{ code: string }
401 No session, expired/revoked session, or a disabled account.{"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)

coderequired string The pairing code (case-insensitive).
{
  "code": "K7WQ2MZP"
}

Responses

200 Paired.{ token: string, user: SessionUser }
400 Code unknown, already used, expired — or the account behind it is gone or disabled (deliberately the same message for all of these).{"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. Sync conflict resolution happens client-side (last-writer-wins by the client-set _ts timestamp).

Requires a session — the cookie set at sign-in, or Authorization: Bearer <token> from mobile-app pairing.

Responses

200 The stored state, or null.{ state: State | null }
401 No session, expired/revoked session, or a disabled account.{"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.

Requires a session — the cookie set at sign-in, or Authorization: Bearer <token> from mobile-app pairing.

Request body (JSON)

staterequired State

Responses

200 Saved.{ ok: always true, ts: number | null }
400 state missing or not an object.{"error":"state required"}
401 No session, expired/revoked session, or a disabled account.{"error":"not signed in"}

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

200 The key.{ key: string }
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.

Requires a session — the cookie set at sign-in, or Authorization: Bearer <token> from mobile-app pairing.

Request body (JSON)

subscriptionrequired PushSubscription

Responses

200 Stored.Ok
400 Malformed subscription, or an endpoint that isn't acceptable.{"error":"invalid subscription"} · {"error":"endpoint must not point at a private address"}
401 No session, expired/revoked session, or a disabled account.{"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)

endpointrequired string (uri)

Responses

200 Removed (or was never there).Ok
401 No session, expired/revoked session, or a disabled account.{"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) are pruned as a side effect.

Requires a session — the cookie set at sign-in, or Authorization: Bearer <token> from mobile-app pairing.

Responses

200 Sends attempted.Ok
401 No session, expired/revoked session, or a disabled account.{"error":"not signed in"}
POST /api/push/rest-timer Schedule a server-side rest-timer push

Schedules one push after seconds (clamped to 1–3600; one pending timer per user, a new call replaces it). 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.

Note: the documented 400 seconds required exists in the code but is unreachable — the clamp turns any missing/invalid value into 1.

Requires a session — the cookie set at sign-in, or Authorization: Bearer <token> from mobile-app pairing.

Request body (JSON)

secondsrequired number (1–3600)
{
  "seconds": 90
}

Responses

200 Timer scheduled.Ok
401 No session, expired/revoked session, or a disabled account.{"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. Idempotent.

Requires a session — the cookie set at sign-in, or Authorization: Bearer <token> from mobile-app pairing.

Responses

200 Cancelled (or nothing was pending).Ok
401 No session, expired/revoked session, or a disabled account.{"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 boolean false ends the presence; true (with the fields below) updates it.
name string (≤ 60 chars) Routine/workout name being trained.
exIdx integer Current exercise index (0-based).
exTotal integer Exercises in the workout.
setsDone integer
setsTotal integer
startedAt number Workout start, ms since epoch (defaults to now).
{
  "active": true,
  "name": "Push Day",
  "exIdx": 2,
  "exTotal": 5,
  "setsDone": 7,
  "setsTotal": 16,
  "startedAt": 1756500000000
}

Responses

200 Presence updated.Ok
401 No session, expired/revoked session, or a disabled account.{"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. 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

200 All users.{ users: AdminUserRow[], invite_only: boolean, now: number }
401 No session, expired/revoked session, or a disabled account.{"error":"not signed in"}
403 Signed in, but not an admin. The attempt is recorded in the audit log.{"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.

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

idrequired string The user id.

Responses

200 The user's detail.AdminUserDetail
401 No session, expired/revoked session, or a disabled account.{"error":"not signed in"}
403 Signed in, but not an admin. The attempt is recorded in the audit log.{"error":"forbidden"}
404 No user with that id.{"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)

idrequired string The user id.
disabledrequired boolean

Responses

200 Flag updated.{ ok: always true, id: string, disabled: boolean }
400 Target is an admin.{"error":"cannot disable an admin"}
401 No session, expired/revoked session, or a disabled account.{"error":"not signed in"}
403 Signed in, but not an admin. The attempt is recorded in the audit log.{"error":"forbidden"}
404 No user with that id.{"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

200 All invites.{ invites: Invite[], invite_only: boolean }
401 No session, expired/revoked session, or a disabled account.{"error":"not signed in"}
403 Signed in, but not an admin. The attempt is recorded in the audit log.{"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)

note string (≤ 60 chars) Free-form label ("for Alex").

Responses

200 The new invite.{ invite: Invite }
401 No session, expired/revoked session, or a disabled account.{"error":"not signed in"}
403 Signed in, but not an admin. The attempt is recorded in the audit log.{"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)

coderequired string

Responses

200 Revoked.Ok
400 The code was already used.{"error":"already used — cannot revoke"}
401 No session, expired/revoked session, or a disabled account.{"error":"not signed in"}
403 Signed in, but not an admin. The attempt is recorded in the audit log.{"error":"forbidden"}
404 No such code.{"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

limit integer (1–200, default 100) Page size.
before integer Only events with id < before (cursor from nextBefore).
cat "auth" | "admin" | "fail" Filter — fail keeps only failed events; any other value keeps events whose name starts with <cat>. (in practice auth or admin).

Responses

200 One page of the log.{ events: AuditEvent[], total: integer, nextBefore: integer | null, enabled: boolean, ip_mode: "off" | "net" | "full", retention: object, now: number }
401 No session, expired/revoked session, or a disabled account.{"error":"not signed in"}
403 Signed in, but not an admin. The attempt is recorded in the audit log.{"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

200 Cleared.Ok
401 No session, expired/revoked session, or a disabled account.{"error":"not signed in"}
403 Signed in, but not an admin. The attempt is recorded in the audit log.{"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
errorrequired string Human-readable message. This is the only error shape the API has.
Ok
ok always true
SessionUser The caller's identity, as returned by /api/me and the sign-in routes.
id string Stable user id (16 base64url chars).
name string
admin boolean
WebAuthnRegistrationOptions PublicKeyCredentialCreationOptionsJSON — pass to startRegistration() (@simplewebauthn/browser) or decode for navigator.credentials.create().

Resident keys are required; attestation is none.

challenge string base64url
rp object
rp.name string
rp.id string The RP_ID the instance is configured with.
user object
user.id string base64url user handle
user.name string
user.displayName string
pubKeyCredParams object[]
authenticatorSelection object
authenticatorSelection.residentKey always "required"
authenticatorSelection.userVerification always "preferred"
attestation always "none"
WebAuthnRegistrationCredential RegistrationResponseJSON — the value startRegistration() resolves with (the created credential plus the authenticator's attestation response), sent back verbatim.
id string base64url credential id
rawId string
type always "public-key"
response object
response.clientDataJSON string base64url
response.attestationObject string base64url
response.transports string[] e.g. ["internal", "hybrid"] — stored for later logins.
WebAuthnAuthenticationOptions PublicKeyCredentialRequestOptionsJSON — pass to startAuthentication().

allowCredentials is empty: the browser offers the user's discoverable passkeys itself.

challenge string base64url
rpId string
userVerification always "preferred"
allowCredentials object[] Always empty.
WebAuthnAuthenticationCredential AuthenticationResponseJSON — the value startAuthentication() resolves with, sent back verbatim.
id string base64url credential id
rawId string
type always "public-key"
response object
response.clientDataJSON string
response.authenticatorData string
response.signature string
response.userHandle string
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, and grows with the app. Conflict resolution is client-side via _ts.

_ts number Client-set last-write timestamp (ms since epoch); drives sync.
unit "kg" | "lb"
lang string UI language code ("en", "de", "pt", …) — also localizes pushes.
theme string
accent string
workouts Workout[] Completed workouts, chronological.
routines Routine[]
week object Weekly plan: weekday (0=Sunday … 6) → routine id.
dayPlan object Per-date overrides: ISO date → routine id, or "rest". Wins over week.
bodyweight BodyweightEntry[]
customEx object[] User-created exercises (id, name, muscles…).
exWeights object Per-exercise last/best weight memory: exercise id → {w, d}.
reminder object Daily "workout planned today" push. The server reads this: at time (HH:MM, in tz) it sends one push if a routine is planned and nothing was logged yet.
reminder.on boolean
reminder.time string
reminder.tz string | null IANA zone ("Europe/Zurich"); the user's own clock.
restSec number Default rest-timer seconds.
effort "none" | "rir" | "rpe" | null
equipProfiles object[]
settings object Catch-all note: the remaining top-level keys (sound, keepAwake, gifSize, targetW, autoBackup, …) are flat settings values like the ones above.
Workout One completed workout (representative shape).
id string
d string (date) ISO day, e.g. "2026-08-30".
start number ms since epoch
end number
routineId string
name string
bw number Body weight that day, in unit.
vol number Total volume (Σ weight × reps).
prs string[] Exercise ids that hit a personal record.
entries object[]
entries[].id string Exercise id.
entries[].topW number | null
entries[].sets object[]
entries[].sets[].w number Weight.
entries[].sets[].r number Reps.
entries[].sets[].done boolean
entries[].sets[].rir number
entries[].sets[].rpe number
Routine A workout template (representative shape).
id string
name string
emoji string
ex object[] Exercises with set/rep targets.
BodyweightEntry
d string (date)
w number Weight in unit.
t number Timestamp (ms).
PushSubscription The browser's PushSubscription.toJSON() — only these fields are stored.
endpointrequired string (uri) Public https:// push-service URL.
keysrequired object
keys.p256dhrequired string
keys.authrequired string
AdminUserRow
id string
name string
created string | null ISO timestamp.
disabled boolean
admin boolean
invitedBy string | null The invite code this account was created with.
workouts integer Total logged workouts.
lastWorkout string | null ISO day of the newest workout.
lastSync number | null The state's _ts (ms).
hasPush boolean Has at least one push subscription.
live Presence | null Currently training, or null.
Presence Live-workout snapshot (from /api/activity heartbeats).
name string
exIdx integer
exTotal integer
setsDone integer
setsTotal integer
startedAt number
updatedAt number
AdminUserDetail
user object
user.id string
user.name string
user.created string | null
user.disabled boolean
user.admin boolean
user.invitedBy string | null
unit "kg" | "lb"
lastSync number | null
routines object[]
routines[].id string
routines[].name string
routines[].emoji string
routines[].count integer Number of exercises.
bodyweight BodyweightEntry[]
workouts Workout[] Full history, newest first.
Invite
code string 16 hex chars.
note string
createdBy string Admin user id.
created string ISO timestamp.
usedBy string | null User id that redeemed the code (absent/null while unused).
usedAt string
usedByName string | null Resolved display name (only in GET /api/admin/invites).
AuditEvent One line of the audit log.
idrequired integer Monotonic, never reset — a cleared log leaves a visible id gap.
tsrequired number ms since epoch.
evrequired string Event name. Currently one of: 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.
okrequired boolean false for failed/denied attempts.
uid string Acting (or affected) user id.
name string Acting user's name (max 40 chars).
tgt string Target user id (admin actions).
tname string Target user's name.
msg string Short detail — a failure reason code, or the invite code involved. Rejected invite guesses and unknown credential ids are deliberately never recorded.
ip string Only when AUDIT_IP is on — the full address (full) or just the network, /24 or /48 (net).