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.

Mobile: Cloudflare Access service token for the paired server

EthanetXYZ39a4d6d23924
diff --git a/api/server.js b/api/server.js
index 8dcb6028d..b72c31e24 100644
--- a/api/server.js
+++ b/api/server.js
@@ -2557,7 +2557,9 @@ const server = http.createServer(async (req, res) => {
&& APP_ORIGINS.has(origin);
res.writeHead(204, {
'Access-Control-Allow-Methods': 'GET,POST,PUT,DELETE,OPTIONS',
- 'Access-Control-Allow-Headers': 'Content-Type, Authorization',
+ // The CF-Access-* pair: a phone's Cloudflare Access service token (frontend lib/cf-access.js),
+ // for an Access application that passes OPTIONS through to the origin.
+ 'Access-Control-Allow-Headers': 'Content-Type, Authorization, CF-Access-Client-Id, CF-Access-Client-Secret',
'Access-Control-Max-Age': '86400',
...(pna ? { 'Access-Control-Allow-Private-Network': 'true' } : {})
});
diff --git a/docs/MOBILE.md b/docs/MOBILE.md
index 89209d69f..ffedf94e3 100644
--- a/docs/MOBILE.md
+++ b/docs/MOBILE.md
@@ -64,6 +64,28 @@ or Settings → Account → **"Connect to my server"** later) to finish. Notes:
changes on the phone and adds them back the next time it is paired with the same server
and account.
+### A server behind Cloudflare Access
+
+If your server sits behind [Cloudflare Access](https://developers.cloudflare.com/cloudflare-one/policies/access/)
+(Zero Trust), the app can't do Access's interactive sign-in from inside its WebView. Use a
+**service token** instead:
+
+1. In Zero Trust → Access → Service Auth, create a service token and note its Client ID and
+ Client Secret.
+2. In the Access application for your openGym host, add a policy with the **Service Auth**
+ action that includes that token.
+3. In the application's **CORS settings**, enable **Bypass OPTIONS requests to origin**. The
+ app runs on its own origin, so every request is preceded by a CORS preflight, and a
+ 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**.
+
+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.
+
### Connection states
Settings → Account → **Server & sync** shows the server, the account, how things stand, when the phone
diff --git a/frontend/src/components/ServerSync.jsx b/frontend/src/components/ServerSync.jsx
index 4e3fa09a7..5c24661a2 100644
--- a/frontend/src/components/ServerSync.jsx
+++ b/frontend/src/components/ServerSync.jsx
@@ -12,7 +12,7 @@ import { MOBILE, shareExport } from '../lib/mobile.js'
import { syncMedia } from '../lib/media-sync.js'
import { DEMO } from '../lib/demo.js'
import { askAddDeviceData, menuSheet } from '../sheets.jsx'
-import { ConnectSheet } from '../views/MobileOnboarding.jsx'
+import { ConnectSheet, CfAccessSheet } from '../views/MobileOnboarding.jsx'
import { passwordOn, openPasswordSignIn } from './PasswordAuth.jsx'
import { Section, Row, Button } from './ui.jsx'
@@ -268,6 +268,8 @@ export function ServerSyncSection({ children }) {
subtitle={t('Signed in as {0}', user.name)} />
<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} />)} />}
{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 ac44849e7..e40726442 100644
--- a/frontend/src/lib/api.js
+++ b/frontend/src/lib/api.js
@@ -24,6 +24,11 @@ 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.
+let accessHeaders = {}
+export function setAccessHeaders(h) { accessHeaders = Object.assign({}, h) }
+const remoteHeaders = () => Object.assign({}, remoteBase ? accessHeaders : {}, remoteToken ? { Authorization: 'Bearer ' + remoteToken } : {})
export { appBase }
@@ -46,8 +51,7 @@ export async function api(path, opts) {
// there and the change was marked as synced while the server never saw it. status 0, not
// undefined: this is not "offline", and the store must not show it as such.
if (MOBILE && !remoteBase) throw failure(t('This phone is not connected to a server.'), 'not-paired', 0)
- const headers = Object.assign({ 'Content-Type': 'application/json' }, init.headers)
- if (remoteToken) headers.Authorization = 'Bearer ' + remoteToken
+ const headers = Object.assign({ 'Content-Type': 'application/json' }, init.headers, remoteHeaders())
// A paired phone has an absolute base of its own; everyone else is relative to where the app
// is served, so a subpath deployment reaches its own API instead of the proxy's root.
const url = remoteBase ? remoteBase + path : appBase().replace(/\/$/, '') + path
@@ -106,7 +110,7 @@ export function beacon(path, body) {
answer allows it for GET and PUT); both refuse to run on a phone without a server, like api(). */
const mediaUrl = path => (remoteBase ? remoteBase + path : appBase().replace(/\/$/, '') + path)
-const mediaHeaders = () => (remoteToken ? { Authorization: 'Bearer ' + remoteToken } : {})
+const mediaHeaders = remoteHeaders
const notPaired = () => failure(t('This phone is not connected to a server.'), 'not-paired', 0)
const timedOut = () => failure(t('The server did not answer in time.'), 'timeout')
@@ -289,12 +293,13 @@ async function blockedAsMixedContent(base) {
}
// 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.
+// 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.
export async function pairRedeem(serverBase, code, { probeMs = PROBE_MS } = {}) {
let data
try {
data = await request(serverBase + '/api/pair/redeem', {
- method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code })
+ method: 'POST', headers: Object.assign({ 'Content-Type': 'application/json' }, accessHeaders), 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
new file mode 100644
index 000000000..5495b13e6
--- /dev/null
+++ b/frontend/src/lib/cf-access.js
@@ -0,0 +1,48 @@
+// Mobile build only: a self-hosted server behind Cloudflare Access (Zero Trust). Access stops
+// every request at Cloudflare's edge until it proves who it is, and a phone cannot do the
+// browser's interactive sign-in from inside the app's WebView. A service token can: two headers,
+// CF-Access-Client-Id and CF-Access-Client-Secret, on every request to the server — the pairing
+// 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.
+import { secureGet, secureSet, secureRemove } from './coach-secrets.js'
+import { setAccessHeaders } from './api.js'
+
+const KEY = 'cfAccess'
+
+const clean = v => String(v || '').trim()
+
+// 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.
+export function accessHeaders(creds) {
+ const id = clean(creds && creds.clientId)
+ const secret = clean(creds && creds.clientSecret)
+ if (!id || !secret) return {}
+ return { 'CF-Access-Client-Id': id, 'CF-Access-Client-Secret': secret }
+}
+
+export async function loadCfAccess() {
+ 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) }
+ } catch { /* unreadable: as if never set */ }
+ setAccessHeaders(accessHeaders(creds))
+ return creds && creds.clientId && creds.clientSecret ? creds : null
+}
+
+// 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) }
+ if (!creds.clientId || !creds.clientSecret) {
+ await secureRemove(KEY)
+ setAccessHeaders({})
+ return null
+ }
+ await secureSet(KEY, JSON.stringify(creds))
+ setAccessHeaders(accessHeaders(creds))
+ return creds
+}
diff --git a/frontend/src/lib/cf-access.test.js b/frontend/src/lib/cf-access.test.js
new file mode 100644
index 000000000..695fb65e2
--- /dev/null
+++ b/frontend/src/lib/cf-access.test.js
@@ -0,0 +1,64 @@
+// @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. */
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+vi.mock('./mobile.js', () => ({ MOBILE: true }))
+const backing = new Map()
+vi.mock('@aparajita/capacitor-secure-storage', () => ({
+ SecureStorage: {
+ get: async k => (backing.has(k) ? backing.get(k) : null),
+ set: async (k, v) => { backing.set(k, v) },
+ remove: async k => { backing.delete(k) }
+ }
+}))
+
+import { api, pairRedeem, setRemoteAuth } from './api.js'
+import { accessHeaders, loadCfAccess, saveCfAccess } from './cf-access.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({}) })
+
+describe('accessHeaders', () => {
+ it('needs both halves, trimmed', () => {
+ expect(accessHeaders({ clientId: ' id.access ', clientSecret: ' s3cret ' }))
+ .toEqual({ 'CF-Access-Client-Id': 'id.access', 'CF-Access-Client-Secret': 's3cret' })
+ expect(accessHeaders({ clientId: 'id', clientSecret: '' })).toEqual({})
+ expect(accessHeaders(null)).toEqual({})
+ })
+})
+
+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 pairRedeem('https://gym.example.com', 'ABCD')
+ expect(fetch.mock.calls[0][1].headers).toMatchObject({ 'CF-Access-Client-Id': 'id', 'CF-Access-Client-Secret': 'secret' })
+ })
+
+ 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' })
+ setRemoteAuth('https://gym.example.com', 'TOKEN')
+ await api('/api/data/rev')
+ expect(fetch.mock.calls[0][1].headers).toMatchObject({
+ Authorization: 'Bearer TOKEN', 'CF-Access-Client-Id': 'id', 'CF-Access-Client-Secret': 'secret'
+ })
+ })
+
+ 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: '', clientSecret: '' })
+ expect(await loadCfAccess()).toBe(null)
+ const fetch = ok({ rev: 1 })
+ vi.stubGlobal('fetch', fetch)
+ setRemoteAuth('https://gym.example.com', 'TOKEN')
+ await api('/api/data/rev')
+ expect(fetch.mock.calls[0][1].headers['CF-Access-Client-Id']).toBeUndefined()
+ })
+})
diff --git a/frontend/src/lib/coach-secrets.js b/frontend/src/lib/coach-secrets.js
index 3939d1129..806e6747e 100644
--- a/frontend/src/lib/coach-secrets.js
+++ b/frontend/src/lib/coach-secrets.js
@@ -36,24 +36,30 @@ export const withTimeout = (promise, ms = NATIVE_TIMEOUT_MS) => new Promise((res
promise.then(v => { clearTimeout(tm); resolve(v) }, e => { clearTimeout(tm); reject(e) })
})
-export async function getApiKey() {
+// Any small secret under a key of its own, with the same fallbacks: lib/cf-access.js keeps the
+// Cloudflare Access service token here, beside the Coach's API key.
+export async function secureGet(key) {
const { store: p } = await plugin()
if (p) {
- try { const v = await withTimeout(p.get(KEY)); return typeof v === 'string' && v ? v : null } catch { /* fall through */ }
+ try { const v = await withTimeout(p.get(key)); return typeof v === 'string' && v ? v : null } catch { /* fall through */ }
}
- return memory.get(KEY) || null
+ return memory.get(key) || null
}
-export async function setApiKey(value) {
+export async function secureSet(key, value) {
const v = String(value || '').trim()
- if (!v) return clearApiKey()
+ if (!v) return secureRemove(key)
const { store: p } = await plugin()
if (p) {
- try { await withTimeout(p.set(KEY, v)); memory.delete(KEY); return } catch { /* fall through */ }
+ try { await withTimeout(p.set(key, v)); memory.delete(key); return } catch { /* fall through */ }
}
- memory.set(KEY, v)
+ memory.set(key, v)
}
-export async function clearApiKey() {
+export async function secureRemove(key) {
const { store: p } = await plugin()
- if (p) { try { await withTimeout(p.remove(KEY)) } catch { /* nothing to clear */ } }
- memory.delete(KEY)
+ if (p) { try { await withTimeout(p.remove(key)) } catch { /* nothing to clear */ } }
+ memory.delete(key)
}
+
+export const getApiKey = () => secureGet(KEY)
+export const setApiKey = value => secureSet(KEY, value)
+export const clearApiKey = () => secureRemove(KEY)
diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.js
index 96842677b..3cf8e3203 100644
--- a/frontend/src/store/useStore.js
+++ b/frontend/src/store/useStore.js
@@ -19,6 +19,7 @@ import { saveWorkoutEdit, deleteEditedWorkout } from '../lib/session-edit.js'
import { appBase } from '../lib/app-base.js'
import { linkTokenFromSearch, stripLinkFromUrl } from '../lib/device-link.js'
import { loadRemote, chooseLocal, forgetRemote, connect, normalizeServerUrl, renewToken } from '../lib/remote.js'
+import { loadCfAccess } from '../lib/cf-access.js'
import { loadCoachDevice, saveCoachDevice, coachDeviceSettings } from '../lib/coach-device.js'
import { RTL_LANGS } from '../lib/i18n-core.js'
import { DEFAULT_TEMPLATE_ID } from '../lib/structuralBalanceTemplates.js'
@@ -1810,6 +1811,8 @@ export const useStore = create((set, get) => {
// case it behaves exactly like the signed-in web flow below, straight from here.
if (MOBILE) {
const remote = await loadRemote()
+ // Before the first request: a server behind Cloudflare Access answers nothing without it.
+ await loadCfAccess()
set({ coachLocal: coachDeviceSettings(await loadCoachDevice()) })
if (remote?.mode === 'remote') {
setRemoteAuth(remote.base, remote.token)
diff --git a/frontend/src/views/MobileOnboarding.jsx b/frontend/src/views/MobileOnboarding.jsx
index af03ac4b1..519b22c9c 100644
--- a/frontend/src/views/MobileOnboarding.jsx
+++ b/frontend/src/views/MobileOnboarding.jsx
@@ -8,6 +8,48 @@ import { t } from '../lib/i18n.js'
import Icon from '../components/Icon.jsx'
import { Button } from '../components/ui.jsx'
import { askAddDeviceData } from '../sheets.jsx'
+import { loadCfAccess, saveCfAccess } from '../lib/cf-access.js'
+
+const openCfAccess = () => useUI.getState().openSheet(close => <CfAccessSheet close={close} />)
+
+// 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 }) {
+ const [clientId, setClientId] = useState('')
+ const [clientSecret, setClientSecret] = useState('')
+ const [had, setHad] = useState(false)
+ const [busy, setBusy] = useState(false)
+ useEffect(() => {
+ loadCfAccess().then(c => { if (c) { setClientId(c.clientId); setClientSecret(c.clientSecret); setHad(true) } })
+ }, [])
+ const save = async (id, secret) => {
+ if (!!id.trim() !== !!secret.trim()) { useUI.getState().toast(t('Enter both the Client ID and the Client Secret')); return }
+ setBusy(true)
+ try {
+ const saved = await saveCfAccess({ clientId: id, clientSecret: secret })
+ close()
+ useUI.getState().toast(saved ? t('Saved') : t('Removed'))
+ } catch (e) { useUI.getState().toast(e.message || t('Could not save')) }
+ finally { setBusy(false) }
+ }
+ return <>
+ <h3>{t('Cloudflare Access')}</h3>
+ <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="CF-Access-Client-Id" value={clientId}
+ onChange={e => setClientId(e.target.value)} autoCapitalize="none" autoCorrect="off" spellCheck={false} />
+ <div style={{ height: 10 }} />
+ <input className="input" type="password" placeholder="CF-Access-Client-Secret" value={clientSecret}
+ onChange={e => setClientSecret(e.target.value)} autoCapitalize="none" autoCorrect="off" spellCheck={false} autoComplete="off" />
+ <div style={{ height: 12 }} />
+ <Button variant="primary" onClick={() => save(clientId, clientSecret)} disabled={busy}>{t('Save')}</Button>
+ {had && <>
+ <div style={{ height: 10 }} />
+ <Button icon="trash" onClick={() => save('', '')} disabled={busy}>{t('Remove')}</Button>
+ </>}
+ </>
+}
// `again`: a phone whose server stopped accepting it (components/ServerSync.jsx pairAgain) — the
// address it had is filled in when it still has one, so only the new code is left to type, and
@@ -46,6 +88,8 @@ export function ConnectSheet({ close, initialUrl = '', again = false }) {
{error && <div className="small" role="alert" style={{ color: 'var(--red)', marginTop: 10, lineHeight: 1.45, overflowWrap: 'anywhere' }}>{error}</div>}
<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>
</>
}
@@ -66,6 +110,8 @@ export default function MobileOnboarding() {
<div className="dim small" style={{ marginTop: 26, lineHeight: 1.5 }}>
{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>
</div>
)
}