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
Coach: extra static headers for OpenAI-compatible endpoints (#385)
janviernine39ab26708cb5
diff --git a/api/coach/core/adapters/http.js b/api/coach/core/adapters/http.jsindex 76c84d0fe..a24ccee7d 100644--- a/api/coach/core/adapters/http.js+++ b/api/coach/core/adapters/http.js@@ -19,7 +19,7 @@** A provider is described by a spec (see anthropic.js etc.); this file owns the transport.*/-import { HTTP_PROVIDERS, baseUrlFor } from '../providers.js';+import { HTTP_PROVIDERS, baseUrlFor, extraHeadersFor } from '../providers.js';export const MAX_OUTPUT_TOKENS = 16000;const DEFAULT_TIMEOUT_MS = 5 * 60000;@@ -101,7 +101,7 @@ export function httpAdapter(spec) {if (!key && !meta.keyOptional) return { ok: false, error: 'no API key configured', models: [] };let res;try {- res = await call(fetchImpl, base + spec.modelsPath, { method: 'GET', headers: spec.headers(key) }, timeoutMs, signal);+ res = await call(fetchImpl, base + spec.modelsPath, { method: 'GET', headers: { ...extraHeadersFor(id, cfg), ...spec.headers(key) } }, timeoutMs, signal);} catch (e) {return { ok: false, error: e.name === 'AbortError' ? 'timed out' : `could not reach ${hostOf(base)}: ${trim(e.message, 120)}`, models: [] };}@@ -135,7 +135,7 @@ export function httpAdapter(spec) {try {res = await call(fetchImpl, base + spec.path(chosen), {method: 'POST',- headers: { 'content-type': 'application/json', ...spec.headers(key) },+ headers: { ...extraHeadersFor(id, cfg), 'content-type': 'application/json', ...spec.headers(key) },body: JSON.stringify(body)}, timeoutMs, signal);} catch (e) {diff --git a/api/coach/core/providers.js b/api/coach/core/providers.jsindex c042b5487..33d427171 100644--- a/api/coach/core/providers.js+++ b/api/coach/core/providers.js@@ -53,6 +53,52 @@ export function baseUrlFor(id, cfg) {return raw.replace(/\/+$/, '');}+/* Extra static headers a provider is called with (compatible endpoints only in practice):+ * gateways that demand routing/session headers (opencode Go's `x-opencode-session`,+ * `X-Title` style attribution headers elsewhere). Stored plaintext next to baseUrl —+ * routing aids, not credentials. Caps keep a mis-paste from becoming a smuggling vector:+ * at most 8 entries, token-shaped names, short values, and the names that would+ * override auth framing or transport are refused outright (re-checked at send time). */+export const MAX_HEADERS = 8;+export const MAX_HEADER_VALUE = 500;+const HEADER_NAME = /^[!#$%&'*+\-.^_`|~0-9a-z]+$/i;+const RESERVED_HEADERS = new Set([+ 'authorization', 'proxy-authorization', 'content-type', 'content-length',+ 'host', 'connection', 'transfer-encoding', 'upgrade', 'cookie', 'set-cookie'+]);+export const isReservedHeader = name => RESERVED_HEADERS.has(String(name || '').toLowerCase());++export function validateHeaders(raw) {+ if (raw == null || raw === '') return { ok: true, value: null };+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return { ok: false, error: 'headers must be an object of name to value' };+ const names = Object.keys(raw);+ if (names.length > MAX_HEADERS) return { ok: false, error: `at most ${MAX_HEADERS} headers` };+ const out = {};+ for (const name of names) {+ const n = String(name).toLowerCase();+ if (!HEADER_NAME.test(name) || name.length > 64) return { ok: false, error: `bad header name: ${name}` };+ if (isReservedHeader(n)) return { ok: false, error: `header is reserved: ${name}` };+ const v = raw[name];+ if (typeof v !== 'string' || !v.trim()) return { ok: false, error: `header ${name} needs a value` };+ if (v.length > MAX_HEADER_VALUE) return { ok: false, error: `header ${name} is too long` };+ out[n] = v.trim();+ }+ return { ok: true, value: Object.keys(out).length ? out : null };+}++/** The extra headers a provider call carries: the configured map minus anything reserved+ * (validated at write; this is the belt to that suspenders — a stored map from before a+ * name was reserved must not override auth framing). */+export function extraHeadersFor(id, cfg) {+ const set = cfg && cfg.providerOptions && cfg.providerOptions[id] && cfg.providerOptions[id].headers;+ if (!set || typeof set !== 'object') return {};+ const out = {};+ for (const [k, v] of Object.entries(set)) {+ if (!isReservedHeader(k) && typeof v === 'string' && v) out[String(k).toLowerCase()] = v;+ }+ return out;+}+/*** Only http(s), only a parseable URL, and never credentials in it — a base URL is admin* configuration, but "admin-configured" and "safe to log" are different properties, and thediff --git a/api/coach/routes.js b/api/coach/routes.jsindex bcf992b59..a041d7bf9 100644--- a/api/coach/routes.js+++ b/api/coach/routes.js@@ -10,7 +10,7 @@ import { computeCohort } from './cohort.js';import { adapterFor } from './adapters/index.js';import { canDropPrivileges } from './adapters/spawn.js';import { DATA_CATEGORIES } from './core/payload.js';-import { validateBaseUrl, baseUrlFor } from './core/providers.js';+import { validateBaseUrl, validateHeaders, baseUrlFor } from './core/providers.js';// Job failures the user sees, in the app's own voice. The raw provider detail never reaches// them — it goes to the admin card, which is where someone can act on it (FR-47).@@ -163,6 +163,10 @@ export function coachRoutes({ json, readBody, readSession, requireAdmin }) {model: cfgStore.modelFor(cfg),models: cfg.models,baseUrl: cfgStore.providerMeta(cfg).http ? baseUrlFor(cfg.provider, cfg) : null,+ // Extra static headers this endpoint is called with (compatible endpoints only).+ // Values, not just names: the admin wrote them and needs to see them to edit them.+ // Plaintext next to baseUrl — routing aids, not credentials (the key stays encrypted).+ headers: cfgStore.providerMeta(cfg).http ? (cfgStore.optionsFor(cfg).headers || null) : null,knownModels: check.models || null,caps: cfg.caps,maxMessageLen: cfg.maxMessageLen,@@ -225,6 +229,15 @@ export function coachRoutes({ json, readBody, readSession, requireAdmin }) {if (!v.value && !cfgStore.PROVIDERS[target].defaultBase) return json(res, 400, { error: `${target} has no default endpoint, enter one` });patch.providerOptions = { ...current.providerOptions, [target]: { ...(current.providerOptions[target] || {}), baseUrl: v.value } };}+ if (body.headers !== undefined) {+ if (!cfgStore.PROVIDERS[target].baseUrl) return json(res, 400, { error: `${target} has a fixed endpoint` });+ const h = validateHeaders(body.headers);+ if (!h.ok) return json(res, 400, { error: h.error });+ // Build on the patch, not on current: a body carrying baseUrl AND headers must keep both.+ const next = { ...((patch.providerOptions && patch.providerOptions[target]) || current.providerOptions[target] || {}) };+ if (h.value) next.headers = h.value; else delete next.headers;+ patch.providerOptions = { ...current.providerOptions, ...(patch.providerOptions || {}), [target]: next };+ }if (body.community !== undefined) patch.community = !!body.community;if (body.caps) {patch.caps = {diff --git a/api/test/adapters-http.test.js b/api/test/adapters-http.test.jsindex 05261579e..79e827769 100644--- a/api/test/adapters-http.test.js+++ b/api/test/adapters-http.test.js@@ -15,7 +15,7 @@ const openai = (await import('../coach/core/adapters/openai.js')).default;const gemini = (await import('../coach/core/adapters/gemini.js')).default;const compatible = (await import('../coach/core/adapters/compatible.js')).default;const { attemptOnce } = await import('../coach/core/pipeline.js');-const { HTTP_PROVIDERS, validateBaseUrl } = await import('../coach/core/providers.js');+const { HTTP_PROVIDERS, validateBaseUrl, validateHeaders } = await import('../coach/core/providers.js');const { SYSTEM_PROMPT } = await import('../coach/core/system-prompt.js');/** A fetch that records what it was asked and answers from a script. Like the real one, it@@ -305,3 +305,36 @@ test('models(): OpenAI’s list is cut to what Chat Completions can use; a compaconst co = fakeFetch([ok({ data: [{ id: 'qwen2.5:3b' }, { id: 'llama3.2' }] })]);assert.deepEqual((await compatible.models({ providerOptions: { compatible: { baseUrl: 'http://ollama:11434' } } }, {}, { fetch: co })).models, ['llama3.2', 'qwen2.5:3b']);});++test('compatible: configured extra headers ride on models, check and jobs — auth framing always wins', async () => {+ const cfg = { provider: 'compatible', providerOptions: { compatible: { baseUrl: 'http://ollama.lan:11434', headers: { 'x-opencode-session': 'sess-1' } } } };+ const m = fakeFetch([ok({ data: [] })]);+ await compatible.models(cfg, env, { fetch: m });+ assert.equal(m.calls[0].headers['x-opencode-session'], 'sess-1');+ assert.equal(m.calls[0].headers.authorization, 'Bearer compat-1');+ const j = fakeFetch([ok({ choices: [{ message: { content: ANSWER }, finish_reason: 'stop' }] })]);+ await compatible.invoke({ cfg, prompt: 'P', env, model: 'llama3', fetch: j });+ assert.equal(j.calls[0].headers['x-opencode-session'], 'sess-1');++ // A stored map from before a name was reserved must not override auth framing.+ const evil = { provider: 'compatible', providerOptions: { compatible: { baseUrl: 'http://x', headers: { authorization: 'Bearer evil', 'content-type': 'text/plain' } } } };+ const e = fakeFetch([ok({ choices: [{ message: { content: ANSWER }, finish_reason: 'stop' }] })]);+ await compatible.invoke({ cfg: evil, prompt: 'P', env, model: 'llama3', fetch: e });+ assert.equal(e.calls[0].headers.authorization, 'Bearer compat-1');+ assert.equal(e.calls[0].headers['content-type'], 'application/json');+});++test('validateHeaders: small maps pass, framing names and junk do not', () => {+ assert.deepEqual(validateHeaders(null).value, null);+ assert.deepEqual(validateHeaders({}).value, null);+ assert.deepEqual(validateHeaders({ 'X-Opencode-Session': ' abc ' }).value, { 'x-opencode-session': 'abc' });+ for (const bad of ['authorization', 'Content-Type', 'content-length', 'Host', 'cookie']) {+ assert.equal(validateHeaders({ [bad]: 'x' }).ok, false, bad);+ }+ assert.equal(validateHeaders({ 'not a name!': 'x' }).ok, false);+ assert.equal(validateHeaders({ a: '' }).ok, false);+ assert.equal(validateHeaders('x-opencode-session: abc').ok, false);+ assert.equal(validateHeaders([['a', 'b']]).ok, false);+ const many = {}; for (let i = 0; i < 9; i++) many['x-h-' + i] = 'v';+ assert.equal(validateHeaders(many).ok, false);+});diff --git a/api/test/routes.test.js b/api/test/routes.test.jsindex 93d457214..38d4b20ce 100644--- a/api/test/routes.test.js+++ b/api/test/routes.test.js@@ -234,3 +234,29 @@ test('an admin can raise the Coach message length past the old 1000-char defaultconst status = await call('GET /api/coach/status');assert.equal(status.body.maxMessageLen, 1800);});++/* ---------- compatible extra headers (issue #385) ---------- */+test('an admin can store extra headers for the compatible endpoint; framing names are refused', async () => {+ fresh();+ const { call } = harness();++ // Empty by default.+ assert.equal((await call('GET /api/admin/coach')).body.headers, null);++ let r = await call('POST /api/admin/coach/config', { provider: 'compatible', baseUrl: 'http://127.0.0.1:9', headers: { 'x-opencode-session': 'sess-1' } });+ assert.equal(r.status, 200);+ assert.deepEqual((await call('GET /api/admin/coach')).body.headers, { 'x-opencode-session': 'sess-1' });+ assert.deepEqual(cfg.load().providerOptions.compatible.headers, { 'x-opencode-session': 'sess-1' }, 'persists with the rest of the Coach config');++ // Reserved framing names are refused, and a fixed-endpoint provider takes none.+ r = await call('POST /api/admin/coach/config', { headers: { authorization: 'Bearer x' } });+ assert.equal(r.status, 400);+ r = await call('POST /api/admin/coach/config', { provider: 'openai', headers: { 'x-a': 'b' } });+ assert.equal(r.status, 400);++ // Clearing with null drops the key rather than storing an empty map.+ r = await call('POST /api/admin/coach/config', { provider: 'compatible', headers: null });+ assert.equal(r.status, 200);+ assert.equal((await call('GET /api/admin/coach')).body.headers, null);+ assert.equal('headers' in cfg.load().providerOptions.compatible, false);+});diff --git a/docs/AI_COACH.md b/docs/AI_COACH.mdindex fed0ccbc3..dfedacd5b 100644--- a/docs/AI_COACH.md+++ b/docs/AI_COACH.md@@ -74,6 +74,9 @@ answers on instead, and a key only if it wants one.- For a compatible endpoint, enter the **Endpoint** — `http://` or `https://`, no username orpassword in it, no query string. The host is written into the job log so you can see wherejobs went.+- A gateway that demands extra headers gets them under **Extra headers**: one `Name: value`+ per line (e.g. opencode Go's `x-opencode-session`), sent with the list, test and job+ calls. `Authorization` and `Content-Type` are refused there — auth framing always wins.- **Use an API key** → paste it. It is encrypted into `./data/coach.json` and is never shownagain.- **List models** asks the endpoint what it serves and turns the model field into a picker.diff --git a/frontend/src/views/AdminCoach.config.test.jsx b/frontend/src/views/AdminCoach.config.test.jsxindex 9248ccf47..374caf4be 100644--- a/frontend/src/views/AdminCoach.config.test.jsx+++ b/frontend/src/views/AdminCoach.config.test.jsx@@ -67,3 +67,21 @@ describe('AdminCoach keeps the app\'s own config current', () => {expect(mocks.refreshConfig).toHaveBeenCalledTimes(2)})})++/* Extra-headers textarea helpers (issue #385): parse client-side, empty clears. */+describe('AdminCoach extra headers', async () => {+ const { parseHeadersText, headersToText } = await import('./AdminCoach.jsx')++ it('round-trips a map through the textarea format', () => {+ expect(headersToText({ 'x-opencode-session': 'sess-1' })).toBe('x-opencode-session: sess-1')+ expect(headersToText(null)).toBe('')+ expect(parseHeadersText('x-opencode-session: sess-1\nX-Title: demo')).toEqual({ headers: { 'x-opencode-session': 'sess-1', 'X-Title': 'demo' } })+ })++ it('treats empty as clear and junk as an error, not a request', () => {+ expect(parseHeadersText('')).toEqual({ headers: null })+ expect(parseHeadersText(' \n ')).toEqual({ headers: null })+ expect(parseHeadersText('no-colon-here').error).toBeTruthy()+ expect(parseHeadersText('name-only:').error).toBeTruthy()+ })+})diff --git a/frontend/src/views/AdminCoach.jsx b/frontend/src/views/AdminCoach.jsxindex 2adccd798..355445c32 100644--- a/frontend/src/views/AdminCoach.jsx+++ b/frontend/src/views/AdminCoach.jsx@@ -3,7 +3,7 @@ import { useUI } from '../store/useUI.js'import { useStore } from '../store/useStore.js'import { api } from '../lib/api.js'import Icon from '../components/Icon.jsx'-import { Button, Switch, TextField } from '../components/ui.jsx'+import { Button, Switch, TextArea, TextField } from '../components/ui.jsx'/* The operator's side of the Coach, laid out as a guided setup: one master switch, numberedsteps that each say what they are for, and everything an owner rarely needs folded away@@ -26,6 +26,27 @@ const rel = ts => {return Math.floor(s / 86400) + ' d ago'}+// Extra static headers for the endpoint, one `Name: value` per line — e.g. a gateway's+// routing/session header (opencode Go's `x-opencode-session`). Parsed client-side so a+// typo reads as a message on the card, not a 400 the admin has to decode. Empty clears.+export const headersToText = h => h && typeof h === 'object'+ ? Object.entries(h).map(([k, v]) => `${k}: ${v}`).join('\n')+ : ''+export function parseHeadersText(text) {+ const lines = String(text || '').split('\n').map(l => l.trim()).filter(Boolean)+ if (!lines.length) return { headers: null }+ const out = {}+ for (const line of lines) {+ const i = line.indexOf(':')+ if (i < 1) return { error: `not a Name: value line: ${line.slice(0, 40)}` }+ const name = line.slice(0, i).trim()+ const value = line.slice(i + 1).trim()+ if (!name || !value) return { error: `not a Name: value line: ${line.slice(0, 40)}` }+ out[name] = value+ }+ return { headers: out }+}+// Which chips go under which heading. Runtime-backed providers are the ones that need the// bigger `coach` image; the fixture exists so the whole loop can be walked without any account.const RUNTIME_IDS = ['claude', 'codex']@@ -182,6 +203,18 @@ export default function AdminCoach() {onBlur={e => e.target.value !== (d.baseUrl || '') && patch({ baseUrl: e.target.value })} /></div><div className="adm-hint" style={{ margin: 0 }}>The host is written to the job log, so you can always see where requests went.</div>+ <div className="adm-field">+ <label>Extra headers (optional)</label>+ <TextArea key={headersToText(d.headers)} defaultValue={headersToText(d.headers)} placeholder={'x-opencode-session: 550e8400-…'} autoCapitalize="none" autoCorrect="off" rows={2}+ onBlur={e => {+ const cur = headersToText(d.headers)+ if (e.target.value === cur) return+ const p = parseHeadersText(e.target.value)+ if (p.error) { toast(p.error); e.target.value = cur; return }+ patch({ headers: p.headers })+ }} />+ </div>+ <div className="adm-hint" style={{ margin: 0 }}>One <code>Name: value</code> per line, sent with every request to this endpoint. For gateways that demand routing headers. Never <code>Authorization</code> or <code>Content-Type</code> — those are refused.</div></Step>}{/* ---------- credential ---------- */}