diff --git a/.env.example b/.env.example index 5b64293..1bdf201 100644 --- a/.env.example +++ b/.env.example @@ -163,9 +163,39 @@ RP_NAME=KuentaGYM # # COACH_JOB_TIMEOUT_MS=1500000 # -# Credentials never live here. They are encrypted into ./data/coach.json, one -# per provider, or for the Codex provider cached in ./coach-auth — a sibling of ./data, never inside it, -# so a live sign-in does not ride along in the documented backup archive. +# ── Configuring the Coach from the environment ───────────────────────────── +# Optional, and the alternative to the admin screen: an instance can be given +# its provider at start-up, so a container is redeployed with the Coach already +# pointed at a model and nobody has to open Settings → AI Coach. Naming a +# provider here is the whole configuration — it also turns the Coach on — and +# anything chosen later in the app wins over it. +# +# COACH_PROVIDER=compatible +# COACH_BASE_URL=https://ai.example.com +# COACH_MODEL=vendor/model-name +# COACH_API_KEY=sk-... +# +# COACH_BASE_URL is the endpoint WITHOUT the /v1 suffix: the adapter appends +# /v1/chat/completions itself, which is why the built-in OpenAI default is +# https://api.openai.com and not .../v1. Getting this wrong looks like a +# mysterious "unexpected response shape" in the job log rather than a 404. +# +# COACH_API_KEY may be omitted in favour of the variable the provider itself +# declares — OPENAI_COMPAT_API_KEY, OPENAI_API_KEY, GEMINI_API_KEY, +# ANTHROPIC_API_KEY — which is also the name the key is passed under when the +# request is made. +# +# A provider chosen in the app (or a key pasted there) outranks these: the +# environment configures an instance nobody has set up in the UI, and never +# overrides a choice someone made in one. What the environment supplies is +# deliberately NOT written back into ./data/coach.json, so changing a variable +# and redeploying always takes effect. +# +# Credentials never live in the config file. The ones pasted in the app are +# encrypted into ./data/coach.json, one per provider, or for the Codex provider +# cached in ./coach-auth — a sibling of ./data, never inside it, so a live +# sign-in does not ride along in the documented backup archive. A key set here +# is read from the environment at request time and written nowhere. # See docs/AI_COACH.md. # ── Hevy map regeneration (developers only) ──────────────────────────────── # Not used by the running app. End users paste their own key in Settings → diff --git a/api/coach/config.js b/api/coach/config.js index 951d2e9..73d819c 100644 --- a/api/coach/config.js +++ b/api/coach/config.js @@ -43,6 +43,52 @@ const FILE = path.join(DATA, 'coach.json'); export const CREDENTIAL_HOME = process.env.COACH_CREDENTIAL_DIR || '/coach-auth'; export const COACH_DISABLED = /^(1|true|yes|on)$/i.test(process.env.COACH_DISABLED || ''); +/* ---------- configured from the environment ---------- + * An instance can be given its provider at start-up, so a container is redeployed with the Coach + * already pointed at a model and nobody has to open an admin screen: + * + * COACH_PROVIDER=compatible + * COACH_BASE_URL=https://ai.example.com (the endpoint WITHOUT /v1 — the adapter adds it) + * COACH_MODEL=some/model + * COACH_API_KEY=sk-… (or the provider's own variable, e.g. OPENAI_COMPAT_API_KEY) + * + * These are the *base* the saved file is layered on top of, exactly like DEFAULTS: an admin who + * picked a provider in the app meant it, and their choice wins. The credential is the exception + * and is not part of the config at all — see envCredentialFor, which reads it fresh and never + * lets it reach the file on disk. */ +const envText = name => (process.env[name] || '').trim() || null; + +function envPatch() { + const provider = envText('COACH_PROVIDER'); + if (!provider || !PROVIDERS[provider]) return {}; + const baseUrl = envText('COACH_BASE_URL'); + const model = envText('COACH_MODEL'); + return { + // Naming a provider in the environment is the whole configuration: an instance started this + // way that then reported "the Coach is off" would be a puzzle with no clue in it. + enabled: true, + provider, + ...(baseUrl ? { providerOptions: { [provider]: { baseUrl } } } : {}), + ...(model ? { models: { [provider]: model } } : {}) + }; +} + +/** + * The credential this instance was started with, if any — `COACH_API_KEY`, or the variable the + * provider itself declares (`OPENAI_COMPAT_API_KEY`, `OPENAI_API_KEY`, …). + * + * Read from the environment every time and held nowhere else. It is deliberately NOT a field of + * the config: that object is cached, written to data/coach.json by any admin action, and included + * in the backup the docs tell people to make. Encrypted credentials the admin pasted live there; + * a key handed to the container does not belong in a file. + */ +export function envCredentialFor(provider) { + const meta = PROVIDERS[provider]; + if (!meta) return null; + const token = envText('COACH_API_KEY') || (meta.apiKeyEnv ? envText(meta.apiKeyEnv) : null); + return token ? { type: 'apikey', account: null, token } : null; +} + // Providers this build can drive. `runtime` is what the adapter runs. Adding one is an adapter // file plus a row here — nothing else in the codebase branches on provider identity. The real // providers arrive with their adapters; this PR ships only the in-repo fixture, so an instance @@ -128,7 +174,19 @@ export function load() { if (cache) return cache; let stored = {}; try { stored = JSON.parse(fs.readFileSync(FILE, 'utf8')); } catch { /* absent = feature off */ } - cache = { ...DEFAULTS, ...stored, caps: { ...DEFAULTS.caps, ...(stored.caps || {}) } }; + // The environment sits between the built-in defaults and the file: it configures an instance + // that was never set up in the UI, and it never overrides a choice someone made in one. + const env = envPatch(); + cache = { + ...DEFAULTS, + ...env, + ...stored, + caps: { ...DEFAULTS.caps, ...(stored.caps || {}) }, + // The per-provider maps merge rather than replace: a file that holds a key for one provider + // must not wipe the endpoint the environment configured for another. + models: { ...(env.models || {}), ...(stored.models || {}) }, + providerOptions: { ...(env.providerOptions || {}), ...(stored.providerOptions || {}) }, + }; // Until v1.2.11 this file held ONE credential, ONE model and ONE binding — for whichever // provider was selected at the time. Lift each onto that provider. One-way on purpose: a @@ -154,10 +212,32 @@ export function load() { if (cache.authMode !== 'profile') cache.authMode = 'instance'; return cache; } +/** + * What actually goes to disk: the whole config, minus whatever the environment supplies. + * + * Writing those back would freeze this start-up's values into the file, and since the file + * outranks the environment, the operator's next change to `COACH_MODEL` would be silently + * ignored — a redeploy that looks like it did nothing. The token never reaches here at all: it + * is not a field of the config (see envCredentialFor). + */ +function persisted(config) { + const env = envPatch(); + const out = { ...config }; + for (const k of ['enabled', 'provider']) if (env[k] !== undefined && out[k] === env[k]) delete out[k]; + for (const k of ['models', 'providerOptions']) { + if (!env[k]) continue; + const merged = { ...(out[k] || {}) }; + for (const p of Object.keys(env[k])) { + if (JSON.stringify(merged[p]) === JSON.stringify(env[k][p])) delete merged[p]; + } + out[k] = merged; + } + return out; +} export function save(patch) { const next = { ...load(), ...patch }; cache = next; - atomicWrite(FILE, JSON.stringify(next, null, 2), 0o600); + atomicWrite(FILE, JSON.stringify(persisted(next), null, 2), 0o600); return next; } // Test seam: forget the in-memory copy so the next load() re-reads from disk. @@ -241,6 +321,12 @@ export function credentialFor(uid) { const rec = authFor(cfg); const auth = rec && rec.data ? decrypt(rec.data) : null; if (!auth || !auth.token) { + // Nothing was ever filed for this provider, so the environment may be carrying the key. + // Deliberately only in that case: a key that WAS filed and fails to decrypt stays a failure, + // because quietly spending a different credential would hide a broken file behind a key + // nobody knows is being used. + const fromEnv = rec ? null : envCredentialFor(cfg.provider); + if (fromEnv) return { ok: true, auth: { token: fromEnv.token }, type: 'apikey', account: null, mode: 'instance', fromEnv: true }; // An endpoint that takes no key (a model on the LAN) is connected without one. Only when // nothing was ever filed — a filed key that fails to decrypt is still a failure. if (providerMeta(cfg).keyOptional && !rec) return { ok: true, auth: null, type: null, account: null, mode: 'instance' }; @@ -302,7 +388,12 @@ export function isConnected() { if (cfg.provider === 'fixture') return true; if (cfg.authMode === 'profile') return true; const rec = authFor(cfg); - if (!rec) return !!providerMeta(cfg).keyOptional && !!baseUrlFor(cfg.provider, cfg); + if (!rec) { + // A key in the environment counts exactly like a pasted one for "can this instance reach a + // model"; without this the Coach would report itself unconfigured while holding a key. + if (envCredentialFor(cfg.provider)) return true; + return !!providerMeta(cfg).keyOptional && !!baseUrlFor(cfg.provider, cfg); + } return !!decrypt(rec.data); } diff --git a/api/test/coach-env.test.js b/api/test/coach-env.test.js new file mode 100644 index 0000000..26c59f0 --- /dev/null +++ b/api/test/coach-env.test.js @@ -0,0 +1,88 @@ +/* An instance configured entirely from its environment. + * + * A container should be able to start with its provider already in place — endpoint, model, key — + * with nobody opening an admin screen. What is asserted here is that the environment configures + * the Coach, that a pasted key still wins over it, and that the key never lands in the file the + * docs tell people to back up. + */ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { tempData } from './helpers.mjs'; + +tempData(); +process.env.COACH_PROVIDER = 'compatible'; +process.env.COACH_BASE_URL = 'https://ai.example.com'; +process.env.COACH_MODEL = 'vendor/model-1'; +process.env.COACH_API_KEY = 'sk-from-the-environment'; + +const cfg = await import('../coach/config.js'); +const { baseUrlFor } = await import('../coach/core/providers.js'); + +const coachFile = () => path.join(process.env.DATA_DIR, 'coach.json'); +const onDisk = () => (fs.existsSync(coachFile()) ? fs.readFileSync(coachFile(), 'utf8') : ''); + +test('the environment alone configures the provider, the endpoint, the model and the key', () => { + assert.equal(cfg.isEnabled(), true, 'naming a provider is the configuration'); + assert.equal(cfg.isConnected(), true); + const c = cfg.load(); + assert.equal(c.provider, 'compatible'); + assert.equal(cfg.modelFor(c), 'vendor/model-1'); + assert.equal(baseUrlFor('compatible', c), 'https://ai.example.com'); + + const cred = cfg.credentialFor('u1'); + assert.equal(cred.ok, true); + assert.equal(cred.auth.token, 'sk-from-the-environment'); + assert.equal(cred.fromEnv, true, 'a caller can tell a key it did not file'); +}); + +test('a credential pasted in the app still wins over the environment one', () => { + cfg.saveAuth('compatible', { type: 'apikey', account: 'admin', data: cfg.encrypt({ token: 'sk-pasted' }) }); + const cred = cfg.credentialFor('u1'); + assert.equal(cred.auth.token, 'sk-pasted'); + assert.equal(cred.fromEnv, undefined); + assert.equal(cfg.isConnected(), true); + // …and once it is removed, the environment is what is left. + cfg.saveAuth('compatible', null); + assert.equal(cfg.credentialFor('u1').auth.token, 'sk-from-the-environment'); +}); + +test('the environment key is never written to the config file', () => { + cfg.save({ caps: { perProfileDaily: 5, instanceDaily: 0 } }); + const written = onDisk(); + assert.ok(written.includes('perProfileDaily'), 'the patch itself is saved'); + assert.ok(!written.includes('sk-from-the-environment'), 'the key must not be in a file people back up'); + assert.ok(!written.includes('sk-pasted'), 'nor a pasted one in the clear — that is encrypted'); + assert.ok(!written.includes('COACH_API_KEY')); +}); + +test('what the environment supplies is not frozen into the file', () => { + // A saved config used to be written back whole, which would have pinned this start-up's values + // into the file — and the file outranks the environment, so a later change to COACH_MODEL would + // have been silently ignored. + const written = JSON.parse(onDisk() || '{}'); + assert.equal(written.provider, undefined); + assert.equal(written.enabled, undefined); + const text = JSON.stringify(written); + assert.ok(!text.includes('vendor/model-1'), 'the model the environment set is not pinned'); + assert.ok(!text.includes('ai.example.com'), 'nor the endpoint'); +}); + +test('the provider\'s own variable works too, and no provider at all turns nothing on', () => { + delete process.env.COACH_API_KEY; + process.env.OPENAI_COMPAT_API_KEY = 'sk-provider-variable'; + cfg.reset(); + assert.equal(cfg.credentialFor('u1').auth.token, 'sk-provider-variable'); + + delete process.env.COACH_PROVIDER; + delete process.env.COACH_BASE_URL; + delete process.env.COACH_MODEL; + delete process.env.OPENAI_COMPAT_API_KEY; + cfg.reset(); + // Back to the built-in default (the fixture), which is not a Coach anybody can use: the whole + // point of naming a provider in the environment is that naming nothing leaves the feature off. + assert.equal(cfg.load().provider, 'fixture'); + assert.equal(cfg.isEnabled(), false, 'no provider named, nothing turned on'); + assert.equal(cfg.isConnected(), false); +});