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: a refused cross-origin write names the ORIGIN/RP_ID fix in the log and a code in the 403
Duarte Santos96e122ceceed
diff --git a/api/openapi.yaml b/api/openapi.yamlindex 9d3007802..46cf88798 100644--- a/api/openapi.yaml+++ b/api/openapi.yaml@@ -59,7 +59,7 @@ info:### CSRFState-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+ a mismatch is refused with `403 {"error":"cross-origin request refused","code":"origin-mismatch","expected":ORIGIN}` on anynon-GET route, the passkey routes included. Exempt: `pair/redeem`, which the mobileapp calls from its own origin (the code in the body is the credential, and the tokencomes back in the body, never as a cookie), and any request a Bearer token@@ -1878,7 +1878,7 @@ paths:content:application/json:schema: { $ref: '#/components/schemas/Error' }- example: { error: "cross-origin request refused" }+ example: { error: "cross-origin request refused", code: "origin-mismatch", expected: "https://gym.example.com" }'408':description: No bytes arrived for 60 seconds (`timeout`). The connection is closed.content:@@ -1973,7 +1973,7 @@ paths:content:application/json:schema: { $ref: '#/components/schemas/Error' }- example: { error: "cross-origin request refused" }+ example: { error: "cross-origin request refused", code: "origin-mismatch", expected: "https://gym.example.com" }/api/media/sweep:post:@@ -2012,7 +2012,7 @@ paths:content:application/json:schema: { $ref: '#/components/schemas/Error' }- example: { error: "cross-origin request refused" }+ example: { error: "cross-origin request refused", code: "origin-mismatch", expected: "https://gym.example.com" }'429':description: More than 10 sweeps this hour (`locked`).headers:diff --git a/api/server.js b/api/server.jsindex 2229e8356..807456dee 100644--- a/api/server.js+++ b/api/server.js@@ -19,7 +19,7 @@ import { coachRoutes } from './coach/routes.js';import { startCadence } from './coach/cadence.js';import { startWarmup } from './coach/warmup.js';import { dayReminderPush, nudgePush, restTimerPush, testPush } from './push-messages.js';-import { verifyError } from './verify-error.js';+import { verifyError, isMisconfigured, originHint } from './verify-error.js';import {hashPassword, verifyPassword, needsRehash, passwordProblem, passwordLength, nameKey, BusyError,MIN_LENGTH, MAX_LENGTH, makeResetCode, hashResetCode, resetCodeMatches, RESET_TTL_MS, warmUp,@@ -757,6 +757,12 @@ 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']);+// A verify error as the answer's body: a passkey made at an address that is not ORIGIN/RP_ID gets+// the same `code` as the origin check's 403, so the app explains both alike.+const verifyAnswer = e => ({+ error: verifyError(e, { rpId: RP_ID, origin: ORIGIN }),+ ...(isMisconfigured(e) ? { code: 'origin-mismatch', expected: ORIGIN } : {})+});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).@@ -1738,7 +1744,7 @@ async function newPasskey(req, res, c, body, ev, user) {} catch (e) {// e.message can echo attacker-supplied response fields, so only the reason code is kept.audit(req, ev, { ok: false, user, msg: 'verify-error' });- json(res, 400, { error: verifyError(e, { rpId: RP_ID, origin: ORIGIN }) });+ json(res, 400, verifyAnswer(e));return null;}if (!verification.verified) {@@ -2198,7 +2204,7 @@ const routes = {} catch (e) {// e.message can echo attacker-supplied response fields, so only the reason code is kept.auditFail(req, 'auth.register.fail', { ok: false, name: c.name, msg: 'verify-error' });- return json(res, 400, { error: verifyError(e, { rpId: RP_ID, origin: ORIGIN }) });+ return json(res, 400, verifyAnswer(e));}if (!verification.verified) {auditFail(req, 'auth.register.fail', { ok: false, name: c.name, msg: 'not-verified' });@@ -2275,7 +2281,7 @@ const routes = {});} catch (e) {auditFail(req, 'auth.login.fail', { ok: false, user: db.users.find(u => u.id === cred.userId), uid: cred.userId, msg: 'verify-error' });- return json(res, 400, { error: verifyError(e, { rpId: RP_ID, origin: ORIGIN }) });+ return json(res, 400, verifyAnswer(e));}if (!verification.verified) {auditFail(req, 'auth.login.fail', { ok: false, user: db.users.find(u => u.id === cred.userId), uid: cred.userId, msg: 'not-verified' });@@ -3011,8 +3017,10 @@ const server = http.createServer(async (req, res) => {// 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.- console.warn('refused cross-origin', key, 'origin=' + req.headers.origin, 'expected=' + ORIGIN);- return json(res, 403, { error: 'cross-origin request refused' });+ // The answer carries ORIGIN too (the app shows it, see passkeyError in lib/api.js): it is no+ // secret, and a hostile page cannot read a response CORS never allowed it.+ console.warn(originHint(key, req.headers.origin, ORIGIN, req.headers['sec-fetch-site']));+ return json(res, 403, { error: 'cross-origin request refused', code: 'origin-mismatch', expected: ORIGIN });}// After the origin check, so a forged request spends nobody's budget. The password routes only// (see the sign-in throttle above).diff --git a/api/test/server-csrf-bearer.test.js b/api/test/server-csrf-bearer.test.jsindex a88492df8..a718778ba 100644--- a/api/test/server-csrf-bearer.test.js+++ b/api/test/server-csrf-bearer.test.js@@ -54,7 +54,7 @@ test('a Bearer header that authenticates nothing does not switch the origin chec// 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' });+ assert.deepEqual(await r.json(), { error: 'cross-origin request refused', code: 'origin-mismatch', expected: 'https://gym.test' });// 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.diff --git a/api/test/server-login-csrf.test.js b/api/test/server-login-csrf.test.jsindex 03aeaa72d..e8f176ce4 100644--- a/api/test/server-login-csrf.test.js+++ b/api/test/server-login-csrf.test.js@@ -104,7 +104,7 @@ test('a cross-site form cannot sign the victim into the attacker\'s account', as});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' });+ assert.deepEqual(await r.json(), { error: 'cross-origin request refused', code: 'origin-mismatch', expected: 'https://gym.test' });});test('the passkey routes are origin-checked, even with a JSON body', async t => {diff --git a/api/test/server-origin-hint.test.js b/api/test/server-origin-hint.test.jsnew file mode 100644index 000000000..018598902--- /dev/null+++ b/api/test/server-origin-hint.test.js@@ -0,0 +1,68 @@+/* Self-hosting friction (Discord tcmac, 10-21): an api service whose ORIGIN is not the address in+ the browser. Over plain http to a LAN address there is no Sec-Fetch-Site, the Origin is compared+ with ORIGIN, and every write is refused. The log has to say which setting fixes it, and the 403+ carries a `code` the app turns into a sentence instead of a bare "cross-origin request refused".+ A passkey ceremony made at the wrong address says the same. 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, softPasskey } from './helpers.mjs';++const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');+const ORIGIN = 'http://localhost:8080';+const key = softPasskey(ORIGIN);++async function startServer(t) {+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-originhint-'));+ fs.writeFileSync(path.join(dataDir, 'secret'), crypto.randomBytes(32).toString('hex'), { mode: 0o600 });+ fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({+ users: [{ id: 'u1', name: 'Ana', created: new Date().toISOString() }],+ creds: [key.row('u1')], 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: 'localhost' }+ });+ 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;+}+const post = (h, p, body, headers = {}) => fetch(h.api + p, { method: 'POST', headers: { 'Content-Type': 'application/json', ...headers }, body: JSON.stringify(body) });++test('a write from the LAN address names ORIGIN in the log and the answer', async t => {+ const h = await startServer(t);+ const r = await post(h, '/api/login/options', {}, { Origin: 'http://10.11.0.4:3030' });+ assert.equal(r.status, 403);+ assert.deepEqual(await r.json(), { error: 'cross-origin request refused', code: 'origin-mismatch', expected: ORIGIN });+ const line = h.log.split('\n').find(l => l.startsWith('refused cross-origin'));+ assert.match(line, /origin="http:\/\/10\.11\.0\.4:3030" expected=http:\/\/localhost:8080/);+ assert.match(line, /set ORIGIN=http:\/\/10\.11\.0\.4:3030 and RP_ID=10\.11\.0\.4 on the api service/);+});++test('a page on another site gets the same refusal, and the log does not advise changing ORIGIN', async t => {+ const h = await startServer(t);+ const r = await post(h, '/api/login/options', {}, { Origin: 'https://evil.test', 'Sec-Fetch-Site': 'cross-site' });+ assert.equal(r.status, 403);+ assert.equal((await r.json()).code, 'origin-mismatch');+ const line = h.log.split('\n').find(l => l.startsWith('refused cross-origin'));+ assert.doesNotMatch(line, /set ORIGIN/);+});++test('a passkey made at another address is refused with the same code', async t => {+ const h = await startServer(t);+ const { cid, options } = await (await post(h, '/api/login/options', {})).json();+ const r = await post(h, '/api/login/verify', { cid, credential: key.assertion(options.challenge, { origin: 'http://10.11.0.4:3030' }) });+ assert.equal(r.status, 400);+ const body = await r.json();+ assert.equal(body.code, 'origin-mismatch');+ assert.equal(body.expected, ORIGIN);+ assert.match(body.error, /ORIGIN=http:\/\/localhost:8080/);+});diff --git a/api/test/verify-error.test.js b/api/test/verify-error.test.jsindex 933d8aae5..27a882c8c 100644--- a/api/test/verify-error.test.js+++ b/api/test/verify-error.test.js@@ -1,6 +1,6 @@import test from 'node:test';import assert from 'node:assert/strict';-import { verifyError } from '../verify-error.js';+import { verifyError, originHint, isMisconfigured } from '../verify-error.js';const cfg = { rpId: 'gym.example.com', origin: 'https://gym.example.com' };@@ -27,3 +27,29 @@ test('does not throw on a missing or empty error', () => {assert.equal(verifyError(undefined, cfg), 'verification failed: verification failed');assert.equal(verifyError(new Error(''), cfg), 'verification failed: verification failed');});++test('a refused write names the setting that fixes it when the browser is just at another address', () => {+ const line = originHint('POST /api/data', 'http://10.11.0.4:3030', 'http://localhost:8080', undefined);+ assert.match(line, /^refused cross-origin POST \/api\/data: origin="http:\/\/10\.11\.0\.4:3030" expected=http:\/\/localhost:8080/);+ assert.match(line, /set ORIGIN=http:\/\/10\.11\.0\.4:3030 and RP_ID=10\.11\.0\.4 on the api service/);+});++test('a page on another site is not told to change ORIGIN', () => {+ const line = originHint('POST /api/data', 'https://evil.test', 'https://gym.test', 'cross-site');+ assert.doesNotMatch(line, /set ORIGIN/);+ assert.match(line, /sec-fetch-site="cross-site"/);+});++test('an Origin header cannot add a line or a suggestion of its own', () => {+ const line = originHint('POST /api/data', 'http://a\nrefused cross-origin fake', 'https://gym.test');+ assert.equal(line.split('\n').length, 1);+ assert.doesNotMatch(line, /set ORIGIN/);+ assert.match(originHint('POST /api/data', undefined, 'https://gym.test'), /origin=\(none\)/);+ assert.doesNotMatch(originHint('POST /api/data', 'null', 'https://gym.test'), /set ORIGIN/);+});++test('tells an origin or RP ID mismatch apart from other verify errors', () => {+ assert.equal(isMisconfigured(new Error('Unexpected RP ID hash')), true);+ assert.equal(isMisconfigured(new Error('Signature verification failed')), false);+ assert.equal(isMisconfigured(undefined), false);+});diff --git a/api/verify-error.js b/api/verify-error.jsindex 935680eeb..57e4e5211 100644--- a/api/verify-error.js+++ b/api/verify-error.js@@ -10,3 +10,24 @@ export function verifyError(e, { rpId, origin } = {}) {return `${msg}. This server is configured with RP_ID=${rpId} and ORIGIN=${origin}, and both `+ 'must match the address you opened. See docs/SELF_HOSTING.md.';}++// Whether a verify error is that misconfiguration, so the route can say so with a `code` the app+// turns into a sentence in the user's language.+export const isMisconfigured = e => MISCONFIGURED.test(String((e && e.message) || ''));++// The log line for a write refused by the origin check. tcmac lost a morning to a bare+// "origin=... expected=..." (Discord, 10-21): the usual cause is not an attack but an api service+// whose ORIGIN is not the address in the browser, so the line says which setting fixes it. Over+// plain http to a LAN address the browser sends no Sec-Fetch-Site (only trustworthy origins get+// one), and Origin is all there is to compare; when it is present the browser itself said the+// page is another site, and no ORIGIN fixes that. The Origin header is the caller's to choose,+// so it is printed escaped and cut short, never as a second line.+export function originHint(key, origin, expected, site) {+ const shown = origin == null ? '(none)' : JSON.stringify(String(origin).slice(0, 200));+ const head = `refused cross-origin ${key}: origin=${shown} expected=${expected}`;+ if (site) return `${head} (the browser says sec-fetch-site=${JSON.stringify(String(site).slice(0, 20))}: open the app at its own address, where the web service proxies /api, not from another site)`;+ let u = null;+ try { u = new URL(String(origin)); } catch { /* not an address, nothing to suggest */ }+ if (!u || !/^https?:$/.test(u.protocol) || u.origin !== String(origin).replace(/\/+$/, '')) return head;+ return `${head}. If ${u.origin} is where you open openGym, set ORIGIN=${u.origin} and RP_ID=${u.hostname} on the api service and restart it (docs/SELF_HOSTING.md)`;+}diff --git a/website/api.html b/website/api.htmlindex 56a18f44c..0b0d1874b 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, 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>+<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":"origin-mismatch","expected":ORIGIN}</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>