mobile: modo "conectar a mi servidor" (emparejamiento por codigo, sin passkeys)
La app movil puede ahora sincronizar de verdad contra un servidor openGym propio en vez de guardar todo solo en el telefono. Como las passkeys no funcionan desde el WebView de la app (su origen nunca coincide con el hostname real), el emparejamiento se hace con un codigo de un solo uso generado desde una sesion ya logueada en el navegador (Ajustes > "Emparejar la app movil"), canjeado por un bearer token con la misma firma que ya usa la cookie de sesion. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ec84f6db06
commit
781e2441ba
22 files changed
+662
-29
No files matched your search
+20
-1
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user