Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.
JavaScript apple-watchbodyweightdockerfitnessfitness-trackergymhealthiosmcpnodejspasskeysprogressive-web-applicationspwareactself-hostedself-hostingvitewebauthnweightliftingworkout-tracker
Pairing says why it failed when a proxy keeps the phone app out
Duarte Santos9d9f576d5d52
diff --git a/api/server.js b/api/server.jsindex debdd4840..06c9b11e2 100644--- a/api/server.js+++ b/api/server.js@@ -2396,10 +2396,14 @@ const server = http.createServer(async (req, res) => {const origin = req.headers.origin;if (origin) { res.setHeader('Access-Control-Allow-Origin', origin); res.setHeader('Vary', 'Origin'); }if (req.method === 'OPTIONS') {+ // Chrome's Private Network Access asks before a page reaches a LAN address (a phone pairing+ // with 192.168.x.x); an answer without this header is refused like a CORS failure (#329).+ const pna = String(req.headers['access-control-request-private-network'] || '').toLowerCase() === 'true';res.writeHead(204, {'Access-Control-Allow-Methods': 'GET,POST,PUT,DELETE,OPTIONS','Access-Control-Allow-Headers': 'Content-Type, Authorization',- 'Access-Control-Max-Age': '86400'+ 'Access-Control-Max-Age': '86400',+ ...(pna ? { 'Access-Control-Allow-Private-Network': 'true' } : {})});return res.end();}diff --git a/api/test/server-cors.test.js b/api/test/server-cors.test.jsnew file mode 100644index 000000000..bec321cb8--- /dev/null+++ b/api/test/server-cors.test.js@@ -0,0 +1,82 @@+/* The paired phone app calls in from its WebView's own origin — https://localhost on Android,+ capacitor://localhost on iOS — so every request it makes with a JSON body or a Bearer token is+ preceded by a CORS preflight. #329 was a proxy in front that answered that preflight itself;+ these pin what openGym's own answer looks like, so a regression here is never the cause.+ Real server.js in a child. */+import { test } from 'node:test';+import assert from 'node:assert/strict';+import fs from 'node:fs';+import http from 'node:http';+import os from 'node:os';+import path from 'node:path';+import { spawn } from 'node:child_process';+import { fileURLToPath } from 'node:url';+import { boundPort } from './helpers.mjs';++const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');++async function startServer(t) {+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-cors-'));+ fs.writeFileSync(path.join(dataDir, 'secret'), 'c'.repeat(64), { mode: 0o600 });+ fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({ users: [], creds: [], subs: [], invites: [] }));+ const child = spawn(process.execPath, ['server.js'], {+ cwd: API, stdio: ['ignore', 'pipe', 'pipe'],+ env: { ...process.env, PORT: '0', DATA_DIR: dataDir, ORIGIN: 'https://gym.example.com', RP_ID: 'gym.example.com' }+ });+ let log = '';+ child.stdout.on('data', d => log += d);+ child.stderr.on('data', d => log += d);+ t.after(() => { child.kill('SIGKILL'); fs.rmSync(dataDir, { recursive: true, force: true }); });+ return await boundPort(child, () => log);+}++// node:http, not fetch: the Origin header is the browser's to set, and fetch may refuse it.+function send(port, method, p, headers = {}, body) {+ return new Promise((resolve, reject) => {+ const req = http.request({ host: '127.0.0.1', port, method, path: p, headers }, res => {+ let data = '';+ res.on('data', d => data += d);+ res.on('end', () => resolve({ status: res.statusCode, headers: res.headers, body: data }));+ });+ req.on('error', reject);+ if (body) req.write(body);+ req.end();+ });+}++const preflight = (origin, extra = {}) => ({+ Origin: origin,+ 'Access-Control-Request-Method': 'POST',+ 'Access-Control-Request-Headers': 'content-type',+ ...extra+});++for (const origin of ['https://localhost', 'capacitor://localhost']) {+ test(`the pairing preflight from ${origin} is answered by openGym with that origin allowed`, async t => {+ const port = await startServer(t);+ const r = await send(port, 'OPTIONS', '/api/pair/redeem', preflight(origin));+ assert.equal(r.status, 204);+ assert.equal(r.headers['access-control-allow-origin'], origin);+ assert.match(r.headers['access-control-allow-methods'], /\bPOST\b/);+ assert.match(r.headers['access-control-allow-methods'], /\bPUT\b/);+ const allowed = r.headers['access-control-allow-headers'].toLowerCase().split(/\s*,\s*/);+ assert.ok(allowed.includes('content-type'), allowed.join());+ assert.ok(allowed.includes('authorization'), allowed.join());+ // The phone authenticates with a Bearer token, never the cookie: credentials stay off.+ assert.equal(r.headers['access-control-allow-credentials'], undefined);+ assert.match(String(r.headers.vary), /Origin/);+ assert.equal(r.headers['access-control-allow-private-network'], undefined);++ // The request itself carries the origin back, so the WebView lets the app read the answer.+ const post = await send(port, 'POST', '/api/pair/redeem', { Origin: origin, 'Content-Type': 'application/json' }, JSON.stringify({ code: 'ZZZZ2222' }));+ assert.equal(post.headers['access-control-allow-origin'], origin);+ assert.ok(post.status >= 400 && post.status < 500, String(post.status));+ });+}++test('a preflight that asks for private-network access gets it', async t => {+ const port = await startServer(t);+ const r = await send(port, 'OPTIONS', '/api/pair/redeem', preflight('https://localhost', { 'Access-Control-Request-Private-Network': 'true' }));+ assert.equal(r.status, 204);+ assert.equal(r.headers['access-control-allow-private-network'], 'true');+});diff --git a/docs/MOBILE.md b/docs/MOBILE.mdindex 3785a781d..2184fe3aa 100644--- a/docs/MOBILE.md+++ b/docs/MOBILE.md@@ -42,6 +42,10 @@ or Settings → **"Connect to my server"** later) to finish. Notes:changes made without a network go to the server as soon as it is reachable again.- Use an HTTPS address if at all possible: the connection carries a bearer token instead ofa cookie, and that token would otherwise cross the network in plain text.+- Pairing says your server "refused the app's request (CORS)", or fails with "Failed to fetch"+ on an older version, while the browser works? A reverse proxy in front is answering the app's+ CORS preflight itself. openGym answers it on its own; see+ [Phone app and CORS](SELF_HOSTING.md#phone-app-and-cors).- The token lasts `SESSION_DAYS` (90 by default, see `docs/SELF_HOSTING.md`) and renewsitself: every time the app starts, a token past half its life is swapped for a fresh one.A phone that is used at all never runs out; one left unopened for longer thandiff --git a/docs/SELF_HOSTING.md b/docs/SELF_HOSTING.mdindex 8907b4516..1bb8aecce 100644--- a/docs/SELF_HOSTING.md+++ b/docs/SELF_HOSTING.md@@ -129,6 +129,28 @@ Visit `https://gym.example.com`, create your profile, and add it to your home sc> Changing `RP_ID` later invalidates existing passkeys (they were bound to the old hostname).> Pick your domain before people register.+#### Phone app and CORS++The browser app is served from your domain, so it never makes a cross-origin request. The+[phone app](MOBILE.md#connecting-the-app-to-your-own-server) does: its WebView runs at+`https://localhost` (Android) or `capacitor://localhost` (iOS), and the browser engine asks your+server first (a CORS preflight, `OPTIONS`) before every request with a JSON body or a token.+**openGym answers that preflight itself** — it allows the requesting origin, the methods+`GET, POST, PUT, DELETE, OPTIONS` and the headers `Content-Type, Authorization` — so the proxy only+has to pass it through unchanged.++Don't put a CORS middleware on the openGym route. A Traefik `headers` middleware with+`accessControlAllowOriginList` (or nginx `add_header Access-Control-*` with an `if+($request_method = OPTIONS) { return 204; }`) answers the preflight on its own and never forwards+it; when the app's origin is not on its list, the phone refuses to send the real request and+pairing fails with "Failed to fetch" while the openGym containers log nothing. In Traefik's access+log that shows as `"OPTIONS /api/pair/redeem HTTP/2.0" 200 0 "-" "-" … "-" 0ms` — no backend+service, no time spent. If the middleware has to stay (it is shared with other routes), add+`https://localhost` and `capacitor://localhost` to the allowed origins, the methods and headers+above to its lists, and don't set allow-credentials (the app authenticates with a bearer token,+never a cookie). The app tells the two cases apart since v1.3.10: when the server is reachable but+the request is refused, pairing says so instead of "Failed to fetch".+## 4. Multiple usersAnyone who can reach the URL can create their own profile — each gets isolated data. That's thediff --git a/frontend/src/lib/api.js b/frontend/src/lib/api.jsindex f75738e4e..b5c0ebe0b 100644--- a/frontend/src/lib/api.js+++ b/frontend/src/lib/api.js@@ -210,12 +210,47 @@ export function apiUpload(path, blob, mime, { onProgress, idleMs = 60000, XHR =})}+// "Failed to fetch" is all the WebView says when pairing never got an answer (#329), and it says+// the same for a wrong address and for a reverse proxy that answered the CORS preflight itself+// without letting the app's origin in (a Traefik `headers` middleware with an allow-list, which+// never passes the OPTIONS on to openGym). A no-cors request needs no preflight and tells the two+// apart: it settles when the server is there at all. Its answer cannot be read, nor needs to be.+const PROBE_MS = 5000+const hostOfBase = base => {+ try { const u = new URL(base); return u.host + u.pathname.replace(/\/$/, '') } catch { return base || '' }+}+async function whyUnreachable(base, ms) {+ let reached = false+ const ctl = typeof AbortController === 'function' ? new AbortController() : null+ let timer = null+ try {+ await Promise.race([+ fetch(base + '/api/health', { mode: 'no-cors', cache: 'no-store', ...(ctl ? { signal: ctl.signal } : {}) }),+ new Promise((_, reject) => { timer = setTimeout(() => { if (ctl) ctl.abort(); reject(new Error('timeout')) }, ms) }),+ ])+ reached = true+ } catch { /* not reachable either */ }+ finally { clearTimeout(timer) }+ if (reached) {+ const origin = globalThis.location?.origin || 'https://localhost'+ return failure(t('Your server was reached, but it refused the app’s request (CORS). If a reverse proxy such as Traefik adds CORS headers, let requests from {0} through to openGym unchanged — see “Phone app and CORS” in docs/SELF_HOSTING.md.', origin), 'cors')+ }+ return failure(t('Could not reach {0}. Check the address and that this phone can reach it.', hostOfBase(base)), 'unreachable')+}+// 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 data = await request(serverBase + '/api/pair/redeem', {- method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code })- }, TIMEOUT_GET_MS)+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 })+ }, TIMEOUT_GET_MS)+ } catch (e) {+ // The server answered (any status) or did not answer in time: that error says it already.+ if (e && (e.status != null || e.code)) throw e+ throw await whyUnreachable(serverBase, probeMs)+ }// Anything that is not a pairing would be saved as one — and the phone would then send every// change to a server that never gave it a token.if (!data.token || !data.user) throw failure(t('The server answered with something other than openGym data.'), 'bad-response', 200)diff --git a/frontend/src/lib/api.pair-probe.test.js b/frontend/src/lib/api.pair-probe.test.jsnew file mode 100644index 000000000..b447d3efa--- /dev/null+++ b/frontend/src/lib/api.pair-probe.test.js@@ -0,0 +1,57 @@+// @vitest-environment happy-dom+// #329: pairing failed with nothing but "Failed to fetch" — the same words for a wrong address+// and for a reverse proxy that answered the CORS preflight itself and kept the app out. A+// no-cors probe of /api/health tells the two apart, and the message says which.+import { afterEach, describe, expect, it, vi } from 'vitest'+import { pairRedeem } from './api.js'++afterEach(() => { vi.unstubAllGlobals(); vi.useRealTimers() })++const failed = () => Promise.reject(new TypeError('Failed to fetch'))+const opaque = () => Promise.resolve(new Response(null, { status: 200 }))++describe('pairRedeem when the request never gets an answer', () => {+ it('server reachable without CORS: says the proxy refused the app, naming the app\'s origin', async () => {+ const fetch = vi.fn((url, init) => (url.endsWith('/api/pair/redeem') ? failed() : opaque()))+ vi.stubGlobal('fetch', fetch)+ const e = await pairRedeem('https://gym.example.com', 'ABCD2345').catch(x => x)+ expect(e.code).toBe('cors')+ expect(e.message).toContain('CORS')+ expect(e.message).toContain(location.origin)+ expect(e.message).toContain('SELF_HOSTING.md')+ const probe = fetch.mock.calls[1]+ expect(probe[0]).toBe('https://gym.example.com/api/health')+ expect(probe[1]).toMatchObject({ mode: 'no-cors', cache: 'no-store' })+ })++ it('server not reachable at all: says so, with the address', async () => {+ vi.stubGlobal('fetch', vi.fn(failed))+ const e = await pairRedeem('https://gym.example.com/sub/', 'ABCD2345').catch(x => x)+ expect(e.code).toBe('unreachable')+ expect(e.message).toBe('Could not reach gym.example.com/sub. Check the address and that this phone can reach it.')+ })++ it('a probe that hangs counts as not reachable', async () => {+ vi.stubGlobal('fetch', vi.fn((url) => (url.endsWith('/api/pair/redeem') ? failed() : new Promise(() => {}))))+ const e = await pairRedeem('https://gym.example.com', 'ABCD2345', { probeMs: 20 }).catch(x => x)+ expect(e.code).toBe('unreachable')+ })++ it('an answer from the server is passed on as it is, with no probe', async () => {+ const fetch = vi.fn(async () => new Response(JSON.stringify({ error: 'invalid or expired code' }), { status: 400, headers: { 'content-type': 'application/json' } }))+ vi.stubGlobal('fetch', fetch)+ await expect(pairRedeem('https://gym.example.com', 'ABCD2345')).rejects.toMatchObject({ status: 400, message: 'invalid or expired code' })+ expect(fetch).toHaveBeenCalledTimes(1)+ })++ it('a timeout stays a timeout', async () => {+ vi.useFakeTimers()+ const fetch = vi.fn(() => new Promise(() => {}))+ vi.stubGlobal('fetch', fetch)+ const p = pairRedeem('https://gym.example.com', 'ABCD2345').catch(x => x)+ await vi.advanceTimersByTimeAsync(21000)+ const e = await p+ expect(e.code).toBe('timeout')+ expect(fetch).toHaveBeenCalledTimes(1)+ })+})diff --git a/frontend/src/locales/ar.js b/frontend/src/locales/ar.jsindex 73f3a70f2..efa44dc6a 100644--- a/frontend/src/locales/ar.js+++ b/frontend/src/locales/ar.js@@ -1717,4 +1717,6 @@ export default {'Teal': 'أزرق مخضر','Yellow': 'أصفر','Enter how long it took — at least 1 minute.': 'أدخل المدة التي استغرقها — دقيقة واحدة على الأقل.',+ 'Your server was reached, but it refused the app’s request (CORS). If a reverse proxy such as Traefik adds CORS headers, let requests from {0} through to openGym unchanged — see “Phone app and CORS” in docs/SELF_HOSTING.md.': 'تم الوصول إلى خادمك، لكنه رفض طلب التطبيق (CORS). إذا كان وكيل عكسي مثل Traefik يضيف ترويسات CORS، فدَع الطلبات القادمة من {0} تمر إلى openGym دون تغيير — راجع «Phone app and CORS» في docs/SELF_HOSTING.md.',+ 'Could not reach {0}. Check the address and that this phone can reach it.': 'تعذّر الوصول إلى {0}. تحقّق من العنوان ومن أن هذا الهاتف يستطيع الوصول إليه.',}diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.jsindex e85b402c0..c9b16e9bc 100644--- a/frontend/src/locales/de.js+++ b/frontend/src/locales/de.js@@ -1684,4 +1684,6 @@ export default {'Teal': 'Türkis','Yellow': 'Gelb','Enter how long it took — at least 1 minute.': 'Gib ein, wie lange es gedauert hat — mindestens 1 Minute.',+ 'Your server was reached, but it refused the app’s request (CORS). If a reverse proxy such as Traefik adds CORS headers, let requests from {0} through to openGym unchanged — see “Phone app and CORS” in docs/SELF_HOSTING.md.': 'Dein Server wurde erreicht, hat die Anfrage der App aber abgelehnt (CORS). Wenn ein Reverse Proxy wie Traefik CORS-Header setzt, lass Anfragen von {0} unverändert zu openGym durch — siehe „Phone app and CORS“ in docs/SELF_HOSTING.md.',+ 'Could not reach {0}. Check the address and that this phone can reach it.': '{0} ist nicht erreichbar. Prüf die Adresse und ob dieses Handy den Server erreichen kann.',}diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.jsindex 1da2b3700..7d45c2bb1 100644--- a/frontend/src/locales/es.js+++ b/frontend/src/locales/es.js@@ -1664,4 +1664,6 @@ export default {'Teal': 'Turquesa','Yellow': 'Amarillo','Enter how long it took — at least 1 minute.': 'Indica cuánto duró — al menos 1 minuto.',+ 'Your server was reached, but it refused the app’s request (CORS). If a reverse proxy such as Traefik adds CORS headers, let requests from {0} through to openGym unchanged — see “Phone app and CORS” in docs/SELF_HOSTING.md.': 'Se llegó a tu servidor, pero rechazó la solicitud de la app (CORS). Si un proxy inverso como Traefik añade cabeceras CORS, deja pasar sin cambios hasta openGym las solicitudes de {0}; consulta «Phone app and CORS» en docs/SELF_HOSTING.md.',+ 'Could not reach {0}. Check the address and that this phone can reach it.': 'No se pudo llegar a {0}. Comprueba la dirección y que este teléfono pueda alcanzarlo.',}diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.jsindex acfe7d768..d578d101b 100644--- a/frontend/src/locales/fr.js+++ b/frontend/src/locales/fr.js@@ -1664,4 +1664,6 @@ export default {'Teal': 'Turquoise','Yellow': 'Jaune','Enter how long it took — at least 1 minute.': 'Indique combien de temps ça a duré — au moins 1 minute.',+ 'Your server was reached, but it refused the app’s request (CORS). If a reverse proxy such as Traefik adds CORS headers, let requests from {0} through to openGym unchanged — see “Phone app and CORS” in docs/SELF_HOSTING.md.': 'Ton serveur a été joint, mais il a refusé la requête de l’app (CORS). Si un proxy inverse comme Traefik ajoute des en-têtes CORS, laisse passer les requêtes de {0} jusqu’à openGym sans les modifier — voir « Phone app and CORS » dans docs/SELF_HOSTING.md.',+ 'Could not reach {0}. Check the address and that this phone can reach it.': 'Impossible de joindre {0}. Vérifie l’adresse et que ce téléphone peut y accéder.',}diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.jsindex cd7c1b398..696c6d937 100644--- a/frontend/src/locales/hi.js+++ b/frontend/src/locales/hi.js@@ -1664,4 +1664,6 @@ export default {'Teal': 'फ़िरोज़ी','Yellow': 'पीला','Enter how long it took — at least 1 minute.': 'बताएँ कि इसमें कितना समय लगा — कम से कम 1 मिनट।',+ 'Your server was reached, but it refused the app’s request (CORS). If a reverse proxy such as Traefik adds CORS headers, let requests from {0} through to openGym unchanged — see “Phone app and CORS” in docs/SELF_HOSTING.md.': 'आपका सर्वर मिल गया, लेकिन उसने ऐप का अनुरोध अस्वीकार कर दिया (CORS)। अगर Traefik जैसा कोई रिवर्स प्रॉक्सी CORS हेडर जोड़ता है, तो {0} से आने वाले अनुरोधों को बिना बदले openGym तक जाने दें — docs/SELF_HOSTING.md में “Phone app and CORS” देखें।',+ 'Could not reach {0}. Check the address and that this phone can reach it.': '{0} तक नहीं पहुँच सके। पता जाँचें और देखें कि यह फ़ोन उस तक पहुँच सकता है।',}diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.jsindex 37c63d206..9917400e8 100644--- a/frontend/src/locales/hu.js+++ b/frontend/src/locales/hu.js@@ -1667,4 +1667,6 @@ export default {'Teal': 'Türkiz','Yellow': 'Sárga','Enter how long it took — at least 1 minute.': 'Add meg, meddig tartott — legalább 1 perc.',+ 'Your server was reached, but it refused the app’s request (CORS). If a reverse proxy such as Traefik adds CORS headers, let requests from {0} through to openGym unchanged — see “Phone app and CORS” in docs/SELF_HOSTING.md.': 'A szervered elérhető, de elutasította az app kérését (CORS). Ha egy reverse proxy, például a Traefik CORS-fejléceket ad hozzá, engedd át változatlanul az openGymhez a(z) {0} felől érkező kéréseket — lásd: „Phone app and CORS”, docs/SELF_HOSTING.md.',+ 'Could not reach {0}. Check the address and that this phone can reach it.': 'A(z) {0} nem érhető el. Ellenőrizd a címet, és hogy ez a telefon eléri-e.',}diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.jsindex dd7557659..391573347 100644--- a/frontend/src/locales/it.js+++ b/frontend/src/locales/it.js@@ -1664,4 +1664,6 @@ export default {'Teal': 'Turchese','Yellow': 'Giallo','Enter how long it took — at least 1 minute.': 'Inserisci quanto è durato — almeno 1 minuto.',+ 'Your server was reached, but it refused the app’s request (CORS). If a reverse proxy such as Traefik adds CORS headers, let requests from {0} through to openGym unchanged — see “Phone app and CORS” in docs/SELF_HOSTING.md.': 'Il server è stato raggiunto, ma ha rifiutato la richiesta dell’app (CORS). Se un reverse proxy come Traefik aggiunge header CORS, lascia passare fino a openGym, senza modificarle, le richieste da {0} — vedi «Phone app and CORS» in docs/SELF_HOSTING.md.',+ 'Could not reach {0}. Check the address and that this phone can reach it.': 'Impossibile raggiungere {0}. Controlla l’indirizzo e che questo telefono possa raggiungerlo.',}diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.jsindex f2363bdcf..525754830 100644--- a/frontend/src/locales/ko.js+++ b/frontend/src/locales/ko.js@@ -1664,4 +1664,6 @@ export default {'Teal': '청록','Yellow': '노랑','Enter how long it took — at least 1 minute.': '걸린 시간을 입력하세요 — 최소 1분.',+ 'Your server was reached, but it refused the app’s request (CORS). If a reverse proxy such as Traefik adds CORS headers, let requests from {0} through to openGym unchanged — see “Phone app and CORS” in docs/SELF_HOSTING.md.': '서버에 연결되었지만 앱의 요청을 거부했습니다(CORS). Traefik 같은 리버스 프록시가 CORS 헤더를 추가한다면 {0}에서 오는 요청을 그대로 openGym까지 통과시키세요 — docs/SELF_HOSTING.md의 “Phone app and CORS”를 참고하세요.',+ 'Could not reach {0}. Check the address and that this phone can reach it.': '{0}에 연결할 수 없습니다. 주소와 이 휴대폰에서 접속할 수 있는지 확인하세요.',}diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.jsindex 2a63ac082..5d3e26904 100644--- a/frontend/src/locales/pl.js+++ b/frontend/src/locales/pl.js@@ -1664,4 +1664,6 @@ export default {'Teal': 'Turkusowy','Yellow': 'Żółty','Enter how long it took — at least 1 minute.': 'Wpisz, ile to trwało — co najmniej 1 minutę.',+ 'Your server was reached, but it refused the app’s request (CORS). If a reverse proxy such as Traefik adds CORS headers, let requests from {0} through to openGym unchanged — see “Phone app and CORS” in docs/SELF_HOSTING.md.': 'Serwer odpowiada, ale odrzucił żądanie aplikacji (CORS). Jeśli reverse proxy, np. Traefik, dodaje nagłówki CORS, przepuść żądania z {0} do openGym bez zmian — zobacz „Phone app and CORS” w docs/SELF_HOSTING.md.',+ 'Could not reach {0}. Check the address and that this phone can reach it.': 'Nie można połączyć się z {0}. Sprawdź adres i czy ten telefon ma do niego dostęp.',}diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.jsindex ba3004327..4ee6861a2 100644--- a/frontend/src/locales/pt-BR.js+++ b/frontend/src/locales/pt-BR.js@@ -1009,6 +1009,8 @@ export const PT_BR_OVERRIDES = {'Yellow': 'Amarelo','Enter how long it took — at least 1 minute.': 'Informe quanto tempo levou — pelo menos 1 minuto.','Move out of the superset': 'Tirar do superset',+ 'Your server was reached, but it refused the app’s request (CORS). If a reverse proxy such as Traefik adds CORS headers, let requests from {0} through to openGym unchanged — see “Phone app and CORS” in docs/SELF_HOSTING.md.': 'Seu servidor foi alcançado, mas recusou a solicitação do aplicativo (CORS). Se um proxy reverso como o Traefik adiciona cabeçalhos CORS, deixe as solicitações de {0} passarem até o openGym sem alterações — veja “Phone app and CORS” em docs/SELF_HOSTING.md.',+ 'Could not reach {0}. Check the address and that this phone can reach it.': 'Não foi possível alcançar {0}. Verifique o endereço e se este celular consegue acessá-lo.',}export default { ...pt, ...PT_BR_OVERRIDES }diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.jsindex 71181165d..7a132bd06 100644--- a/frontend/src/locales/pt.js+++ b/frontend/src/locales/pt.js@@ -1664,4 +1664,6 @@ export default {'Teal': 'Turquesa','Yellow': 'Amarelo','Enter how long it took — at least 1 minute.': 'Indica quanto tempo demorou — pelo menos 1 minuto.',+ 'Your server was reached, but it refused the app’s request (CORS). If a reverse proxy such as Traefik adds CORS headers, let requests from {0} through to openGym unchanged — see “Phone app and CORS” in docs/SELF_HOSTING.md.': 'O teu servidor foi alcançado, mas recusou o pedido da app (CORS). Se um proxy inverso como o Traefik acrescenta cabeçalhos CORS, deixa passar os pedidos de {0} até ao openGym sem alterações — vê “Phone app and CORS” em docs/SELF_HOSTING.md.',+ 'Could not reach {0}. Check the address and that this phone can reach it.': 'Não foi possível alcançar {0}. Verifica o endereço e se este telemóvel o consegue alcançar.',}diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.jsindex e20eeb57f..e51c35bef 100644--- a/frontend/src/locales/ru.js+++ b/frontend/src/locales/ru.js@@ -1664,4 +1664,6 @@ export default {'Teal': 'Бирюзовый','Yellow': 'Жёлтый','Enter how long it took — at least 1 minute.': 'Укажите, сколько это длилось — не меньше 1 минуты.',+ 'Your server was reached, but it refused the app’s request (CORS). If a reverse proxy such as Traefik adds CORS headers, let requests from {0} through to openGym unchanged — see “Phone app and CORS” in docs/SELF_HOSTING.md.': 'Сервер доступен, но отклонил запрос приложения (CORS). Если обратный прокси, например Traefik, добавляет заголовки CORS, пропускайте запросы с {0} к openGym без изменений — см. «Phone app and CORS» в docs/SELF_HOSTING.md.',+ 'Could not reach {0}. Check the address and that this phone can reach it.': 'Не удалось связаться с {0}. Проверьте адрес и доступен ли сервер с этого телефона.',}diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.jsindex fff0b0fdf..229c189cc 100644--- a/frontend/src/locales/th.js+++ b/frontend/src/locales/th.js@@ -1675,4 +1675,6 @@ export default {'Teal': 'เขียวน้ำทะเล','Yellow': 'เหลือง','Enter how long it took — at least 1 minute.': 'ใส่ระยะเวลาที่ใช้ — อย่างน้อย 1 นาที',+ 'Your server was reached, but it refused the app’s request (CORS). If a reverse proxy such as Traefik adds CORS headers, let requests from {0} through to openGym unchanged — see “Phone app and CORS” in docs/SELF_HOSTING.md.': 'เข้าถึงเซิร์ฟเวอร์ได้ แต่เซิร์ฟเวอร์ปฏิเสธคำขอของแอป (CORS) หากรีเวิร์สพร็อกซีอย่าง Traefik เพิ่มเฮดเดอร์ CORS ให้ปล่อยคำขอจาก {0} ผ่านไปยัง openGym โดยไม่แก้ไข — ดู “Phone app and CORS” ใน docs/SELF_HOSTING.md',+ 'Could not reach {0}. Check the address and that this phone can reach it.': 'ไม่สามารถเข้าถึง {0} ได้ ตรวจสอบที่อยู่และดูว่าโทรศัพท์เครื่องนี้เข้าถึงได้หรือไม่',}diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.jsindex 18e1ac261..d58e8a1b3 100644--- a/frontend/src/locales/tr.js+++ b/frontend/src/locales/tr.js@@ -1664,4 +1664,6 @@ export default {'Teal': 'Turkuaz','Yellow': 'Sarı','Enter how long it took — at least 1 minute.': 'Ne kadar sürdüğünü gir — en az 1 dakika.',+ 'Your server was reached, but it refused the app’s request (CORS). If a reverse proxy such as Traefik adds CORS headers, let requests from {0} through to openGym unchanged — see “Phone app and CORS” in docs/SELF_HOSTING.md.': "Sunucuna ulaşıldı ama uygulamanın isteğini reddetti (CORS). Traefik gibi bir ters vekil sunucu CORS başlıkları ekliyorsa {0} adresinden gelen istekleri değiştirmeden openGym'e ilet — docs/SELF_HOSTING.md içindeki “Phone app and CORS” bölümüne bak.",+ 'Could not reach {0}. Check the address and that this phone can reach it.': '{0} adresine ulaşılamadı. Adresi ve bu telefonun ona erişebildiğini kontrol et.',}diff --git a/frontend/src/locales/uk.js b/frontend/src/locales/uk.jsindex bfac12cb0..27245bbe9 100644--- a/frontend/src/locales/uk.js+++ b/frontend/src/locales/uk.js@@ -1661,4 +1661,6 @@ export default {'Teal': 'Бірюзовий','Yellow': 'Жовтий','Enter how long it took — at least 1 minute.': 'Вкажи, скільки це тривало — щонайменше 1 хвилину.',+ 'Your server was reached, but it refused the app’s request (CORS). If a reverse proxy such as Traefik adds CORS headers, let requests from {0} through to openGym unchanged — see “Phone app and CORS” in docs/SELF_HOSTING.md.': 'Сервер доступний, але відхилив запит застосунку (CORS). Якщо зворотний проксі, як-от Traefik, додає заголовки CORS, пропускай запити з {0} до openGym без змін — див. «Phone app and CORS» у docs/SELF_HOSTING.md.',+ 'Could not reach {0}. Check the address and that this phone can reach it.': 'Не вдалося зв’язатися з {0}. Перевір адресу і чи може цей телефон до нього дістатися.',}diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.jsindex 32313ace2..2ae4e3217 100644--- a/frontend/src/locales/zh.js+++ b/frontend/src/locales/zh.js@@ -1664,4 +1664,6 @@ export default {'Teal': '青色','Yellow': '黄色','Enter how long it took — at least 1 minute.': '请输入用时 — 至少 1 分钟。',+ 'Your server was reached, but it refused the app’s request (CORS). If a reverse proxy such as Traefik adds CORS headers, let requests from {0} through to openGym unchanged — see “Phone app and CORS” in docs/SELF_HOSTING.md.': '已连接到你的服务器,但它拒绝了应用的请求(CORS)。如果 Traefik 等反向代理会添加 CORS 头,请让来自 {0} 的请求原样转发到 openGym — 参见 docs/SELF_HOSTING.md 中的 “Phone app and CORS”。',+ 'Could not reach {0}. Check the address and that this phone can reach it.': '无法连接到 {0}。请检查地址,以及这部手机能否访问它。',}diff --git a/frontend/src/views/MobileOnboarding.connect-error.test.jsx b/frontend/src/views/MobileOnboarding.connect-error.test.jsxnew file mode 100644index 000000000..28d5a3c90--- /dev/null+++ b/frontend/src/views/MobileOnboarding.connect-error.test.jsx@@ -0,0 +1,49 @@+// @vitest-environment happy-dom+// #329: why pairing failed used to be a two-second toast — too short for "the server was reached+// but refused the app's request (CORS)…" to be read, let alone acted on. It stays under the fields.+import React, { act } from 'react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { createRoot } from 'react-dom/client'+import { useStore } from '../store/useStore.js'+import { useUI } from '../store/useUI.js'+import { _setLangState } from '../lib/i18n-core.js'+import { ConnectSheet } 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 connectButton = () => [...host.querySelectorAll('button')].find(b => b.textContent.trim() === 'Connect')++beforeEach(() => {+ globalThis.IS_REACT_ACT_ENVIRONMENT = true+ _setLangState('en', null, null, null)+ useUI.setState({ sheets: [], toastMsg: '' })+ host = document.createElement('div')+ document.body.appendChild(host)+ root = createRoot(host)+})+afterEach(() => { act(() => root.unmount()); host.remove() })++describe('ConnectSheet', () => {+ it('shows why connecting failed under the fields, and clears it on the next try', async () => {+ const long = 'Your server was reached, but it refused the app’s request (CORS).'+ const connectToServer = vi.fn().mockRejectedValueOnce(Object.assign(new Error(long), { code: 'cors' })).mockResolvedValueOnce(undefined)+ useStore.setState({ connectToServer })+ const close = vi.fn()+ act(() => root.render(<ConnectSheet close={close} />))+ const [url, code] = host.querySelectorAll('input')+ type(url, 'gym.example.com')+ type(code, 'abcd2345')+ await act(async () => { connectButton().click() })+ const alert = host.querySelector('[role="alert"]')+ expect(alert?.textContent).toBe(long)+ expect(close).not.toHaveBeenCalled()++ await act(async () => { connectButton().click() })+ expect(host.querySelector('[role="alert"]')).toBeNull()+ expect(close).toHaveBeenCalled()+ expect(connectToServer).toHaveBeenLastCalledWith('gym.example.com', 'ABCD2345', expect.any(Function))+ })+})diff --git a/frontend/src/views/MobileOnboarding.jsx b/frontend/src/views/MobileOnboarding.jsxindex f05e299cb..30df31888 100644--- a/frontend/src/views/MobileOnboarding.jsx+++ b/frontend/src/views/MobileOnboarding.jsx@@ -17,14 +17,18 @@ export function ConnectSheet({ close, initialUrl = '', again = false }) {const [url, setUrl] = useState(initialUrl)const [code, setCode] = useState('')const [busy, setBusy] = useState(false)+ // Why the last try failed, under the fields: a toast is gone in two seconds, too soon to read+ // "the server was reached but refused the app's request" and act on it (#329).+ const [error, setError] = useState('')const ref = useRef(null)const codeRef = useRef(null)useEffect(() => { setTimeout(() => (initialUrl ? codeRef : 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)+ setError('')try { await connectToServer(url.trim(), code.trim(), askAddDeviceData); close(); useUI.getState().toast(t('Connected')) }- catch (e) { useUI.getState().toast(e.message || t('Could not connect')) }+ catch (e) { setError(e.message || t('Could not connect')) }finally { setBusy(false) }}return <>@@ -39,6 +43,7 @@ export function ConnectSheet({ close, initialUrl = '', again = false }) {<div style={{ height: 10 }} /><input ref={codeRef} className="input" placeholder={t('Pairing code')} maxLength={8} value={code}onChange={e => setCode(e.target.value.toUpperCase())} style={{ letterSpacing: '.14em', fontWeight: 600, textAlign: 'center' }} />+ {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></>