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
Pairing a phone asks the owner proof
Duarte Santosde52c43f1d0b
diff --git a/api/openapi.yaml b/api/openapi.yamlindex aee8eb459..dbab4e326 100644--- a/api/openapi.yaml+++ b/api/openapi.yaml@@ -650,7 +650,15 @@ paths:Called from an already signed-in browser tab (Settings → "Pair the mobileapp"). Returns an 8-character code (alphabet without 0/O/1/I) the phoneredeems within 5 minutes via /api/pair/redeem. One-shot. One live code per- profile: minting a new one retires the previous one.+ profile: minting a new one retires the previous one. Same proof as a device+ link (a passkey assertion made for this request, or the current password while+ password sign-in is on), since the phone token a code turns into is renewed for+ as long as it is used. Audited as `auth.pair.create`.+ requestBody:+ required: true+ content:+ application/json:+ schema: { $ref: '#/components/schemas/OwnerProof' }responses:'200':description: A fresh pairing code.@@ -664,6 +672,9 @@ paths:description: 8 chars from ABCDEFGHJKLMNPQRSTUVWXYZ23456789.example: { code: "K7WQ2MZP" }'401': { $ref: '#/components/responses/Unauthorized' }+ '403': { $ref: '#/components/responses/ProofRefused' }+ '429': { $ref: '#/components/responses/TooManyRequests' }+ '503': { $ref: '#/components/responses/Busy' }/api/pair/redeem:post:diff --git a/api/server.js b/api/server.jsindex 6629e7b62..9662248d0 100644--- a/api/server.js+++ b/api/server.js@@ -1081,6 +1081,8 @@ const THROTTLED = {// budget: the password that may prove them counts its own failures (passwordAttempt).'POST /api/device-link/options': 'link', 'POST /api/device-link/verify': 'link','POST /api/account/passkeys/options': null, 'POST /api/account/device-link': null,+ // Pairing a phone: the same, for the password that may prove it.+ 'POST /api/pair/create': null,'DELETE /api/account/passkeys': null,// Deleting the account: the same, for the password that may prove it.'POST /api/account/delete': null@@ -2335,16 +2337,26 @@ const routes = {},// Mobile app pairing: called from an already signed-in browser tab (Settings → "Pair the- // mobile app") to mint a short code the phone can redeem below.+ // mobile app") to mint a short code the phone can redeem below. The code turns into a phone's+ // token, which /api/me renews for as long as it is used and which gets the device pass on the+ // account's own delete, so it asks the proof a device link asks (proveOwner): a session alone+ // may be a cookie someone walked off with, and minting a phone token is how that cookie would+ // stop having to expire.'POST /api/pair/create': async (req, res) => {const user = readSession(req);if (!user) return json(res, 401, { error: 'not signed in' });+ const body = await readBody(req);+ const proof = await proveOwner(req, res, user, body, 'pair');+ if (!proof) return;+ // Awaited: a sign-out everywhere, a disable or an admin reset may have ended this session.+ if (readSession(req) !== user) return json(res, 401, { error: 'not signed in' });+ if (proof === 'passkey') saveDb(); // the confirming passkey's counter and last use// One live code per profile: the newest is the one on screen. Keeping every code minted// let one session grow this Map without limit for five minutes at a time.for (const [k, v] of pairings) if (v.uid === user.id) pairings.delete(k);const code = makePairCode();pairings.set(code, { uid: user.id, exp: Date.now() + 5 * 60000 });- audit(req, 'auth.pair.create', { user });+ audit(req, 'auth.pair.create', { user, msg: proof });json(res, 200, { code });},diff --git a/api/test/helpers.mjs b/api/test/helpers.mjsindex 383b665f2..597e4ea91 100644--- a/api/test/helpers.mjs+++ b/api/test/helpers.mjs@@ -5,6 +5,7 @@* import. Hence dynamic imports everywhere below, and one helper that does it in the right* order. node:test runs each file in its own process, so one directory per file is enough.*/+import crypto from 'node:crypto';import fs from 'node:fs';import os from 'node:os';import path from 'node:path';@@ -101,3 +102,55 @@ export function sampleState(over = {}) {...over};}++/* A software authenticator: a P-256 key that makes attestations ("none") and assertions the way+ a browser's would, for tests that need a passkey ceremony or a passkey step-up (proveOwner).+ `row(userId)` is its db.creds entry. */+const b64u = b => Buffer.from(b).toString('base64url');+const sha = b => crypto.createHash('sha256').update(b).digest();+// Just enough CBOR for an attestation object: a map of text keys to text, bytes or an empty map.+const cborHead = (major, n) => n < 24 ? Buffer.from([(major << 5) | n])+ : n < 256 ? Buffer.from([(major << 5) | 24, n]) : Buffer.from([(major << 5) | 25, n >> 8, n & 255]);+const cborText = s => Buffer.concat([cborHead(3, Buffer.byteLength(s)), Buffer.from(s)]);+const cborBytes = b => Buffer.concat([cborHead(2, b.length), b]);++export function softPasskey(ORIGIN = 'http://localhost:8080') {+ const { privateKey, publicKey } = crypto.generateKeyPairSync('ec', { namedCurve: 'P-256' });+ const jwk = publicKey.export({ format: 'jwk' });+ const cose = Buffer.concat([+ Buffer.from([0xa5, 0x01, 0x02, 0x03, 0x26, 0x20, 0x01, 0x21, 0x58, 0x20]), Buffer.from(jwk.x, 'base64url'),+ Buffer.from([0x22, 0x58, 0x20]), Buffer.from(jwk.y, 'base64url')+ ]);+ const raw = crypto.randomBytes(16);+ const id = b64u(raw);+ let counter = 0;+ return {+ id,+ row: (userId, extra = {}) => ({ id, userId, publicKey: cose.toString('base64url'), counter: 0, transports: ['internal'], ...extra }),+ // What navigator.credentials.create() hands back, serialised the way lib/api.js does.+ attestation(challenge, { origin = ORIGIN } = {}) {+ const clientDataJSON = Buffer.from(JSON.stringify({ type: 'webauthn.create', challenge, origin, crossOrigin: false }));+ const len = Buffer.from([raw.length >> 8, raw.length & 255]);+ const authData = Buffer.concat([sha('localhost'), Buffer.from([0x45]), Buffer.alloc(4), Buffer.alloc(16), len, raw, cose]);+ const attestationObject = Buffer.concat([+ Buffer.from([0xa3]), cborText('fmt'), cborText('none'), cborText('attStmt'), Buffer.from([0xa0]),+ cborText('authData'), cborBytes(authData)+ ]);+ return {+ id, rawId: id, type: 'public-key', clientExtensionResults: {}, authenticatorAttachment: 'platform',+ response: { clientDataJSON: b64u(clientDataJSON), attestationObject: b64u(attestationObject), transports: ['internal', 'hybrid'] }+ };+ },+ assertion(challenge, { origin = ORIGIN } = {}) {+ const clientDataJSON = Buffer.from(JSON.stringify({ type: 'webauthn.get', challenge, origin, crossOrigin: false }));+ const c = Buffer.alloc(4); c.writeUInt32BE(++counter);+ const authData = Buffer.concat([sha('localhost'), Buffer.from([0x05]), c]);+ const signature = crypto.sign('sha256', Buffer.concat([authData, sha(clientDataJSON)]), privateKey);+ return {+ id, rawId: id, type: 'public-key', clientExtensionResults: {}, authenticatorAttachment: 'platform',+ response: { clientDataJSON: b64u(clientDataJSON), authenticatorData: b64u(authData), signature: b64u(signature), userHandle: null }+ };+ }+ };+}+diff --git a/api/test/server-anon-flood.test.js b/api/test/server-anon-flood.test.jsindex ce97fe729..bc79d8193 100644--- a/api/test/server-anon-flood.test.js+++ b/api/test/server-anon-flood.test.js@@ -10,7 +10,9 @@ 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';+import { boundPort, softPasskey } from './helpers.mjs';++const KEY = softPasskey();const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');const SECRET = crypto.randomBytes(32).toString('hex');@@ -25,7 +27,7 @@ async function startServer(t) {const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-flood-'));fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({- users: [{ id: 'u_test_1', name: 'One', created: new Date().toISOString() }], creds: [], subs: [], invites: []+ users: [{ id: 'u_test_1', name: 'One', created: new Date().toISOString() }], creds: [KEY.row('u_test_1')], subs: [], invites: []}));const child = spawn(process.execPath, ['server.js'], {cwd: API, stdio: ['ignore', 'pipe', 'pipe'],@@ -74,7 +76,12 @@ test('junk passkey sign-ins and sign-ups are answered but not each written to thtest('minting a pairing code retires the profile\'s previous one', async t => {const h = await startServer(t);- const mint = async () => (await (await h.post('/api/pair/create', {}, { ...cookie, Origin: 'http://localhost:8080' })).json()).code;+ // Each code asks the owner proof: a passkey assertion made for that request.+ const mint = async () => {+ const { cid, options } = await (await h.post('/api/login/options')).json();+ const body = { cid, credential: KEY.assertion(options.challenge) };+ return (await (await h.post('/api/pair/create', body, { ...cookie, Origin: 'http://localhost:8080' })).json()).code;+ };const first = await mint();const second = await mint();assert.notEqual(first, second);diff --git a/api/test/server-pairing.test.js b/api/test/server-pairing.test.jsindex 4573e0c59..531a8eb72 100644--- a/api/test/server-pairing.test.js+++ b/api/test/server-pairing.test.js@@ -1,7 +1,8 @@/* "Sign out everywhere" (POST /api/logout/all) has to take the account's outstanding pairingcodes with it: a code is a session-in-waiting, and one minted before the sign-out could- otherwise be redeemed for a fresh token carrying the new session version. Real server.js in a- child. */+ otherwise be redeemed for a fresh token carrying the new session version. And minting a code+ asks the owner proof (proveOwner): a session alone, which may be a stolen cookie, gets no code.+ Real server.js in a child. */import { test } from 'node:test';import assert from 'node:assert/strict';import crypto from 'node:crypto';@@ -10,7 +11,7 @@ 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';+import { boundPort, softPasskey } from './helpers.mjs';const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');const SECRET = crypto.randomBytes(32).toString('hex');@@ -22,6 +23,7 @@ function mintSession(uid, sv = 0) {}const cookie = (uid, sv) => ({ Cookie: `gymsid=${mintSession(uid, sv)}` });+const KEYS = { u_test_1: softPasskey(), u_test_2: softPasskey() };const USERS = [{ id: 'u_test_1', name: 'One', created: new Date().toISOString() },{ id: 'u_test_2', name: 'Two', created: new Date().toISOString() }@@ -30,7 +32,7 @@ const USERS = [async function startServer(t) {const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-pair-'));fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });- fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({ users: USERS, creds: [], subs: [], invites: [] }));+ fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({ users: USERS, creds: Object.entries(KEYS).map(([uid, k]) => k.row(uid)), subs: [], invites: [] }));const child = spawn(process.execPath, ['server.js'], {cwd: API, stdio: ['ignore', 'pipe', 'pipe'],env: { ...process.env, PORT: '0', DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost' }@@ -49,8 +51,13 @@ 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 ? { ...headers, 'Content-Type': 'application/json' } : headers, body: body && JSON.stringify(body) });+ // A passkey assertion made for this request, the way Settings confirms before showing a code.+ const proof = async uid => {+ const { cid, options } = await (await post('/api/login/options', {}, {})).json();+ return { cid, credential: KEYS[uid].assertion(options.challenge) };+ };const create = async (uid, sv) => {- const r = await post('/api/pair/create', cookie(uid, sv));+ const r = await post('/api/pair/create', cookie(uid, sv), await proof(uid));assert.equal(r.status, 200);return (await r.json()).code;};@@ -76,3 +83,34 @@ test('logout/all invalidates the account\'s outstanding pairing codes and nobodyconst { token } = await fresh.json();assert.match(token.split('.')[0], /^u_test_1:\d+:1:b$/);});++test('minting a pairing code asks the owner proof: a session alone gets none', async t => {+ const h = await startServer(t);+ const post = (p, headers, body) => fetch(`${h.api}${p}`, { method: 'POST', headers: { ...headers, 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) });+ const options = async () => (await post('/api/login/options', {}, {}).then(r => r.json()));++ // No proof: refused, and nothing a phone could redeem was made.+ const none = await post('/api/pair/create', cookie('u_test_1', 0), {});+ assert.equal(none.status, 403);+ assert.equal((await none.json()).code, 'passkey-required');++ // Another profile's passkey proves nothing about this one.+ const o1 = await options();+ const foreign = await post('/api/pair/create', cookie('u_test_1', 0), { cid: o1.cid, credential: KEYS.u_test_2.assertion(o1.options.challenge) });+ assert.equal(foreign.status, 403);+ assert.equal((await foreign.json()).code, 'passkey');++ // A cookie replayed as a Bearer is no shortcut either.+ const asBearer = { Authorization: 'Bearer ' + cookie('u_test_1', 0).Cookie.slice('gymsid='.length) };+ assert.equal((await post('/api/pair/create', asBearer, {})).status, 403);++ // The account's own passkey: a code, which redeems once.+ const o2 = await options();+ const ok = await post('/api/pair/create', cookie('u_test_1', 0), { cid: o2.cid, credential: KEYS.u_test_1.assertion(o2.options.challenge) });+ assert.equal(ok.status, 200);+ const { code } = await ok.json();+ assert.match(code, /^[A-HJ-NP-Z2-9]{8}$/);+ assert.equal((await post('/api/pair/redeem', {}, { code })).status, 200);+ // The challenge was spent on the proof.+ assert.equal((await post('/api/pair/create', cookie('u_test_1', 0), { cid: o2.cid, credential: KEYS.u_test_1.assertion(o2.options.challenge) })).status, 403);+});diff --git a/api/test/server-passkeys.test.js b/api/test/server-passkeys.test.jsindex 632f9c192..7a64c1f43 100644--- a/api/test/server-passkeys.test.js+++ b/api/test/server-passkeys.test.js@@ -16,7 +16,7 @@ import { fileURLToPath } from 'node:url';import { hashPassword } from '../password.js';import { hashLinkCode } from '../device-link.js';import { MAX_PASSKEYS } from '../passkeys-store.js';-import { boundPort } from './helpers.mjs';+import { boundPort, softPasskey as makeSoftPasskey } from './helpers.mjs';const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');const SECRET = crypto.randomBytes(32).toString('hex');@@ -29,51 +29,7 @@ const mintSession = (uid, sv = 0) => {return 'gymsid=' + payload + '.' + crypto.createHmac('sha256', SECRET).update(payload).digest('base64url');};-// Just enough CBOR for an attestation object: a map of text keys to text, bytes or an empty map.-const cborHead = (major, n) => n < 24 ? Buffer.from([(major << 5) | n])- : n < 256 ? Buffer.from([(major << 5) | 24, n]) : Buffer.from([(major << 5) | 25, n >> 8, n & 255]);-const cborText = s => Buffer.concat([cborHead(3, Buffer.byteLength(s)), Buffer.from(s)]);-const cborBytes = b => Buffer.concat([cborHead(2, b.length), b]);--function softPasskey() {- const { privateKey, publicKey } = crypto.generateKeyPairSync('ec', { namedCurve: 'P-256' });- const jwk = publicKey.export({ format: 'jwk' });- const cose = Buffer.concat([- Buffer.from([0xa5, 0x01, 0x02, 0x03, 0x26, 0x20, 0x01, 0x21, 0x58, 0x20]), Buffer.from(jwk.x, 'base64url'),- Buffer.from([0x22, 0x58, 0x20]), Buffer.from(jwk.y, 'base64url')- ]);- const raw = crypto.randomBytes(16);- const id = b64u(raw);- let counter = 0;- return {- id,- row: (userId, extra = {}) => ({ id, userId, publicKey: cose.toString('base64url'), counter: 0, transports: ['internal'], ...extra }),- // What navigator.credentials.create() hands back, serialised the way lib/api.js does.- attestation(challenge, { origin = ORIGIN } = {}) {- const clientDataJSON = Buffer.from(JSON.stringify({ type: 'webauthn.create', challenge, origin, crossOrigin: false }));- const len = Buffer.from([raw.length >> 8, raw.length & 255]);- const authData = Buffer.concat([sha('localhost'), Buffer.from([0x45]), Buffer.alloc(4), Buffer.alloc(16), len, raw, cose]);- const attestationObject = Buffer.concat([- Buffer.from([0xa3]), cborText('fmt'), cborText('none'), cborText('attStmt'), Buffer.from([0xa0]),- cborText('authData'), cborBytes(authData)- ]);- return {- id, rawId: id, type: 'public-key', clientExtensionResults: {}, authenticatorAttachment: 'platform',- response: { clientDataJSON: b64u(clientDataJSON), attestationObject: b64u(attestationObject), transports: ['internal', 'hybrid'] }- };- },- assertion(challenge) {- const clientDataJSON = Buffer.from(JSON.stringify({ type: 'webauthn.get', challenge, origin: ORIGIN, crossOrigin: false }));- const c = Buffer.alloc(4); c.writeUInt32BE(++counter);- const authData = Buffer.concat([sha('localhost'), Buffer.from([0x05]), c]);- const signature = crypto.sign('sha256', Buffer.concat([authData, sha(clientDataJSON)]), privateKey);- return {- id, rawId: id, type: 'public-key', clientExtensionResults: {}, authenticatorAttachment: 'platform',- response: { clientDataJSON: b64u(clientDataJSON), authenticatorData: b64u(authData), signature: b64u(signature), userHandle: null }- };- }- };-}+const softPasskey = () => makeSoftPasskey(ORIGIN);const GOOD = 'correct horse battery staple';let pwHash;diff --git a/api/test/server-password.test.js b/api/test/server-password.test.jsindex 5b25f8534..5b5287d59 100644--- a/api/test/server-password.test.js+++ b/api/test/server-password.test.js@@ -262,7 +262,8 @@ test('a flood from a shared address leaves passkey sign-in, registration and paiassert.equal(signedIn.status, 200, 'passkey sign-in');assert.ok(signedIn.cookie);assert.equal((await h.req('POST', '/api/register/options', { body: { name: 'Cleo', code: 'goodcode' } })).status, 200, 'passkey signup');- const { code } = (await h.req('POST', '/api/pair/create', { cookie: signedIn.cookie })).body;+ const pairProof = (await h.req('POST', '/api/login/options', { body: {} })).body;+ const { code } = (await h.req('POST', '/api/pair/create', { cookie: signedIn.cookie, body: { cid: pairProof.cid, credential: key.assertion(pairProof.options.challenge) } })).body;assert.equal((await h.req('POST', '/api/pair/redeem', { body: { code } })).status, 200, 'pairing');assert.equal(h.audit().some(e => e.ev === 'auth.throttled' && e.msg !== 'password'), false);diff --git a/docs/SELF_HOSTING.md b/docs/SELF_HOSTING.mdindex 76b33bc15..3a9bfa743 100644--- a/docs/SELF_HOSTING.md+++ b/docs/SELF_HOSTING.md@@ -67,7 +67,8 @@ Settings → Account → "Pair the mobile app" in an already signed-in browser tsent as an `Authorization` header rather than a cookie. Two consequences worth knowing ifyou're poking at the API directly:-- `POST /api/pair/create` (needs a session) and `POST /api/pair/redeem` (doesn't) implement+- `POST /api/pair/create` (needs a session plus the owner proof: a passkey, or the current+ password where that counts) and `POST /api/pair/redeem` (doesn't) implementthis — see `api/server.js`. The returned token is the exact same signed value a cookiecarries, so "sign out everywhere" invalidates it too — and a phone has no passkey to signback in with, so every paired phone has to be **paired again** afterwards. The phone saysdiff --git a/frontend/src/components/Passkeys.jsx b/frontend/src/components/Passkeys.jsxindex 8f40156da..0c1f2a869 100644--- a/frontend/src/components/Passkeys.jsx+++ b/frontend/src/components/Passkeys.jsx@@ -251,6 +251,49 @@ export function DeviceLinkSheet({ close }) {</>}+/* Settings → Account → "Pair the mobile app": the code the phone app redeems for its own token+ (/api/pair/create, /api/pair/redeem). The token is renewed for as long as the phone uses it, so+ the server asks the same proof a device link does before it makes one: a session alone may be a+ cookie someone walked off with. Then the code, and when its five minutes are up, a new one on a+ tap. A paired phone can pair another only with the password, as with a device link. */+const PAIR_MINUTES = 5+export function PairSheet({ close }) {+ const { st } = usePasskeys(true)+ const [pair, setPair] = useState(null) // { code, expires }+ const [expired, setExpired] = useState(false)+ useEffect(() => {+ if (!pair) return+ setExpired(false)+ const timer = setTimeout(() => setExpired(true), Math.max(0, pair.expires - Date.now()))+ return () => clearTimeout(timer)+ }, [pair])+ const passkey = !MOBILE && !!st && st.passkeys.length > 0+ const made = async proof => {+ const r = await post('/api/pair/create', proof)+ setPair({ code: r.code, expires: Date.now() + PAIR_MINUTES * 60000 })+ }+ return <>+ <h3>{t('Pair the mobile app')}</h3>+ {!st ? <div className="muted small">…</div> : !pair ? <>+ <div className="muted small" style={{ marginBottom: 14 }}>{t('First confirm that it is you.')}</div>+ {MOBILE && !st.password+ ? <div className="dim small">{t('This app can’t confirm with a passkey. Make the code in a browser signed in to this profile, or add a password there first.')}</div>+ : <ProveOwner passkey={passkey} password={st.password} explain={passkeyError} onProof={made} />}+ </> : expired ? <>+ <div className="muted small" style={{ marginBottom: 14 }}>{t('This code has expired.')}</div>+ <Button variant="primary" onClick={() => setPair(null)}>{t('Make a new code')}</Button>+ </> : <>+ <div className="muted small" style={{ marginBottom: 14 }}>+ {t('On the openGym app, choose “Connect to my server”, then enter this address and the code below. It expires in 5 minutes.')}+ </div>+ {/* Read out or typed character by character: left to right in every language. */}+ <div className="card" dir="ltr" style={{ textAlign: 'center', fontSize: 30, fontWeight: 700, letterSpacing: '.16em', padding: '18px 0' }}>{pair.code}</div>+ </>}+ <div style={{ height: 12 }} />+ <Button onClick={close}>{t('Done')}</Button>+ </>+}+/* ------------------------------------------------------------------ the other device -------Redeeming a code: the device being added creates a passkey of its own, and that passkey signs itin. The code comes from the link's ?link= (the store holds it, see boot()) or is typed. A codediff --git a/frontend/src/components/Passkeys.test.jsx b/frontend/src/components/Passkeys.test.jsxindex 1e59c1353..a1e42561c 100644--- a/frontend/src/components/Passkeys.test.jsx+++ b/frontend/src/components/Passkeys.test.jsx@@ -2,7 +2,7 @@import React, { act } from 'react'import { createRoot } from 'react-dom/client'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { passkeyError, PasskeysRow, PasskeysSheet, DeviceLinkSheet, DeviceLinkRedeemSheet } from './Passkeys.jsx'+import { passkeyError, PasskeysRow, PasskeysSheet, DeviceLinkSheet, DeviceLinkRedeemSheet, PairSheet } from './Passkeys.jsx'globalThis.IS_REACT_ACT_ENVIRONMENT = true@@ -400,6 +400,53 @@ describe('a code for another device, from the paired phone app', () => {})})+// Pairing the phone app: the code becomes a token the server keeps renewing, so it is minted only+// after the same proof as a device link (api/server.js POST /api/pair/create).+describe('Settings: pairing the mobile app', () => {+ afterEach(() => { mocks.MOBILE = false })+ it('asks for the proof first, and only then shows the code', async () => {+ mocks.answers['GET /api/account/passkeys'] = LIST+ mocks.answers['POST /api/pair/create'] = { code: 'K7WQ2MZP' }+ const host = mount(<PairSheet close={() => {}} />)+ await settle()+ expect(host.textContent).not.toContain('K7WQ2MZP')+ expect(mocks.calls.filter(c => c.method !== 'GET')).toEqual([])+ await click(host, 'Confirm with a passkey')+ expect(mocks.calls.at(-1)).toEqual({ path: '/api/pair/create', method: 'POST', body: { cid: 'login-cid', credential: { id: 'k1' } } })+ expect(host.textContent).toContain('K7WQ2MZP')+ expect(host.textContent).toMatch(/expires in 5 minutes/)+ })+ it('takes the password where that is the proof, and words a refusal', async () => {+ mocks.answers['GET /api/account/passkeys'] = { passkeys: [], password: true, lastWayIn: true }+ mocks.answers['POST /api/pair/create'] = fail(403, { error: 'your current password is not right', code: 'current-wrong' })+ const host = mount(<PairSheet close={() => {}} />)+ await settle()+ expect(button(host, 'Confirm with a passkey')).toBeUndefined()+ type(byPlaceholder(host, 'Current password'), 'nope')+ await submit(host)+ expect(mocks.calls.at(-1)).toEqual({ path: '/api/pair/create', method: 'POST', body: { current: 'nope' } })+ expect(alertText(host)).toBeTruthy()+ expect(host.querySelector('.card')).toBeNull()+ })+ it('a closed passkey prompt is no error and makes no code', async () => {+ mocks.answers['GET /api/account/passkeys'] = LIST+ const host = mount(<PairSheet close={() => {}} />)+ await settle()+ mocks.passkeyAssertion.mockRejectedValueOnce(named('NotAllowedError'))+ await click(host, 'Confirm with a passkey')+ expect(alertText(host)).toBeNull()+ expect(mocks.calls.filter(c => c.method !== 'GET')).toEqual([])+ })+ it('on the paired phone without a password says where to do it, and sends nothing', async () => {+ mocks.MOBILE = true+ mocks.answers['GET /api/account/passkeys'] = { ...LIST, password: false }+ const host = mount(<PairSheet close={() => {}} />)+ await settle()+ expect(host.textContent).toContain('Make the code in a browser signed in to this profile')+ expect(mocks.calls.filter(c => c.method !== 'GET')).toEqual([])+ })+})+describe('the other device: redeeming a code', () => {const OPTIONS = { cid: 'link-cid', options: { challenge: 'xyz' }, id: 'u1', name: 'Ana' }const CAUTION = 'Only continue if this code comes from a device of your own. This browser is then signed in to “Ana”, and what you log here goes to that profile.'diff --git a/frontend/src/views/Settings.jsx b/frontend/src/views/Settings.jsxindex 23ccc5958..f13d6a97e 100644--- a/frontend/src/views/Settings.jsx+++ b/frontend/src/views/Settings.jsx@@ -44,7 +44,7 @@ import BackupFolderRow, { useBackupFolder, autoBackupSubtitle } from '../componeimport { AnimationQualityRow } from '../components/Animations.jsx'import { ServerSyncSection, KeptChangesRows, leaveServer, connectServer, passkeySignIn } from '../components/ServerSync.jsx'import { passwordOn, PasswordRow, openPasswordSignIn, openPasswordRegister } from '../components/PasswordAuth.jsx'-import { usePasskeys, PasskeysRow, DeviceLinkRow, openDeviceLinkRedeem } from '../components/Passkeys.jsx'+import { usePasskeys, PasskeysRow, DeviceLinkRow, openDeviceLinkRedeem, PairSheet } from '../components/Passkeys.jsx'import { DeleteAccountRow } from '../components/DeleteAccount.jsx'import { Section, Row, SelectRow, Switch, Segmented, Button, TextField, SearchField } from '../components/ui.jsx'import { PAGES, ROOT_GROUPS, pageVisible, searchSettings, pageTrail } from './settings-pages.js'@@ -1452,28 +1452,6 @@ function AccountIdRow({ id }) {return <Row icon="personCircle" iconTint="var(--grey)" title={t('Account ID')} subtitle={<span className="acct-id">{id}</span>} onClick={copy} />}-// Lets the mobile app's "connect to my server" mode (lib/remote.js) authenticate without a-// WebAuthn ceremony of its own — the code is minted here, from an already signed-in session,-// and redeemed by the app for a bearer token. See /api/pair/create in api/server.js.-function PairSheet({ close }) {- const [code, setCode] = useState(null)- const [err, setErr] = useState(null)- useEffect(() => { api('/api/pair/create', { method: 'POST', body: '{}' }).then(r => setCode(r.code)).catch(e => setErr(e.message || t('Could not generate a code'))) }, [])- return <>- <h3>{t('Pair the mobile app')}</h3>- <div className="muted small" style={{ marginBottom: 14 }}>- {t('On the openGym app, choose “Connect to my server”, then enter this address and the code below. It expires in 5 minutes.')}- </div>- {err ? <div className="dim small">{err}</div> : (- <div className="card" style={{ textAlign: 'center', fontSize: 30, fontWeight: 700, letterSpacing: '.16em', padding: '18px 0' }}>- {code || '········'}- </div>- )}- <div style={{ height: 12 }} />- <Button onClick={close}>{t('Done')}</Button>- </>-}-// The same registration as the sign-in screen's, reached from Settings instead. It asks for// the invite code on the same terms: an invite-only instance rejects a registration without// one, so a form that cannot collect it is a form that cannot succeed.diff --git a/website/api.html b/website/api.htmlindex 2b4371e6e..1cea060d4 100644--- a/website/api.html+++ b/website/api.html@@ -653,10 +653,10 @@ main.api-main .lead { color: var(--fg-2); max-width: 58ch; margin: 14px 0 0; fon<span class="ep-sum">Mint a pairing code for the mobile app</span></summary><div class="ep-body">-<p>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. One live code per profile: minting a new one retires the previous one.</p>+<p>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. One live code per profile: minting a new one retires the previous one. Same proof as a device link (a passkey assertion made for this request, or the current password while password sign-in is on), since the phone token a code turns into is renewed for as long as it is used. Audited as <code>auth.pair.create</code>.</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>Requires a session: the cookie set at sign-in, or <code>Authorization: Bearer <token></code> from mobile-app pairing.</span></p>-+<p class="ep-h">Request body</p><p class="p-desc"><a href="#schema-OwnerProof">OwnerProof</a></p><p class="ep-h">Responses</p><div class="ptab"><div class="prow rrow">@@ -666,6 +666,18 @@ main.api-main .lead { color: var(--fg-2); max-width: 58ch; margin: 14px 0 0; fon<div class="prow rrow"><span class="r-code s4">401</span><span class="p-desc">No session, expired/revoked session, or a disabled account.<span class="r-sig"><code>{"error":"not signed in"}</code></span></span>+ </div>+ <div class="prow rrow">+ <span class="r-code s4">403</span>+ <span class="p-desc">No acceptable proof that the owner is here: <code>passkey-required</code> (no password that counts, because none is set or <code>PASSWORD_LOGIN</code> is off, so a passkey has to confirm), <code>passkey</code> (the assertion did not verify, belongs to another profile, or was made for another challenge, one handed out for another ceremony or one already used), <code>current-required</code> or <code>current-wrong</code>.<span class="r-sig"><code>{"error":"confirm with your passkey first"}</code></span></span>+ </div>+ <div class="prow rrow">+ <span class="r-code s4">429</span>+ <span class="p-desc">Paused by the sign-in throttle (see <i>Throttling</i> in the description). The request was not looked at; try again after <code>Retry-After</code> seconds.<span class="r-sig"><code>{"error":"too many attempts, try again later"}</code></span></span>+ </div>+ <div class="prow rrow">+ <span class="r-code s5">503</span>+ <span class="p-desc">Every password check slot and the short queue behind them are taken.<span class="r-sig"><code>{"error":"the server is busy, try again in a moment"}</code></span></span></div></div></div>