From 9bef3854903fcc4fed5a018b58e922c93740938f Mon Sep 17 00:00:00 2001 From: ehonis Date: Wed, 14 Oct 2026 20:35:43 -0400 Subject: [PATCH] WHOOP: read the burn from Bushido, not the Totem bridge Published from the private repository by oss-sync. - WHOOP: read the burn from Bushido, not the Totem bridge 19 files changed, 537 insertions(+), 111 deletions(-) --- .env.example | 13 +- AGENTS.md | 57 ++++--- README.md | 6 +- app/balance.test.jsx | 6 +- app/package.json | 2 +- app/src/lib/whoop.js | 2 +- app/src/settings.jsx | 46 +++++- app/src/today.jsx | 4 +- docs/self-hosting.md | 48 ++++-- mobile/src/features/settings/SettingsPane.tsx | 47 +++++- mobile/src/features/today/Today.tsx | 4 +- mobile/src/lib/whoop.ts | 2 +- server/auth.test.js | 53 +++++++ server/install.test.js | 48 +++++- server/server.js | 28 ++-- server/settings.js | 72 ++++++--- server/totem.js | 13 +- server/whoop.js | 51 +++--- server/whoop.test.js | 146 ++++++++++++++++++ 19 files changed, 537 insertions(+), 111 deletions(-) create mode 100644 server/whoop.test.js diff --git a/.env.example b/.env.example index 57ec503..6b3661f 100644 --- a/.env.example +++ b/.env.example @@ -55,8 +55,15 @@ KRAKATOA_NUTRITIONIX_KEY= # KRAKATOA_ASK_MODEL=claude-sonnet-5 # KRAKATOA_ASK_EFFORT=medium -# --- Totem bridge: habit push and WHOOP burn (optional, off by default) ---------- -# Krakatoa holds no WHOOP credentials; it reads them through a Totem bridge. +# --- WHOOP burn, read from Bushido (optional, off by default) -------------------- +# Krakatoa holds no WHOOP credentials; Bushido holds the grant and Krakatoa asks +# it (POST /api/whoop/owner). Off unless both are set, here or in Settings. +# BUSHIDO_API_URL=http://127.0.0.1:8099 +# BUSHIDO_API_TOKEN= +# KRAKATOA_WHOOP_STALE_MS=1200000 +# KRAKATOA_WHOOP_DAYS=30 + +# --- Totem bridge: habit push (optional, off by default) ------------------------- # Off unless KRAKATOA_TOTEM=1, KRAKATOA_TOTEM_URL is set, or Settings turns it on. # KRAKATOA_TOTEM=0 # KRAKATOA_TOTEM_URL=http://127.0.0.1:8787 @@ -66,8 +73,6 @@ BRIDGE_SECRET= # No default. (An install upgraded from before Settings records where it read it.) # KRAKATOA_TOTEM_ENV= # KRAKATOA_TOTEM_HABIT=krakatoa -# KRAKATOA_WHOOP_STALE_MS=1200000 -# KRAKATOA_WHOOP_DAYS=30 # --- Digest file (optional, off by default) -------------------------------------- # Write data/digest.json, a small summary of the last two weeks, after every diff --git a/AGENTS.md b/AGENTS.md index 9b48785..f22e3af 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -36,7 +36,7 @@ disk. Default port **8101**. | The generic foods | `content/basics.json` + `app/src/lib/basics.js` | | …and the script that generates them | `scripts/basics.build.mjs` | | Optional Totem bridge: habit push | `server/totem.js` | -| Optional Totem bridge: WHOOP's daily burn, and the deficit | `server/whoop.js` + `app/src/lib/whoop.js` | +| Optional WHOOP daily burn, read from Bushido, and the deficit | `server/whoop.js` + `app/src/lib/whoop.js` | | Chain menus (OPTIONAL file: every reader must cope with it absent) | `scripts/restaurants.build.mjs` → `content/restaurants.json` | | …one reader per way a chain publishes | `scripts/restaurants/*.mjs` | | …and the bowl or order built from one | `app/src/lib/restaurants.js` + `app/src/bowl.jsx` | @@ -120,7 +120,8 @@ shows which build is being served. backslashes. Do not go back to a regex. - **Machine callers** (MCP clients, scripts) use `Authorization: Bearer `: the API token from Settings (`KRAKATOA_API_TOKEN`), or the Totem bridge - secret. A bearer opens `/api/*` and `/mcp`, never the pages. + secret. (The Bushido token goes the other way: Krakatoa sends it to Bushido, + and it opens nothing here.) A bearer opens `/api/*` and `/mcp`, never the pages. - **The iPhone app** (`mobile/`) signs in with the owner's password like a browser, but sends `X-Krakatoa-Client: native` and gets the session in the JSON reply instead of a cookie (also on a password change). It sends it back @@ -142,7 +143,9 @@ shows which build is being served. (`settingsWriteRefused`). Proxy mode on a non-loopback bind logs a warning. - **A changed bridge URL** sets `totem.ownSecretOnly` (`guardTotemUrl`), so neither `BRIDGE_SECRET` nor Totem's .env is sent to the new host; only a - secret entered for it. + secret entered for it. A changed Bushido URL does the same for + `BUSHIDO_API_TOKEN` (`bushido.ownTokenOnly`, `guardBushidoUrl`); the PUT + runs both through `guardUrls`. ### Settings (`server/settings.js`, `app/src/settings.jsx`) @@ -168,9 +171,13 @@ reaches outside the app off**: - **AI.** Without a CLI, `/api/label` and `/api/ask` answer 503 with `setup: 'ai'`, and the screens show "Set up AI in Settings" instead of an error. -- **The Totem bridge** (WHOOP burn and the habit push). While off, nothing - contacts it, `/api/whoop` answers `configured: false`, and the day has no - energy panel. `totemConfig()` returning null is the off switch everywhere. +- **The Totem bridge** (the habit push). While off, nothing contacts it. + `totemConfig()` returning null is the off switch everywhere. +- **Bushido** (WHOOP burn). On only with a URL and a token + (`BUSHIDO_API_URL`, `BUSHIDO_API_TOKEN`, or Settings); there is no default + URL and no on switch. While off, nothing contacts it, `/api/whoop` answers + `configured: false`, `features.whoop` is false, and the day has no energy + panel. `bushidoConfig()` returning null is the off switch. - **The digest file** (`data/digest.json`). `/api/digest` still answers live. `settings.migrate()` runs once per data dir (when `settings.json` is absent). @@ -179,12 +186,14 @@ bridge and the digest on. With no `owner.json` it predates sign-in and gets `auth.mode: proxy`; **with an `owner.json` it never gets proxy**. The legacy Totem `.env` path is recorded only if that file exists; it has no default. Nobody upgrading should find their setup switched off. The "off" defaults are -for fresh installs only. `server/install.test.js` boots real servers for all +for fresh installs only. (One deliberate exception: WHOOP moved from the bridge +to Bushido, and an upgraded install needs the Bushido URL and token set to keep +the energy panel. Nothing is migrated for it.) `server/install.test.js` boots real servers for all three paths (fresh, proxy, existing). Keep it passing. There is no `examples/` directory and nothing is seeded: `content/` is generic (USDA foods and chain menus), and there are no timers, jobs or scheduled tasks. -The only background work is a WHOOP refresh on read when the bridge is on, and +The only background work is a WHOOP refresh on read when Bushido is set up, and resuming Ask AI threads that were mid-run at restart. ## 3. A barcode carries no nutrition, and that is the whole design @@ -370,10 +379,17 @@ Two traps: ### WHOOP: under or over (optional) -`GET /api/whoop` mirrors the Totem bridge into `data/whoop.json`, and only when -the bridge is on. **One token holder**: WHOOP rotates its refresh token and -invalidates the old pair, so the bridge holds it and Krakatoa never does. The -cache is **disposable**, and **nothing blocks on it**. +`GET /api/whoop` mirrors Bushido's WHOOP figures into `data/whoop.json`, and +only when Bushido is set up. **One token holder**: WHOOP rotates its refresh +token and invalidates the old pair, so Bushido holds it and Krakatoa never +does. Krakatoa asks with `POST /api/whoop/owner`, +`Authorization: Bearer ` and +`{ "method": "training", "args": [{ "days": N }] }`; Bushido answers +`200 { result }` (the training payload; only `recovery[].calories`, `strain` +and `body.weightLb` are kept) or a non-2xx `{ error, needsReauth?, rateLimited? }` +(409 no WHOOP set up, 403 wrong token, 429 rate limited, 502 WHOOP failed), +whose `error` is shown verbatim. The cache is **disposable**, and **nothing +blocks on it**. Pinned in `server/whoop.test.js`. The design problem is honesty. `balanceFor` handles it, and the flags are the feature: @@ -385,9 +401,9 @@ feature: - **`untracked`**: a day with nothing logged is not a 2,800 deficit, it is a day the app was not opened. -**The refresh button** is the only synchronous path to the bridge. It shows how -stale the number is; **a failed pull keeps the previous numbers** with the -bridge's own error text beside them; with no balance at all, an error still +**The refresh button** is the only synchronous path to Bushido. It shows how +stale the number is; **a failed pull keeps the previous numbers** with +Bushido's own error text beside them; with no balance at all, an error still renders the panel and the button. **The panel is a tug of war on one track**: eaten from the left, burned from the @@ -580,7 +596,7 @@ the model in 30 KB chunks, three at a time, every item verified. Use the regional variants, normalise categories, and do not count identical numbers under another label as a second size. -## 12. Other programs: MCP, and the optional Totem bridge +## 12. Other programs: MCP, the optional Totem bridge, and Bushido **MCP.** `server/mcp.js` serves MCP Streamable HTTP (JSON replies) at `POST /mcp`, with a bearer token unless sign-in is left to a proxy. 16 tools: `get_day`, @@ -599,7 +615,7 @@ prefix because gateways namespace them (`krakatoa__log_food`). - **Every tool states all four hints**; deletes are `destructiveHint` and the descriptions say to ask first. Tested in `server/mcp.test.js`. -**The Totem bridge** (off by default; Settings or `KRAKATOA_TOTEM=1`). Two wires: +**The Totem bridge** (off by default; Settings or `KRAKATOA_TOTEM=1`). One wire: - **A habit push.** `server/totem.js` posts one record per DAY: calories as `value`, the macro split as `parts`, the foods as the note, `count` = foods @@ -607,8 +623,11 @@ prefix because gateways namespace them (`krakatoa__log_food`). the last write win). **Fire and forget**: the bridge being down never fails a log. **The streak is whether the day was TRACKED**, not whether it was a good day, so bad days still get logged. `node server/totem.js --ensure` creates the - habit once; it is deliberately never called from the request path. -- **WHOOP burn**, read from the bridge (§8). + habit once; it is deliberately never called from the request path. The + Settings Test only reads (`findHabit`). + +**Bushido** (off until a URL and token are set): WHOOP burn, read from Bushido, +which holds the WHOOP grant (§8). It used to come through the bridge. **The digest file** (off by default): every write regenerates `data/digest.json`: today's foods, a fortnight of totals, targets, the average diff --git a/README.md b/README.md index 6b72992..1b0defb 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,8 @@ Formerly called **Fuel** (renamed 2026-10-02). that it is one tap. Favourites ("stars") pin foods you buy. - **One screen per food.** It shows the food, a way to fix the entry you tapped, and every time you have logged it. -- **WHOOP energy balance.** Shows eaten vs. burned on one track. It won't give a +- **WHOOP energy balance** (optional, read from Bushido, which holds the WHOOP + connection). Shows eaten vs. burned on one track. It won't give a verdict on a day that is still being counted or was never logged, and compares a partial day against your typical complete day. - **Water**, with quick-add buttons for common container sizes and a 64 oz @@ -83,7 +84,8 @@ server/ Node HTTP server with zero npm dependencies (Node built-ins only) nutrition.js normalises both databases into one food shape label.js, ai.js, aithreads.js, learned.js label reader and Ask AI (headless `claude`) mcp.js MCP Streamable HTTP endpoint - whoop.js, totem.js optional bridge integration (WHOOP burn, habit push) + whoop.js optional WHOOP burn, read from Bushido (which holds the grant) + totem.js optional Totem bridge: the habit push digest.js compact day rollup written to data/digest.json for other tools content/ generated data: basics.json (USDA); restaurants.json (chains, optional) scripts/ generators for content/, with one reader per way a chain publishes diff --git a/app/balance.test.jsx b/app/balance.test.jsx index b69403d..e57e929 100644 --- a/app/balance.test.jsx +++ b/app/balance.test.jsx @@ -131,9 +131,9 @@ test('a failed pull keeps the numbers AND says why they did not move', () => { test('with NO balance at all, an error still renders a panel with a way out', () => { // This is the state someone presses refresh to escape. Rendering nothing would - // leave a bridge that is down looking exactly like a feature that is off. - const html = render(null, { onRefresh: () => {}, whoop: { error: 'no BRIDGE_SECRET found' } }) - assert.ok(html.includes('no BRIDGE_SECRET found')) + // leave a Bushido that is down looking exactly like a feature that is off. + const html = render(null, { onRefresh: () => {}, whoop: { error: 'Bushido has no WHOOP connection' } }) + assert.ok(html.includes('Bushido has no WHOOP connection')) assert.ok(html.includes('Refresh from WHOOP')) // …but no error and no balance is still nothing, as before. assert.equal(render(null, { onRefresh: () => {}, whoop: { burn: {} } }), '') diff --git a/app/package.json b/app/package.json index 925df05..a791a2d 100644 --- a/app/package.json +++ b/app/package.json @@ -17,7 +17,7 @@ "test:digest": "node ../server/digest.test.js", "lint": "eslint src", "test:combos": "node combos.test.js", - "test:whoop": "node whoop.test.js", + "test:whoop": "node whoop.test.js && node ../server/whoop.test.js", "test:balance": "esbuild balance.test.jsx --bundle --platform=node --format=esm --jsx=automatic --packages=external --outfile=.balance.mjs --log-level=error && node .balance.mjs", "test:macros": "node macros.test.js", "test:restaurants": "node restaurants.test.js", diff --git a/app/src/lib/whoop.js b/app/src/lib/whoop.js index 4c789b4..5b99cdb 100644 --- a/app/src/lib/whoop.js +++ b/app/src/lib/whoop.js @@ -7,7 +7,7 @@ * background, so a reload is as current as anything needs to be. * * `refresh` is the exception, and it is a BUTTON. It is the one synchronous path - * to the bridge — everything else serves the cache and refetches behind itself — + * to Bushido — everything else serves the cache and refetches behind itself — * because the case it exists for is standing there having just finished a * workout, wanting the number to catch up now rather than within twenty minutes. */ diff --git a/app/src/settings.jsx b/app/src/settings.jsx index 970db73..5044f1c 100644 --- a/app/src/settings.jsx +++ b/app/src/settings.jsx @@ -2,7 +2,8 @@ * Krakatoa — Settings. * * Everything a new install needs, set up in the browser: the account, the AI, - * the food-database keys, and the optional connection to a Totem bridge. Each + * the food-database keys, and the optional connections to Bushido (WHOOP) and a + * Totem bridge (the habit push). Each * section saves on its own. A field set by the server's environment is shown * locked with the variable's name, because the environment always wins and an * editable box that changes nothing is a lie. Stored secrets never come back @@ -300,6 +301,43 @@ function Databases({ s, d, save, test }) { /* ------------------------------------------------------------- connections */ +/* WHOOP's burn, read from Bushido, which holds the WHOOP grant. On when it has + a URL and a token; there is no switch, because there is no default URL. */ +function BushidoLink({ s, d, save, test }) { + const [result, setResult] = useState(null) + const b = s.bushido + if (!b) return null + const onSave = async (doTest) => { + setResult({ busy: doTest ? 'Connecting…' : 'Saving…' }) + try { + if (d.draft.bushido) await save('bushido') + setResult(doTest ? await test('bushido') : { ok: true, detail: 'Saved.' }) + } catch (e) { setResult({ ok: false, detail: e.message }) } + } + return ( +
+

WHOOP, through Bushido (optional)

+

+ For people who also run Bushido, the training app that holds the WHOOP connection. With a Bushido URL and token, the day + shows WHOOP's calorie burn beside what you ate. Without them, Krakatoa never contacts it and the energy panel is hidden. +

+

+ {b.connected ? 'Connected' : 'Not connected'} +

+ + +
+ + +
+ +
+ ) +} + function Connections({ s, d, save, test, saveNow }) { const [result, setResult] = useState(null) const t = s.totem @@ -315,9 +353,8 @@ function Connections({ s, d, save, test, saveNow }) {

Totem bridge (optional)

- For people who also run Totem, a personal assistant that holds the WHOOP connection. With the bridge on, the day shows - WHOOP's calorie burn beside what you ate, and each logged day is written to a Totem habit. Off, Krakatoa never contacts it - and the energy panel is hidden. + For people who also run Totem, a personal assistant. With the bridge on, each logged day is written to a Totem habit. + Off, Krakatoa never contacts it.

{t.connected ? 'Connected' : 'Not connected'} @@ -445,6 +482,7 @@ export default function SettingsPane({ section = null, onClose }) { + diff --git a/app/src/today.jsx b/app/src/today.jsx index 80f27b8..217d5c9 100644 --- a/app/src/today.jsx +++ b/app/src/today.jsx @@ -152,7 +152,7 @@ function ago(iso) { export function Balance({ balance, whoop, onRefresh, refreshing }) { /* * The panel renders for the ERROR case even with no balance, because that is - * the state someone presses refresh to get out of: a bridge that is down or a + * the state someone presses refresh to get out of: a Bushido that is down or a * grant that needs reconnecting says so here, with WHOOP's own wording, rather * than the card silently not existing. */ @@ -257,7 +257,7 @@ export function Balance({ balance, whoop, onRefresh, refreshing }) { {/* A failed pull leaves the previous cache in place and carries its reason alongside — so the numbers above are still real and this says why they - did not move. The bridge's wording travels verbatim because it names + did not move. Bushido's wording (WHOOP's, passed on) travels verbatim because it names the fix ("reconnect WHOOP", "authorized without read:workout"). */} {err && (

diff --git a/docs/self-hosting.md b/docs/self-hosting.md index 2902952..be47d56 100644 --- a/docs/self-hosting.md +++ b/docs/self-hosting.md @@ -118,7 +118,10 @@ with the Totem bridge and the digest file still on. If there is no proxy mode. An owner account means built-in sign-in, never proxy. If `$HOME/projects/personal-assistant/.env` exists, it is recorded as the place the bridge secret is read from; there is no default for that path otherwise. That is how the install -already behaved, so it keeps working with no env change. To switch to built-in +already behaved, so it keeps working with no env change. The one exception is +WHOOP: it used to come through the Totem bridge and now comes from Bushido, so +an install that showed WHOOP's burn needs `BUSHIDO_API_URL` and +`BUSHIDO_API_TOKEN` (or Settings) to keep it. To switch to built-in sign-in later, set `KRAKATOA_AUTH=builtin` and use the printed setup link. ## Configuration @@ -152,7 +155,7 @@ written: Nutritionix closed its free tier. Chain menus don't depend on it. There are no OAuth integrations in this app, so there are no redirect URIs to -register. WHOOP is reached only through the Totem bridge (below). +register. WHOOP is reached only through Bushido (below). ### Label reader and Ask AI @@ -167,23 +170,38 @@ effort can be chosen there too; the defaults are `claude-sonnet-5` and `medium`. Without the CLI, the label form still works by hand, and the photo and Ask AI screens show a "Set up AI in Settings" prompt. -### Totem bridge: WHOOP and the habit push +### WHOOP, through Bushido + +Krakatoa holds no WHOOP credentials. It can read the day's burn from Bushido, +the author's training app, which holds the WHOOP grant: Krakatoa sends +`POST /api/whoop/owner` with +`Authorization: Bearer ` and the body +`{ "method": "training", "args": [{ "days": 30 }] }`, and keeps only the daily +calories (and the body weight) from the answer. This is **off until both a URL +and a token are set**, in Settings → WHOOP, through Bushido, or with +`BUSHIDO_API_URL` (a loopback address such as `http://127.0.0.1:8099` is +typical) and `BUSHIDO_API_TOKEN`. There is no default URL. While it is off, +Krakatoa never contacts Bushido, `/api/whoop` answers `configured: false`, and +the day screen has no energy panel. Bushido's error text (its "no WHOOP set +up", a wrong token, a rate limit, or WHOOP's own "reconnect WHOOP") is shown +beside the refresh button as it arrives. Changing the URL in Settings stops the +existing token from being sent: enter the token for the new URL along with it. + +Anyone running this without Bushido could replace `server/whoop.js` with a +reader for some other source of daily energy expenditure. + +### Totem bridge: the habit push -Krakatoa holds no WHOOP credentials. It can read the day's burn from a bridge -run by the author's personal assistant, Totem, and write one habit record per -logged day to the same bridge. This is **off on a fresh install**. While it is -off, Krakatoa never contacts the bridge, `/api/whoop` answers -`configured: false`, and the day screen has no energy panel. Turn it on in -Settings → Totem bridge, or with `KRAKATOA_TOTEM=1` or `KRAKATOA_TOTEM_URL`. It +Krakatoa can write one habit record per logged day to a bridge run by the +author's personal assistant, Totem. This is **off on a fresh install**. While +it is off, Krakatoa never contacts the bridge. Turn it on in Settings → Totem +bridge, or with `KRAKATOA_TOTEM=1` or `KRAKATOA_TOTEM_URL`. It needs a bridge URL (default `http://127.0.0.1:8787`) and the bridge secret: either `BRIDGE_SECRET`, one pasted in Settings, or the `BRIDGE_SECRET=` line of Totem's `.env` (`KRAKATOA_TOTEM_ENV`, which has no default). Changing the bridge URL in Settings stops any existing secret from being sent: enter the secret for the new -URL along with it. To create the habit once, run `node server/totem.js --ensure`. -AGENTS.md §3e and §4 have the details. - -Anyone running this without Totem could replace `server/whoop.js` with a -reader for some other source of daily energy expenditure. +URL along with it. To create the habit once, run `node server/totem.js --ensure`; +the Test button checks that the habit is there. ### MCP @@ -215,7 +233,7 @@ These are disposable caches, safe to delete: - `data/foods.json` holds every food that has resolved - `data/images/` holds proxied product photos -- `data/whoop.json` mirrors the bridge +- `data/whoop.json` mirrors Bushido's WHOOP figures `data/ai/` holds Ask AI threads and their photos. `data/menus/learned.json` holds menus Ask AI has learned. `data/settings.json` and `data/owner.json` hold the diff --git a/mobile/src/features/settings/SettingsPane.tsx b/mobile/src/features/settings/SettingsPane.tsx index 402b1a7..473eedf 100644 --- a/mobile/src/features/settings/SettingsPane.tsx +++ b/mobile/src/features/settings/SettingsPane.tsx @@ -2,7 +2,8 @@ * Krakatoa — Settings. Ported from app/src/settings.jsx. * * Everything a new install needs, set up from the app: the account, the AI, - * the food-database keys, and the optional connection to a Totem bridge. Each + * the food-database keys, and the optional connections to Bushido (WHOOP) and a + * Totem bridge (the habit push). Each * section saves on its own. A field set by the server's environment is shown * locked with the variable's name, because the environment always wins and an * editable box that changes nothing is a lie. Stored secrets never come back @@ -398,6 +399,44 @@ function Databases({ s, d, save, test }: { s: any; d: D; save: Save; test: Test /* ------------------------------------------------------------- connections */ +/* WHOOP's burn, read from Bushido, which holds the WHOOP grant. On when it has + a URL and a token; there is no switch, because there is no default URL. A + server from before Bushido sends no `bushido` section, and then it is hidden. */ +function BushidoLink({ s, d, save, test }: { s: any; d: D; save: Save; test: Test }) { + const [result, setResult] = useState(null) + const b = s.bushido + if (!b) return null + const onSave = async (doTest: boolean) => { + setResult({ busy: doTest ? 'Connecting…' : 'Saving…' }) + try { + if (d.draft.bushido) await save('bushido') + setResult(doTest ? await test('bushido') : { ok: true, detail: 'Saved.' }) + } catch (e: any) { setResult({ ok: false, detail: e.message }) } + } + return ( +

+ + + For people who also run Bushido, the training app that holds the WHOOP connection. With a Bushido URL and token, the day + shows WHOOP's calorie burn beside what you ate. Without them, Krakatoa never contacts it and the energy panel is hidden. + + + {b.connected ? 'Connected' : 'Not connected'} + + + + + onSave(true)} /> + onSave(false)} /> + + +
+ ) +} + function Connections({ s, d, save, test, saveNow }: { s: any; d: D; save: Save; test: Test; saveNow: SaveNow }) { const [result, setResult] = useState(null) const t = s.totem @@ -413,9 +452,8 @@ function Connections({ s, d, save, test, saveNow }: { s: any; d: D; save: Save;
- For people who also run Totem, a personal assistant that holds the WHOOP connection. With the bridge on, the day shows - WHOOP's calorie burn beside what you ate, and each logged day is written to a Totem habit. Off, Krakatoa never contacts it - and the energy panel is hidden. + For people who also run Totem, a personal assistant. With the bridge on, each logged day is written to a Totem habit. + Off, Krakatoa never contacts it. {t.connected ? 'Connected' : 'Not connected'} @@ -560,6 +598,7 @@ export default function SettingsPane() { setAiY(e.nativeEvent.layout.y)} /> + diff --git a/mobile/src/features/today/Today.tsx b/mobile/src/features/today/Today.tsx index d6817a6..246416a 100644 --- a/mobile/src/features/today/Today.tsx +++ b/mobile/src/features/today/Today.tsx @@ -181,7 +181,7 @@ function ago(iso?: string) { export function Balance({ balance, whoop, onRefresh, refreshing }: { balance: BalanceT | null; whoop: Whoop | null; onRefresh?: () => void; refreshing: boolean }) { /* * The panel renders for the ERROR case even with no balance, because that is - * the state someone presses refresh to get out of: a bridge that is down or a + * the state someone presses refresh to get out of: a Bushido that is down or a * grant that needs reconnecting says so here, with WHOOP's own wording, rather * than the card silently not existing. */ @@ -276,7 +276,7 @@ export function Balance({ balance, whoop, onRefresh, refreshing }: { balance: Ba {/* A failed pull leaves the previous cache in place and carries its reason alongside — so the numbers above are still real and this says why they - did not move. The bridge's wording travels verbatim because it names + did not move. Bushido's wording (WHOOP's, passed on) travels verbatim because it names the fix ("reconnect WHOOP", "authorized without read:workout"). */} {err ? ( {err} diff --git a/mobile/src/lib/whoop.ts b/mobile/src/lib/whoop.ts index 2bdb6a1..c67a5dc 100644 --- a/mobile/src/lib/whoop.ts +++ b/mobile/src/lib/whoop.ts @@ -7,7 +7,7 @@ * background, so a reload is as current as anything needs to be. * * `refresh` is the exception, and it is a BUTTON. It is the one synchronous path - * to the bridge — everything else serves the cache and refetches behind itself — + * to Bushido — everything else serves the cache and refetches behind itself — * because the case it exists for is standing there having just finished a * workout, wanting the number to catch up now rather than within twenty minutes. * diff --git a/server/auth.test.js b/server/auth.test.js index adb39db..0047f05 100644 --- a/server/auth.test.js +++ b/server/auth.test.js @@ -158,6 +158,7 @@ test('a fresh data dir gets settings with every outside link off', () => { assert.equal(e.auth.mode, 'builtin') assert.equal(e.totem.enabled.value, false) assert.equal(S.totemConfig(e), null) + assert.equal(S.bushidoConfig(e), null, 'no Bushido, so no WHOOP') assert.equal(e.digestFile.value, false) assert.equal(e.usda.value, '') }) @@ -312,6 +313,58 @@ test("Totem's .env has no default; an upgraded install records it only if it exi assert.equal(S.totemConfig(s2.effective()).secret, 'abc') }) +test('Bushido is on only with a URL and a token, env first', () => { + const dir = tmp() + const mk = (env) => S.makeSettings({ dataDir: dir, env: { HOME: dir, ...env }, log: () => {} }) + assert.equal(S.bushidoConfig(mk({}).effective()), null) + assert.equal(S.bushidoConfig(mk({ BUSHIDO_API_URL: 'http://127.0.0.1:8099' }).effective()), null, 'a URL alone is off') + assert.equal(S.bushidoConfig(mk({ BUSHIDO_API_TOKEN: 't' }).effective()), null, 'a token alone is off: there is no default URL') + assert.deepEqual(S.bushidoConfig(mk({ BUSHIDO_API_URL: 'http://127.0.0.1:8099/', BUSHIDO_API_TOKEN: 'tok' }).effective()), + { url: 'http://127.0.0.1:8099', token: 'tok' }) + // An existing install keeps the bridge but gets no Bushido: nothing is migrated. + const old = tmp() + fs.writeFileSync(path.join(old, 'state.json'), '{"entries":{}}') + const so = S.makeSettings({ dataDir: old, env: { HOME: old }, log: () => {} }) + so.migrate() + assert.equal(so.stored().bushido, undefined) + assert.equal(S.bushidoConfig(so.effective()), null) + + // From Settings, and the token never goes back to the browser. + const s = mk({}) + s.save(S.guardUrls(S.cleanPatch({ bushido: { url: 'http://127.0.0.1:8099', token: 'stored-bushido-token' } }), s.effective())) + assert.deepEqual(S.bushidoConfig(s.effective()), { url: 'http://127.0.0.1:8099', token: 'stored-bushido-token' }) + const view = S.publicView(s.effective()) + assert.equal(view.bushido.connected, true) + assert.equal(view.bushido.token.set, true) + assert.ok(!JSON.stringify(view).includes('stored-bushido-token')) + assert.deepEqual(S.cleanPatch({ bushido: { token: view.bushido.token.value } }), {}, 'the mask coming back is not a token') + assert.throws(() => S.cleanPatch({ bushido: { url: 'javascript:alert(1)' } }), /not a URL/) + // Env beats the stored value, and shows locked. + const d2 = tmp() + S.makeSettings({ dataDir: d2, env: {}, log: () => {} }).save({ bushido: { token: 'stored' } }) + const e = S.makeSettings({ dataDir: d2, env: { BUSHIDO_API_TOKEN: 'env-token' }, log: () => {} }).effective() + assert.equal(e.bushido.token.value, 'env-token') + assert.equal(S.publicView(e).bushido.token.locked, true) +}) + +test('a new Bushido URL does not inherit the old token', () => { + const dir = tmp() + const env = { HOME: dir, BUSHIDO_API_URL: 'http://127.0.0.1:8099', BUSHIDO_API_TOKEN: 'env-token' } + const s = S.makeSettings({ dataDir: dir, env: { HOME: dir }, log: () => {} }) + const withEnv = () => S.makeSettings({ dataDir: dir, env, log: () => {} }).effective() + // The same URL (give or take a slash) keeps the token. + s.save(S.guardUrls(S.cleanPatch({ bushido: { url: 'http://127.0.0.1:8099/' } }), withEnv())) + assert.equal(S.bushidoConfig(withEnv()).token, 'env-token') + // A different one sends nothing until a token is entered for it. + s.save(S.guardUrls(S.cleanPatch({ bushido: { url: 'https://elsewhere.example' } }), withEnv())) + assert.equal(s.stored().bushido.ownTokenOnly, true) + assert.equal(S.bushidoConfig(withEnv()), null, 'BUSHIDO_API_TOKEN is not sent to the new host') + s.save(S.guardUrls(S.cleanPatch({ bushido: { token: 'typed-for-new-url' } }), withEnv())) + assert.equal(S.bushidoConfig(withEnv()).token, 'typed-for-new-url') + // And the bridge guard is untouched by a Bushido patch. + assert.deepEqual(S.guardUrls({ bushido: { token: 'x' } }, withEnv()), { bushido: { token: 'x' } }) +}) + test("a new bridge URL does not inherit the old secret", () => { const dir = tmp() fs.writeFileSync(path.join(dir, 'state.json'), '{}') diff --git a/server/install.test.js b/server/install.test.js index 57e0bd4..657497b 100644 --- a/server/install.test.js +++ b/server/install.test.js @@ -7,12 +7,12 @@ * - FRESH: nothing is reachable until the owner is created from the one-time * setup link printed to stdout; then the session cookie works, a bearer * token works for machine callers, and every outside link (AI, Totem bridge, - * WHOOP, digest file) is off and says so instead of failing. + * WHOOP through Bushido, digest file) is off and says so instead of failing. * - PROXY: KRAKATOA_AUTH=proxy asks for no sign-in at all. * - EXISTING: a data dir that already holds a log behaves as it did before * sign-in existed, with no new env. * - * HOME and PATH point at empty places, so no real `claude` or Totem is found. + * HOME and PATH point at empty places, so no real `claude`, Totem or Bushido is found. */ const assert = require('assert') @@ -155,6 +155,9 @@ test('fresh install: setup token, owner, session, bearer, everything off', async assert.match(r.json.error, /Settings/) r = await http(s.base, '/api/settings/test', { method: 'POST', cookie, body: { what: 'totem' } }) assert.equal(r.json.ok, false) + r = await http(s.base, '/api/settings/test', { method: 'POST', cookie, body: { what: 'bushido' } }) + assert.equal(r.json.ok, false) + assert.match(r.json.detail, /URL and a token/) // Settings: secrets go in and never come back out. r = await http(s.base, '/api/settings', { method: 'PUT', cookie, body: { usda: { key: 'usda-secret-123456' }, auth: { mode: 'proxy' } } }) // gitleaks:allow (test fixture) @@ -362,6 +365,47 @@ test('no chain menu file: the server, the menus and the MCP all work without it' assert.doesNotMatch(s.log(), /restaurants|ENOENT|Error/i, 'nothing logged about the missing file') }) +/* ---------------------------------------------------------------- bushido */ + +test('WHOOP comes from Bushido when its URL and token are set, and from nowhere else', async () => { + const seen = [] + const fake = require('http').createServer((req, res) => { + let raw = '' + req.on('data', c => { raw += c }) + req.on('end', () => { + seen.push({ url: req.url, auth: req.headers.authorization, body: raw }) + res.writeHead(200, { 'content-type': 'application/json' }) + res.end(JSON.stringify({ result: { ok: true, body: { weightLb: 170 }, recovery: [{ date: '2026-10-13', calories: 2500, strain: 9 }] } })) + }) + }) + await new Promise(r => fake.listen(0, '127.0.0.1', r)) + try { + const url = `http://127.0.0.1:${fake.address().port}` + const s = await boot({ KRAKATOA_AUTH: 'proxy', BUSHIDO_API_URL: `${url}/`, BUSHIDO_API_TOKEN: 'bushido-token-xyz' }) // gitleaks:allow (test fixture) + const me = (await http(s.base, '/api/me')).json + assert.equal(me.features.whoop, true) + assert.equal(me.features.totem, false, 'the bridge is a separate switch') + + const set = await http(s.base, '/api/settings') + assert.ok(!set.text.includes('bushido-token-xyz'), 'the token is masked') + assert.equal(set.json.bushido.connected, true) + assert.equal(set.json.bushido.token.locked, true) + + const r = await http(s.base, '/api/whoop/pull', { method: 'POST' }) + assert.equal(r.json.configured, true) + assert.deepEqual(r.json.burn, { '2026-10-13': { kcal: 2500, strain: 9 } }) + assert.equal(seen.at(-1).url, '/api/whoop/owner') + assert.equal(seen.at(-1).auth, 'Bearer bushido-token-xyz') + assert.deepEqual(JSON.parse(seen.at(-1).body), { method: 'training', args: [{ days: 30 }] }) + + const t = await http(s.base, '/api/settings/test', { method: 'POST', body: { what: 'bushido' } }) + assert.equal(t.json.ok, true) + assert.match(t.json.detail, /1 days of WHOOP burn/) + } finally { + await new Promise(r => fake.close(r)) + } +}) + test('existing install with KRAKATOA_AUTH=builtin asks for setup', async () => { const s = await boot({ KRAKATOA_AUTH: 'builtin' }, { 'state.json': '{"entries":{}}' }) assert.ok(s.token) diff --git a/server/server.js b/server/server.js index 97352d4..0017cad 100644 --- a/server/server.js +++ b/server/server.js @@ -12,7 +12,7 @@ * GET /api/me who is signed in, and which features are configured * GET|PUT /api/settings Settings, secrets masked. See server/settings.js. * GET /api/settings/ai/status is the CLI installed and signed in - * POST /api/settings/test { what: 'ai'|'usda'|'nutritionix'|'totem' } + * POST /api/settings/test { what: 'ai'|'usda'|'nutritionix'|'totem'|'bushido' } * POST /api/settings/token a new API token for machine callers (shown once) * GET /api/health liveness + paths * GET /api/state { version, updatedAt, state } @@ -31,7 +31,7 @@ * GET /api/restaurant?q= chain menu items (Nutritionix; needs a key) * GET /api/restaurant/item?id= one menu item in full, with its macros * GET /api/whoop cached daily calorie burn (data/whoop.json) - * POST /api/whoop/pull refetch from the bridge now (the button) + * POST /api/whoop/pull refetch from Bushido now (the button) * GET /api/image?gtin=&u= one product photo, proxied and cached to disk * GET /api/recent foods worth offering again, most recent first * GET /api/day?date= one day resolved: total, target, what filled it @@ -82,7 +82,7 @@ const BACKUP_DIR = path.join(DATA_DIR, 'backups') /* Proxied product photos, one JPEG per gtin. Disposable — delete it and the next scan refetches. Same disposition as data/foods.json. */ const IMAGE_DIR = path.join(DATA_DIR, 'images') -/* WHOOP's daily burn, mirrored from Totem's bridge. A CACHE — see server/whoop.js. */ +/* WHOOP's daily burn, mirrored from Bushido. A CACHE — see server/whoop.js. */ const WHOOP_FILE = path.join(DATA_DIR, 'whoop.json') const PORT = Number(process.env.KRAKATOA_PORT || 8101) @@ -275,10 +275,12 @@ const nixConfig = () => { return { nutritionixId: n.id.value, nutritionixKey: n.key.value } } const totemCfg = () => settingsMod.totemConfig(eff()) +const bushidoCfg = () => settingsMod.bushidoConfig(eff()) -/* WHOOP's burn comes only through the Totem bridge. With the bridge off, the - store answers "not configured" and the day screen shows no energy panel. */ -const whoopStore = whoop.makeStore(WHOOP_FILE, { config: totemCfg }) +/* WHOOP's burn comes only from Bushido, which holds the grant. With no Bushido + URL and token, the store answers "not configured" and the day screen shows + no energy panel. */ +const whoopStore = whoop.makeStore(WHOOP_FILE, { config: bushidoCfg }) /* -------------------------------------------------------------------- store */ @@ -608,7 +610,7 @@ async function api(req, res, url) { authMode: e.auth.mode, features: { ai: aiReady(), - whoop: !!totemCfg(), + whoop: !!bushidoCfg(), totem: !!totemCfg(), usda: !!e.usda.value, nutritionix: !!nutritionix.credsFrom(nixConfig()), @@ -623,7 +625,7 @@ async function api(req, res, url) { /* * Changing settings (and the Test buttons, which reach out from the server) * needs a signed-in browser session, never an API token: a token handed to an - * MCP client must not be able to rewrite keys or the bridge URL. In proxy mode + * MCP client must not be able to rewrite keys or the bridge and Bushido URLs. In proxy mode * there are no sessions, so it needs the request to come from this machine, * which is where cloudflared and local reverse proxies connect from. */ @@ -635,7 +637,7 @@ async function api(req, res, url) { if (p === '/api/settings' && req.method === 'PUT') { let patch const body = await readBody(req, 64 * 1024) - try { patch = settingsMod.guardTotemUrl(settingsMod.cleanPatch(body), eff()) } catch (e) { return send(res, 400, { error: e.message }) } + try { patch = settingsMod.guardUrls(settingsMod.cleanPatch(body), eff()) } catch (e) { return send(res, 400, { error: e.message }) } settings.save(patch) return send(res, 200, { ...settingsMod.publicView(eff()), owner: auth.owner() }) } @@ -1061,7 +1063,13 @@ async function testIntegration(what) { return done(true, `Answered with ${out.foods.length} results.`) } if (what === 'totem') { - if (!totemCfg()) return done(false, 'The Totem bridge is off, or no bridge secret was found.') + const cfg = totemCfg() + if (!cfg) return done(false, 'The Totem bridge is off, or no bridge secret was found.') + const found = await totem.findHabit(cfg) + return done(true, found ? `Connected. Habit "${found.id}" is there.` : `Connected, but there is no habit "${cfg.habit}" yet: run node server/totem.js --ensure.`) + } + if (what === 'bushido') { + if (!bushidoCfg()) return done(false, 'Bushido needs a URL and a token.') const doc = await whoopStore.refresh() return doc.error ? done(false, doc.error) : done(true, `Connected. ${Object.keys(doc.burn || {}).length} days of WHOOP burn.`) } diff --git a/server/settings.js b/server/settings.js index 5c7f1eb..8171624 100644 --- a/server/settings.js +++ b/server/settings.js @@ -13,10 +13,12 @@ * keeps its keys without a migration step. * * FRESH INSTALL vs EXISTING INSTALL. Everything that reaches another app (the - * Totem bridge: WHOOP burn and the habit push; the digest file Bushido reads) is - * OFF for a fresh install. An install that already has a log is an existing one, - * and the first time this code runs there it writes settings.json with those - * links ON, because that is how it already behaved. If it also has no owner + * Totem bridge's habit push; WHOOP burn read from Bushido; the digest file + * Bushido reads) is OFF for a fresh install. An install that already has a log + * is an existing one, and the first time this code runs there it writes + * settings.json with the bridge and the digest ON, because that is how it + * already behaved. Bushido has no on switch of its own: it is on when it has a + * URL and a token, and nothing is migrated for it. If it also has no owner * account it predates sign-in, so sign-in is left to the proxy it was behind. * An owner account means sign-in was already in use: never proxy then. * Nobody upgrading should find their setup quietly switched off. @@ -194,6 +196,19 @@ function makeSettings({ dataDir, env = process.env, log = console.log }) { const totemHabit = src('KRAKATOA_TOTEM_HABIT', s.totem?.habit) if (!totemHabit.value) { totemHabit.value = DEFAULTS.totemHabit; totemHabit.from = 'default' } + /* + * Bushido, the one holder of the owner's WHOOP grant. On when it has a URL + * and a token, from the environment or Settings; there is no default URL, + * so an install that never names one never contacts it. As with the bridge, + * a token from the environment belongs to the URL it was set up with: + * changing the URL in Settings sets `ownTokenOnly`. + */ + const bushidoUrl = src('BUSHIDO_API_URL', s.bushido?.url) + const bushidoOwnTokenOnly = s.bushido?.ownTokenOnly === true + const bushidoToken = bushidoOwnTokenOnly + ? (str(s.bushido?.token) ? { value: str(s.bushido.token), from: 'settings', env: 'BUSHIDO_API_TOKEN' } : { value: '', from: null, env: 'BUSHIDO_API_TOKEN' }) + : src('BUSHIDO_API_TOKEN', s.bushido?.token) + const digestFlag = flag(env.KRAKATOA_DIGEST_FILE) const digestFile = digestFlag !== undefined ? { value: digestFlag, from: 'env' } @@ -208,6 +223,7 @@ function makeSettings({ dataDir, env = process.env, log = console.log }) { usda, nutritionix: { id: nixId, key: nixKey }, totem: { enabled: totemEnabled, url: totemUrl, envFile: totemEnvFile, secret: totemSecret, habit: totemHabit, ownSecretOnly }, + bushido: { url: bushidoUrl, token: bushidoToken, ownTokenOnly: bushidoOwnTokenOnly }, digestFile, publicUrl, apiToken, @@ -241,6 +257,13 @@ function totemConfig(eff) { return { url: t.url.value.replace(/\/+$/, ''), secret: t.secret.value, habit: t.habit.value } } +/** Where WHOOP is read from: Bushido's `{ url, token }`, or null when it has no URL or no token. */ +function bushidoConfig(eff) { + const b = eff.bushido + if (!b?.url.value || !b.token.value) return null + return { url: b.url.value.replace(/\/+$/, ''), token: b.token.value } +} + /* -------------------------------------------------------- for the browser */ /* The last four characters, enough to tell two keys apart and no more. */ @@ -276,6 +299,11 @@ function publicView(eff) { habit: field(eff.totem.habit), connected: !!totemConfig(eff), }, + bushido: { + url: field(eff.bushido.url), + token: field(eff.bushido.token, true), + connected: !!bushidoConfig(eff), + }, digestFile: { value: eff.digestFile.value, from: eff.digestFile.from, locked: eff.digestFile.from === 'env' }, publicUrl: field(eff.publicUrl), apiToken: field(eff.apiToken, true), @@ -296,6 +324,7 @@ const EDITABLE = { usda: { key: 'secret' }, nutritionix: { id: 'text', key: 'secret' }, totem: { enabled: 'bool', url: 'url', secret: 'secret', habit: 'text' }, + bushido: { url: 'url', token: 'secret' }, digestFile: 'bool', publicUrl: 'url', } @@ -334,26 +363,33 @@ function cleanPatch(body) { } /* - * A changed (or cleared) bridge URL drops any secret it did not come with: the stored one, - * BRIDGE_SECRET and Totem's .env all belong to the old URL. Only a secret in - * the same patch goes with the new URL. Returns the patch to save. + * A changed (or cleared) URL drops any secret it did not come with: for the + * bridge the stored one, BRIDGE_SECRET and Totem's .env; for Bushido the stored + * token and BUSHIDO_API_TOKEN. All of them belong to the old URL. Only a secret + * in the same patch goes with the new URL. Returns the patch to save. */ -function guardTotemUrl(patch, eff) { - if (!patch?.totem || !('url' in patch.totem)) return patch - const url = patch.totem.url - // Clearing a stored URL sends the bridge somewhere else too (the env value or - // the default), so it is a change of destination like any other. Clearing +function guardUrl(patch, current, section, secretKey, onlyKey) { + if (!patch?.[section] || !('url' in patch[section])) return patch + const url = patch[section].url + // Clearing a stored URL sends the requests somewhere else too (the env value + // or the default), so it is a change of destination like any other. Clearing // when nothing was stored changes nothing. if (url === null) { - if (eff.totem.url.from !== 'settings') return patch - } else if (url.replace(/\/+$/, '') === eff.totem.url.value.replace(/\/+$/, '')) { + if (current.from !== 'settings') return patch + } else if (url.replace(/\/+$/, '') === current.value.replace(/\/+$/, '')) { return patch } - const totem = { ...patch.totem, ownSecretOnly: true } - if (!('secret' in patch.totem)) totem.secret = null - return { ...patch, totem } + const next = { ...patch[section], [onlyKey]: true } + if (!(secretKey in patch[section])) next[secretKey] = null + return { ...patch, [section]: next } } +const guardTotemUrl = (patch, eff) => guardUrl(patch, eff.totem.url, 'totem', 'secret', 'ownSecretOnly') +const guardBushidoUrl = (patch, eff) => guardUrl(patch, eff.bushido.url, 'bushido', 'token', 'ownTokenOnly') + +/** Every URL guard, for the Settings PUT. */ +const guardUrls = (patch, eff) => guardBushidoUrl(guardTotemUrl(patch, eff), eff) + /* ------------------------------------------------------------- AI status */ /** @@ -391,4 +427,4 @@ function aiReady(eff) { try { fs.accessSync(eff.ai.bin.value, fs.constants.X_OK); return true } catch { return false } } -module.exports = { makeSettings, publicView, cleanPatch, guardTotemUrl, aiEnv, aiStatus, aiReady, totemConfig, mask, secretFromEnvFile, AI_BACKENDS } +module.exports = { makeSettings, publicView, cleanPatch, guardTotemUrl, guardBushidoUrl, guardUrls, aiEnv, aiStatus, aiReady, totemConfig, bushidoConfig, mask, secretFromEnvFile, AI_BACKENDS } diff --git a/server/totem.js b/server/totem.js index 1ff4721..1c9caec 100644 --- a/server/totem.js +++ b/server/totem.js @@ -87,6 +87,13 @@ async function syncDay(state, digest, date, cfg) { } } +/** The habit this app writes to, or null when Totem does not have it. Read-only: the Settings Test. */ +async function findHabit(cfg) { + const payload = await call(cfg, 'GET', '/api/habits') + const habits = payload?.habits || payload || [] + return habits.find(h => h.id === cfg?.habit || String(h.name || '').toLowerCase() === HABIT_NAME.toLowerCase()) || null +} + /** * Create the habit if Totem does not have it. Idempotent and deliberately NOT * called from the request path — a food log must never create things in another @@ -94,9 +101,7 @@ async function syncDay(state, digest, date, cfg) { */ async function ensureHabit(cfg) { const HABIT_ID = cfg?.habit - const payload = await call(cfg, 'GET', '/api/habits') - const habits = payload?.habits || payload || [] - const found = habits.find(h => h.id === HABIT_ID || h.name.toLowerCase() === HABIT_NAME.toLowerCase()) + const found = await findHabit(cfg) if (found) return { created: false, id: found.id, name: found.name } await call(cfg, 'POST', '/api/habits', { @@ -120,7 +125,7 @@ async function ensureHabit(cfg) { const status = () => ({ ...last }) -module.exports = { syncDay, ensureHabit, status, noteFor } +module.exports = { syncDay, ensureHabit, findHabit, status, noteFor } /* node server/totem.js --ensure — create the habit in Totem, once. Reads the same settings the server does (KRAKATOA_DATA_DIR, env, data/settings.json). */ diff --git a/server/whoop.js b/server/whoop.js index 965f66d..cccc7da 100644 --- a/server/whoop.js +++ b/server/whoop.js @@ -3,20 +3,21 @@ * * What he BURNED, so the day can say whether he is under or over. WHOOP computes * a whole-day energy expenditure from heart rate plus basal rate and publishes it - * per cycle; the bridge already hands it over as `recovery[].calories`. + * per cycle; Bushido already hands it over as `recovery[].calories`. * * Three rules, inherited wholesale from Bushido and structural rather than a matter * of care (see `bushido/AGENTS.md` §6): * * - ONE TOKEN HOLDER. WHOOP rotates its refresh token on every refresh and - * invalidates the old pair, so exactly one process may hold it — Totem. - * This app reads `GET /api/whoop/training` on the bridge with the same - * BRIDGE_SECRET the habit push uses, exactly as Bushido does. Copying the - * credentials here would give one member two grants and silently kill one. + * invalidates the old pair, so exactly one process may hold it — Bushido. + * This app asks Bushido for the owner's training data + * (`POST /api/whoop/owner`, method `training`) with BUSHIDO_API_TOKEN. + * Copying the credentials here would give one member two grants and + * silently kill one. * - THE CACHE IS DISPOSABLE. `data/whoop.json` is a refetchable mirror. * Delete it freely; never hand-edit it, because the next pull overwrites the * edit and it is a lie with a short life. - * - NOTHING BLOCKS ON IT. A WHOOP outage, a revoked grant or a bridge that is + * - NOTHING BLOCKS ON IT. A WHOOP outage, a revoked grant or a Bushido that is * down must leave the cache as it was and must never fail a food log. A day * with no burn figure simply has no balance line. * @@ -37,27 +38,39 @@ const DAYS = Number(process.env.KRAKATOA_WHOOP_DAYS || 30) const NOT_CONFIGURED = Object.freeze({ fetchedAt: null, burn: {}, error: null, configured: false }) /** - * Pull from the bridge and reshape to the only thing this app wants: burn per - * day. The bridge's payload also carries workouts, zones and heart rates, none - * of which is Krakatoa's business — Bushido owns training. + * Pull from Bushido and reshape to the only thing this app wants: burn per day. + * The payload also carries workouts, zones and heart rates, none of which is + * Krakatoa's business — Bushido owns training. + * + * Bushido answers `200 { result }`, where `result` is the training payload + * (`{ ok, fetchedAt, days, maxHeartRate, body, workouts, recovery, sleep }`), or + * a non-2xx `{ error, needsReauth?, rateLimited? }`: 409 when it has no WHOOP set + * up, 403 for a wrong token, 429 rate limited, 502 for an error from WHOOP. */ -async function pull({ url, secret, days = DAYS } = {}) { - if (!url || !secret) throw new Error('The Totem bridge is not configured — see Settings.') +async function pull({ url, token, days = DAYS } = {}) { + if (!url || !token) throw new Error('Bushido is not configured — see Settings.') - const res = await fetch(`${url}/api/whoop/training?days=${days}`, { - headers: { authorization: `Bearer ${secret}` }, + const res = await fetch(`${url}/api/whoop/owner`, { + method: 'POST', + headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' }, + body: JSON.stringify({ method: 'training', args: [{ days }] }), signal: AbortSignal.timeout(15000), }) const text = await res.text() if (!res.ok) { - // The bridge's message is the FIX ("authorized without read:workout", - // "reconnect WHOOP"), so it travels verbatim rather than being flattened. + // Bushido passes on WHOOP's message, and it is the FIX ("authorized without + // read:workout", "reconnect WHOOP"), so it travels verbatim rather than + // being flattened. let msg = text.slice(0, 200) try { msg = JSON.parse(text).error || msg } catch { /* not JSON, use the text */ } - throw new Error(msg) + throw new Error(msg || `Bushido answered ${res.status}.`) } - const body = JSON.parse(text) + let body + try { body = JSON.parse(text).result } catch { /* handled below */ } + if (!body || typeof body !== 'object') throw new Error('Bushido answered without a WHOOP result.') + if (body.ok === false) throw new Error(String(body.error || 'Bushido could not read WHOOP.').slice(0, 200)) + const burn = {} for (const row of body.recovery || []) { if (!row?.date) continue @@ -79,7 +92,7 @@ async function pull({ url, secret, days = DAYS } = {}) { /* --------------------------------------------------------------- the cache */ /* - * `config()` is asked on every call and returns the bridge's `{ url, secret }`, + * `config()` is asked on every call and returns Bushido's `{ url, token }`, * or null when no source is configured. Null means OFF: no request is made, no * error is logged, and reads answer NOT_CONFIGURED so the screen shows no panel. */ @@ -112,7 +125,7 @@ function makeStore(file, { config = () => null } = {}) { return { ...doc, configured: true } } catch (e) { // The previous cache SURVIVES a failed pull. Yesterday's burn is still - // yesterday's burn, and blanking it because the bridge is down would + // yesterday's burn, and blanking it because Bushido is down would // lose a real number to a transient one. const prev = readFile() const doc = { ...prev, error: String(e.message || e), erroredAt: new Date().toISOString() } diff --git a/server/whoop.test.js b/server/whoop.test.js new file mode 100644 index 0000000..66982d6 --- /dev/null +++ b/server/whoop.test.js @@ -0,0 +1,146 @@ +/* + * node server/whoop.test.js + * + * The WHOOP pull against a stand-in Bushido on a loopback port: what is sent + * (method, path, token, body), what is kept from the answer, that Bushido's + * error text arrives verbatim, and that with no Bushido configured nothing is + * sent at all. The arithmetic (`balanceFor`) is pinned in app/whoop.test.js. + */ + +const assert = require('assert') +const fs = require('fs') +const http = require('http') +const os = require('os') +const path = require('path') +const W = require('./whoop.js') + +let passed = 0 +const tests = [] +const test = (name, fn) => tests.push([name, fn]) + +/* A fake Bushido. `reply` decides each answer; every request is recorded. */ +function fakeBushido() { + const seen = [] + let reply = () => ({ status: 200, body: { result: { ok: true, recovery: [] } } }) + const server = http.createServer((req, res) => { + let raw = '' + req.on('data', c => { raw += c }) + req.on('end', () => { + seen.push({ method: req.method, url: req.url, headers: req.headers, raw }) + const r = reply(req) + res.writeHead(r.status, { 'content-type': typeof r.body === 'string' ? 'text/plain' : 'application/json' }) + res.end(typeof r.body === 'string' ? r.body : JSON.stringify(r.body)) + }) + }) + return new Promise(resolve => server.listen(0, '127.0.0.1', () => resolve({ + url: `http://127.0.0.1:${server.address().port}`, + seen, + answer: (fn) => { reply = fn }, + close: () => new Promise(r => server.close(r)), + }))) +} + +const TRAINING = { + ok: true, + fetchedAt: '2026-10-14T08:00:00Z', + days: 7, + maxHeartRate: 190, + body: { weightLb: 172.4 }, + workouts: [{ id: 'w1', sport: 'running' }], + recovery: [ + { date: '2026-10-13', calories: 2612.6, strain: 14.2 }, + { date: '2026-10-14', calories: 940, strain: 3.1 }, + { date: '2026-10-12', calories: 0 }, // no figure: dropped, not a zero-burn day + { calories: 2000 }, // no date: dropped + ], + sleep: [], +} + +test('sends POST /api/whoop/owner with the token and the training method', async (b) => { + b.answer(() => ({ status: 200, body: { result: TRAINING } })) + const doc = await W.pull({ url: b.url, token: 'tok-123', days: 7 }) + assert.equal(b.seen.length, 1) + const r = b.seen[0] + assert.equal(r.method, 'POST') + assert.equal(r.url, '/api/whoop/owner') + assert.equal(r.headers.authorization, 'Bearer tok-123') + assert.match(r.headers['content-type'], /^application\/json/) + assert.deepEqual(JSON.parse(r.raw), { method: 'training', args: [{ days: 7 }] }) + + // Only the burn and the body weight are kept; training is Bushido's business. + assert.deepEqual(doc.burn, { + '2026-10-13': { kcal: 2613, strain: 14.2 }, + '2026-10-14': { kcal: 940, strain: 3.1 }, + }) + assert.equal(doc.weightLb, 172.4) + assert.equal(doc.days, 7) + assert.ok(!('workouts' in doc)) +}) + +test("Bushido's error text arrives verbatim, whatever the status", async (b) => { + const cases = [ + [409, { error: 'Bushido has no WHOOP connection set up.' }], + [403, { error: 'wrong token' }], + [429, { error: 'WHOOP rate limit, try again in a minute', rateLimited: true }], + [502, { error: 'WHOOP said: reconnect WHOOP to grant read:cycles', needsReauth: true }], + ] + for (const [status, body] of cases) { + b.answer(() => ({ status, body })) + await assert.rejects(W.pull({ url: b.url, token: 't' }), (e) => e.message === body.error, `status ${status}`) + } + b.answer(() => ({ status: 500, body: 'upstream exploded' })) + await assert.rejects(W.pull({ url: b.url, token: 't' }), /^Error: upstream exploded$/) + b.answer(() => ({ status: 500, body: '' })) + await assert.rejects(W.pull({ url: b.url, token: 't' }), /Bushido answered 500/) +}) + +test('a 200 with no result, or a result that says it failed, is an error', async (b) => { + b.answer(() => ({ status: 200, body: { ok: true } })) + await assert.rejects(W.pull({ url: b.url, token: 't' }), /without a WHOOP result/) + b.answer(() => ({ status: 200, body: 'not json' })) + await assert.rejects(W.pull({ url: b.url, token: 't' }), /without a WHOOP result/) + b.answer(() => ({ status: 200, body: { result: { ok: false, error: 'reconnect WHOOP' } } })) + await assert.rejects(W.pull({ url: b.url, token: 't' }), /^Error: reconnect WHOOP$/) +}) + +test('no URL or no token: refused before any request', async (b) => { + await assert.rejects(W.pull({ url: b.url, token: '' }), /not configured/) + await assert.rejects(W.pull({ url: '', token: 't' }), /not configured/) + assert.equal(b.seen.length, 0) +}) + +test('unset is OFF: the store answers not-configured and sends nothing', async (b) => { + const file = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'krakatoa-whoop-')), 'whoop.json') + const store = W.makeStore(file, { config: () => null }) + assert.deepEqual(store.get(), W.NOT_CONFIGURED) + assert.deepEqual(await store.refresh(), W.NOT_CONFIGURED) + assert.equal(store.read().configured, false) + assert.equal(b.seen.length, 0) + assert.equal(fs.existsSync(file), false, 'nothing written either') +}) + +test('a failed refresh keeps the previous numbers, with the reason beside them', async (b) => { + const file = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'krakatoa-whoop-')), 'whoop.json') + const store = W.makeStore(file, { config: () => ({ url: b.url, token: 't' }) }) + b.answer(() => ({ status: 200, body: { result: TRAINING } })) + const ok = await store.refresh() + assert.equal(ok.configured, true) + assert.equal(ok.burn['2026-10-13'].kcal, 2613) + + b.answer(() => ({ status: 502, body: { error: 'reconnect WHOOP', needsReauth: true } })) + const failed = await store.refresh() + assert.equal(failed.error, 'reconnect WHOOP') + assert.equal(failed.burn['2026-10-13'].kcal, 2613, 'yesterday is still yesterday') + assert.equal(store.read().error, 'reconnect WHOOP') +}) + +;(async () => { + for (const [name, fn] of tests) { + const b = await fakeBushido() + try { await fn(b); passed++ } catch (e) { + console.error(`FAIL ${name}\n ${e.message}`) + process.exitCode = 1 + } finally { await b.close() } + } + console.log(`server whoop: ${passed} passed`) +})()