Skip to content

Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.

api: which provider this box talks to is not public

Boris 'B' Kurktchiev1d8b04104cd5
diff --git a/api/openapi.yaml b/api/openapi.yaml
index e2867f055..ea6778baa 100644
--- a/api/openapi.yaml
+++ b/api/openapi.yaml
@@ -117,14 +117,24 @@ paths:
get:
tags: [meta]
operationId: getConfig
- summary: Public instance configuration
+ summary: Instance configuration
description: |
The flags the login screen needs before anyone is signed in. Both reflect
environment variables on the server (`INVITE_ONLY`, `ALLOW_GUEST`).
+
+ A caller with a valid session also gets a `coach` key: the block when the
+ instance has the AI Coach switched on **and** a provider connected, and `null`
+ when it has not. A caller with no session gets no key at all — the block names
+ the provider this instance talks to, which is the same fact
+ `GET /api/coach/disclosure` will not hand out unauthenticated.
+
+ The key is always present for a session, `null` included, so a client that
+ caches this answer can tell "no Coach on this instance" from "you were not
+ signed in when you asked" and knows whether asking again would change it.
security: []
responses:
'200':
- description: Instance flags.
+ description: Instance flags, plus the Coach block for a signed-in caller.
content:
application/json:
schema:
@@ -138,7 +148,33 @@ paths:
description: >-
When false, the client hides "continue without account".
Guest mode is purely client-side and never calls this API.
- example: { invite_only: true, allow_guest: false }
+ coach:
+ description: >-
+ Present for a signed-in caller and absent otherwise; `null` when this
+ instance has no Coach enabled and connected. Every Coach entry point
+ in the client hangs off the block being there.
+ type: ['object', 'null']
+ properties:
+ enabled: { type: boolean, const: true }
+ provider:
+ type: string
+ description: Provider id, e.g. `anthropic`, `compatible`, `fixture`.
+ providerLabel: { type: string, description: Human-readable provider name. }
+ authMode:
+ type: string
+ enum: [instance, profile]
+ description: Whose credential the jobs spend.
+ community:
+ type: boolean
+ description: Whether "compare with others" is offered on this instance.
+ examples:
+ anonymous: { value: { invite_only: true, allow_guest: false } }
+ signedInNoCoach: { value: { invite_only: true, allow_guest: false, coach: null } }
+ signedIn:
+ value:
+ invite_only: true
+ allow_guest: false
+ coach: { enabled: true, provider: compatible, providerLabel: "OpenAI-compatible endpoint", authMode: instance, community: false }
/api/me:
get:
diff --git a/api/server.js b/api/server.js
index 777a2f6cb..ca97e4ddb 100644
--- a/api/server.js
+++ b/api/server.js
@@ -717,8 +717,24 @@ const routes = {
// single flag every piece of Coach UI hangs off, so an unconfigured instance is byte-for-byte
// the app it was before the feature existed.
'GET /api/config': async (req, res) => {
- const coach = coachConfig.publicConfig();
- json(res, 200, { invite_only: INVITE_ONLY, allow_guest: ALLOW_GUEST, ...(coach ? { coach } : {}) });
+ // The Coach block names the provider this instance is wired to — the same fact
+ // /api/coach/disclosure refuses to hand out without a session, and for the same reason: on an
+ // invite-only instance, which model this box talks to is nobody's business who has not been
+ // let in. The two flags above it are what the login screen and the pre-login boot read
+ // (invite code field, "continue without account"), so those stay public.
+ //
+ // Every Coach consumer on the client side already requires a signed-in user before it looks
+ // at this block (lib/coach.js coachAvailable), so nothing that could render loses anything.
+ //
+ // A signed-in caller always gets the key, even on an instance with no Coach, where it is
+ // null. The client caches this answer for the page load and has to know whether the copy it
+ // holds was made for a session: without the key it cannot tell "no Coach here" from "you
+ // were not signed in when you asked", and would re-ask on every sign-in on every instance
+ // that has no Coach. The key's absence is that answer.
+ json(res, 200, {
+ invite_only: INVITE_ONLY, allow_guest: ALLOW_GUEST,
+ ...(readSession(req) ? { coach: coachConfig.publicConfig() } : {})
+ });
},
'GET /api/me': async (req, res) => {
diff --git a/api/test/server-config-session.test.js b/api/test/server-config-session.test.js
new file mode 100644
index 000000000..9d498626c
--- /dev/null
+++ b/api/test/server-config-session.test.js
@@ -0,0 +1,88 @@
+/* GET /api/config carries two kinds of fact. The flags the login screen and the pre-login boot
+ need (invite_only for the invite field, allow_guest for "continue without account") are public
+ — there is nobody to authenticate at the point they are read. The Coach block is not: it names
+ the provider this instance talks to, which is exactly what GET /api/coach/disclosure refuses to
+ answer without a session. */
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import crypto from 'node:crypto';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { spawn } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+
+const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
+const SECRET = crypto.randomBytes(32).toString('hex');
+const UID = 'u_cfg_1';
+
+const mint = uid => {
+ const payload = `${uid}:${Date.now() + 86400000}:0`;
+ return payload + '.' + crypto.createHmac('sha256', SECRET).update(payload).digest('base64url');
+};
+
+async function startServer(t, env = {}) {
+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-config-'));
+ fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });
+ fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({
+ users: [{ id: UID, name: 'C', created: new Date().toISOString() }], creds: [], subs: [], invites: []
+ }));
+ // The fixture provider is "connected" by definition (coach/config.js isConnected), which is all
+ // publicConfig() needs to produce a block.
+ fs.writeFileSync(path.join(dataDir, 'coach.json'), JSON.stringify({ enabled: true, provider: 'fixture' }));
+ const child = spawn(process.execPath, ['server.js'], {
+ cwd: API, stdio: ['ignore', 'pipe', 'pipe'],
+ env: { ...process.env, PORT: '0', DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost', INVITE_ONLY: '1', ALLOW_GUEST: '0', COACH_DISABLED: '', ...env }
+ });
+ t.after(() => { child.kill('SIGKILL'); fs.rmSync(dataDir, { recursive: true, force: true }); });
+ let log = '';
+ const port = await new Promise((resolve, reject) => {
+ const give = setTimeout(() => reject(new Error(`server never announced a port:\n${log}`)), 20000);
+ child.stdout.on('data', d => { log += d; const m = /gym-api on :(\d+)/.exec(log); if (m) { clearTimeout(give); resolve(+m[1]); } });
+ child.stderr.on('data', d => { log += d; });
+ child.on('exit', c => { clearTimeout(give); reject(new Error(`server exited (${c}):\n${log}`)); });
+ });
+ return { api: `http://127.0.0.1:${port}`, dataDir };
+}
+
+test('GET /api/config: the login flags are public, the Coach block needs a session', async t => {
+ const h = await startServer(t);
+ const config = headers => fetch(`${h.api}/api/config`, headers ? { headers } : undefined).then(r => r.json());
+
+ // Nobody signed in — what the login screen and boot() actually read, and nothing else.
+ const anon = await config();
+ assert.deepEqual(anon, { invite_only: true, allow_guest: false }, 'no coach block for a stranger');
+
+ // A session cookie gets the block, provider and all.
+ const signedIn = await config({ Cookie: `gymsid=${mint(UID)}` });
+ assert.equal(signedIn.invite_only, true);
+ assert.equal(signedIn.allow_guest, false);
+ assert.equal(signedIn.coach.enabled, true);
+ assert.equal(signedIn.coach.provider, 'fixture');
+
+ // The paired mobile app carries the same token in a header, and boot() reads this route with it.
+ const paired = await config({ Authorization: `Bearer ${mint(UID)}` });
+ assert.equal(paired.coach.provider, 'fixture');
+
+ // A signature that does not verify is a stranger, not a session.
+ const forged = await config({ Cookie: 'gymsid=u_cfg_1:99999999999999:0.notarealmac' });
+ assert.deepEqual(forged, { invite_only: true, allow_guest: false });
+});
+
+test('a session always gets the key, so the client can tell "no Coach" from "not signed in"', async t => {
+ const h = await startServer(t, { COACH_DISABLED: '1' });
+ const config = headers => fetch(`${h.api}/api/config`, headers ? { headers } : undefined).then(r => r.json());
+
+ // The client caches this answer for the page load. Without the key it cannot tell an instance
+ // with no Coach from an answer made for nobody, and re-asks on every sign-in forever.
+ assert.deepEqual(await config({ Cookie: `gymsid=${mint(UID)}` }), { invite_only: true, allow_guest: false, coach: null },
+ 'signed in, no Coach configured: the key is there and it is null');
+ assert.deepEqual(await config(), { invite_only: true, allow_guest: false }, 'and a stranger gets no key at all');
+});
+
+test('no Coach configured: no block for anyone, signed in or not', async t => {
+ const h = await startServer(t, { COACH_DISABLED: '1' });
+ assert.deepEqual(await fetch(`${h.api}/api/config`).then(r => r.json()), { invite_only: true, allow_guest: false });
+ const signedIn = await fetch(`${h.api}/api/config`, { headers: { Cookie: `gymsid=${mint(UID)}` } }).then(r => r.json());
+ assert.equal(signedIn.coach, null, 'the key says "asked with a session"; null says "no Coach here"');
+});
diff --git a/frontend/src/store/useStore.config.test.jsx b/frontend/src/store/useStore.config.test.jsx
index 47f583520..f2d735c02 100644
--- a/frontend/src/store/useStore.config.test.jsx
+++ b/frontend/src/store/useStore.config.test.jsx
@@ -34,6 +34,47 @@ describe('server config', () => {
expect(api).toHaveBeenCalledTimes(2)
})
+ it('a sign-in re-asks only when the held copy was fetched without a session', async () => {
+ // GET /api/config carries a `coach` key only for a session — the block, or null on an
+ // instance with no Coach (api/server.js). So no key means the copy came back
+ // unauthenticated, and coachAvailable() hangs every Coach entry point off that block.
+ localStorage.clear()
+ api.mockResolvedValueOnce({ invite_only: false, allow_guest: true })
+ await useStore.getState().loadConfig()
+ expect(useStore.getState().config.coach).toBeUndefined()
+
+ api.mockResolvedValueOnce({ invite_only: false, allow_guest: true, coach: { enabled: true, provider: 'compatible' } })
+ useStore.getState().setUser({ id: 'u1', name: 'A' })
+ await vi.waitFor(() => expect(useStore.getState().config.coach.enabled).toBe(true))
+ expect(api).toHaveBeenCalledTimes(2)
+
+ // A copy that carries the key was made for a session and is already the right answer.
+ useStore.getState().setUser({ id: 'u1', name: 'A' })
+ expect(api).toHaveBeenCalledTimes(2)
+
+ // Including on an instance with no Coach at all, where the key is null — this is the case
+ // that used to re-ask on every sign-in, and on every boot of a signed-in browser.
+ useStore.setState({ config: { invite_only: false, allow_guest: true, coach: null } })
+ useStore.getState().setUser({ id: 'u1', name: 'A' })
+ expect(api).toHaveBeenCalledTimes(2)
+ useStore.setState({ user: null })
+ localStorage.clear()
+ })
+
+ it('two callers asking at once make one request', async () => {
+ // Signing in re-asks and the pairing flow awaits a refresh of its own right after it, so
+ // both used to go out. It is one answer.
+ api.mockResolvedValue({ invite_only: false, allow_guest: true, coach: null })
+ const [a, b] = await Promise.all([useStore.getState().refreshConfig(), useStore.getState().refreshConfig()])
+ expect(api).toHaveBeenCalledTimes(1)
+ expect(a).toEqual(b)
+
+ // Not a cache, though: the next caller gets a fresh answer, which is the whole point of
+ // refreshConfig — an admin can switch the Coach on while a phone sits on the setup screen.
+ await useStore.getState().refreshConfig()
+ expect(api).toHaveBeenCalledTimes(2)
+ })
+
it('an unreachable server leaves the cached config alone', async () => {
useStore.setState({ config: { coach: { enabled: true } } })
api.mockRejectedValueOnce(new Error('offline'))
diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.js
index 00fc90d83..43a377eec 100644
--- a/frontend/src/store/useStore.js
+++ b/frontend/src/store/useStore.js
@@ -112,6 +112,7 @@ export const useStore = create((set, get) => {
let pushing = null // the PUT in flight, so a second push waits for it instead of racing it
let pushAgain = false // a push asked for while one was in flight — run once more after it
let pulling = null // the GET in flight, so two resume signals make one request
+ let configFetch = null // the /api/config in flight, so two callers make one request
let pushPending = false // a change made before boot's pull — pushed once boot is through
let forceNext = false // the next push replaces the server copy outright (import, reset)
let lastCheck = 0
@@ -360,9 +361,16 @@ export const useStore = create((set, get) => {
},
// Always asks. The cached copy is right for one boot, but an admin can switch the Coach on
// while a paired phone sits on the setup screen — that screen wants today's answer.
+ // Two callers that ask at once get one request: signing in re-asks (setUser) and the pairing
+ // flow awaits a refresh of its own immediately after, and there is one answer to have.
async refreshConfig() {
- try { const c = await api('/api/config'); set({ config: c }); return c }
- catch { return null }
+ if (configFetch) return configFetch
+ configFetch = (async () => {
+ try { const c = await api('/api/config'); set({ config: c }); return c }
+ catch { return null }
+ finally { configFetch = null }
+ })()
+ return configFetch
},
setUser(u) {
@@ -381,6 +389,13 @@ export const useStore = create((set, get) => {
}
localStorage.setItem('gym_owner', u.id)
localStorage.setItem('gym_user', JSON.stringify(u)); localStorage.removeItem('gym_guest')
+ // The server answers /api/config with a `coach` key only to a session — the block, or
+ // null on an instance that has no Coach. So a copy with no key at all is one fetched
+ // before this sign-in (boot's, or the login screen asking for invite_only), and every
+ // Coach entry point would stay hidden until the next reload. Ask again, unawaited:
+ // nothing on this path waits for the answer. A copy that has the key was made for a
+ // session and is already the right answer, Coach or no Coach.
+ if (get().config && !('coach' in get().config)) get().refreshConfig()
} else localStorage.removeItem('gym_user')
set({ user: u })
},