Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.
JavaScript apple-watchbodyweightdockerfitnessfitness-trackergymhealthiosmcpnodejspasskeysprogressive-web-applicationspwareactself-hostedself-hostingvitewebauthnweightliftingworkout-tracker
api: close login CSRF on the passkey routes (GHSA-48ff-v63h-99xr)
Boris 'B' Kurktchieveaf22ab84c16
diff --git a/SECURITY.md b/SECURITY.mdindex 92b76bd0d..15de9a55c 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -249,12 +249,17 @@ Read this before hosting openGym for anyone other than yourself.reverse proxy, several apps, i.e. the usual self-hosting layout) is the *same* site and doesget the cookie. So every state-changing request that a browser sent must also be`Sec-Fetch-Site: same-origin` (or `none`, which only the user's own navigation produces), or- carry an `Origin` equal to `ORIGIN` where that header is missing (`csrfOk`). Requests- authenticated with a Bearer token skip the check —- a browser never attaches one by itself, so there is no ambient authority to borrow — as do the- register/login/pair handshakes, which carry their own credential in the body and act on no- existing session (`CSRF_EXEMPT`). The device-code routes are not exempt: a code is- redeemed on the app's own origin, the only one a passkey for it can be created on.+ carry an `Origin` equal to `ORIGIN` where that header is missing (`csrfOk`). Requests a Bearer+ token authenticates skip the check — a browser never attaches one by itself, so there is no+ ambient authority to borrow. The token has to verify and be the only credential (no session+ cookie beside it), so a header that merely starts with `Bearer ` switches nothing off, and it+ buys nothing on the sign-in routes (passkey, password, reset code, device code), where what the+ body carries is the credential and a Bearer never is. The mobile app's pairing redeem skips it+ too: the app calls it from its own origin, and it answers with a token in the body, never a+ cookie. The passkey routes are checked like any other: their challenge is bound to nothing but+ an id anyone can ask for, so exempting them let another site finish the attacker's own sign-in+ in the victim's browser. And a route that reads a body refuses one not declared+ `application/json`, the one type a form cannot send.- **User verification is preferred, not required.** Both handshakes pass`requireUserVerification: false` (the `POST /api/register/verify` and `POST /api/login/verify`handlers), so a passkey released without a biometric or PIN is still accepted. In practice:diff --git a/api/openapi.yaml b/api/openapi.yamlindex ca178cb63..931d4abb6 100644--- a/api/openapi.yaml+++ b/api/openapi.yaml@@ -60,14 +60,21 @@ info:State-changing browser requests must come from the app's own origin. The serverchecks `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: passkey sign-up and sign-in (`register/options`,- `register/verify`, `login/options`, `login/verify`) and `pair/redeem`, each of which- carries its own one-shot credential in the body, and any request authenticated with a- Bearer token.- The password routes are **not** exempt: a hostile page knows a valid name and- password of its own, and could otherwise sign a visitor into it (login CSRF).- Neither are the device-link routes: a link is redeemed on the app's own origin,- the only one a passkey can be created for.+ non-GET route, the passkey routes included. Exempt: `pair/redeem`, which the mobile+ app calls from its own origin (the code in the body is the credential, and the token+ comes back in the body, never as a cookie), and any request a Bearer token+ authenticates by itself: a valid session token, with no session cookie beside it, on+ any route but the sign-in ones — the four passkey routes, the password and reset-code+ routes and the two device-link routes, which act on the credential in the body, never+ on a Bearer. A cross-origin request whose Bearer does not buy the exemption is refused+ before any handler runs: `401 {"error":"not signed in"}` when that Bearer does not+ verify and is the only credential (a paired app whose token was revoked or expired),+ the 403 otherwise.+ The passkey routes were exempt before, on the grounds that the challenge id is a+ credential; but it is bound to nothing else, so a hostile page could complete the+ attacker's own passkey sign-in in the victim's browser (login CSRF) and the answer+ set the victim's session to the attacker's account. The password routes are **not**+ exempt for the same reason: a hostile page knows a valid name and password of its own.### Environment-dependent behavior- `INVITE_ONLY=1`: registration requires a valid invite code (minted by an admin).@@ -103,7 +110,11 @@ info:`media` routes add a stable `code` for the client to word in its own language.- Unknown method+path pairs return `404 {"error":"not found"}`; an unhandledexception returns `500 {"error":"server error"}`.- - Request bodies are parsed as JSON regardless of Content-Type. A body that does+ - Every route that reads a request body requires `Content-Type: application/json`+ (a `charset` parameter is fine) and answers any other type with+ `415 {"error":"content-type must be application/json"}` — the types a form can+ send are the ones that skip the CORS preflight, which is how a cross-site form+ reached these routes. A request with no body needs no Content-Type. A body that doesnot 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 countsas `{}`. A body over 5 MiB is `413 {"error":"body too large"}`; the rest of the@@ -331,7 +342,7 @@ paths:`startRegistration`) and sends the result to `/api/register/verify` togetherwith the `cid`. Challenges are one-shot and expire after 5 minutes.- CSRF-exempt (the challenge is the credential). No session required.+ No session required.security: []requestBody:required: true@@ -386,7 +397,7 @@ paths:Verifies the authenticator's attestation response against the storedchallenge (`verifyRegistrationResponse`), creates the user + credential, andsigns the caller in (sets the session cookie). On an invite-only instance the- invite is re-checked and burned here. CSRF-exempt.+ invite is re-checked and burned here.security: []requestBody:required: true@@ -447,7 +458,7 @@ paths:(`generateAuthenticationOptions` with an empty `allowCredentials`; discoverablecredentials / resident keys are required at registration, so the browser offersthe user their passkeys itself) plus a one-shot challenge id `cid`.- CSRF-exempt. Takes no request body.+ Takes no request body.security: []responses:'200':@@ -468,7 +479,7 @@ paths: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.+ counter, and signs the caller in (sets the session cookie).security: []requestBody:required: truediff --git a/api/server.js b/api/server.jsindex 938fca7dc..d67e7047b 100644--- a/api/server.js+++ b/api/server.js@@ -595,6 +595,12 @@ function sessionOf(req) {const auth = req.headers.authorization || '';const cookie = cookieToken(req);const tok = cookie || (auth.startsWith('Bearer ') ? auth.slice(7).trim() : null);+ const s = sessionUser(tok);+ return s && { ...s, bearer: !cookie };+}+// The session a token (a cookie value or a bearer) stands for — { user, exp } — or null. Split+// out of sessionOf so the origin check can ask whether a bearer authenticates on its own.+function sessionUser(tok) {if (!tok) return null;const payload = verifySig(tok);if (!payload) return null;@@ -607,7 +613,7 @@ function sessionOf(req) {// payload (it still had to pass the HMAC, so this is belt-and-braces) and is refused outright.const claimed = ver === undefined ? 0 : Number(ver);if (!Number.isInteger(claimed) || claimed !== sessionVersion(user)) return null;- return { user, exp: +exp, bearer: !cookie };+ return { user, exp: +exp };}function readSession(req) {return sessionOf(req)?.user || null;@@ -640,26 +646,56 @@ const clearCookie = COOKIE === LEGACY_COOKIE// Content-Type claims, so a hostile page could reach the state-changing routes with a form-style// POST that needs no CORS preflight at all.//-// So a state-changing request that came from a browser has to come from ORIGIN. The exemptions-// below are not holes: each of those routes carries its own credential in the body (a WebAuthn-// challenge id, a one-shot pairing code), none of them acts on the caller's existing session, and-// they have to keep working from the mobile WebView, whose origin is never ORIGIN.+// So a state-changing request that came from a browser has to come from ORIGIN, the passkey+// routes included. They used to be exempt on the grounds that the challenge id is a credential,+// but it is the attacker's credential: /api/login/options hands a `cid` to anyone, the challenge+// is bound to nothing else, and the attacker's own passkey can sign it — so a form on another site+// could complete their sign-in in the victim's browser, and the Set-Cookie on that response+// replaced the victim's session with one for the attacker's account. No legitimate caller is+// cross-origin: a passkey only verifies against ORIGIN, so the mobile WebView could never use+// these routes anyway.+//+// pair/redeem is the one exemption, and it has to be: the paired app calls it from its own+// WebView origin, which is never ORIGIN. It is not a hole. The pairing code in the body is the+// credential, and the answer sets no cookie: the token comes back in the body, which a+// cross-site form or a no-cors fetch cannot read.//-// The password routes are deliberately NOT here. A name and a password are a credential too,+// The password routes are deliberately NOT exempt. A name and a password are a credential too,// but one a hostile page can know — its own — so an exempt POST /api/login/password would let// any site sign a visitor into the attacker's account and collect what they log (login CSRF).-const CSRF_EXEMPT = new Set([+const CSRF_EXEMPT = new Set(['POST /api/pair/redeem']);+// The routes that answer to the credential in the body and never to a Bearer. No Bearer is the+// credential that acts there, so none buys the shortcut below: any valid token would do, the+// attacker's own included.+const PASSKEY_ROUTES = new Set(['POST /api/register/options', 'POST /api/register/verify',- 'POST /api/login/options', 'POST /api/login/verify',- 'POST /api/pair/redeem'+ 'POST /api/login/options', 'POST /api/login/verify'+]);+// The other ways in are the same kind of route: the name and password, the reset code or the+// device code in the body is the credential, never a Bearer.+const SIGN_IN_ROUTES = new Set([+ 'POST /api/login/password', 'POST /api/register/password', 'POST /api/login/password-reset',+ 'POST /api/device-link/options', 'POST /api/device-link/verify']);const originsMatch = (a, b) => a.replace(/\/+$/, '') === b.replace(/\/+$/, '');+// Whether a Bearer is the credential that would act on this request: it verifies, and no session+// cookie sits beside it (readSession takes the cookie first, so a cookie is what would act then).+function bearerAuthenticates(req) {+ const auth = req.headers.authorization || '';+ if (!auth.startsWith('Bearer ') || cookieToken(req)) return false;+ return !!sessionUser(auth.slice(7).trim());+}function csrfOk(req, key) {if (req.method === 'GET' || req.method === 'HEAD' || req.method === 'OPTIONS') return true;if (CSRF_EXEMPT.has(key)) return true;// The paired mobile app authenticates with a Bearer token. A browser never attaches one on its// own, so there is no ambient authority for a hostile page to borrow and no origin to check.- if ((req.headers.authorization || '').startsWith('Bearer ')) return true;+ // That holds only when the Bearer is the credential that acts, so it has to authenticate by+ // itself: a header that merely starts with "Bearer " used to switch the check off, and then+ // readSession acted on the session cookie next to it — safe only because the CORS preflight+ // never allows credentials. And it buys nothing on the sign-in routes, where the body carries+ // the credential and a Bearer never is.+ if (!PASSKEY_ROUTES.has(key) && !SIGN_IN_ROUTES.has(key) && bearerAuthenticates(req)) return true;// Sec-Fetch-Site is set by the browser itself and no page can forge it, and it states exactly// the property wanted here — more precisely than comparing origins can. 'same-origin' is the// app talking to its own backend; a hostile page reports 'cross-site'; a sibling subdomain,@@ -756,6 +792,14 @@ function readBody(req) {req.on('end', () => {if (over) return;if (!chunks.length) return resolve({});+ // A body has to say it is JSON. The three types a form can send, and the ones a no-cors+ // fetch can send, are exactly the ones that need no CORS preflight; parsing them anyway+ // let another site's form reach any route that reads a body, and on the passkey sign-in+ // that meant setting the victim's session to an account the attacker holds. Every client+ // in the tree already sends application/json (lib/api.js, sw.js).+ if (!/^application\/json\s*(;|$)/i.test(req.headers['content-type'] || '')) {+ return reject(new HttpError(415, 'content-type must be application/json'));+ }let body;try { body = JSON.parse(Buffer.concat(chunks).toString('utf8')); }catch { return reject(new HttpError(400, 'invalid json')); }@@ -2661,6 +2705,13 @@ const server = http.createServer(async (req, res) => {const handler = routes[key];if (!handler) return json(res, 404, { error: 'not found' });if (!csrfOk(req, key)) {+ // A Bearer that does not verify and no cookie beside it: nothing ambient is in play, the caller+ // is simply not signed in. That is the paired app once its token is revoked or expired, and it+ // needs the 401 to know it (lib/api.js callers and the boot path act on the status), not a 403+ // and a log line that blames ORIGIN. Still refused before any handler runs.+ if ((req.headers.authorization || '').startsWith('Bearer ') && !cookieToken(req) && !bearerAuthenticates(req)) {+ return json(res, 401, { error: 'not signed in' });+ }// Logged, not audited: this is reachable without a session, and an audit entry per attempt// would let anyone fill the log. An operator who has genuinely mis-set ORIGIN needs to see// the mismatch, and the container log is where they will look.diff --git a/api/test/server-csrf-bearer.test.js b/api/test/server-csrf-bearer.test.jsnew file mode 100644index 000000000..a88492df8--- /dev/null+++ b/api/test/server-csrf-bearer.test.js@@ -0,0 +1,97 @@+/* The Bearer shortcut in csrfOk: a request a Bearer token authenticates has no origin to check,+ because a browser never attaches one on its own. It used to be keyed on the header's shape —+ anything starting with "Bearer " skipped the check — and then readSession authenticated the+ request with the session COOKIE whenever one was present, so the header that bought the+ exemption was not the credential that acted. Only the CORS preflight (no+ Access-Control-Allow-Credentials) kept a hostile page from sending both. Now the exemption+ needs a Bearer that authenticates on its own: a valid session token, and no session cookie+ beside it. A Bearer that does not verify, with no cookie, is a caller who is not+ signed in and gets the 401 before any handler runs. Real server.js in a child. */+import { test } from 'node:test';+import assert from 'node:assert/strict';+import crypto from 'node:crypto';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { spawn } from 'node:child_process';+import { fileURLToPath } from 'node:url';+import { boundPort } from './helpers.mjs';++const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');+const SECRET = crypto.randomBytes(32).toString('hex');++function mintSession(uid) {+ const payload = `${uid}:${Date.now() + 86400000}:0`;+ return payload + '.' + crypto.createHmac('sha256', SECRET).update(payload).digest('base64url');+}++async function startServer(t) {+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-csrfbearer-'));+ fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });+ fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({+ users: [+ { id: 'u_victim', name: 'Victim', created: new Date().toISOString() },+ { id: 'u_phone', name: 'Phone', created: new Date().toISOString() }+ ], creds: [], subs: [], invites: []+ }));+ const child = spawn(process.execPath, ['server.js'], {+ cwd: API, stdio: ['ignore', 'pipe', 'pipe'],+ env: { ...process.env, PORT: '0', DATA_DIR: dataDir, ORIGIN: 'https://gym.test', RP_ID: 'gym.test' }+ });+ let log = '';+ child.stdout.on('data', d => log += d);+ child.stderr.on('data', d => log += d);+ t.after(() => { child.kill('SIGKILL'); fs.rmSync(dataDir, { recursive: true, force: true }); });+ return `http://127.0.0.1:${await boundPort(child, () => log)}`;+}+const evil = { Origin: 'https://evil.test', 'Sec-Fetch-Site': 'cross-site', 'Content-Type': 'application/json' };+const victimCookie = { Cookie: `__Host-gymsid=${mintSession('u_victim')}` };+const activity = (api, headers) => fetch(`${api}/api/activity`, { method: 'POST', headers, body: JSON.stringify({ active: false }) });++test('a Bearer header that authenticates nothing does not switch the origin check off', async t => {+ const api = await startServer(t);+ const bogus = { Authorization: 'Bearer not-a-token' };+ // With the victim's cookie beside it, this used to be a 200 acting as the victim.+ const r = await activity(api, { ...evil, ...victimCookie, ...bogus });+ assert.equal(r.status, 403);+ assert.deepEqual(await r.json(), { error: 'cross-origin request refused' });+ // With no cookie, nothing ambient is in play: that caller is not signed in, and is told so+ // with the 401 the paired app acts on, before any handler runs. login/options answers anybody+ // with a 200, so the 401 there is the proof the handler was never reached.+ assert.equal((await activity(api, { ...evil, ...bogus })).status, 401);+ const opts = await fetch(`${api}/api/login/options`, { method: 'POST', headers: { ...evil, ...bogus } });+ assert.equal(opts.status, 401);+ assert.deepEqual(await opts.json(), { error: 'not signed in' });+ // An empty "Bearer " arrives trimmed to "Bearer", which is no Bearer at all: the origin check.+ assert.equal((await activity(api, { ...evil, Authorization: 'Bearer ' })).status, 403);+ // A valid token is still not the credential that acts when a cookie is there: readSession+ // takes the cookie first, so the request would run as the victim.+ assert.equal((await activity(api, { ...evil, ...victimCookie, Authorization: `Bearer ${mintSession('u_phone')}` })).status, 403);+});++test('the paired app still gets through from its own origin', async t => {+ const api = await startServer(t);+ // The WebView: its own origin, cross-site by definition, a session token and no cookie.+ for (const Origin of ['capacitor://localhost', 'https://localhost']) {+ const phone = { ...evil, Origin, Authorization: `Bearer ${mintSession('u_phone')}` };+ assert.equal((await activity(api, phone)).status, 200, Origin);+ const put = await fetch(`${api}/api/data`, { method: 'PUT', headers: phone, body: JSON.stringify({ state: { unit: 'kg', workouts: [], routines: [] } }) });+ assert.equal(put.status, 200, Origin);+ }+ // and the web app on its own origin needs no Bearer at all+ assert.equal((await activity(api, { ...victimCookie, 'Content-Type': 'application/json', 'Sec-Fetch-Site': 'same-origin' })).status, 200);+});++test('a paired phone whose token is dead is told it is signed out, not that its origin is wrong', async t => {+ const api = await startServer(t);+ const expired = (() => {+ const payload = `u_phone:${Date.now() - 1000}:0`;+ return payload + '.' + crypto.createHmac('sha256', SECRET).update(payload).digest('base64url');+ })();+ const r = await fetch(`${api}/api/data`, {+ method: 'PUT', headers: { ...evil, Origin: 'capacitor://localhost', Authorization: `Bearer ${expired}` },+ body: JSON.stringify({ state: { unit: 'kg', workouts: [], routines: [] } })+ });+ assert.equal(r.status, 401);+ assert.deepEqual(await r.json(), { error: 'not signed in' });+});diff --git a/api/test/server-login-csrf.test.js b/api/test/server-login-csrf.test.jsnew file mode 100644index 000000000..03aeaa72d--- /dev/null+++ b/api/test/server-login-csrf.test.js@@ -0,0 +1,205 @@+/* Login CSRF: another site signing the victim's browser into an account the attacker controls.++ The challenge from /api/login/options is bound to nothing but the `cid` that comes back in the+ response body — a server-side map, no cookie, no tie to the browser that asked. So the attacker+ asks for one from their own machine, has their own passkey sign it, and needs the victim's+ browser only for the last step: a form on their page that POSTs the finished assertion to+ /api/login/verify. A form cannot send application/json, but `enctype="text/plain"` with the+ JSON as a field name gets a body JSON.parse accepts, and it needs no CORS preflight. The+ response to a top-level form navigation may set a SameSite=Lax cookie, so the victim's session+ is replaced with the attacker's.++ Two things stop it now: the passkey routes are origin-checked like every other write, and a+ body that is not declared application/json is refused before anything reads it.++ The passkey here is a real P-256 key, the assertion is signed the way an authenticator signs+ one, and @simplewebauthn/server verifies it. Real server.js in a child. */+import { test } from 'node:test';+import assert from 'node:assert/strict';+import crypto from 'node:crypto';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { spawn } from 'node:child_process';+import { fileURLToPath } from 'node:url';+import { boundPort } from './helpers.mjs';++const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');+const SECRET = crypto.randomBytes(32).toString('hex');+const ORIGIN = 'https://gym.test';+const RP_ID = 'gym.test';+const b64u = b => Buffer.from(b).toString('base64url');+const sha256 = b => crypto.createHash('sha256').update(b).digest();++function mintSession(uid) {+ const payload = `${uid}:${Date.now() + 86400000}:0`;+ return payload + '.' + crypto.createHmac('sha256', SECRET).update(payload).digest('base64url');+}++/* The attacker's own passkey: stored the way register/verify stores one (COSE, base64url). */+const KEY = crypto.generateKeyPairSync('ec', { namedCurve: 'P-256' });+const CRED_ID = b64u(crypto.randomBytes(16));+function coseKey() {+ const { x, y } = KEY.publicKey.export({ format: 'jwk' });+ // {1: 2 (EC2), 3: -7 (ES256), -1: 1 (P-256), -2: x, -3: y}+ return Buffer.concat([+ Buffer.from([0xa5, 0x01, 0x02, 0x03, 0x26, 0x20, 0x01, 0x21, 0x58, 0x20]), Buffer.from(x, 'base64url'),+ Buffer.from([0x22, 0x58, 0x20]), Buffer.from(y, 'base64url')+ ]);+}+function assertion(challenge) {+ const clientDataJSON = Buffer.from(JSON.stringify({ type: 'webauthn.get', challenge, origin: ORIGIN, crossOrigin: false }));+ const authData = Buffer.concat([sha256(RP_ID), Buffer.from([0x05]), Buffer.alloc(4)]); // UP|UV, counter 0+ const signature = crypto.sign('sha256', Buffer.concat([authData, sha256(clientDataJSON)]), KEY.privateKey);+ return {+ id: CRED_ID, rawId: CRED_ID, type: 'public-key', clientExtensionResults: {},+ response: { clientDataJSON: b64u(clientDataJSON), authenticatorData: b64u(authData), signature: b64u(signature), userHandle: b64u('u_attacker') }+ };+}++async function startServer(t, extraEnv = {}) {+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-logincsrf-'));+ fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });+ fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({+ users: [+ { id: 'u_victim', name: 'Victim', created: new Date().toISOString() },+ { id: 'u_attacker', name: 'Attacker', created: new Date().toISOString() }+ ],+ creds: [{ id: CRED_ID, userId: 'u_attacker', publicKey: b64u(coseKey()), counter: 0, transports: ['internal'] }],+ subs: [], invites: []+ }));+ const child = spawn(process.execPath, ['server.js'], {+ cwd: API, stdio: ['ignore', 'pipe', 'pipe'],+ env: { ...process.env, PORT: '0', DATA_DIR: dataDir, ORIGIN, RP_ID, ...extraEnv }+ });+ const h = { api: '', log: '' };+ child.stdout.on('data', d => h.log += d);+ child.stderr.on('data', d => h.log += d);+ t.after(() => { child.kill('SIGKILL'); fs.rmSync(dataDir, { recursive: true, force: true }); });+ h.api = `http://127.0.0.1:${await boundPort(child, () => h.log)}`;+ return h;+}++// Step one happens on the attacker's own machine: no browser, so no Origin and no Sec-Fetch-Site.+async function attackerChallenge(h) {+ const r = await fetch(`${h.api}/api/login/options`, { method: 'POST' });+ assert.equal(r.status, 200);+ const { cid, options } = await r.json();+ return { cid, credential: assertion(options.challenge) };+}++// What <form enctype="text/plain"> builds out of one field whose name is most of a JSON document:+// `name=value` and a CRLF. The value closes the string the name left open.+const textPlainForm = obj => JSON.stringify({ ...obj, pad: '' }).slice(0, -2) + '=' + '"}' + '\r\n';+const sessionUid = r => /__Host-gymsid=([^.;]+)/.exec(r.headers.get('set-cookie') || '')?.[1]?.split(':')[0] || null;++test('a cross-site form cannot sign the victim into the attacker\'s account', async t => {+ const h = await startServer(t);+ const r = await fetch(`${h.api}/api/login/verify`, {+ method: 'POST',+ // The victim's browser: a top-level cross-site form POST. Their Lax session cookie is not+ // sent, and does not need to be; the response is what would replace it.+ headers: { 'Content-Type': 'text/plain', Origin: 'https://evil.test', 'Sec-Fetch-Site': 'cross-site' },+ body: textPlainForm(await attackerChallenge(h))+ });+ assert.equal(sessionUid(r), null, 'no session cookie for the attacker\'s account');+ assert.equal(r.status, 403);+ assert.deepEqual(await r.json(), { error: 'cross-origin request refused' });+});++test('the passkey routes are origin-checked, even with a JSON body', async t => {+ const h = await startServer(t);+ const cross = { 'Content-Type': 'application/json', Origin: 'https://evil.test', 'Sec-Fetch-Site': 'cross-site' };+ for (const p of ['/api/login/options', '/api/login/verify', '/api/register/options', '/api/register/verify']) {+ const r = await fetch(`${h.api}${p}`, { method: 'POST', headers: cross, body: JSON.stringify(p === '/api/login/verify' ? await attackerChallenge(h) : { name: 'x' }) });+ assert.equal(r.status, 403, p);+ assert.equal(sessionUid(r), null, p);+ }+ // A sibling subdomain is the same site, which is exactly what SameSite=Lax lets through.+ const r = await fetch(`${h.api}/api/login/verify`, {+ method: 'POST', headers: { ...cross, Origin: 'https://other.test', 'Sec-Fetch-Site': 'same-site' },+ body: JSON.stringify(await attackerChallenge(h))+ });+ assert.equal(r.status, 403);+ // A browser that does not send Sec-Fetch-Site still sends Origin, and that is compared.+ const noFetchSite = await fetch(`${h.api}/api/login/verify`, {+ method: 'POST', headers: { 'Content-Type': 'application/json', Origin: 'https://evil.test' },+ body: JSON.stringify(await attackerChallenge(h))+ });+ assert.equal(noFetchSite.status, 403);+});++test('a body not declared as JSON is refused before anything reads it', async t => {+ const h = await startServer(t);+ // No Origin, no Sec-Fetch-Site: past the origin check, so this is the body rule on its own.+ // `text/plain; application/json` is still text/plain to a browser (no preflight), so the match+ // has to be on the media type itself, not anywhere in the header.+ for (const type of ['text/plain', 'text/plain;charset=UTF-8', 'text/plain; application/json', 'application/x-www-form-urlencoded', 'multipart/form-data; boundary=x', null]) {+ const r = await fetch(`${h.api}/api/login/verify`, {+ method: 'POST', headers: type ? { 'Content-Type': type } : {}, body: Buffer.from(textPlainForm(await attackerChallenge(h)))+ });+ assert.equal(r.status, 415, String(type));+ assert.deepEqual(await r.json(), { error: 'content-type must be application/json' });+ assert.equal(sessionUid(r), null, String(type));+ }+ // pair/redeem stays exempt from the origin check (the phone's WebView is never ORIGIN), so on+ // that route this rule is the one that keeps a form out.+ const pair = await fetch(`${h.api}/api/pair/redeem`, {+ method: 'POST', headers: { 'Content-Type': 'text/plain', Origin: 'https://evil.test', 'Sec-Fetch-Site': 'cross-site' },+ body: '{"code":"ABCDEFGH","x":"="}'+ });+ assert.equal(pair.status, 415);+});++test('the app\'s own sign-in still works, charset and all, and body-less posts are untouched', async t => {+ const h = await startServer(t);+ const same = { 'Content-Type': 'application/json; charset=utf-8', Origin: ORIGIN, 'Sec-Fetch-Site': 'same-origin' };+ const opts = await fetch(`${h.api}/api/login/options`, { method: 'POST', headers: same, body: '{}' });+ assert.equal(opts.status, 200);+ const { cid, options } = await opts.json();+ const r = await fetch(`${h.api}/api/login/verify`, { method: 'POST', headers: same, body: JSON.stringify({ cid, credential: assertion(options.challenge) }) });+ assert.equal(r.status, 200, JSON.stringify(await r.clone().json()));+ assert.equal(sessionUid(r), 'u_attacker', 'the passkey\'s owner, signed in on their own device');++ // Older Safari: no Sec-Fetch-Site, an Origin that is ORIGIN.+ assert.equal((await fetch(`${h.api}/api/login/options`, { method: 'POST', headers: { Origin: ORIGIN } })).status, 200);+ // Routes that read no body never needed a Content-Type, and a POST with no body has nothing to declare.+ const victim = { Cookie: `__Host-gymsid=${mintSession('u_victim')}`, 'Sec-Fetch-Site': 'same-origin' };+ assert.equal((await fetch(`${h.api}/api/push/rest-timer/cancel`, { method: 'POST', headers: victim })).status, 200);+ assert.equal((await fetch(`${h.api}/api/logout`, { method: 'POST', headers: victim })).status, 200);+});++// The Bearer shortcut in csrfOk skips the origin check for a request a Bearer authenticates by+// itself. On the passkey routes no Bearer is the credential that acts (the assertion in the body+// is), so any valid token bought the skip there, the attacker's own included, and only the CORS+// preflight never allowing credentials kept a browser from storing the Set-Cookie that came back.+test('a valid Bearer, even the attacker\'s own, does not switch the origin check off on the passkey routes', async t => {+ const h = await startServer(t);+ const own = { Authorization: `Bearer ${mintSession('u_attacker')}`, 'Content-Type': 'application/json', Origin: 'https://evil.test', 'Sec-Fetch-Site': 'cross-site' };+ const r = await fetch(`${h.api}/api/login/verify`, { method: 'POST', headers: own, body: JSON.stringify(await attackerChallenge(h)) });+ assert.equal(sessionUid(r), null, 'no session cookie for the attacker\'s account');+ assert.notEqual(r.status, 200);+ for (const p of ['/api/login/options', '/api/register/options', '/api/register/verify']) {+ const x = await fetch(`${h.api}${p}`, { method: 'POST', headers: own, body: JSON.stringify({ name: 'x', cid: 'nope' }) });+ assert.equal(x.status, 403, p);+ }+ assert.equal(r.status, 403);+ // The same token still carries the paired app everywhere it is the credential.+ const act = await fetch(`${h.api}/api/activity`, { method: 'POST', headers: own, body: JSON.stringify({ active: false }) });+ assert.equal(act.status, 200);+});++// The same holds for the password, reset-code and device-code routes: the credential is in the+// body, so a Bearer, any valid one, buys no skip of the origin check there.+test('a valid Bearer does not switch the origin check off on the password and device-code routes', async t => {+ const h = await startServer(t, { PASSWORD_LOGIN: '1' });+ const own = { Authorization: `Bearer ${mintSession('u_attacker')}`, 'Content-Type': 'application/json', Origin: 'https://evil.test', 'Sec-Fetch-Site': 'cross-site' };+ for (const p of ['/api/login/password', '/api/register/password', '/api/login/password-reset', '/api/device-link/options', '/api/device-link/verify']) {+ const r = await fetch(`${h.api}${p}`, { method: 'POST', headers: own, body: JSON.stringify({ name: 'Attacker', password: 'correct horse battery', code: 'x' }) });+ assert.equal(r.status, 403, p);+ assert.equal(sessionUid(r), null, p);+ }+ // The same token still carries the paired app everywhere it is the credential.+ const act = await fetch(`${h.api}/api/activity`, { method: 'POST', headers: own, body: JSON.stringify({ active: false }) });+ assert.equal(act.status, 200);+});diff --git a/api/test/server-nudge.test.js b/api/test/server-nudge.test.jsindex 4a9e4d714..8852f690c 100644--- a/api/test/server-nudge.test.js+++ b/api/test/server-nudge.test.js@@ -115,7 +115,7 @@ test('no push subscription, or a workout on screen right now: no nudge', async tconst h = await startServer(t);const live = await fetch(`${h.api}/api/activity`, {- method: 'POST', headers: { Cookie: `gymsid=${mintSession(UID)}` },+ method: 'POST', headers: { Cookie: `gymsid=${mintSession(UID)}`, 'Content-Type': 'application/json' },body: JSON.stringify({ active: true, name: 'Push Day', startedAt: Date.now() })});assert.equal(live.status, 200);@@ -123,7 +123,7 @@ test('no push subscription, or a workout on screen right now: no nudge', async tawait wait(1000);assert.equal(firings(h.log), 0, `a session is under way:\n${h.log}`);// the session ends without a workout being saved: the nudge is owed again- await fetch(`${h.api}/api/activity`, { method: 'POST', headers: { Cookie: `gymsid=${mintSession(UID)}` }, body: JSON.stringify({ active: false }) });+ await fetch(`${h.api}/api/activity`, { method: 'POST', headers: { Cookie: `gymsid=${mintSession(UID)}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ active: false }) });await until(() => firings(h.log) > 0);assert.equal(firings(h.log), 1, h.log);});diff --git a/api/test/server-pairing.test.js b/api/test/server-pairing.test.jsindex cd8d909d1..e5154ba5e 100644--- a/api/test/server-pairing.test.js+++ b/api/test/server-pairing.test.js@@ -48,7 +48,7 @@ async function startServer(t) {test('logout/all invalidates the account\'s outstanding pairing codes and nobody else\'s', async t => {const h = await startServer(t);- const post = (p, headers, body) => fetch(`${h.api}${p}`, { method: 'POST', headers, body: body && JSON.stringify(body) });+ const post = (p, headers, body) => fetch(`${h.api}${p}`, { method: 'POST', headers: body ? { ...headers, 'Content-Type': 'application/json' } : headers, body: body && JSON.stringify(body) });const create = async (uid, sv) => {const r = await post('/api/pair/create', cookie(uid, sv));assert.equal(r.status, 200);diff --git a/api/test/server-push-allowed-private.test.js b/api/test/server-push-allowed-private.test.jsindex 7f3f8e86e..93707c433 100644--- a/api/test/server-push-allowed-private.test.js+++ b/api/test/server-push-allowed-private.test.js@@ -37,7 +37,7 @@ async function startServer(t, allowedPrivateIps) {t.after(() => { child.kill('SIGKILL'); fs.rmSync(dataDir, { recursive: true, force: true }); });h.api = `http://127.0.0.1:${await boundPort(child, () => h.log)}`;h.subscribe = async endpoint => (await fetch(`${h.api}/api/push/subscribe`, {- method: 'POST', headers: cookie, body: JSON.stringify({ subscription: { endpoint, keys } })+ method: 'POST', headers: { ...cookie, 'Content-Type': 'application/json' }, body: JSON.stringify({ subscription: { endpoint, keys } })})).status;return h;}diff --git a/api/test/server-push-filter.test.js b/api/test/server-push-filter.test.jsindex f0551411d..33deaa965 100644--- a/api/test/server-push-filter.test.js+++ b/api/test/server-push-filter.test.js@@ -55,7 +55,7 @@ async function startServer(t, subs = []) {test('subscribe refuses every spelling of a private IP literal and accepts public ones', async t => {const h = await startServer(t);const subscribe = endpoint => fetch(`${h.api}/api/push/subscribe`, {- method: 'POST', headers: cookie, body: JSON.stringify({ subscription: { endpoint, keys } })+ method: 'POST', headers: { ...cookie, 'Content-Type': 'application/json' }, body: JSON.stringify({ subscription: { endpoint, keys } })});const privateForms = ['https://[::ffff:127.0.0.1]/x', // mapped loopback, dotteddiff --git a/api/test/server-push-status.test.js b/api/test/server-push-status.test.jsindex 1f01c0cec..3b242b9f3 100644--- a/api/test/server-push-status.test.js+++ b/api/test/server-push-status.test.js@@ -46,7 +46,7 @@ async function startServer(t, subs = []) {return h;}const readDb = h => JSON.parse(fs.readFileSync(path.join(h.dataDir, 'db.json'), 'utf8'));-const post = (h, p, body, hdr = cookie) => fetch(`${h.api}${p}`, { method: 'POST', headers: hdr, body: JSON.stringify(body) });+const post = (h, p, body, hdr = cookie) => fetch(`${h.api}${p}`, { method: 'POST', headers: { ...hdr, 'Content-Type': 'application/json' }, body: JSON.stringify(body) });const status = (h, endpoint, hdr = cookie) => fetch(`${h.api}/api/push/status?endpoint=${encodeURIComponent(endpoint)}`, { headers: hdr }).then(r => r.json());test('status tells whether the server holds the endpoint; subscribe is an upsert that keeps created and stores the device id', async t => {diff --git a/api/test/server-reminder.test.js b/api/test/server-reminder.test.jsindex 451f81fcb..0b373cc85 100644--- a/api/test/server-reminder.test.js+++ b/api/test/server-reminder.test.js@@ -52,7 +52,7 @@ async function startServer(t, subs = []) {test('PUT /api/data refuses a state whose workouts or routines is not an array', async t => {const h = await startServer(t);- const put = state => fetch(`${h.api}/api/data`, { method: 'PUT', headers: cookie, body: JSON.stringify({ state }) });+ const put = state => fetch(`${h.api}/api/data`, { method: 'PUT', headers: { ...cookie, 'Content-Type': 'application/json' }, body: JSON.stringify({ state }) });const file = path.join(h.dataDir, 'state-u_test_1.json');for (const bad of [{ workouts: {} }, { workouts: 'abc' }, { workouts: 7 }, { workouts: true }, { routines: {} }, { routines: 'r1' }, { workouts: [], routines: {} }]) {diff --git a/docs/SELF_HOSTING.md b/docs/SELF_HOSTING.mdindex df5bdb53c..d15260de0 100644--- a/docs/SELF_HOSTING.md+++ b/docs/SELF_HOSTING.md@@ -79,6 +79,8 @@ you're poking at the API directly:header, so the app's own WebView origin can call the API cross-origin. It never sends`Access-Control-Allow-Credentials`, so this doesn't let a browser read your cookie sessionfrom another origin — only bearer-token requests benefit from it.+- A request body has to be sent as `Content-Type: application/json`; any other type gets a+ `415`. `curl -d` sends a form type, so a script needs `-H 'Content-Type: application/json'`.## 3. Expose it over HTTPS on your own domaindiff --git a/website/api.html b/website/api.htmlindex 645aeca0d..fece9ea1e 100644--- a/website/api.html+++ b/website/api.html@@ -273,7 +273,7 @@ main.api-main .lead { color: var(--fg-2); max-width: 58ch; margin: 14px 0 0; fon</div><div class="ov"><h3>CSRF</h3>-<p>State-changing browser requests must come from the app's own origin. The server checks <code>Sec-Fetch-Site</code> (falling back to <code>Origin</code> vs the configured <code>ORIGIN</code>); a mismatch is refused with <code>403 {"error":"cross-origin request refused"}</code> on any non-GET route. Exempt: passkey sign-up and sign-in (<code>register/options</code>, <code>register/verify</code>, <code>login/options</code>, <code>login/verify</code>) and <code>pair/redeem</code>, each of which carries its own one-shot credential in the body, and any request authenticated with a Bearer token. The password routes are <b>not</b> exempt: a hostile page knows a valid name and password of its own, and could otherwise sign a visitor into it (login CSRF). Neither are the device-link routes: a link is redeemed on the app's own origin, the only one a passkey can be created for.</p>+<p>State-changing browser requests must come from the app's own origin. The server checks <code>Sec-Fetch-Site</code> (falling back to <code>Origin</code> vs the configured <code>ORIGIN</code>); a mismatch is refused with <code>403 {"error":"cross-origin request refused"}</code> on any non-GET route, the passkey routes included. Exempt: <code>pair/redeem</code>, which the mobile app calls from its own origin (the code in the body is the credential, and the token comes back in the body, never as a cookie), and any request a Bearer token authenticates by itself: a valid session token, with no session cookie beside it, on any route but the sign-in ones — the four passkey routes, the password and reset-code routes and the two device-link routes, which act on the credential in the body, never on a Bearer. A cross-origin request whose Bearer does not buy the exemption is refused before any handler runs: <code>401 {"error":"not signed in"}</code> when that Bearer does not verify and is the only credential (a paired app whose token was revoked or expired), the 403 otherwise. The passkey routes were exempt before, on the grounds that the challenge id is a credential; but it is bound to nothing else, so a hostile page could complete the attacker's own passkey sign-in in the victim's browser (login CSRF) and the answer set the victim's session to the attacker's account. The password routes are <b>not</b> exempt for the same reason: a hostile page knows a valid name and password of its own.</p></div><div class="ov"><h3>Environment-dependent behavior</h3>@@ -281,7 +281,7 @@ main.api-main .lead { color: var(--fg-2); max-width: 58ch; margin: 14px 0 0; fon</div><div class="ov"><h3>Conventions</h3>-<ul><li>Every response body is JSON with <code>Cache-Control: no-store</code>. The one exception is <code>GET /api/media/{hash}</code>, which answers with the stored file itself (<code>Cache-Control: private, no-store</code>).</li><li>Errors are always <code>{"error": "<human-readable message>"}</code>. The <code>password</code>, throttle and <code>media</code> routes add a stable <code>code</code> for the client to word in its own language.</li><li>Unknown method+path pairs return <code>404 {"error":"not found"}</code>; an unhandled exception returns <code>500 {"error":"server error"}</code>.</li><li>Request bodies are parsed as JSON regardless of Content-Type. A body that does not parse, or parses to anything but an object (<code>null</code>, a string, an array), is <code>400 {"error":"invalid json"}</code> on every route that reads one; an empty body counts as <code>{}</code>. A body over 5 MiB is <code>413 {"error":"body too large"}</code>; the rest of the upload is discarded so the answer reaches the client.</li><li>CORS: the request's <code>Origin</code> is reflected in <code>Access-Control-Allow-Origin</code> <b>without</b> <code>Allow-Credentials</code>, so cross-origin callers can only ever authenticate with a Bearer token, never with the cookie.</li></ul>+<ul><li>Every response body is JSON with <code>Cache-Control: no-store</code>. The one exception is <code>GET /api/media/{hash}</code>, which answers with the stored file itself (<code>Cache-Control: private, no-store</code>).</li><li>Errors are always <code>{"error": "<human-readable message>"}</code>. The <code>password</code>, throttle and <code>media</code> routes add a stable <code>code</code> for the client to word in its own language.</li><li>Unknown method+path pairs return <code>404 {"error":"not found"}</code>; an unhandled exception returns <code>500 {"error":"server error"}</code>.</li><li>Every route that reads a request body requires <code>Content-Type: application/json</code> (a <code>charset</code> parameter is fine) and answers any other type with <code>415 {"error":"content-type must be application/json"}</code> — the types a form can send are the ones that skip the CORS preflight, which is how a cross-site form reached these routes. A request with no body needs no Content-Type. A body that does not parse, or parses to anything but an object (<code>null</code>, a string, an array), is <code>400 {"error":"invalid json"}</code> on every route that reads one; an empty body counts as <code>{}</code>. A body over 5 MiB is <code>413 {"error":"body too large"}</code>; the rest of the upload is discarded so the answer reaches the client.</li><li>CORS: the request's <code>Origin</code> is reflected in <code>Access-Control-Allow-Origin</code> <b>without</b> <code>Allow-Credentials</code>, so cross-origin callers can only ever authenticate with a Bearer token, never with the cookie.</li></ul></div></div></section>@@ -391,7 +391,7 @@ main.api-main .lead { color: var(--fg-2); max-width: 58ch; margin: 14px 0 0; fon</summary><div class="ep-body"><p>Returns <code>PublicKeyCredentialCreationOptions</code> (from <code>@simplewebauthn/server</code>'s <code>generateRegistrationOptions</code>) plus a challenge id <code>cid</code>. The client passes <code>options</code> to <code>navigator.credentials.create()</code> (or <code>@simplewebauthn/browser</code>'s <code>startRegistration</code>) and sends the result to <code>/api/register/verify</code> together with the <code>cid</code>. Challenges are one-shot and expire after 5 minutes.</p>-<p>CSRF-exempt (the challenge is the credential). No session required.</p>+<p>No session required.</p><p class="ep-auth"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="4" y="11" width="16" height="10" rx="2.5"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></svg><span>Public: no authentication required.</span></p><p class="ep-h">Request body <span class="p-hint">(JSON)</span></p><div class="ptab">@@ -436,7 +436,7 @@ main.api-main .lead { color: var(--fg-2); max-width: 58ch; margin: 14px 0 0; fon<span class="ep-sum">Finish passkey registration (WebAuthn ceremony, step 2)</span></summary><div class="ep-body">-<p>Verifies the authenticator's attestation response against the stored challenge (<code>verifyRegistrationResponse</code>), 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.</p>+<p>Verifies the authenticator's attestation response against the stored challenge (<code>verifyRegistrationResponse</code>), 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.</p><p class="ep-auth"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="4" y="11" width="16" height="10" rx="2.5"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></svg><span>Public: no authentication required.</span></p><p class="ep-h">Request body <span class="p-hint">(JSON)</span></p><div class="ptab">@@ -481,7 +481,7 @@ main.api-main .lead { color: var(--fg-2); max-width: 58ch; margin: 14px 0 0; fon<span class="ep-sum">Start passkey login (WebAuthn ceremony, step 1)</span></summary><div class="ep-body">-<p>Returns <code>PublicKeyCredentialRequestOptions</code> (<code>generateAuthenticationOptions</code> with an empty <code>allowCredentials</code>; discoverable credentials / resident keys are required at registration, so the browser offers the user their passkeys itself) plus a one-shot challenge id <code>cid</code>. CSRF-exempt. Takes no request body.</p>+<p>Returns <code>PublicKeyCredentialRequestOptions</code> (<code>generateAuthenticationOptions</code> with an empty <code>allowCredentials</code>; discoverable credentials / resident keys are required at registration, so the browser offers the user their passkeys itself) plus a one-shot challenge id <code>cid</code>. Takes no request body.</p><p class="ep-auth"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="4" y="11" width="16" height="10" rx="2.5"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></svg><span>Public: no authentication required.</span></p>@@ -503,7 +503,7 @@ main.api-main .lead { color: var(--fg-2); max-width: 58ch; margin: 14px 0 0; fon<span class="ep-sum">Finish passkey login (WebAuthn ceremony, step 2)</span></summary><div class="ep-body">-<p>Verifies the assertion (<code>verifyAuthenticationResponse</code>), updates the signature counter, and signs the caller in (sets the session cookie). CSRF-exempt.</p>+<p>Verifies the assertion (<code>verifyAuthenticationResponse</code>), updates the signature counter, and signs the caller in (sets the session cookie).</p><p class="ep-auth"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="4" y="11" width="16" height="10" rx="2.5"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></svg><span>Public: no authentication required.</span></p><p class="ep-h">Request body <span class="p-hint">(JSON)</span></p><div class="ptab">