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: tell a server that isn't openGym apart from a CORS refusal (#329)
Duarte Santos0f8b11a0e099
diff --git a/frontend/src/lib/api.js b/frontend/src/lib/api.jsindex c94a6a3a2..b1d443312 100644--- a/frontend/src/lib/api.js+++ b/frontend/src/lib/api.js@@ -2,6 +2,7 @@import { t } from './i18n-core.js'import { MOBILE } from './mobile.js'import { appBase } from './app-base.js'+import { nativeFetch } from './capacitor-fetch.js'export const IS_APPLE = /iPhone|iPad|iPod|Macintosh/.test(navigator.userAgent)export const IS_ANDROID = /Android/.test(navigator.userAgent)@@ -219,6 +220,21 @@ const PROBE_MS = 5000const hostOfBase = base => {try { const u = new URL(base); return u.host + u.pathname.replace(/\/$/, '') } catch { return base || '' }}+async function healthIsNotOpenGym(base, ms) {+ const ctl = typeof AbortController === 'function' ? new AbortController() : null+ let timer = null+ try {+ const res = await Promise.race([+ nativeFetch(base + '/api/health', { method: 'GET', headers: { Accept: 'application/json' }, ...(ctl ? { signal: ctl.signal } : {}) }),+ new Promise((_, reject) => { timer = setTimeout(() => { if (ctl) ctl.abort(); reject(new Error('timeout')) }, ms) }),+ ])+ let body = null+ try { body = JSON.parse(await res.text()) } catch { body = null }+ return !(res.ok && body && typeof body === 'object' && body.ok === true)+ } catch {+ return false+ } finally { clearTimeout(timer) }+}async function whyUnreachable(base, ms) {let reached = falseconst ctl = typeof AbortController === 'function' ? new AbortController() : null@@ -231,6 +247,12 @@ async function whyUnreachable(base, ms) {reached = true} catch { /* not reachable either */ }finally { clearTimeout(timer) }+ // Something answered. Whether it is openGym needs a readable answer: in the app the native+ // fetch reads /api/health past CORS. A page that is not openGym's health JSON means a wrong+ // address, not a proxy (#329). No readable answer at all leaves the CORS explanation.+ if (reached && (await healthIsNotOpenGym(base, ms))) {+ return failure(t('That address answers, but it isn’t an openGym server. Check the URL.'), 'not-opengym')+ }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')diff --git a/frontend/src/lib/api.pair-probe.test.js b/frontend/src/lib/api.pair-probe.test.jsindex b447d3efa..455937248 100644--- a/frontend/src/lib/api.pair-probe.test.js+++ b/frontend/src/lib/api.pair-probe.test.js@@ -9,10 +9,13 @@ afterEach(() => { vi.unstubAllGlobals(); vi.useRealTimers() })const failed = () => Promise.reject(new TypeError('Failed to fetch'))const opaque = () => Promise.resolve(new Response(null, { status: 200 }))+// The no-cors probe settles; the readable one is refused by the browser, as for any server+// that does not let this origin in.+const corsOnly = (url, init) => (init && init.mode === 'no-cors' ? opaque() : failed())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()))+ const fetch = vi.fn((url, init) => (url.endsWith('/api/pair/redeem') ? failed() : corsOnly(url, init)))vi.stubGlobal('fetch', fetch)const e = await pairRedeem('https://gym.example.com', 'ABCD2345').catch(x => x)expect(e.code).toBe('cors')@@ -24,6 +27,25 @@ describe('pairRedeem when the request never gets an answer', () => {expect(probe[1]).toMatchObject({ mode: 'no-cors', cache: 'no-store' })})+ it('openGym behind a proxy that refuses the app: its health answer read, still the CORS message', async () => {+ const health = () => Promise.resolve(new Response(JSON.stringify({ ok: true, users: 2 }), { status: 200, headers: { 'content-type': 'application/json' } }))+ vi.stubGlobal('fetch', vi.fn((url, init) => (url.endsWith('/api/pair/redeem') ? failed() : init && init.mode === 'no-cors' ? opaque() : health())))+ const e = await pairRedeem('https://gym.example.com', 'ABCD2345').catch(x => x)+ expect(e.code).toBe('cors')+ })++ // A static site, another app, a router page: it answers, but /api/health is not openGym's.+ it.each([+ ['a 404 page', () => new Response('<h1>not found</h1>', { status: 404, headers: { 'content-type': 'text/html' } })],+ ['an HTML page', () => new Response('<h1>static</h1>', { status: 200, headers: { 'content-type': 'text/html' } })],+ ['another app\'s JSON', () => new Response(JSON.stringify({ status: 'UP' }), { status: 200, headers: { 'content-type': 'application/json' } })],+ ])('a server that answers with %s: says it is not an openGym server', async (_, page) => {+ vi.stubGlobal('fetch', vi.fn((url, init) => (url.endsWith('/api/pair/redeem') ? failed() : init && init.mode === 'no-cors' ? opaque() : Promise.resolve(page()))))+ const e = await pairRedeem('https://gym.example.com', 'ABCD2345').catch(x => x)+ expect(e.code).toBe('not-opengym')+ expect(e.message).toBe('That address answers, but it isn’t an openGym server. Check the URL.')+ })+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)diff --git a/frontend/src/locales/ar.js b/frontend/src/locales/ar.jsindex a99f1e652..34d8d8e23 100644--- a/frontend/src/locales/ar.js+++ b/frontend/src/locales/ar.js@@ -1844,4 +1844,5 @@ export default {'{0} doesn’t do itself, recruit. Move it!': '{0} لن ينجز نفسه أيها المجنّد. تحرّك!','Excuses don’t lift weights. Report for {0} tomorrow!': 'الأعذار لا ترفع الأوزان. احضر غدًا إلى {0}!','Your muscles filed a missing-person report. Show up for {0}!': 'عضلاتك أبلغت عن فقدانك. احضر إلى {0}!',+ 'That address answers, but it isn’t an openGym server. Check the URL.': 'هذا العنوان يستجيب، لكنه ليس خادم openGym. تحقّق من الرابط.',}diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.jsindex 70956f0e6..dd6c8d4c7 100644--- a/frontend/src/locales/de.js+++ b/frontend/src/locales/de.js@@ -1811,4 +1811,5 @@ export default {'{0} doesn’t do itself, recruit. Move it!': '{0} macht sich nicht von allein, Rekrut. Bewegung!','Excuses don’t lift weights. Report for {0} tomorrow!': 'Ausreden stemmen keine Gewichte. Morgen trittst du zu {0} an!','Your muscles filed a missing-person report. Show up for {0}!': 'Deine Muskeln haben eine Vermisstenanzeige aufgegeben. Antreten zu {0}!',+ 'That address answers, but it isn’t an openGym server. Check the URL.': 'Unter dieser Adresse antwortet etwas, aber kein openGym-Server. Prüf die URL.',}diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.jsindex 346260b71..67ed26f5a 100644--- a/frontend/src/locales/es.js+++ b/frontend/src/locales/es.js@@ -1791,4 +1791,5 @@ export default {'{0} doesn’t do itself, recruit. Move it!': '{0} no se hace solo, recluta. ¡Muévete!','Excuses don’t lift weights. Report for {0} tomorrow!': 'Las excusas no levantan pesas. ¡Mañana te presentas a {0}!','Your muscles filed a missing-person report. Show up for {0}!': 'Tus músculos pusieron una denuncia por desaparición. ¡Preséntate a {0}!',+ 'That address answers, but it isn’t an openGym server. Check the URL.': 'Esa dirección responde, pero no es un servidor de openGym. Revisa la URL.',}diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.jsindex c89976027..8f4a3bdc2 100644--- a/frontend/src/locales/fr.js+++ b/frontend/src/locales/fr.js@@ -1791,4 +1791,5 @@ export default {'{0} doesn’t do itself, recruit. Move it!': '{0} ne va pas se faire tout seul, recrue. Au pas de course !','Excuses don’t lift weights. Report for {0} tomorrow!': 'Les excuses ne soulèvent pas de poids. Présentez-vous demain pour {0} !','Your muscles filed a missing-person report. Show up for {0}!': 'Vos muscles ont signalé votre disparition. Présentez-vous pour {0} !',+ 'That address answers, but it isn’t an openGym server. Check the URL.': 'Cette adresse répond, mais ce n’est pas un serveur openGym. Vérifie l’URL.',}diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.jsindex b936af0f1..6ecc13194 100644--- a/frontend/src/locales/hi.js+++ b/frontend/src/locales/hi.js@@ -1791,4 +1791,5 @@ export default {'{0} doesn’t do itself, recruit. Move it!': '{0} अपने आप नहीं होगा, रंगरूट। चलो, हिलो!','Excuses don’t lift weights. Report for {0} tomorrow!': 'बहाने वज़न नहीं उठाते। कल {0} के लिए हाज़िर हो!','Your muscles filed a missing-person report. Show up for {0}!': 'आपकी मांसपेशियों ने गुमशुदगी की रिपोर्ट लिखाई है। {0} के लिए हाज़िर हो!',+ 'That address answers, but it isn’t an openGym server. Check the URL.': 'यह पता जवाब देता है, लेकिन यह openGym सर्वर नहीं है। URL जाँचें।',}diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.jsindex 038a4a4eb..57ac01e87 100644--- a/frontend/src/locales/hu.js+++ b/frontend/src/locales/hu.js@@ -1794,4 +1794,5 @@ export default {'{0} doesn’t do itself, recruit. Move it!': 'A(z) {0} nem csinálja meg magát, újonc. Mozgás!','Excuses don’t lift weights. Report for {0} tomorrow!': 'A kifogások nem emelnek súlyt. Holnap jelentkezel: {0}!','Your muscles filed a missing-person report. Show up for {0}!': 'Az izmaid eltűntként jelentettek. Jelentkezz: {0}!',+ 'That address answers, but it isn’t an openGym server. Check the URL.': 'Ez a cím válaszol, de nem openGym-szerver. Ellenőrizd az URL-t.',}diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.jsindex c70382f11..a3e437fc9 100644--- a/frontend/src/locales/it.js+++ b/frontend/src/locales/it.js@@ -1791,4 +1791,5 @@ export default {'{0} doesn’t do itself, recruit. Move it!': '{0} non si fa da solo, recluta. Muoviti!','Excuses don’t lift weights. Report for {0} tomorrow!': 'Le scuse non sollevano pesi. Domani ti presenti a {0}!','Your muscles filed a missing-person report. Show up for {0}!': 'I tuoi muscoli hanno denunciato la tua scomparsa. Presentati a {0}!',+ 'That address answers, but it isn’t an openGym server. Check the URL.': 'Quell’indirizzo risponde, ma non è un server openGym. Controlla l’URL.',}diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.jsindex 5c8897627..74483df5c 100644--- a/frontend/src/locales/ko.js+++ b/frontend/src/locales/ko.js@@ -1791,4 +1791,5 @@ export default {'{0} doesn’t do itself, recruit. Move it!': '{0}은(는) 저절로 되지 않는다, 훈련병. 움직여!','Excuses don’t lift weights. Report for {0} tomorrow!': '핑계는 무게를 들지 않는다. 내일 {0}에 집합!','Your muscles filed a missing-person report. Show up for {0}!': '근육들이 실종 신고를 냈다. {0}에 출석하라!',+ 'That address answers, but it isn’t an openGym server. Check the URL.': '이 주소는 응답하지만 openGym 서버가 아닙니다. URL을 확인하세요.',}diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.jsindex d95b55da8..fc4f91240 100644--- a/frontend/src/locales/pl.js+++ b/frontend/src/locales/pl.js@@ -1791,4 +1791,5 @@ export default {'{0} doesn’t do itself, recruit. Move it!': 'Trening „{0}” sam się nie zrobi, rekrucie. Ruszaj się!','Excuses don’t lift weights. Report for {0} tomorrow!': 'Wymówki nie podnoszą ciężarów. Jutro meldujesz się na „{0}”!','Your muscles filed a missing-person report. Show up for {0}!': 'Twoje mięśnie zgłosiły twoje zaginięcie. Stawić się na „{0}”!',+ 'That address answers, but it isn’t an openGym server. Check the URL.': 'Ten adres odpowiada, ale to nie jest serwer openGym. Sprawdź URL.',}diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.jsindex 5fdc52880..0c9cd2f68 100644--- a/frontend/src/locales/pt-BR.js+++ b/frontend/src/locales/pt-BR.js@@ -1112,6 +1112,7 @@ export const PT_BR_OVERRIDES = {'A clean printout, one page per plan. No exercise ever gets split across pages.': 'Uma impressão limpa, uma página por plano. Nenhum exercício fica dividido entre páginas.','{1} animated exercises + 1 of your own': '{1} exercícios animados + 1 seu','{1} animated exercises + {0} of your own': '{1} exercícios animados + {0} seus',+ 'That address answers, but it isn’t an openGym server. Check the URL.': 'Esse endereço responde, mas não é um servidor openGym. Verifique a URL.',}export default { ...pt, ...PT_BR_OVERRIDES }diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.jsindex 217e34d2f..35d7d9fe7 100644--- a/frontend/src/locales/pt.js+++ b/frontend/src/locales/pt.js@@ -1791,4 +1791,5 @@ export default {'{0} doesn’t do itself, recruit. Move it!': '{0} não se faz sozinho, recruta. Mexe-te!','Excuses don’t lift weights. Report for {0} tomorrow!': 'Desculpas não levantam pesos. Amanhã apresentas-te para {0}!','Your muscles filed a missing-person report. Show up for {0}!': 'Os teus músculos deram-te como desaparecido. Apresenta-te para {0}!',+ 'That address answers, but it isn’t an openGym server. Check the URL.': 'Esse endereço responde, mas não é um servidor openGym. Verifica o URL.',}diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.jsindex 87954bf7e..954279df1 100644--- a/frontend/src/locales/ru.js+++ b/frontend/src/locales/ru.js@@ -1795,4 +1795,5 @@ export default {'{0} doesn’t do itself, recruit. Move it!': 'Тренировка «{0}» сама себя не сделает, новобранец. Шевелитесь!','Excuses don’t lift weights. Report for {0} tomorrow!': 'Отговорки не поднимают веса. Завтра явиться на «{0}»!','Your muscles filed a missing-person report. Show up for {0}!': 'Ваши мышцы подали заявление о пропаже. Явиться на «{0}»!',+ 'That address answers, but it isn’t an openGym server. Check the URL.': 'По этому адресу что-то отвечает, но это не сервер openGym. Проверьте URL.',}diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.jsindex 656e0b3c2..269dc95df 100644--- a/frontend/src/locales/th.js+++ b/frontend/src/locales/th.js@@ -1802,4 +1802,5 @@ export default {'{0} doesn’t do itself, recruit. Move it!': '{0} ไม่ทำตัวเองหรอก พลทหาร เคลื่อนไหว!','Excuses don’t lift weights. Report for {0} tomorrow!': 'ข้ออ้างยกน้ำหนักไม่ได้ พรุ่งนี้มารายงานตัวที่ {0}!','Your muscles filed a missing-person report. Show up for {0}!': 'กล้ามเนื้อของคุณแจ้งคนหายแล้ว มารายงานตัวที่ {0}!',+ 'That address answers, but it isn’t an openGym server. Check the URL.': 'ที่อยู่นี้ตอบกลับ แต่ไม่ใช่เซิร์ฟเวอร์ openGym ตรวจสอบ URL อีกครั้ง',}diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.jsindex 2e6bb601b..67cc2b646 100644--- a/frontend/src/locales/tr.js+++ b/frontend/src/locales/tr.js@@ -1791,4 +1791,5 @@ export default {'{0} doesn’t do itself, recruit. Move it!': '{0} kendi kendine yapılmaz, acemi. Kımılda!','Excuses don’t lift weights. Report for {0} tomorrow!': 'Bahaneler ağırlık kaldırmaz. Yarın {0} için hazır ol!','Your muscles filed a missing-person report. Show up for {0}!': 'Kasların kayıp ilanı verdi. {0} için içtimaya gel!',+ 'That address answers, but it isn’t an openGym server. Check the URL.': 'Bu adres yanıt veriyor ama bir openGym sunucusu değil. URL’yi kontrol et.',}diff --git a/frontend/src/locales/uk.js b/frontend/src/locales/uk.jsindex 6a648dfc2..36dfac22d 100644--- a/frontend/src/locales/uk.js+++ b/frontend/src/locales/uk.js@@ -1788,4 +1788,5 @@ export default {'{0} doesn’t do itself, recruit. Move it!': 'Тренування «{0}» саме себе не зробить, новобранцю. Ворушися!','Excuses don’t lift weights. Report for {0} tomorrow!': 'Відмовки не піднімають ваги. Завтра з’явитися на «{0}»!','Your muscles filed a missing-person report. Show up for {0}!': 'Твої м’язи заявили про твоє зникнення. З’явитися на «{0}»!',+ 'That address answers, but it isn’t an openGym server. Check the URL.': 'Ця адреса відповідає, але це не сервер openGym. Перевір URL.',}diff --git a/frontend/src/locales/zh-TW.js b/frontend/src/locales/zh-TW.jsindex abd32246c..d75de756e 100644--- a/frontend/src/locales/zh-TW.js+++ b/frontend/src/locales/zh-TW.js@@ -1784,4 +1784,5 @@ export default {'{0} doesn’t do itself, recruit. Move it!': '{0} 不會自己完成,菜鳥。動起來!','Excuses don’t lift weights. Report for {0} tomorrow!': '藉口舉不起重量。明天準時報到練 {0}!','Your muscles filed a missing-person report. Show up for {0}!': '你的肌肉已經報案協尋你了。馬上來練 {0}!',+ 'That address answers, but it isn’t an openGym server. Check the URL.': '這個位址有回應,但不是 openGym 伺服器。請檢查網址。',}diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.jsindex 6f70ef2c2..6e5a43e56 100644--- a/frontend/src/locales/zh.js+++ b/frontend/src/locales/zh.js@@ -1791,4 +1791,5 @@ export default {'{0} doesn’t do itself, recruit. Move it!': '{0}不会自己完成,新兵。动起来!','Excuses don’t lift weights. Report for {0} tomorrow!': '借口举不起重量。明天准时报到练{0}!','Your muscles filed a missing-person report. Show up for {0}!': '你的肌肉已经报了失踪。马上来练{0}!',+ 'That address answers, but it isn’t an openGym server. Check the URL.': '该地址有响应,但不是 openGym 服务器。请检查网址。',}