diff --git a/api/server.js b/api/server.js index ca994fa..c20934c 100644 --- a/api/server.js +++ b/api/server.js @@ -178,7 +178,10 @@ function readSession(req) { const cookies = Object.fromEntries((req.headers.cookie || '').split(';').map(c => { const i = c.indexOf('='); return i < 0 ? ['', ''] : [c.slice(0, i).trim(), c.slice(i + 1).trim()]; })); - const tok = cookies.gymsid; + // The paired mobile app has no cookie jar shared with the API's origin, so it carries the same + // signed token in an Authorization header instead — same payload, same verification below. + const auth = req.headers.authorization || ''; + const tok = cookies.gymsid || (auth.startsWith('Bearer ') ? auth.slice(7).trim() : null); if (!tok) return null; const payload = verifySig(tok); if (!payload) return null; @@ -222,6 +225,21 @@ function takeChallenge(cid) { } setInterval(() => { for (const [k, v] of challenges) if (v.exp < Date.now()) challenges.delete(k); }, 60000).unref(); +// ---------- device pairing (mobile app "connect to my server", no WebAuthn ceremony) ---------- +// A passkey ceremony can't run inside the app's WebView (its origin never matches RP_ID), so the +// app authenticates by redeeming a short code minted from an already signed-in browser tab — +// same 5-min-TTL/one-shot shape as the WebAuthn challenge store above. +const pairings = new Map(); // code -> {uid, exp} +const PAIR_CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; // no 0/O/1/I — read off a screen +function makePairCode() { + let code; + do { + code = Array.from(crypto.randomBytes(8)).map(b => PAIR_CODE_ALPHABET[b % PAIR_CODE_ALPHABET.length]).join(''); + } while (pairings.has(code)); + return code; +} +setInterval(() => { for (const [k, v] of pairings) if (v.exp < Date.now()) pairings.delete(k); }, 60000).unref(); + /* ---------- helpers ---------- */ function json(res, code, obj, extraHeaders) { const body = JSON.stringify(obj); @@ -519,6 +537,37 @@ const routes = { json(res, 200, { ok: true }, { 'Set-Cookie': clearCookie }); }, + // 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. + 'POST /api/pair/create': async (req, res) => { + const user = readSession(req); + if (!user) return json(res, 401, { error: 'not signed in' }); + const code = makePairCode(); + pairings.set(code, { uid: user.id, exp: Date.now() + 5 * 60000 }); + audit(req, 'auth.pair.create', { user }); + json(res, 200, { code }); + }, + + // Called from the mobile app itself with the code shown in the browser. No session required — + // the code IS the credential, one-shot and 5-minute-lived like a WebAuthn challenge. + 'POST /api/pair/redeem': async (req, res) => { + const body = await readBody(req); + const code = String(body.code || '').trim().toUpperCase(); + const p = pairings.get(code); + if (p) pairings.delete(code); + if (!p || p.exp < Date.now()) { + audit(req, 'auth.pair.fail', { ok: false, msg: 'code-invalid' }); + return json(res, 400, { error: 'invalid or expired code' }); + } + const user = db.users.find(u => u.id === p.uid); + if (!user || user.disabled) { + audit(req, 'auth.pair.fail', { ok: false, uid: p.uid, msg: 'user-unavailable' }); + return json(res, 400, { error: 'invalid or expired code' }); + } + audit(req, 'auth.pair.ok', { user }); + json(res, 200, { token: makeSession(user), user: { id: user.id, name: user.name, admin: isAdmin(user) } }); + }, + 'GET /api/data': async (req, res) => { const user = readSession(req); if (!user) return json(res, 401, { error: 'not signed in' }); @@ -728,6 +777,20 @@ const routes = { }; http.createServer(async (req, res) => { + // Same-origin (the deployed nginx-proxied web app) never triggers CORS, so this only matters + // for the paired mobile app calling in from its own WebView origin. It carries no cookie + // (auth is the Authorization header instead), so Allow-Credentials is deliberately never set — + // reflecting the origin here can't expose the cookie session to anyone. + const origin = req.headers.origin; + if (origin) { res.setHeader('Access-Control-Allow-Origin', origin); res.setHeader('Vary', 'Origin'); } + if (req.method === 'OPTIONS') { + res.writeHead(204, { + 'Access-Control-Allow-Methods': 'GET,POST,PUT,DELETE,OPTIONS', + 'Access-Control-Allow-Headers': 'Content-Type, Authorization', + 'Access-Control-Max-Age': '86400' + }); + return res.end(); + } const url = new URL(req.url, 'http://x'); const key = req.method + ' ' + url.pathname; const handler = routes[key]; diff --git a/docs/MOBILE.md b/docs/MOBILE.md index 4aeeb10..9d1e24c 100644 --- a/docs/MOBILE.md +++ b/docs/MOBILE.md @@ -10,11 +10,35 @@ openGym ships in two flavors from the same codebase: | Reminders | Web Push from your server | native local notifications, no server involved | | Exercise media | served by your server (`img/`, `gif/`) | loaded from the jsDelivr CDN | -The mobile flavor never talks to a backend: no sign-in screen, no sync, no telemetry. -State is mirrored from `localStorage` into `opengym-state.json` in the app's private data -directory on every change (iOS is allowed to evict WebView storage under pressure — the -file mirror is the durable copy and is restored on launch). Backups go out through the -OS share sheet instead of a browser download. +The mobile flavor never talks to a backend by default: no sign-in screen, no sync, no +telemetry. State is mirrored from `localStorage` into `opengym-state.json` in the app's +private data directory on every change (iOS is allowed to evict WebView storage under +pressure — the file mirror is the durable copy and is restored on launch). Backups go out +through the OS share sheet instead of a browser download. + +### Connecting the app to your own server + +On first launch the app asks how you want to use it. Alongside the fully local mode above, +you can instead **connect it to a self-hosted openGym server** — your data then lives there, +synced the same way the browser PWA does, instead of only on the phone. This is a mode of the +same app, not a different build or download. + +Passkeys can't be used for this: the app's WebView runs at its own origin, which never +matches the real hostname WebAuthn needs. Instead you *pair* the device from a browser +that's already signed in: Settings → **"Pair the mobile app"** shows a one-time code (valid +5 minutes); enter your server's address and that code in the app (same first-launch screen, +or Settings → **"Connect to my server"** later) to finish. Notes: + +- Requires network access every time the app is used — there's no offline file mirror once + connected, same as the browser PWA. +- Use an HTTPS address if at all possible: the connection carries a bearer token instead of + a cookie, and that token would otherwise cross the network in plain text. +- "Sign out everywhere" (Settings → Account, in the browser) revokes a paired app's access + too — it's the same signed session token either way, just delivered over a header instead + of a cookie. See `/api/pair/create` and `/api/pair/redeem` in `api/server.js` for the + exchange itself. +- Settings → "Disconnect" syncs one last time, then drops the device cleanly back to local + mode. ## Prerequisites diff --git a/docs/SELF_HOSTING.md b/docs/SELF_HOSTING.md index 4ae67d7..5cd98fd 100644 --- a/docs/SELF_HOSTING.md +++ b/docs/SELF_HOSTING.md @@ -42,6 +42,21 @@ passkey prompt won't appear. To use openGym from your phone you need a real HTTP (You can still open it over LAN in **guest mode**, which stores data only in that browser.) +The standalone mobile app (`docs/MOBILE.md`) sidesteps this entirely for its "connect to my +server" mode: instead of a passkey ceremony (impossible from inside its WebView, which never +runs at your real hostname), it pairs by redeeming a short one-time code — minted from +Settings → "Pair the mobile app" in an already signed-in browser tab — for a bearer token +sent as an `Authorization` header rather than a cookie. Two consequences worth knowing if +you're poking at the API directly: + +- `POST /api/pair/create` (needs a session) and `POST /api/pair/redeem` (doesn't) implement + this — see `api/server.js`. The returned token is the exact same signed value a cookie + carries, so "sign out everywhere" invalidates it too. +- The server reflects `Access-Control-Allow-Origin` for any request that sends an `Origin` + header, so the app's own WebView origin can call the API cross-origin. It never sends + `Access-Control-Allow-Credentials`, so this doesn't let a browser read your cookie session + from another origin — only bearer-token requests benefit from it. + ## 3. Expose it over HTTPS on your own domain Put openGym behind something that terminates TLS for a hostname you control, then point it at diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index d310957..04487c7 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -16,6 +16,7 @@ import Modals from './components/Modals.jsx' import Toast from './components/Toast.jsx' import RestTimer from './components/RestTimer.jsx' import Login from './views/Login.jsx' +import MobileOnboarding from './views/MobileOnboarding.jsx' import Home from './views/Home.jsx' import Plan from './views/Plan.jsx' import RoutineEdit from './views/RoutineEdit.jsx' @@ -46,6 +47,7 @@ function Shell() { const loc = useLocation() const { S, user, ready } = useStore() const isGuest = useStore(s => s.isGuest()) + const needsMobileOnboarding = useStore(s => s.needsMobileOnboarding) const langV = useLang() // re-renders the whole shell when the language (pack) changes useEffect(() => { setNav(navigate) }, [navigate]) useEffect(() => { applyPrefs(S.theme, S.accent) }, [S.theme, S.accent]) @@ -81,7 +83,7 @@ function Shell() { re-mounts the boundary, so the tab bar is always a way out */}
- {!authed ? : ( + {!authed ? : needsMobileOnboarding ? : ( } /> } /> diff --git a/frontend/src/lib/api.js b/frontend/src/lib/api.js index 6a7e620..340dd9f 100644 --- a/frontend/src/lib/api.js +++ b/frontend/src/lib/api.js @@ -5,8 +5,27 @@ export const BIO = IS_APPLE ? 'Face ID / Touch ID' : IS_ANDROID ? 'fingerprint o export const VAULT = IS_APPLE ? 'iCloud Keychain' : IS_ANDROID ? 'Google Password Manager' : 'your password manager' export const webauthnOK = () => !!(window.PublicKeyCredential && navigator.credentials) +// The paired mobile app (lib/remote.js) is the only caller of these — everywhere else stays on +// same-origin cookies, so remoteBase/remoteToken stay empty and api() behaves exactly as before. +let remoteBase = '' +let remoteToken = null +export function setRemoteAuth(base, token) { remoteBase = base || ''; remoteToken = token || null } + export async function api(path, opts) { - const r = await fetch(path, Object.assign({ headers: { 'Content-Type': 'application/json' } }, opts)) + const headers = Object.assign({ 'Content-Type': 'application/json' }, opts && opts.headers) + if (remoteToken) headers.Authorization = 'Bearer ' + remoteToken + const r = await fetch(remoteBase + path, Object.assign({}, opts, { headers })) + const data = await r.json().catch(() => ({})) + if (!r.ok) { const e = new Error(data.error || ('HTTP ' + r.status)); e.status = r.status; throw e } + return data +} + +// 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. +export async function pairRedeem(serverBase, code) { + const r = await fetch(serverBase + '/api/pair/redeem', { + method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code }) + }) const data = await r.json().catch(() => ({})) if (!r.ok) { const e = new Error(data.error || ('HTTP ' + r.status)); e.status = r.status; throw e } return data diff --git a/frontend/src/lib/mobile.js b/frontend/src/lib/mobile.js index 439b155..cc848d2 100644 --- a/frontend/src/lib/mobile.js +++ b/frontend/src/lib/mobile.js @@ -31,6 +31,27 @@ export async function nativeSave(state) { } catch (e) { /* keep the localStorage copy */ } } +// "Connect to my server" mode (lib/remote.js): which of local-only / a paired remote account this +// device chose, kept in its own file — never inside opengym-state.json, since that file's content +// is exactly what pushState() PUTs to a server, and a device's own connection secret must never +// travel as if it were training data. +const REMOTE_FILE = 'opengym-remote.json' + +export async function loadRemoteFile() { + try { + const { Filesystem, Directory, Encoding } = await import('@capacitor/filesystem') + const r = await Filesystem.readFile({ path: REMOTE_FILE, directory: Directory.Data, encoding: Encoding.UTF8 }) + return JSON.parse(r.data) + } catch (e) { return null } // never decided yet +} + +export async function saveRemoteFile(data) { + try { + const { Filesystem, Directory, Encoding } = await import('@capacitor/filesystem') + await Filesystem.writeFile({ path: REMOTE_FILE, directory: Directory.Data, data: JSON.stringify(data), encoding: Encoding.UTF8 }) + } catch (e) { /* worst case: onboarding asks again next launch */ } +} + // (Re)schedule the workout-day reminder: one repeating notification per weekday that has a // routine in the weekly plan. Cheap enough to run after any state change — the plan or the // reminder time may just have been edited. `interactive` gates the OS permission prompt to diff --git a/frontend/src/lib/remote.js b/frontend/src/lib/remote.js new file mode 100644 index 0000000..22ef5a9 --- /dev/null +++ b/frontend/src/lib/remote.js @@ -0,0 +1,48 @@ +// Mobile build only: "connect to my server" mode (see mobile.js's header comment for why the +// mobile flavor has no backend at all by default). This is the alternative — pairing the app to +// an already self-hosted openGym server instead of keeping data device-local. +// +// Passkeys can't be used from inside the app's own WebView (its origin never matches the +// server's RP_ID), so auth here is a short one-time code redeemed from an already signed-in +// browser tab (Settings → "Pair the mobile app") for a bearer token — see api/server.js's +// /api/pair/create + /api/pair/redeem. +import { pairRedeem, setRemoteAuth } from './api.js' +import { loadRemoteFile, saveRemoteFile } from './mobile.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, +// still parses fine without a scheme). Returns null for anything that isn't a usable URL at all. +export function normalizeServerUrl(raw) { + const s = String(raw || '').trim() + if (!s) return null + const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(s) ? s : 'https://' + s + try { + const u = new URL(withScheme) + if (!u.hostname) return null + return u.origin + } catch (e) { return null } +} + +export async function loadRemote() { + return loadRemoteFile() +} + +export async function chooseLocal() { + await saveRemoteFile({ mode: 'local' }) +} + +export async function forgetRemote() { + await saveRemoteFile({ mode: 'local' }) + setRemoteAuth('', null) +} + +// Redeems the pairing code, wires api.js at the resolved base, and persists the connection so +// boot() can restore it on the next launch. +export async function connect(rawUrl, code) { + const base = normalizeServerUrl(rawUrl) + if (!base) throw new Error('Enter a valid server address') + const { token, user } = await pairRedeem(base, String(code || '').trim()) + setRemoteAuth(base, token) + await saveRemoteFile({ mode: 'remote', base, token, user }) + return user +} diff --git a/frontend/src/lib/remote.test.js b/frontend/src/lib/remote.test.js new file mode 100644 index 0000000..0f5ec58 --- /dev/null +++ b/frontend/src/lib/remote.test.js @@ -0,0 +1,26 @@ +import { describe, expect, it } from 'vitest' +import { normalizeServerUrl } from './remote.js' + +// The pairing flow lives or dies on this being forgiving about what someone types on a phone +// keyboard, while still refusing input that can't possibly be a server address. +describe('normalizeServerUrl', () => { + it('accepts a bare host and adds https://', () => { + expect(normalizeServerUrl('gym.example.com')).toBe('https://gym.example.com') + }) + + it('keeps an explicit scheme, including http for LAN testing', () => { + expect(normalizeServerUrl('http://192.168.1.20:8080')).toBe('http://192.168.1.20:8080') + expect(normalizeServerUrl('https://gym.example.com')).toBe('https://gym.example.com') + }) + + it('trims whitespace and a trailing path/slash down to the origin', () => { + expect(normalizeServerUrl(' gym.example.com/ ')).toBe('https://gym.example.com') + expect(normalizeServerUrl('https://gym.example.com/some/path')).toBe('https://gym.example.com') + }) + + it('rejects empty or unusable input', () => { + for (const v of ['', ' ', null, undefined, 'not a url at all!!']) { + expect(normalizeServerUrl(v)).toBe(null) + } + }) +}) diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js index eb6e1ad..7f4a79f 100644 --- a/frontend/src/locales/de.js +++ b/frontend/src/locales/de.js @@ -617,5 +617,30 @@ export default { 'secondary': 'sekundär', 'No exercises with an estimated 1RM yet.': 'Noch keine Übungen mit geschätztem 1RM.', 'Tap a muscle to see its exercises.': 'Tippe auf einen Muskel, um seine Übungen zu sehen.', - 'Unpair': 'Trennen' + 'Unpair': 'Trennen', + + // "Connect to my server" (mobile app pairing) + 'Your server': 'Dein Server', + 'Synced with your openGym server.': 'Mit deinem openGym-Server synchronisiert.', + 'Disconnect': 'Trennen', + 'Disconnect from your server?': 'Verbindung zum Server trennen?', + 'Your data is synced to your server first, then this device switches back to local-only.': 'Deine Daten werden zuerst mit deinem Server synchronisiert, dann wechselt dieses Gerät zurück in den lokalen Modus.', + 'Disconnected — back to local-only': 'Verbindung getrennt — zurück im lokalen Modus', + 'Connect to my server': 'Mit meinem Server verbinden', + 'Sync this device to your own self-hosted openGym instead.': 'Dieses Gerät stattdessen mit deinem eigenen self-hosted openGym synchronisieren.', + 'Pair the mobile app': 'Mobile App koppeln', + 'Connect the openGym app on your phone to this account.': 'Verbinde die openGym-App auf deinem Handy mit diesem Konto.', + 'Could not generate a code': 'Code konnte nicht erstellt werden', + 'On the openGym app, choose “Connect to my server”, then enter this address and the code below. It expires in 5 minutes.': 'Wähle in der openGym-App „Mit meinem Server verbinden“, gib dann diese Adresse und den Code unten ein. Er läuft in 5 Minuten ab.', + 'Enter your server address and the code': 'Serveradresse und Code eingeben', + 'Connected': 'Verbunden', + 'Could not connect': 'Verbindung fehlgeschlagen', + 'Open Settings → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.': 'Öffne auf der openGym-Seite, bei der du bereits angemeldet bist, Einstellungen → „Mobile App koppeln“, und gib dann deren Adresse und den dort angezeigten Code ein.', + 'Server address (e.g. gym.example.com)': 'Serveradresse (z. B. gym.example.com)', + 'Pairing code': 'Kopplungscode', + 'Connecting…': 'Verbinde …', + 'Connect': 'Verbinden', + 'How do you want to use openGym?': 'Wie möchtest du openGym nutzen?', + 'Use on this device': 'Auf diesem Gerät nutzen', + 'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'Lokal behält alles auf diesem Handy. Verbinden synchronisiert stattdessen mit deinem eigenen openGym-Server — du kannst das später in den Einstellungen ändern.' } diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js index 6050aa3..4051364 100644 --- a/frontend/src/locales/es.js +++ b/frontend/src/locales/es.js @@ -600,5 +600,30 @@ export default { 'secondary': 'secundario', 'No exercises with an estimated 1RM yet.': 'Aún no hay ejercicios con 1RM estimado.', 'Tap a muscle to see its exercises.': 'Toca un músculo para ver sus ejercicios.', - 'Unpair': 'Desvincular' + 'Unpair': 'Desvincular', + + // "Connect to my server" (mobile app pairing) + 'Your server': 'Tu servidor', + 'Synced with your openGym server.': 'Sincronizado con tu servidor de openGym.', + 'Disconnect': 'Desconectar', + 'Disconnect from your server?': '¿Desconectar de tu servidor?', + 'Your data is synced to your server first, then this device switches back to local-only.': 'Tus datos se sincronizan primero con tu servidor, y luego este dispositivo vuelve a modo local.', + 'Disconnected — back to local-only': 'Desconectado — de vuelta a modo local', + 'Connect to my server': 'Conectar a mi servidor', + 'Sync this device to your own self-hosted openGym instead.': 'Sincroniza este dispositivo con tu propio openGym self-hosted.', + 'Pair the mobile app': 'Emparejar la app móvil', + 'Connect the openGym app on your phone to this account.': 'Conecta la app de openGym en tu móvil a esta cuenta.', + 'Could not generate a code': 'No se pudo generar un código', + 'On the openGym app, choose “Connect to my server”, then enter this address and the code below. It expires in 5 minutes.': 'En la app de openGym, elige «Conectar a mi servidor», luego introduce esta dirección y el código de abajo. Caduca en 5 minutos.', + 'Enter your server address and the code': 'Introduce la dirección de tu servidor y el código', + 'Connected': 'Conectado', + 'Could not connect': 'No se pudo conectar', + 'Open Settings → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.': 'En Ajustes → «Emparejar la app móvil» del sitio de openGym en el que ya has iniciado sesión, luego introduce su dirección y el código que aparece ahí.', + 'Server address (e.g. gym.example.com)': 'Dirección del servidor (p. ej. gym.example.com)', + 'Pairing code': 'Código de emparejamiento', + 'Connecting…': 'Conectando…', + 'Connect': 'Conectar', + 'How do you want to use openGym?': '¿Cómo quieres usar openGym?', + 'Use on this device': 'Usar en este dispositivo', + 'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'Local mantiene todo en este teléfono. Conectar sincroniza con tu propio servidor de openGym — puedes cambiarlo luego en Ajustes.' } diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js index 713021d..f33ce99 100644 --- a/frontend/src/locales/fr.js +++ b/frontend/src/locales/fr.js @@ -600,5 +600,30 @@ export default { 'secondary': 'secondaire', "No exercises with an estimated 1RM yet.": "Aucun exercice avec un 1RM estimé pour l'instant.", 'Tap a muscle to see its exercises.': 'Touchez un muscle pour voir ses exercices.', - 'Unpair': 'Dissocier' + 'Unpair': 'Dissocier', + + // "Connect to my server" (mobile app pairing) + 'Your server': 'Votre serveur', + 'Synced with your openGym server.': 'Synchronisé avec votre serveur openGym.', + 'Disconnect': 'Déconnecter', + 'Disconnect from your server?': 'Se déconnecter de votre serveur ?', + 'Your data is synced to your server first, then this device switches back to local-only.': "Vos données sont d'abord synchronisées avec votre serveur, puis cet appareil repasse en mode local.", + 'Disconnected — back to local-only': 'Déconnecté — retour en mode local', + 'Connect to my server': 'Se connecter à mon serveur', + 'Sync this device to your own self-hosted openGym instead.': 'Synchronise plutôt cet appareil avec votre propre openGym self-hosted.', + 'Pair the mobile app': "Associer l'application mobile", + 'Connect the openGym app on your phone to this account.': "Associez l'application openGym de votre téléphone à ce compte.", + 'Could not generate a code': 'Impossible de générer un code', + 'On the openGym app, choose “Connect to my server”, then enter this address and the code below. It expires in 5 minutes.': "Dans l'application openGym, choisissez « Se connecter à mon serveur », puis saisissez cette adresse et le code ci-dessous. Il expire dans 5 minutes.", + 'Enter your server address and the code': "Saisissez l'adresse de votre serveur et le code", + 'Connected': 'Connecté', + 'Could not connect': 'Connexion impossible', + 'Open Settings → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.': "Dans Réglages → « Associer l'application mobile » sur le site openGym où vous êtes déjà connecté, saisissez ensuite son adresse et le code qui s'y affiche.", + 'Server address (e.g. gym.example.com)': 'Adresse du serveur (ex. gym.example.com)', + 'Pairing code': "Code d'association", + 'Connecting…': 'Connexion…', + 'Connect': 'Connecter', + 'How do you want to use openGym?': 'Comment voulez-vous utiliser openGym ?', + 'Use on this device': 'Utiliser sur cet appareil', + 'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'Local garde tout sur ce téléphone. Se connecter synchronise plutôt avec votre propre serveur openGym — vous pourrez changer cela plus tard dans Réglages.' } diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js index be844d1..f513e4c 100644 --- a/frontend/src/locales/hi.js +++ b/frontend/src/locales/hi.js @@ -600,5 +600,30 @@ export default { 'secondary': 'द्वितीयक', 'No exercises with an estimated 1RM yet.': 'अभी तक अनुमानित 1RM वाला कोई व्यायाम नहीं।', 'Tap a muscle to see its exercises.': 'व्यायाम देखने के लिए किसी मांसपेशी पर टैप करें।', - 'Unpair': 'अलग करें' + 'Unpair': 'अलग करें', + + // "Connect to my server" (mobile app pairing) + 'Your server': 'आपका सर्वर', + 'Synced with your openGym server.': 'आपके openGym सर्वर के साथ सिंक हो गया।', + 'Disconnect': 'डिस्कनेक्ट करें', + 'Disconnect from your server?': 'क्या सर्वर से डिस्कनेक्ट करें?', + 'Your data is synced to your server first, then this device switches back to local-only.': 'आपका डेटा पहले आपके सर्वर से सिंक होगा, फिर यह डिवाइस लोकल मोड में वापस चला जाएगा।', + 'Disconnected — back to local-only': 'डिस्कनेक्ट हो गया — वापस लोकल मोड में', + 'Connect to my server': 'मेरे सर्वर से कनेक्ट करें', + 'Sync this device to your own self-hosted openGym instead.': 'इसके बजाय इस डिवाइस को अपने खुद के सेल्फ़-होस्टेड openGym से सिंक करें।', + 'Pair the mobile app': 'मोबाइल ऐप पेयर करें', + 'Connect the openGym app on your phone to this account.': 'अपने फ़ोन पर openGym ऐप को इस अकाउंट से जोड़ें।', + 'Could not generate a code': 'कोड जनरेट नहीं हो सका', + 'On the openGym app, choose “Connect to my server”, then enter this address and the code below. It expires in 5 minutes.': 'openGym ऐप में "मेरे सर्वर से कनेक्ट करें" चुनें, फिर यह पता और नीचे दिया कोड डालें। यह 5 मिनट में समाप्त हो जाता है।', + 'Enter your server address and the code': 'अपने सर्वर का पता और कोड डालें', + 'Connected': 'कनेक्ट हो गया', + 'Could not connect': 'कनेक्ट नहीं हो सका', + 'Open Settings → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.': 'जिस openGym साइट में आप पहले से साइन इन हैं, वहाँ सेटिंग्स → "मोबाइल ऐप पेयर करें" खोलें, फिर उसका पता और वहाँ दिखा कोड डालें।', + 'Server address (e.g. gym.example.com)': 'सर्वर का पता (जैसे gym.example.com)', + 'Pairing code': 'पेयरिंग कोड', + 'Connecting…': 'कनेक्ट हो रहा है…', + 'Connect': 'कनेक्ट करें', + 'How do you want to use openGym?': 'आप openGym का उपयोग कैसे करना चाहते हैं?', + 'Use on this device': 'इस डिवाइस पर उपयोग करें', + 'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'लोकल सब कुछ इसी फ़ोन पर रखता है। कनेक्ट करने पर इसके बजाय आपके अपने openGym सर्वर से सिंक होता है — इसे बाद में सेटिंग्स में बदला जा सकता है।' } diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js index c273173..bd21b48 100644 --- a/frontend/src/locales/it.js +++ b/frontend/src/locales/it.js @@ -600,5 +600,30 @@ export default { 'secondary': 'secondario', 'No exercises with an estimated 1RM yet.': 'Nessun esercizio con 1RM stimato finora.', 'Tap a muscle to see its exercises.': 'Tocca un muscolo per vedere i suoi esercizi.', - 'Unpair': 'Separa' + 'Unpair': 'Separa', + + // "Connect to my server" (mobile app pairing) + 'Your server': 'Il tuo server', + 'Synced with your openGym server.': 'Sincronizzato con il tuo server openGym.', + 'Disconnect': 'Disconnetti', + 'Disconnect from your server?': 'Disconnettersi dal server?', + 'Your data is synced to your server first, then this device switches back to local-only.': 'I tuoi dati vengono prima sincronizzati con il tuo server, poi questo dispositivo torna alla modalità locale.', + 'Disconnected — back to local-only': 'Disconnesso — tornato alla modalità locale', + 'Connect to my server': 'Connettiti al mio server', + 'Sync this device to your own self-hosted openGym instead.': 'Sincronizza invece questo dispositivo con il tuo openGym self-hosted.', + 'Pair the mobile app': "Abbina l'app mobile", + 'Connect the openGym app on your phone to this account.': "Collega l'app openGym sul tuo telefono a questo account.", + 'Could not generate a code': 'Impossibile generare un codice', + 'On the openGym app, choose “Connect to my server”, then enter this address and the code below. It expires in 5 minutes.': "Nell'app openGym scegli «Connettiti al mio server», poi inserisci questo indirizzo e il codice qui sotto. Scade tra 5 minuti.", + 'Enter your server address and the code': "Inserisci l'indirizzo del tuo server e il codice", + 'Connected': 'Connesso', + 'Could not connect': 'Connessione non riuscita', + 'Open Settings → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.': "In Impostazioni → «Abbina l'app mobile» sul sito openGym in cui hai già effettuato l'accesso, poi inserisci il suo indirizzo e il codice mostrato lì.", + 'Server address (e.g. gym.example.com)': 'Indirizzo del server (es. gym.example.com)', + 'Pairing code': 'Codice di abbinamento', + 'Connecting…': 'Connessione…', + 'Connect': 'Connetti', + 'How do you want to use openGym?': 'Come vuoi usare openGym?', + 'Use on this device': 'Usa su questo dispositivo', + 'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'Locale mantiene tutto su questo telefono. Connettersi sincronizza invece con il tuo server openGym — potrai cambiarlo più tardi nelle Impostazioni.' } diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js index 871975c..c0df5f7 100644 --- a/frontend/src/locales/ko.js +++ b/frontend/src/locales/ko.js @@ -600,5 +600,30 @@ export default { 'secondary': '보조', 'No exercises with an estimated 1RM yet.': '추정 1RM이 있는 운동이 아직 없습니다.', 'Tap a muscle to see its exercises.': '근육을 눌러 해당 운동을 확인하세요.', - 'Unpair': '분리' + 'Unpair': '분리', + + // "Connect to my server" (mobile app pairing) + 'Your server': '내 서버', + 'Synced with your openGym server.': 'openGym 서버와 동기화됨', + 'Disconnect': '연결 해제', + 'Disconnect from your server?': '서버와 연결을 해제할까요?', + 'Your data is synced to your server first, then this device switches back to local-only.': '데이터가 먼저 서버와 동기화된 후, 이 기기는 로컬 모드로 돌아갑니다.', + 'Disconnected — back to local-only': '연결 해제됨 — 로컬 모드로 전환', + 'Connect to my server': '내 서버에 연결', + 'Sync this device to your own self-hosted openGym instead.': '대신 이 기기를 직접 호스팅하는 openGym 서버와 동기화합니다.', + 'Pair the mobile app': '모바일 앱 페어링', + 'Connect the openGym app on your phone to this account.': '휴대폰의 openGym 앱을 이 계정에 연결하세요.', + 'Could not generate a code': '코드를 생성하지 못했습니다', + 'On the openGym app, choose “Connect to my server”, then enter this address and the code below. It expires in 5 minutes.': 'openGym 앱에서 "내 서버에 연결"을 선택한 다음, 이 주소와 아래 코드를 입력하세요. 5분 후 만료됩니다.', + 'Enter your server address and the code': '서버 주소와 코드를 입력하세요', + 'Connected': '연결됨', + 'Could not connect': '연결하지 못했습니다', + 'Open Settings → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.': '이미 로그인된 openGym 사이트에서 설정 → "모바일 앱 페어링"을 열고, 주소와 거기에 표시된 코드를 입력하세요.', + 'Server address (e.g. gym.example.com)': '서버 주소 (예: gym.example.com)', + 'Pairing code': '페어링 코드', + 'Connecting…': '연결 중…', + 'Connect': '연결', + 'How do you want to use openGym?': 'openGym을 어떻게 사용하시겠어요?', + 'Use on this device': '이 기기에서 사용', + 'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': '로컬 모드는 모든 것을 이 휴대폰에 보관합니다. 연결하면 대신 자신의 openGym 서버와 동기화됩니다 — 나중에 설정에서 변경할 수 있습니다.' } diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js index 90e8a2f..012b2a2 100644 --- a/frontend/src/locales/pl.js +++ b/frontend/src/locales/pl.js @@ -600,5 +600,30 @@ export default { 'secondary': 'drugorzędny', 'No exercises with an estimated 1RM yet.': 'Brak ćwiczeń z oszacowanym 1RM.', 'Tap a muscle to see its exercises.': 'Dotknij mięśnia, aby zobaczyć jego ćwiczenia.', - 'Unpair': 'Rozłącz' + 'Unpair': 'Rozłącz', + + // "Connect to my server" (mobile app pairing) + 'Your server': 'Twój serwer', + 'Synced with your openGym server.': 'Zsynchronizowano z Twoim serwerem openGym.', + 'Disconnect': 'Rozłącz', + 'Disconnect from your server?': 'Rozłączyć z serwerem?', + 'Your data is synced to your server first, then this device switches back to local-only.': 'Twoje dane zostaną najpierw zsynchronizowane z serwerem, a następnie to urządzenie wróci do trybu lokalnego.', + 'Disconnected — back to local-only': 'Rozłączono — z powrotem w trybie lokalnym', + 'Connect to my server': 'Połącz z moim serwerem', + 'Sync this device to your own self-hosted openGym instead.': 'Zsynchronizuj to urządzenie z własnym, samodzielnie hostowanym openGym.', + 'Pair the mobile app': 'Sparuj aplikację mobilną', + 'Connect the openGym app on your phone to this account.': 'Połącz aplikację openGym na telefonie z tym kontem.', + 'Could not generate a code': 'Nie udało się wygenerować kodu', + 'On the openGym app, choose “Connect to my server”, then enter this address and the code below. It expires in 5 minutes.': 'W aplikacji openGym wybierz „Połącz z moim serwerem”, a potem wpisz ten adres i poniższy kod. Wygasa po 5 minutach.', + 'Enter your server address and the code': 'Wpisz adres swojego serwera i kod', + 'Connected': 'Połączono', + 'Could not connect': 'Nie udało się połączyć', + 'Open Settings → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.': 'W Ustawieniach → „Sparuj aplikację mobilną” na stronie openGym, na której jesteś już zalogowany, wpisz jej adres i wyświetlony tam kod.', + 'Server address (e.g. gym.example.com)': 'Adres serwera (np. gym.example.com)', + 'Pairing code': 'Kod parowania', + 'Connecting…': 'Łączenie…', + 'Connect': 'Połącz', + 'How do you want to use openGym?': 'Jak chcesz korzystać z openGym?', + 'Use on this device': 'Użyj na tym urządzeniu', + 'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'Tryb lokalny zachowuje wszystko na tym telefonie. Połączenie synchronizuje zamiast tego z Twoim własnym serwerem openGym — możesz to później zmienić w Ustawieniach.' } diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js index 90d105a..9ceb7a6 100644 --- a/frontend/src/locales/pt.js +++ b/frontend/src/locales/pt.js @@ -600,5 +600,30 @@ export default { 'secondary': 'secundário', 'No exercises with an estimated 1RM yet.': 'Ainda não há exercícios com 1RM estimado.', 'Tap a muscle to see its exercises.': 'Toque num músculo para ver os seus exercícios.', - 'Unpair': 'Desfazer' + 'Unpair': 'Desfazer', + + // "Connect to my server" (mobile app pairing) + 'Your server': 'O teu servidor', + 'Synced with your openGym server.': 'Sincronizado com o teu servidor openGym.', + 'Disconnect': 'Desligar', + 'Disconnect from your server?': 'Desligar do teu servidor?', + 'Your data is synced to your server first, then this device switches back to local-only.': 'Os teus dados são primeiro sincronizados com o teu servidor, depois este dispositivo volta ao modo local.', + 'Disconnected — back to local-only': 'Desligado — de volta ao modo local', + 'Connect to my server': 'Ligar ao meu servidor', + 'Sync this device to your own self-hosted openGym instead.': 'Sincroniza este dispositivo com o teu próprio openGym self-hosted.', + 'Pair the mobile app': 'Emparelhar a app móvel', + 'Connect the openGym app on your phone to this account.': 'Liga a app openGym no teu telemóvel a esta conta.', + 'Could not generate a code': 'Não foi possível gerar um código', + 'On the openGym app, choose “Connect to my server”, then enter this address and the code below. It expires in 5 minutes.': 'Na app openGym, escolhe «Ligar ao meu servidor», depois introduz este endereço e o código abaixo. Expira em 5 minutos.', + 'Enter your server address and the code': 'Introduz o endereço do teu servidor e o código', + 'Connected': 'Ligado', + 'Could not connect': 'Não foi possível ligar', + 'Open Settings → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.': 'Em Definições → «Emparelhar a app móvel» no site openGym em que já tens sessão iniciada, introduz depois o endereço e o código apresentado aí.', + 'Server address (e.g. gym.example.com)': 'Endereço do servidor (ex. gym.example.com)', + 'Pairing code': 'Código de emparelhamento', + 'Connecting…': 'A ligar…', + 'Connect': 'Ligar', + 'How do you want to use openGym?': 'Como queres usar o openGym?', + 'Use on this device': 'Usar neste dispositivo', + 'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'Local mantém tudo neste telemóvel. Ligar sincroniza antes com o teu próprio servidor openGym — podes mudar mais tarde em Definições.' } diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js index 4e959a4..e61e20f 100644 --- a/frontend/src/locales/ru.js +++ b/frontend/src/locales/ru.js @@ -600,5 +600,30 @@ export default { 'secondary': 'вспомогательная', 'No exercises with an estimated 1RM yet.': 'Пока нет упражнений с расчётным 1ПМ.', 'Tap a muscle to see its exercises.': 'Нажмите на мышцу, чтобы увидеть её упражнения.', - 'Unpair': 'Разъединить' + 'Unpair': 'Разъединить', + + // "Connect to my server" (mobile app pairing) + 'Your server': 'Ваш сервер', + 'Synced with your openGym server.': 'Синхронизировано с вашим сервером openGym.', + 'Disconnect': 'Отключить', + 'Disconnect from your server?': 'Отключиться от сервера?', + 'Your data is synced to your server first, then this device switches back to local-only.': 'Сначала данные синхронизируются с сервером, затем это устройство вернётся в локальный режим.', + 'Disconnected — back to local-only': 'Отключено — снова локальный режим', + 'Connect to my server': 'Подключиться к моему серверу', + 'Sync this device to your own self-hosted openGym instead.': 'Синхронизировать это устройство с вашим собственным self-hosted openGym.', + 'Pair the mobile app': 'Сопряжение мобильного приложения', + 'Connect the openGym app on your phone to this account.': 'Подключите приложение openGym на телефоне к этому аккаунту.', + 'Could not generate a code': 'Не удалось создать код', + 'On the openGym app, choose “Connect to my server”, then enter this address and the code below. It expires in 5 minutes.': 'В приложении openGym выберите «Подключиться к моему серверу», затем введите этот адрес и код ниже. Он действителен 5 минут.', + 'Enter your server address and the code': 'Введите адрес вашего сервера и код', + 'Connected': 'Подключено', + 'Could not connect': 'Не удалось подключиться', + 'Open Settings → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.': 'В Настройках → «Сопряжение мобильного приложения» на сайте openGym, где вы уже вошли, введите его адрес и показанный там код.', + 'Server address (e.g. gym.example.com)': 'Адрес сервера (например, gym.example.com)', + 'Pairing code': 'Код сопряжения', + 'Connecting…': 'Подключение…', + 'Connect': 'Подключить', + 'How do you want to use openGym?': 'Как вы хотите использовать openGym?', + 'Use on this device': 'Использовать на этом устройстве', + 'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'Локальный режим хранит всё на этом телефоне. Подключение вместо этого синхронизирует данные с вашим сервером openGym — вы сможете изменить это позже в Настройках.' } diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js index 969d873..1b450ce 100644 --- a/frontend/src/locales/tr.js +++ b/frontend/src/locales/tr.js @@ -600,5 +600,30 @@ export default { 'secondary': 'ikincil', 'No exercises with an estimated 1RM yet.': 'Henüz tahmini 1RM olan egzersiz yok.', 'Tap a muscle to see its exercises.': 'Egzersizlerini görmek için bir kas seçin.', - 'Unpair': 'Ayır' + 'Unpair': 'Ayır', + + // "Connect to my server" (mobile app pairing) + 'Your server': 'Sunucun', + 'Synced with your openGym server.': 'openGym sunucunla senkronize edildi.', + 'Disconnect': 'Bağlantıyı kes', + 'Disconnect from your server?': 'Sunucuyla bağlantı kesilsin mi?', + 'Your data is synced to your server first, then this device switches back to local-only.': 'Verilerin önce sunucunla senkronize edilir, ardından bu cihaz yerel moda geri döner.', + 'Disconnected — back to local-only': 'Bağlantı kesildi — yerel moda dönüldü', + 'Connect to my server': 'Sunucuma bağlan', + 'Sync this device to your own self-hosted openGym instead.': "Bu cihazı bunun yerine kendi self-hosted openGym'inle senkronize et.", + 'Pair the mobile app': 'Mobil uygulamayı eşleştir', + 'Connect the openGym app on your phone to this account.': 'Telefonundaki openGym uygulamasını bu hesaba bağla.', + 'Could not generate a code': 'Kod oluşturulamadı', + 'On the openGym app, choose “Connect to my server”, then enter this address and the code below. It expires in 5 minutes.': 'openGym uygulamasında “Sunucuma bağlan”ı seç, ardından bu adresi ve aşağıdaki kodu gir. 5 dakika içinde sona erer.', + 'Enter your server address and the code': 'Sunucu adresini ve kodu gir', + 'Connected': 'Bağlandı', + 'Could not connect': 'Bağlanılamadı', + 'Open Settings → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.': 'Zaten oturum açtığın openGym sitesinde Ayarlar → “Mobil uygulamayı eşleştir”i aç, ardından adresini ve orada gösterilen kodu gir.', + 'Server address (e.g. gym.example.com)': 'Sunucu adresi (ör. gym.example.com)', + 'Pairing code': 'Eşleştirme kodu', + 'Connecting…': 'Bağlanıyor…', + 'Connect': 'Bağlan', + 'How do you want to use openGym?': "openGym'i nasıl kullanmak istersin?", + 'Use on this device': 'Bu cihazda kullan', + 'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': "Yerel, her şeyi bu telefonda tutar. Bağlanmak ise bunun yerine kendi openGym sunucunla senkronize eder — bunu daha sonra Ayarlar'dan değiştirebilirsin." } diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js index bb5f8c6..4f5b62f 100644 --- a/frontend/src/locales/zh.js +++ b/frontend/src/locales/zh.js @@ -600,5 +600,30 @@ export default { 'secondary': '次要', 'No exercises with an estimated 1RM yet.': '暂无估算1RM的动作。', 'Tap a muscle to see its exercises.': '点击肌肉查看其动作。', - 'Unpair': '取消组合' + 'Unpair': '取消组合', + + // "Connect to my server" (mobile app pairing) + 'Your server': '你的服务器', + 'Synced with your openGym server.': '已与你的 openGym 服务器同步。', + 'Disconnect': '断开连接', + 'Disconnect from your server?': '要断开与服务器的连接吗?', + 'Your data is synced to your server first, then this device switches back to local-only.': '你的数据会先同步到服务器,然后此设备将切换回本地模式。', + 'Disconnected — back to local-only': '已断开连接——已切换回本地模式', + 'Connect to my server': '连接到我的服务器', + 'Sync this device to your own self-hosted openGym instead.': '改为将此设备与你自己的自托管 openGym 同步。', + 'Pair the mobile app': '配对手机应用', + 'Connect the openGym app on your phone to this account.': '将手机上的 openGym 应用连接到此账户。', + 'Could not generate a code': '无法生成配对码', + 'On the openGym app, choose “Connect to my server”, then enter this address and the code below. It expires in 5 minutes.': '在 openGym 应用中选择“连接到我的服务器”,然后输入此地址和下面的配对码。5 分钟后失效。', + 'Enter your server address and the code': '输入你的服务器地址和配对码', + 'Connected': '已连接', + 'Could not connect': '无法连接', + 'Open Settings → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.': '在你已登录的 openGym 网站上,打开设置 →“配对手机应用”,然后输入其地址和那里显示的配对码。', + 'Server address (e.g. gym.example.com)': '服务器地址(例如 gym.example.com)', + 'Pairing code': '配对码', + 'Connecting…': '连接中…', + 'Connect': '连接', + 'How do you want to use openGym?': '你想如何使用 openGym?', + 'Use on this device': '在此设备上使用', + 'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': '本地模式会把所有内容保留在这部手机上。连接则会改为与你自己的 openGym 服务器同步——之后可以在设置中更改。' } diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.js index ebdb692..3b33ad2 100644 --- a/frontend/src/store/useStore.js +++ b/frontend/src/store/useStore.js @@ -1,10 +1,11 @@ import { create } from 'zustand' -import { api } from '../lib/api.js' +import { api, setRemoteAuth } from '../lib/api.js' import { localTZ } from '../lib/format.js' import { registerCustom } from '../lib/exercises.js' import { DEMO, DEMO_SEEDED } from '../lib/demo.js' import { guestAllowed } from '../lib/guest.js' import { MOBILE, nativeLoad, nativeSave, syncReminder, writeAutoBackup } from '../lib/mobile.js' +import { loadRemote, chooseLocal, forgetRemote, connect } from '../lib/remote.js' const KEY = 'gym_state_v1' export const DEF = { @@ -84,6 +85,7 @@ export const useStore = create((set, get) => { S: (() => { const s = loadState(); registerCustom(s.customEx); return s })(), user: (() => { try { return JSON.parse(localStorage.getItem('gym_user')) || null } catch { return null } })(), ready: false, + needsMobileOnboarding: false, // mobile build only — set true by boot() on a genuine first launch // Mutate a draft of S via producer fn, then persist + schedule sync. update(mut, push = true) { @@ -145,6 +147,31 @@ export const useStore = create((set, get) => { clearLocalSession() }, + // Mobile-only ("connect to my server" onboarding, see App.jsx's needsMobileOnboarding). + // Picking local — even before there's any data — persists the choice so onboarding never + // asks again. + async chooseLocalMode() { + await chooseLocal() + set({ needsMobileOnboarding: false }) + }, + // Redeems the pairing code shown in the browser (Settings → "Pair the mobile app") and + // switches this device over to that account, same as signing in on the web does. + async connectToServer(url, code) { + const user = await connect(url, code) // throws on a bad URL/expired code — caller shows it + get().setUser(user) + await get().pullState() + syncReminder(get().S) + set({ needsMobileOnboarding: false }) + }, + // Leaves remote mode and drops cleanly back to local-only, without losing whatever was last + // synced (signOut() already pushes before it clears). + async disconnectServer() { + await get().signOut() + await forgetRemote() + get().setGuest(true) + set({ ready: true }) + }, + // "Sign out everywhere": the server bumps this profile's session version, which kills every // session it has on any device — this browser included, so the app has to end up exactly // where a normal signOut leaves it. Unlike signOut the request is NOT swallowed: if it fails @@ -166,9 +193,26 @@ export const useStore = create((set, get) => { // Boot: ask the server who we are, then pull. async boot() { - // Mobile build: no backend either — restore from the file mirror (the durable copy; - // localStorage may have been evicted since the last run) and go straight in. + // Mobile build: no backend by default — restore from the file mirror (the durable copy; + // localStorage may have been evicted since the last run) and go straight in. Unless this + // device was paired to a server ("connect to my server" mode, lib/remote.js), in which + // case it behaves exactly like the signed-in web flow below, straight from here. if (MOBILE) { + const remote = await loadRemote() + if (remote?.mode === 'remote') { + setRemoteAuth(remote.base, remote.token) + try { + const me = await api('/api/me') // also catches a token revoked elsewhere (sign out everywhere) + get().setUser(me.user) + await get().pullState() + } catch (e) { + if (e.status === 401) { await forgetRemote(); get().setGuest(true) } + else get().setUser(remote.user) // offline — keep going from the last-synced local copy + } + syncReminder(get().S) + set({ ready: true }) + return + } const saved = await nativeLoad() const S = get().S if (saved && (!hasData(S) || (saved._ts || 0) >= (S._ts || 0))) { @@ -178,7 +222,10 @@ export const useStore = create((set, get) => { } get().setGuest(true) syncReminder(get().S) - set({ ready: true }) + // Only a genuinely first launch — nothing chosen yet and nothing to lose either — offers + // the choice. Picking local (even with no data yet) persists that choice below and this + // never asks again. + set({ ready: true, needsMobileOnboarding: !remote && !hasData(get().S) }) return } // Demo build (GitHub Pages): no backend at all — seed once, stay in guest mode. diff --git a/frontend/src/views/MobileOnboarding.jsx b/frontend/src/views/MobileOnboarding.jsx new file mode 100644 index 0000000..45bf75f --- /dev/null +++ b/frontend/src/views/MobileOnboarding.jsx @@ -0,0 +1,59 @@ +// Mobile build only, first launch: the choice useStore.boot() couldn't make on its own — keep +// everything on this device, or connect to a self-hosted openGym server instead. See +// lib/remote.js for the pairing flow this hands off to. +import { useState, useRef, useEffect } from 'react' +import { useStore } from '../store/useStore.js' +import { useUI } from '../store/useUI.js' +import { t } from '../lib/i18n.js' +import Icon from '../components/Icon.jsx' +import { Button } from '../components/ui.jsx' + +export function ConnectSheet({ close }) { + const { connectToServer } = useStore() + const [url, setUrl] = useState('') + const [code, setCode] = useState('') + const [busy, setBusy] = useState(false) + const ref = useRef(null) + useEffect(() => { setTimeout(() => ref.current?.focus(), 250) }, []) + const go = async () => { + if (!url.trim() || !code.trim()) { useUI.getState().toast(t('Enter your server address and the code')); return } + setBusy(true) + try { await connectToServer(url.trim(), code.trim()); close(); useUI.getState().toast(t('Connected')) } + catch (e) { useUI.getState().toast(e.message || t('Could not connect')) } + finally { setBusy(false) } + } + return <> +

{t('Connect to my server')}

+
+ {t('Open Settings → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.')} +
+ setUrl(e.target.value)} autoCapitalize="none" autoCorrect="off" inputMode="url" /> +
+ setCode(e.target.value.toUpperCase())} style={{ letterSpacing: '.14em', fontWeight: 600, textAlign: 'center' }} /> +
+ + +} + +export default function MobileOnboarding() { + const { chooseLocalMode } = useStore() + const head = <> +
+

openGym

+ + const wrap = { display: 'flex', flexDirection: 'column', justifyContent: 'center', minHeight: '78vh', textAlign: 'center' } + return ( +
+ {head} +
{t('How do you want to use openGym?')}
+ +
+ +
+ {t('Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.')} +
+
+ ) +} diff --git a/frontend/src/views/Settings.jsx b/frontend/src/views/Settings.jsx index c56debe..4d5d661 100644 --- a/frontend/src/views/Settings.jsx +++ b/frontend/src/views/Settings.jsx @@ -10,6 +10,7 @@ import { wakeLockSupported } from '../lib/wakelock.js' import { t, LANGS, INSTR_LANGS } from '../lib/i18n.js' import { DEMO, REPO } from '../lib/demo.js' import { MOBILE, shareExport, syncReminder } from '../lib/mobile.js' +import { ConnectSheet } from './MobileOnboarding.jsx' import { loadStarterPlan, confirmSheet, importFromApp } from '../sheets.jsx' import Icon from '../components/Icon.jsx' import { Section, Row, SelectRow, Switch, Segmented, Button, TextField } from '../components/ui.jsx' @@ -18,7 +19,7 @@ export default function Settings() { const nav = useNavigate() const S = useStore(s => s.S) const user = useStore(s => s.user) - const { update, replaceState, setUser, pullState, pushState, signOut, signOutAll, resetDemo } = useStore() + const { update, replaceState, setUser, pullState, pushState, signOut, signOutAll, resetDemo, disconnectServer } = useStore() const toast = useUI(s => s.toast) const fileRef = useRef(null) const importRef = useRef(null) @@ -73,12 +74,21 @@ export default function Settings() {
{/* ---------- account (demo and mobile builds have nothing to sign in to) ---------- */} -
- {MOBILE ? <> +
+ {MOBILE ? (user ? <> + + {user.admin && nav('/admin')} />} + confirmSheet({ + title: t('Disconnect from your server?'), + message: t('Your data is synced to your server first, then this device switches back to local-only.'), + confirmText: t('Disconnect'), danger: true, + onConfirm: async () => { await disconnectServer(); nav('/home'); toast(t('Disconnected — back to local-only')) }, + })} /> + : <> - window.open(REPO, '_blank', 'noopener')} /> - : DEMO ? <> + useUI.getState().openSheet(close => )} /> + ) : DEMO ? <> confirmSheet({ title: t('Reset demo data?'), message: t('Puts the example plan, workouts and weigh-ins back the way they started.'), confirmText: t('Reset'), onConfirm: () => { resetDemo(); nav('/home'); toast(t('Demo data reset')) } })} /> @@ -87,6 +97,8 @@ export default function Settings() { : user ? <> {user.admin && nav('/admin')} />} + useUI.getState().openSheet(close => )} /> confirmSheet({ title: t('Sign out?'), message: t('Your data is synced to your profile first, then cleared from this device.'), confirmText: t('Sign out'), danger: true, onConfirm: () => { signOut(); nav('/home') } })} /> : webauthnOK() ? <> @@ -342,6 +354,28 @@ function PushCard({ S, update, toast }) { } +// 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 <> +

{t('Pair the mobile app')}

+
+ {t('On the openGym app, choose “Connect to my server”, then enter this address and the code below. It expires in 5 minutes.')} +
+ {err ?
{err}
: ( +
+ {code || '········'} +
+ )} +
+ + +} + // 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.