Skip to content

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.

fix(mobile): a Cloudflare Access token is bound to the server it was entered for (#439)

Duarte Santos57d29b82a11d
diff --git a/docs/MOBILE.md b/docs/MOBILE.md
index 8f78395b6..c67274ab2 100644
--- a/docs/MOBILE.md
+++ b/docs/MOBILE.md
@@ -83,12 +83,15 @@ If your server sits behind [Cloudflare Access](https://developers.cloudflare.com
preflight never carries the token — without the bypass, Access refuses it and nothing
gets through. The openGym API answers the preflight itself and allows both headers.
4. In the app, before connecting: first-launch screen → **Connection settings** (or the
- **Cloudflare Access** button in the Connect sheet), enter the two values, then pair as usual.
- They can be changed later under Settings → **Server & sync** → **Cloudflare Access**.
+ **Cloudflare Access** button in the Connect sheet), enter your server's address and the two
+ values, then pair as usual. They can be changed later under Settings → **Server & sync** →
+ **Cloudflare Access**.
The app then sends `CF-Access-Client-Id` and `CF-Access-Client-Secret` with every request to
-the paired server, including the pairing itself, and with nothing else. Both are kept in the
-phone's secure storage (Android Keystore / iOS Keychain), never in synced data or backups.
+the server address they were entered for (scheme, host and port), including the pairing itself,
+and with nothing else: a pairing with any other address goes without them. Disconnecting from
+the server removes them. Both are kept in the phone's secure storage (Android Keystore / iOS
+Keychain), never in synced data or backups.
### Connection states
diff --git a/frontend/src/components/ServerSync.jsx b/frontend/src/components/ServerSync.jsx
index 7f73c44c7..995897918 100644
--- a/frontend/src/components/ServerSync.jsx
+++ b/frontend/src/components/ServerSync.jsx
@@ -272,7 +272,7 @@ export function ServerSyncSection({ children }) {
<Row icon={view.icon} iconTint={TINT[view.tone]} title={view.line} subtitle={sub} className="sync-status" />
<Row icon="reset" iconTint="var(--acc)" title={busy ? t('Syncing…') : t('Sync now')} onClick={now} />
{MOBILE && <Row icon="key" iconTint="var(--orange)" title={t('Cloudflare Access')} accessory="chevron"
- onClick={() => ui().openSheet(close => <CfAccessSheet close={close} />)} />}
+ onClick={() => ui().openSheet(close => <CfAccessSheet close={close} server={sync.server || ''} />)} />}
{sync.status === 'auth' && (MOBILE
? <Row icon="qr" iconTint="var(--indigo)" title={t('Pair again')} subtitle={t('Your changes are kept here, and merged into your account once it is paired again.')} accessory="chevron" onClick={pairAgain} />
: canSignIn() && <Row icon={pwOn() ? 'person' : 'fingerprint'} iconTint="var(--blue)" title={pwOn() ? t('Sign in') : t('Sign in with passkey')} subtitle={t('Your changes are kept here, and merged into your account once you are signed in again.')} accessory="chevron" onClick={signInAgain} />)}
diff --git a/frontend/src/lib/api.js b/frontend/src/lib/api.js
index 9b6c01c98..d92fc6fb9 100644
--- a/frontend/src/lib/api.js
+++ b/frontend/src/lib/api.js
@@ -24,11 +24,15 @@ export const webauthnOK = () => typeof window.PublicKeyCredential !== 'undefined
let remoteBase = ''
let remoteToken = null
export function setRemoteAuth(base, token) { remoteBase = base || ''; remoteToken = token || null }
-// A Cloudflare Access service token (lib/cf-access.js): sent only to the paired server, never on
-// a same-origin request, where the browser's own Access session cookie already does the job.
+// A Cloudflare Access service token (lib/cf-access.js): sent only to the origin it was entered
+// for, never on a same-origin request, where the browser's own Access session cookie already
+// does the job, and never to a server that merely happens to be paired or typed in.
let accessHeaders = {}
-export function setAccessHeaders(h) { accessHeaders = Object.assign({}, h) }
-const remoteHeaders = () => Object.assign({}, remoteBase ? accessHeaders : {}, remoteToken ? { Authorization: 'Bearer ' + remoteToken } : {})
+let accessOrigin = ''
+export function setAccessHeaders(h, origin) { accessHeaders = Object.assign({}, h); accessOrigin = origin || '' }
+const originOf = base => { try { return new URL(base).origin } catch { return '' } }
+const accessFor = base => (base && accessOrigin && originOf(base) === accessOrigin ? accessHeaders : {})
+const remoteHeaders = () => Object.assign({}, accessFor(remoteBase), remoteToken ? { Authorization: 'Bearer ' + remoteToken } : {})
export { appBase }
@@ -305,12 +309,13 @@ export function looksLocal(hostname) {
// Bootstraps the connection itself: the base isn't configured yet (that's what this call decides),
// so it talks straight to the server the user typed in, no Authorization header. A Cloudflare
-// Access token goes along all the same: without it Access never lets the code through.
+// Access token goes along when it was entered for that server: without it Access never lets
+// the code through, and to any other server it would be handed to a stranger.
export async function pairRedeem(serverBase, code, { probeMs = PROBE_MS } = {}) {
let data
try {
data = await request(serverBase + '/api/pair/redeem', {
- method: 'POST', headers: Object.assign({ 'Content-Type': 'application/json' }, accessHeaders), body: JSON.stringify({ code })
+ method: 'POST', headers: Object.assign({ 'Content-Type': 'application/json' }, accessFor(serverBase)), body: JSON.stringify({ code })
}, TIMEOUT_GET_MS)
} catch (e) {
// A wrong, spent or expired code is the one refusal a person can fix, and the server says it
diff --git a/frontend/src/lib/cf-access.js b/frontend/src/lib/cf-access.js
index 5495b13e6..8ad92634b 100644
--- a/frontend/src/lib/cf-access.js
+++ b/frontend/src/lib/cf-access.js
@@ -5,14 +5,22 @@
// itself included, which is why they are entered before it (MobileOnboarding.jsx).
//
// Both live in the platform's secure storage (lib/coach-secrets.js), never in S or the pairing
-// file, and are handed to lib/api.js, which adds them to the requests that go to the paired
-// server and to nothing else.
+// file, together with the origin of the server they were entered for, and are handed to
+// lib/api.js, which adds them to requests to that origin and to nothing else: a token typed for
+// one server never travels to another one, not even to a pairing typed in by mistake.
import { secureGet, secureSet, secureRemove } from './coach-secrets.js'
import { setAccessHeaders } from './api.js'
const KEY = 'cfAccess'
const clean = v => String(v || '').trim()
+// Scheme, host and port only, or '' for anything that is not an http(s) URL.
+export function originOf(base) {
+ try {
+ const u = new URL(clean(base))
+ return u.protocol === 'https:' || u.protocol === 'http:' ? u.origin : ''
+ } catch { return '' }
+}
// The headers for a pair of values, or {} when either is missing: Access refuses a token with
// only half of it, and an empty header would be sent as one.
@@ -23,26 +31,39 @@ export function accessHeaders(creds) {
return { 'CF-Access-Client-Id': id, 'CF-Access-Client-Secret': secret }
}
-export async function loadCfAccess() {
+// `pairedBase`: the server this phone is paired with. A token saved before tokens knew their
+// server has no origin; it is bound to that server on the first start that has one. Without a
+// pairing it is kept but sent nowhere until it is entered again with its address.
+export async function loadCfAccess({ pairedBase = '' } = {}) {
let creds = null
try {
const raw = await secureGet(KEY)
const v = raw ? JSON.parse(raw) : null
- if (v && typeof v === 'object') creds = { clientId: clean(v.clientId), clientSecret: clean(v.clientSecret) }
+ if (v && typeof v === 'object') creds = { clientId: clean(v.clientId), clientSecret: clean(v.clientSecret), origin: originOf(v.origin) }
} catch { /* unreadable: as if never set */ }
- setAccessHeaders(accessHeaders(creds))
- return creds && creds.clientId && creds.clientSecret ? creds : null
+ if (!creds || !creds.clientId || !creds.clientSecret) { setAccessHeaders({}, ''); return null }
+ if (!creds.origin && originOf(pairedBase)) {
+ creds.origin = originOf(pairedBase)
+ try { await secureSet(KEY, JSON.stringify(creds)) } catch { /* bound again on the next start */ }
+ }
+ setAccessHeaders(accessHeaders(creds), creds.origin)
+ return creds
}
-// Empty values clear the token; anything half-filled is refused by the caller (CfAccessSheet).
-export async function saveCfAccess({ clientId, clientSecret } = {}) {
- const creds = { clientId: clean(clientId), clientSecret: clean(clientSecret) }
+// Empty values clear the token; anything half-filled, or without the server it is for, is
+// refused by the caller (CfAccessSheet), and here as well.
+export async function saveCfAccess({ clientId, clientSecret, server } = {}) {
+ const creds = { clientId: clean(clientId), clientSecret: clean(clientSecret), origin: originOf(server) }
if (!creds.clientId || !creds.clientSecret) {
await secureRemove(KEY)
- setAccessHeaders({})
+ setAccessHeaders({}, '')
return null
}
+ if (!creds.origin) throw new Error('A Cloudflare Access token needs the server it is for')
await secureSet(KEY, JSON.stringify(creds))
- setAccessHeaders(accessHeaders(creds))
+ setAccessHeaders(accessHeaders(creds), creds.origin)
return creds
}
+
+// Disconnecting from the server takes its token along: the next server is a fresh start.
+export const clearCfAccess = () => saveCfAccess({})
diff --git a/frontend/src/lib/cf-access.test.js b/frontend/src/lib/cf-access.test.js
index 695fb65e2..b50b3fa7b 100644
--- a/frontend/src/lib/cf-access.test.js
+++ b/frontend/src/lib/cf-access.test.js
@@ -1,10 +1,10 @@
// @vitest-environment happy-dom
/* A server behind Cloudflare Access: the phone's service token goes along on every request to the
- paired server — the pairing itself included — and on nothing else. */
+ server it was entered for — the pairing itself included — and on nothing else. */
import { afterEach, describe, expect, it, vi } from 'vitest'
-vi.mock('./mobile.js', () => ({ MOBILE: true }))
+vi.mock('./mobile.js', () => ({ MOBILE: true, loadRemoteFile: async () => null, saveRemoteFile: async () => {} }))
const backing = new Map()
vi.mock('@aparajita/capacitor-secure-storage', () => ({
SecureStorage: {
@@ -16,10 +16,13 @@ vi.mock('@aparajita/capacitor-secure-storage', () => ({
import { api, pairRedeem, setRemoteAuth } from './api.js'
import { accessHeaders, loadCfAccess, saveCfAccess } from './cf-access.js'
+import { forgetRemote } from './remote.js'
const ok = body => vi.fn(async () => new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' } }))
-afterEach(async () => { vi.unstubAllGlobals(); setRemoteAuth('', null); await saveCfAccess({}) })
+afterEach(async () => { vi.unstubAllGlobals(); setRemoteAuth('', null); await saveCfAccess({}); backing.clear() })
+
+const GYM = 'https://gym.example.com'
describe('accessHeaders', () => {
it('needs both halves, trimmed', () => {
@@ -34,7 +37,7 @@ describe('the Cloudflare Access token on the phone', () => {
it('goes with the pairing request', async () => {
const fetch = ok({ token: 'T', user: { id: 'u' } })
vi.stubGlobal('fetch', fetch)
- await saveCfAccess({ clientId: 'id', clientSecret: 'secret' })
+ await saveCfAccess({ clientId: 'id', clientSecret: 'secret', server: GYM })
await pairRedeem('https://gym.example.com', 'ABCD')
expect(fetch.mock.calls[0][1].headers).toMatchObject({ 'CF-Access-Client-Id': 'id', 'CF-Access-Client-Secret': 'secret' })
})
@@ -42,7 +45,7 @@ describe('the Cloudflare Access token on the phone', () => {
it('goes with every api() call to the paired server, beside the pairing token', async () => {
const fetch = ok({ rev: 1 })
vi.stubGlobal('fetch', fetch)
- await saveCfAccess({ clientId: 'id', clientSecret: 'secret' })
+ await saveCfAccess({ clientId: 'id', clientSecret: 'secret', server: GYM })
setRemoteAuth('https://gym.example.com', 'TOKEN')
await api('/api/data/rev')
expect(fetch.mock.calls[0][1].headers).toMatchObject({
@@ -51,8 +54,8 @@ describe('the Cloudflare Access token on the phone', () => {
})
it('survives a restart and is gone once removed', async () => {
- await saveCfAccess({ clientId: 'id', clientSecret: 'secret' })
- expect(await loadCfAccess()).toEqual({ clientId: 'id', clientSecret: 'secret' })
+ await saveCfAccess({ clientId: 'id', clientSecret: 'secret', server: GYM })
+ expect(await loadCfAccess()).toEqual({ clientId: 'id', clientSecret: 'secret', origin: GYM })
await saveCfAccess({ clientId: '', clientSecret: '' })
expect(await loadCfAccess()).toBe(null)
const fetch = ok({ rev: 1 })
@@ -61,4 +64,59 @@ describe('the Cloudflare Access token on the phone', () => {
await api('/api/data/rev')
expect(fetch.mock.calls[0][1].headers['CF-Access-Client-Id']).toBeUndefined()
})
+
+ it('goes to nothing but the origin it was entered for', async () => {
+ const fetch = ok({ token: 'T', user: { id: 'u' } })
+ vi.stubGlobal('fetch', fetch)
+ await saveCfAccess({ clientId: 'id', clientSecret: 'secret', server: GYM + '/' })
+ // a pairing typed for another server, another port or plain http: no token
+ for (const other of ['https://evil.example.net', 'https://gym.example.com:8443', 'http://gym.example.com']) {
+ await pairRedeem(other, 'ABCD')
+ setRemoteAuth(other, 'TOKEN')
+ await api('/api/data/rev')
+ }
+ for (const call of fetch.mock.calls) expect(call[1].headers['CF-Access-Client-Id']).toBeUndefined()
+ // its own server, whatever the path: the token
+ setRemoteAuth(GYM + '/', 'TOKEN')
+ await api('/api/data/rev')
+ expect(fetch.mock.calls.at(-1)[1].headers['CF-Access-Client-Id']).toBe('id')
+ })
+
+ it('is not saved without the server it is for', async () => {
+ await expect(saveCfAccess({ clientId: 'id', clientSecret: 'secret' })).rejects.toThrow()
+ await expect(saveCfAccess({ clientId: 'id', clientSecret: 'secret', server: 'not a url' })).rejects.toThrow()
+ expect(await loadCfAccess()).toBe(null)
+ })
+
+ it('is gone once the phone disconnects from the server', async () => {
+ await saveCfAccess({ clientId: 'id', clientSecret: 'secret', server: GYM })
+ setRemoteAuth(GYM, 'TOKEN')
+ await forgetRemote()
+ expect(await loadCfAccess({ pairedBase: GYM })).toBe(null)
+ const fetch = ok({ token: 'T', user: { id: 'u' } })
+ vi.stubGlobal('fetch', fetch)
+ await pairRedeem(GYM, 'ABCD')
+ expect(fetch.mock.calls[0][1].headers['CF-Access-Client-Id']).toBeUndefined()
+ })
+
+ it('saved before tokens knew their server: bound to the paired server on the next start', async () => {
+ backing.set('cfAccess', JSON.stringify({ clientId: 'id', clientSecret: 'secret' }))
+ expect(await loadCfAccess({ pairedBase: GYM })).toEqual({ clientId: 'id', clientSecret: 'secret', origin: GYM })
+ expect(JSON.parse(backing.get('cfAccess')).origin).toBe(GYM)
+ const fetch = ok({ token: 'T', user: { id: 'u' } })
+ vi.stubGlobal('fetch', fetch)
+ await pairRedeem('https://other.example.net', 'ABCD')
+ await pairRedeem(GYM, 'ABCD')
+ expect(fetch.mock.calls[0][1].headers['CF-Access-Client-Id']).toBeUndefined()
+ expect(fetch.mock.calls[1][1].headers['CF-Access-Client-Id']).toBe('id')
+ })
+
+ it('saved before tokens knew their server, on a phone not paired: sent nowhere until entered again', async () => {
+ backing.set('cfAccess', JSON.stringify({ clientId: 'id', clientSecret: 'secret' }))
+ expect(await loadCfAccess()).toEqual({ clientId: 'id', clientSecret: 'secret', origin: '' })
+ const fetch = ok({ token: 'T', user: { id: 'u' } })
+ vi.stubGlobal('fetch', fetch)
+ await pairRedeem(GYM, 'ABCD')
+ expect(fetch.mock.calls[0][1].headers['CF-Access-Client-Id']).toBeUndefined()
+ })
})
diff --git a/frontend/src/lib/pt-br-locale.test.js b/frontend/src/lib/pt-br-locale.test.js
index 78bbcc7cb..f8d8caead 100644
--- a/frontend/src/lib/pt-br-locale.test.js
+++ b/frontend/src/lib/pt-br-locale.test.js
@@ -41,7 +41,7 @@ describe('Brazilian Portuguese locale', () => {
// has to be taught is a number nobody reads. What the numbers stood for is asserted above.
// If the hash fails, review the changed keys and wording before accepting a new one. From
// frontend/: node scripts/pt-br-inheritance-fingerprint.mjs --list
- expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('6c4d701859a947aa77290f08353d4df650b08e2dbc6232e9a95e1b277b79ea8d')
+ expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('b26830bf6168909344b7c2901d5463cbbd885118ffea665cba1d60bb2d2fdb15')
})
// pt-PT labelled Unpair 'Desfazer': Undo, in Portuguese (it is pt-BR's Undo), on the button that
diff --git a/frontend/src/lib/remote.js b/frontend/src/lib/remote.js
index 038e854e1..ab80ddd64 100644
--- a/frontend/src/lib/remote.js
+++ b/frontend/src/lib/remote.js
@@ -8,6 +8,7 @@
// /api/pair/create + /api/pair/redeem.
import { pairRedeem, setRemoteAuth } from './api.js'
import { loadRemoteFile, saveRemoteFile } from './mobile.js'
+import { clearCfAccess } from './cf-access.js'
// Accepts what someone actually types: bare host, no scheme, trailing slash, stray whitespace.
// Defaults to https:// (self-hosting docs already push for HTTPS; the one exception, localhost,
@@ -31,9 +32,11 @@ export async function chooseLocal() {
await saveRemoteFile({ mode: 'local' })
}
+// The server's Cloudflare Access token goes with it (lib/cf-access.js).
export async function forgetRemote() {
await saveRemoteFile({ mode: 'local' })
setRemoteAuth('', null)
+ await clearCfAccess()
}
// The server renewed the token (GET /api/me hands one out once the old is past half its life):
diff --git a/frontend/src/locales/ar.js b/frontend/src/locales/ar.js
index 9b8eee100..aa4ffb547 100644
--- a/frontend/src/locales/ar.js
+++ b/frontend/src/locales/ar.js
@@ -2208,4 +2208,6 @@ export default {
'Where an exercise is drawn on both figures. Your workouts stay exactly as they are.': 'أي شكل يظهر عندما يكون التمرين مرسومًا على الشكلين. تمريناتك تبقى كما هي تمامًا.',
'estimated': 'تقديري',
'{0} rated · {1} estimated of {2} sets': '{0} مُقيَّمة · {1} تقديرية من أصل {2} مجموعة',
+ 'Enter the address of the server this token is for': 'أدخل عنوان الخادم الذي يخصّه هذا الرمز',
+ 'Sent only to {0}, never to another server.': 'يُرسل إلى {0} فقط، ولا يُرسل إلى أي خادم آخر.',
}
diff --git a/frontend/src/locales/bn.js b/frontend/src/locales/bn.js
index 34e8b015f..212fe61d5 100644
--- a/frontend/src/locales/bn.js
+++ b/frontend/src/locales/bn.js
@@ -2232,4 +2232,6 @@ export default {
'Sets open at {0}. The first set goes up when every set reaches its reps, and the rest follow it.': 'সেট শুরু হয় {0} দিয়ে। প্রতিটি সেট তার রেপ ছুঁলে প্রথম সেটের ওজন বাড়ে, বাকিগুলো তার সাথে চলে।',
'The first set goes up when every set reaches its reps, and the rest follow it.': 'প্রতিটি সেট তার রেপ ছুঁলে প্রথম সেটের ওজন বাড়ে, বাকিগুলো তার সাথে চলে।',
'All sets at the same weight.': 'সব সেট একই ওজনে।',
+ 'Enter the address of the server this token is for': 'এই টোকেন যে সার্ভারের, তার ঠিকানা দিন',
+ 'Sent only to {0}, never to another server.': 'শুধু {0}-এ পাঠানো হয়, অন্য কোনো সার্ভারে কখনো নয়।',
}
diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js
index b34700c95..0e0bbeaae 100644
--- a/frontend/src/locales/de.js
+++ b/frontend/src/locales/de.js
@@ -2173,4 +2173,6 @@ export default {
'Where an exercise is drawn on both figures. Your workouts stay exactly as they are.': 'Welche Figur eine Übung zeigt, wenn sie für beide gezeichnet ist. Deine Trainings bleiben genau, wie sie sind.',
'estimated': 'geschätzt',
'{0} rated · {1} estimated of {2} sets': '{0} bewertet · {1} geschätzt, von {2} Sätzen',
+ 'Enter the address of the server this token is for': 'Trag die Adresse des Servers ein, zu dem dieser Token gehört',
+ 'Sent only to {0}, never to another server.': 'Geht nur an {0}, nie an einen anderen Server.',
}
diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js
index d6c667917..86675dcbc 100644
--- a/frontend/src/locales/es.js
+++ b/frontend/src/locales/es.js
@@ -2153,4 +2153,6 @@ export default {
'Where an exercise is drawn on both figures. Your workouts stay exactly as they are.': 'Qué figura muestra un ejercicio cuando está dibujado en las dos. Tus entrenamientos se quedan exactamente como están.',
'estimated': 'estimado',
'{0} rated · {1} estimated of {2} sets': '{0} valoradas · {1} estimadas de {2} series',
+ 'Enter the address of the server this token is for': 'Introduce la dirección del servidor al que pertenece este token',
+ 'Sent only to {0}, never to another server.': 'Solo se envía a {0}, nunca a otro servidor.',
}
diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js
index 102e8a40e..66ac53246 100644
--- a/frontend/src/locales/fr.js
+++ b/frontend/src/locales/fr.js
@@ -2153,4 +2153,6 @@ export default {
'Where an exercise is drawn on both figures. Your workouts stay exactly as they are.': 'Quelle figure montre un exercice quand il est dessiné sur les deux. Tes séances restent exactement comme elles sont.',
'estimated': 'estimé',
'{0} rated · {1} estimated of {2} sets': '{0} notées · {1} estimées sur {2} séries',
+ 'Enter the address of the server this token is for': 'Saisis l’adresse du serveur auquel appartient ce jeton',
+ 'Sent only to {0}, never to another server.': 'Envoyé uniquement à {0}, jamais à un autre serveur.',
}
diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js
index 60dcfec99..4d7501449 100644
--- a/frontend/src/locales/hi.js
+++ b/frontend/src/locales/hi.js
@@ -2153,4 +2153,6 @@ export default {
'Where an exercise is drawn on both figures. Your workouts stay exactly as they are.': 'जहाँ कोई एक्सरसाइज़ दोनों फ़िगर पर बनी है, वहाँ कौन-सा फ़िगर दिखे। आपके वर्कआउट बिल्कुल जैसे हैं वैसे ही रहेंगे।',
'estimated': 'अनुमानित',
'{0} rated · {1} estimated of {2} sets': '{0} रेट किए · {1} अनुमानित, कुल {2} सेट में से',
+ 'Enter the address of the server this token is for': 'जिस सर्वर का यह टोकन है, उसका पता डालें',
+ 'Sent only to {0}, never to another server.': 'सिर्फ़ {0} को भेजा जाता है, किसी दूसरे सर्वर को कभी नहीं।',
}
diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.js
index a8db2bdff..8be1aa86e 100644
--- a/frontend/src/locales/hu.js
+++ b/frontend/src/locales/hu.js
@@ -2156,4 +2156,6 @@ export default {
'Where an exercise is drawn on both figures. Your workouts stay exactly as they are.': 'Melyik alakot mutatja egy gyakorlat, ha mindkettőn le van rajzolva. Az edzéseid pontosan úgy maradnak, ahogy vannak.',
'estimated': 'becsült',
'{0} rated · {1} estimated of {2} sets': '{0} értékelt · {1} becsült ({2} sorozatból)',
+ 'Enter the address of the server this token is for': 'Add meg annak a szervernek a címét, amelyhez ez a token tartozik',
+ 'Sent only to {0}, never to another server.': 'Csak ide megy: {0}, más szerverre soha.',
}
diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js
index 3cca2bdae..4f1f789ee 100644
--- a/frontend/src/locales/it.js
+++ b/frontend/src/locales/it.js
@@ -2153,4 +2153,6 @@ export default {
'Where an exercise is drawn on both figures. Your workouts stay exactly as they are.': 'Quale figura mostra un esercizio quando è disegnato su entrambe. I tuoi allenamenti restano esattamente come sono.',
'estimated': 'stimato',
'{0} rated · {1} estimated of {2} sets': '{0} valutate · {1} stimate su {2} serie',
+ 'Enter the address of the server this token is for': 'Inserisci l\'indirizzo del server a cui appartiene questo token',
+ 'Sent only to {0}, never to another server.': 'Inviato solo a {0}, mai a un altro server.',
}
diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js
index c82b4fe6d..d16347b8b 100644
--- a/frontend/src/locales/ko.js
+++ b/frontend/src/locales/ko.js
@@ -2153,4 +2153,6 @@ export default {
'Where an exercise is drawn on both figures. Your workouts stay exactly as they are.': '운동이 두 인체 그림 모두에 그려져 있을 때 어느 쪽을 보여 줄지 정합니다. 기록한 운동은 그대로 유지됩니다.',
'estimated': '추정',
'{0} rated · {1} estimated of {2} sets': '총 {2}세트 중 {0}개 평가 · {1}개 추정',
+ 'Enter the address of the server this token is for': '이 토큰을 쓸 서버 주소를 입력하세요',
+ 'Sent only to {0}, never to another server.': '{0}에만 보내고 다른 서버에는 절대 보내지 않아요.',
}
diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js
index 22dc27dfe..1a1087091 100644
--- a/frontend/src/locales/pl.js
+++ b/frontend/src/locales/pl.js
@@ -2153,4 +2153,6 @@ export default {
'Where an exercise is drawn on both figures. Your workouts stay exactly as they are.': 'Którą sylwetkę pokazują ćwiczenia narysowane na obu. Twoje treningi zostają dokładnie takie, jakie są.',
'estimated': 'szacowane',
'{0} rated · {1} estimated of {2} sets': 'Ocenione: {0} · szacowane: {1} z {2} serii',
+ 'Enter the address of the server this token is for': 'Podaj adres serwera, do którego należy ten token',
+ 'Sent only to {0}, never to another server.': 'Wysyłany tylko do {0}, nigdy do innego serwera.',
}
diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.js
index 127bbddb8..994ce5881 100644
--- a/frontend/src/locales/pt-BR.js
+++ b/frontend/src/locales/pt-BR.js
@@ -1329,6 +1329,7 @@ export const PT_BR_OVERRIDES = {
'Enter both the Client ID and the Client Secret': 'Informe o Client ID e o Client Secret',
'Only if your server is behind Cloudflare Access: the service token this phone sends with every request to it. Kept in this phone’s secure storage.': 'Só se o seu servidor estiver atrás do Cloudflare Access: o token de serviço que este celular envia a cada requisição. Fica guardado no armazenamento seguro do celular.',
'Where an exercise is drawn on both figures. Your workouts stay exactly as they are.': 'Que figura mostra um exercício quando está desenhado nas duas. Seus treinos ficam exatamente como estão.',
+ 'Enter the address of the server this token is for': 'Informe o endereço do servidor a que este token pertence',
}
export default { ...pt, ...PT_BR_OVERRIDES }
diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js
index 7c3b6fa7e..b526462cd 100644
--- a/frontend/src/locales/pt.js
+++ b/frontend/src/locales/pt.js
@@ -2153,4 +2153,6 @@ export default {
'Where an exercise is drawn on both figures. Your workouts stay exactly as they are.': 'Que figura mostra um exercício quando está desenhado nas duas. Os teus treinos ficam exatamente como estão.',
'estimated': 'estimado',
'{0} rated · {1} estimated of {2} sets': '{0} avaliadas · {1} estimadas de {2} séries',
+ 'Enter the address of the server this token is for': 'Introduz o endereço do servidor a que este token pertence',
+ 'Sent only to {0}, never to another server.': 'Enviado só para {0}, nunca para outro servidor.',
}
diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js
index 5ae8e6ff1..c135b672a 100644
--- a/frontend/src/locales/ru.js
+++ b/frontend/src/locales/ru.js
@@ -2157,4 +2157,6 @@ export default {
'Where an exercise is drawn on both figures. Your workouts stay exactly as they are.': 'Какая фигура показывается там, где упражнение нарисовано на обеих. Ваши тренировки останутся ровно такими, как есть.',
'estimated': 'оценочно',
'{0} rated · {1} estimated of {2} sets': '{0} с оценкой · {1} расчётных из {2} подходов',
+ 'Enter the address of the server this token is for': 'Введите адрес сервера, к которому относится этот токен',
+ 'Sent only to {0}, never to another server.': 'Отправляется только на {0} и никогда на другой сервер.',
}
diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.js
index 5fac718ca..0d8f053a0 100644
--- a/frontend/src/locales/th.js
+++ b/frontend/src/locales/th.js
@@ -2164,4 +2164,6 @@ export default {
'Where an exercise is drawn on both figures. Your workouts stay exactly as they are.': 'เลือกว่าท่าที่วาดไว้ทั้งสองรูปร่างจะแสดงรูปแบบไหน การออกกำลังกายของคุณยังเหมือนเดิมทุกอย่าง',
'estimated': 'ประมาณ',
'{0} rated · {1} estimated of {2} sets': 'ให้คะแนนแล้ว {0} · ประมาณ {1} จาก {2} เซ็ต',
+ 'Enter the address of the server this token is for': 'กรอกที่อยู่ของเซิร์ฟเวอร์ที่โทเค็นนี้ใช้ด้วย',
+ 'Sent only to {0}, never to another server.': 'ส่งไปที่ {0} เท่านั้น ไม่ส่งไปเซิร์ฟเวอร์อื่นเลย',
}
diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js
index 9e86e55b7..85f120fc3 100644
--- a/frontend/src/locales/tr.js
+++ b/frontend/src/locales/tr.js
@@ -2153,4 +2153,6 @@ export default {
'Where an exercise is drawn on both figures. Your workouts stay exactly as they are.': 'Bir egzersiz iki figürde de çizilmişse hangisinin gösterileceği. Antrenmanların olduğu gibi kalır.',
'estimated': 'tahmini',
'{0} rated · {1} estimated of {2} sets': '{0} puanlandı · {1} tahmini, toplam {2} set',
+ 'Enter the address of the server this token is for': 'Bu token’ın ait olduğu sunucunun adresini gir',
+ 'Sent only to {0}, never to another server.': 'Yalnızca {0} adresine gider, asla başka bir sunucuya gitmez.',
}
diff --git a/frontend/src/locales/uk.js b/frontend/src/locales/uk.js
index 3bfa57a73..5cb156c16 100644
--- a/frontend/src/locales/uk.js
+++ b/frontend/src/locales/uk.js
@@ -2150,4 +2150,6 @@ export default {
'Where an exercise is drawn on both figures. Your workouts stay exactly as they are.': 'Яка фігура показується там, де вправу намальовано на обох. Твої тренування залишаються точно такими, як були.',
'estimated': 'оціночно',
'{0} rated · {1} estimated of {2} sets': '{0} з оцінкою · {1} орієнтовних із {2} підходів',
+ 'Enter the address of the server this token is for': 'Введи адресу сервера, до якого належить цей токен',
+ 'Sent only to {0}, never to another server.': 'Надсилається лише на {0}, ніколи на інший сервер.',
}
diff --git a/frontend/src/locales/zh-TW.js b/frontend/src/locales/zh-TW.js
index fcbfc9cd0..cafb7cc97 100644
--- a/frontend/src/locales/zh-TW.js
+++ b/frontend/src/locales/zh-TW.js
@@ -2146,4 +2146,6 @@ export default {
'Where an exercise is drawn on both figures. Your workouts stay exactly as they are.': '動作在兩種人體圖上都有繪製時,顯示哪一種。你的訓練紀錄保持原樣。',
'estimated': '估算',
'{0} rated · {1} estimated of {2} sets': '{0} 組已評分 · {1} 組為估算,共 {2} 組',
+ 'Enter the address of the server this token is for': '輸入這個權杖所屬伺服器的位址',
+ 'Sent only to {0}, never to another server.': '只會傳送到 {0},絕不會傳給其他伺服器。',
}
diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js
index fbc407a84..8a31351bc 100644
--- a/frontend/src/locales/zh.js
+++ b/frontend/src/locales/zh.js
@@ -2153,4 +2153,6 @@ export default {
'Where an exercise is drawn on both figures. Your workouts stay exactly as they are.': '动作在两种人体图上都有绘制时,显示哪一种。你的训练记录保持原样。',
'estimated': '估算',
'{0} rated · {1} estimated of {2} sets': '{0} 组已评分 · {1} 组为估算,共 {2} 组',
+ 'Enter the address of the server this token is for': '输入这个令牌所属服务器的地址',
+ 'Sent only to {0}, never to another server.': '只发送到 {0},绝不会发给其他服务器。',
}
diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.js
index fdf67014e..0650de78a 100644
--- a/frontend/src/store/useStore.js
+++ b/frontend/src/store/useStore.js
@@ -1828,7 +1828,7 @@ export const useStore = create((set, get) => {
if (MOBILE) {
const remote = await loadRemote()
// Before the first request: a server behind Cloudflare Access answers nothing without it.
- await loadCfAccess()
+ await loadCfAccess({ pairedBase: remote?.mode === 'remote' ? remote.base : '' })
set({ coachLocal: coachDeviceSettings(await loadCoachDevice()) })
if (remote?.mode === 'remote') {
setRemoteAuth(remote.base, remote.token)
diff --git a/frontend/src/views/MobileOnboarding.cf-access.test.jsx b/frontend/src/views/MobileOnboarding.cf-access.test.jsx
new file mode 100644
index 000000000..d336a69d0
--- /dev/null
+++ b/frontend/src/views/MobileOnboarding.cf-access.test.jsx
@@ -0,0 +1,68 @@
+// @vitest-environment happy-dom
+// A Cloudflare Access token belongs to one server and is only sent there (lib/cf-access.js): the
+// sheet asks for that server's address beside the token, says where it goes, and a stored token
+// shows its own server rather than whatever address is being typed for a pairing.
+import React, { act } from 'react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { createRoot } from 'react-dom/client'
+import { useUI } from '../store/useUI.js'
+import { _setLangState } from '../lib/i18n-core.js'
+
+const cf = vi.hoisted(() => ({ stored: null, save: null }))
+vi.mock('../lib/cf-access.js', () => ({
+ loadCfAccess: async () => cf.stored,
+ saveCfAccess: (...a) => cf.save(...a)
+}))
+import { CfAccessSheet } from './MobileOnboarding.jsx'
+
+let root, host
+const type = (el, value) => act(() => {
+ Object.getOwnPropertyDescriptor(el.constructor.prototype, 'value').set.call(el, value)
+ el.dispatchEvent(new Event('input', { bubbles: true }))
+})
+const button = label => [...host.querySelectorAll('button')].find(b => b.textContent.trim() === label)
+const note = () => host.querySelector('[role="note"]')?.textContent
+
+beforeEach(() => {
+ globalThis.IS_REACT_ACT_ENVIRONMENT = true
+ _setLangState('en', null, null, null)
+ useUI.setState({ sheets: [], toastMsg: '' })
+ cf.stored = null
+ cf.save = vi.fn(async c => c)
+ host = document.createElement('div')
+ document.body.appendChild(host)
+ root = createRoot(host)
+})
+afterEach(() => { act(() => root.unmount()); host.remove() })
+
+describe('CfAccessSheet', () => {
+ it('saves the token with the server it is for, and says so', async () => {
+ const close = vi.fn()
+ await act(async () => root.render(<CfAccessSheet close={close} server="https://gym.example.com" />))
+ const [addr, id, secret] = host.querySelectorAll('input')
+ expect(addr.value).toBe('https://gym.example.com')
+ expect(note()).toBe('Sent only to gym.example.com, never to another server.')
+ type(id, 'id.access')
+ type(secret, 's3cret')
+ await act(async () => { button('Save').click() })
+ expect(cf.save).toHaveBeenCalledWith({ clientId: 'id.access', clientSecret: 's3cret', server: 'https://gym.example.com' })
+ expect(close).toHaveBeenCalled()
+ })
+
+ it('refuses a token without an address', async () => {
+ await act(async () => root.render(<CfAccessSheet close={() => {}} />))
+ const [, id, secret] = host.querySelectorAll('input')
+ type(id, 'id.access')
+ type(secret, 's3cret')
+ await act(async () => { button('Save').click() })
+ expect(cf.save).not.toHaveBeenCalled()
+ expect(useUI.getState().toastMsg).toBe('Enter the address of the server this token is for')
+ })
+
+ it('shows the server a stored token belongs to, not the one being typed for a pairing', async () => {
+ cf.stored = { clientId: 'id', clientSecret: 'secret', origin: 'https://gym.example.com' }
+ await act(async () => root.render(<CfAccessSheet close={() => {}} server="https://other.example.net" />))
+ expect(host.querySelector('input').value).toBe('https://gym.example.com')
+ expect(note()).toContain('gym.example.com')
+ })
+})
diff --git a/frontend/src/views/MobileOnboarding.jsx b/frontend/src/views/MobileOnboarding.jsx
index fa211d448..064b677f6 100644
--- a/frontend/src/views/MobileOnboarding.jsx
+++ b/frontend/src/views/MobileOnboarding.jsx
@@ -22,23 +22,29 @@ export function plainHttp(raw) {
}
-const openCfAccess = () => useUI.getState().openSheet(close => <CfAccessSheet close={close} />)
+// `server`: the address the token is most likely for (the one being typed into ConnectSheet).
+const openCfAccess = server => useUI.getState().openSheet(close => <CfAccessSheet close={close} server={server} />)
// A server behind Cloudflare Access (lib/cf-access.js): the service token that lets this phone
-// through, entered before pairing because the pairing request has to get through as well.
-export function CfAccessSheet({ close }) {
+// through, entered before pairing because the pairing request has to get through as well. It is
+// saved with the address of its server and only ever sent there, so the sheet asks for that
+// address too and says it: a stored token shows the server it belongs to, not `server`.
+export function CfAccessSheet({ close, server = '' }) {
+ const [addr, setAddr] = useState(typeof server === 'string' ? server : '')
const [clientId, setClientId] = useState('')
const [clientSecret, setClientSecret] = useState('')
const [had, setHad] = useState(false)
const [busy, setBusy] = useState(false)
+ const origin = normalizeServerUrl(addr)
useEffect(() => {
- loadCfAccess().then(c => { if (c) { setClientId(c.clientId); setClientSecret(c.clientSecret); setHad(true) } })
+ loadCfAccess().then(c => { if (c) { setClientId(c.clientId); setClientSecret(c.clientSecret); setHad(true); if (c.origin) setAddr(c.origin) } })
}, [])
const save = async (id, secret) => {
if (!!id.trim() !== !!secret.trim()) { useUI.getState().toast(t('Enter both the Client ID and the Client Secret')); return }
+ if (id.trim() && !origin) { useUI.getState().toast(t('Enter the address of the server this token is for')); return }
setBusy(true)
try {
- const saved = await saveCfAccess({ clientId: id, clientSecret: secret })
+ const saved = await saveCfAccess({ clientId: id, clientSecret: secret, server: origin })
close()
useUI.getState().toast(saved ? t('Saved') : t('Removed'))
} catch (e) { useUI.getState().toast(e.message || t('Could not save')) }
@@ -49,6 +55,12 @@ export function CfAccessSheet({ close }) {
<div className="muted small" style={{ marginBottom: 14 }}>
{t('Only if your server is behind Cloudflare Access: the service token this phone sends with every request to it. Kept in this phone’s secure storage.')}
</div>
+ <input className="input" placeholder={t('Server address (e.g. gym.example.com)')} value={addr} aria-label={t('Server address (e.g. gym.example.com)')}
+ onChange={e => setAddr(e.target.value)} autoCapitalize="none" autoCorrect="off" inputMode="url" />
+ {origin && <div className="dim small" role="note" style={{ marginTop: 8, lineHeight: 1.45, overflowWrap: 'anywhere' }}>
+ {t('Sent only to {0}, never to another server.', new URL(origin).host)}
+ </div>}
+ <div style={{ height: 10 }} />
<input className="input" placeholder="CF-Access-Client-Id" value={clientId}
onChange={e => setClientId(e.target.value)} autoCapitalize="none" autoCorrect="off" spellCheck={false} />
<div style={{ height: 10 }} />
@@ -104,7 +116,7 @@ export function ConnectSheet({ close, initialUrl = '', again = false }) {
<div style={{ height: 12 }} />
<Button variant="primary" onClick={go} disabled={busy}>{busy ? t('Connecting…') : t('Connect')}</Button>
<div style={{ height: 10 }} />
- <Button icon="key" onClick={openCfAccess} disabled={busy}>{t('Cloudflare Access')}</Button>
+ <Button icon="key" onClick={() => openCfAccess(normalizeServerUrl(url) || '')} disabled={busy}>{t('Cloudflare Access')}</Button>
</>
}
@@ -126,7 +138,7 @@ export default function MobileOnboarding() {
{t('Local keeps everything on this phone. Connecting syncs to your own openGym server instead. You can switch later in Settings.')}
</div>
<div style={{ height: 18 }} />
- <Button icon="gear" onClick={openCfAccess}>{t('Connection settings')}</Button>
+ <Button icon="gear" onClick={() => openCfAccess()}>{t('Connection settings')}</Button>
</div>
)
}