Author SHA1 Message Date
inference-admin f63096d4dc security: make Woodpecker status advisory until runners are isolated 2026-11-20 01:08:33 +00:00
inference-admin 86012fc879 security: document root-trust watchdog 2026-11-20 00:50:00 +00:00
inference-admin 3d4fac124d security: record residual root-trust gap in the backup timer 2026-11-20 00:31:09 +00:00
inference-admin 5d1c2a5158 security: document restricted sudo policy and root-owned backup path 2026-11-20 00:25:31 +00:00
inference-admin e2879dbdc2 security: document timestamped HMAC on the key feed 2026-11-20 00:23:28 +00:00
inference-admin ec7fa33c77 security: enable backup bucket versioning; document object-lock gap 2026-11-20 00:13:26 +00:00
inference-admin 5ad233c612 security: root-only backup credentials, internal-only key feed, corrected cadence 2026-11-19 23:41:16 +00:00
inference-admin d106f7cf01 inventory: page-fetch app and fetcher key; portal Matrix bot is @coop-portal 2026-11-19 23:09:09 +00:00
inference-admin 3044e448cd credentials: drop retired Open WebUI keys and rag_refresh job 2026-11-19 22:44:50 +00:00
inference-admin 2ea42979b5 credentials: PORTAL_SECRET retired with the /v1 proxy 2026-11-19 22:39:15 +00:00
inference-admin 82eaf274af Agent fleet: portal uses a non-admin room bot; @ops_audit retired 2026-11-19 21:55:03 +00:00
inference-admin c585cb7228 pricing docs: nightly ECB FX refresh (boot sync + 04:30 UTC restart timer) 2026-11-18 18:11:15 +00:00
inference-admin b792198b36 pricing docs: USD conversion is the ECB daily rate, not a frozen 1.16 2026-11-18 17:58:40 +00:00
inference-admin 4525142e0b pricing docs: EUR is the source of truth; gateway converts at 1.16 to USD
GreenPT and Regolo tables now show EUR list prices plus the USD figures the gateway
stores. Notes the policy date and that historical spend rows were understated (no
backfill).
2026-11-18 17:24:48 +00:00
inference-admin 2fda1bcc29 ops: working-group bots get one Unix user each, with their own studio room
Supersedes the tier-2 profile plan (#33). Shared Unix users let sibling profiles read
each other's .env, so permission boundaries between working groups would be nominal.
Records designbot as the first instance: own user/unit/team, #DesignBot Studio room
outside the Space, invite-only, mention-only.
2026-11-17 21:54:17 +00:00
inference-admin c2a9029d00 README: index the model-transitions runbook 2026-11-16 20:12:50 +00:00
inference-admin 02a75a1868 runbook: model transitions (repoint vs rename), with the three lists to keep in step
Written from today's DeepSeek 1017 repoint: the spend-log measurement that chose
repointing (3,014 calls on the prefixed id vs 84 on the alias), the aliases that
duplicate litellm_params and must move with the pointer, the emission-factor keys
that silently degrade on a rename, and the picker that only needs touching when
the id changes. Verification is a spend row, not an HTTP 200.
2026-11-16 20:12:44 +00:00
inference-admin 4a7a4be1a7 greenpt: default model serves the 1017 snapshot at the new rates 2026-11-16 15:53:14 +00:00
inference-admin 3008a02553 coop_chart: one concise chart vocabulary for both apps
Members · Requests · Spend · Money · Energy · Carbon. The titles were carrying
the unit ('Requests per day', 'Token spend per day') while the axis already
labels the unit, so the menus read long and the two apps said different things
in different places. The aria label still reads '<title> over time'.
2026-11-13 21:26:27 +00:00
inference-admin 8557f636f8 woodpecker-ci: the shared chart module also owns the definitions now 2026-11-13 21:02:05 +00:00
inference-admin e6d27b3775 chart module: add the definition layer — one description of every chart
The two UIs shared only the drawing primitives, so the same five metrics shipped
with different titles AND different kinds (the panel's "Spend per day" was the
dashboard's "What the co-op spent (members + the co-op's own accounts)"), and
Money was a whole separate tab with four renderers of its own.

CHART_METRICS is now the one place a chart is described — id, title, kind
(line|bar|multi), axis rule, value formatter, series — and renderChart() draws any
of them, registering the exact tooltip values and breaking lines at NULLs as
before. Money is a metric like the others (a "multi" chart: cumulative revenue,
cumulative token spend, and the OC balance as a gap before snapshots began).
fmtMoney/fmtMetric/fmtMoneyTick are shared so labels cannot drift.

Each app keeps what legitimately differs: its data source, its toggle classes, its
empty-state markup, its DOM. Nothing identifying belongs in this list.
2026-11-13 20:55:52 +00:00
inference-bot 65e3726d90 shared chart module: canonical coop_chart.js + sync/check scripts
Hand-rolled chart rendering + exact-value hover tooltips as ONE module
(no library, no CDN): tooltip machinery, niceStep (count vs 1/2/5 x 10^k),
measured runs (NULL stays a gap), frame/date-marks/bars/lines/hover-targets.
Byte-identical copies ship in admin-panel and member-dashboard (app/coop_chart.js),
pinned by tests/test_chart_sync.py in each; check-chart-sync.py is the
pre-deploy gate, sync-chart-module.sh re-copies + re-pins both apps.
Vendored check-page-js.sh (skill copy + both apps) now splices the module
into the extracted page JS exactly as the apps do at import time.
2026-11-13 16:11:16 +00:00
inference-bot 23d2fc0eb2 Shared code: single-source the OIDC client; record the guest-state consolidation
- scripts/shared/oidc_client.py is the canonical OIDC client module; the
  dashboard and panel ship byte-identical copies (pinned by
  tests/test_oidc_sync.py in each repo). sync-oidc-module.sh re-copies +
  re-pins; check-oidc-sync.py is the pre-deploy gate;
  scripts/shared/test_oidc_client.py is the behaviour harness.
- maintenance/shared-code-and-guest-state.md records the guest-state
  single-derivation design (portal serves state; panel/dashboard are pure
  shims), the deploy record with rollback tags, and the CI follow-up.
- app-inventory.md: the three apps' tags refreshed to the 20261111 deploys;
  the stale 'admin panel = local/coop...' registry-path note corrected
  against the live API (all three live under code/).
2026-11-11 05:24:57 +00:00
inference-bot 206c3d5379 ops: push-gated CI live (12+2 suites, red-test proven, merge gate on); fail-closed config validators shipped to gateway+chat and proven; three backfilled incident write-ups (yaml outage, Loomio invite blast, stale-image deploy) + the 69-var portal env manifest 2026-11-11 04:13:00 +00:00
inference-bot 2c38f4d2c3 upgrade window 2026-11-09: executed (gateway 1.108.3, chat overlay 1.4.8) — record the outcome, the 400 MB task-limit OOM and its --no-backup remedy, and refresh the live image pins 2026-11-09 05:04:27 +00:00
inference-bot 52e3c9d502 runbook: re-check the upgrade window against live state — correct the rollback tag, mark the prebuilt candidate stale, extend the marker list to ten, and flag the failing backups as the open risk 2026-11-09 04:17:06 +00:00
inference-bot 5a4492e725 ops: document the member provisioning boundary (org-backed, credit-pack, manual, hidden-email) and the daily paid-but-unprovisioned watchdog 2026-11-07 00:27:15 +00:00
inference-bot 0f40dcc519 runbook: add the standing supply-chain IoC check to the gateway verify steps 2026-11-06 04:11:11 +00:00
inference-bot 816961fb2d runbook: 2026-11-08 upgrade window — LiteLLM 1.103.2→1.108.0 + LibreChat overlay 1.4.5→1.4.8
Prepared and validated on 2026-11-06; nothing deployed. Candidates:
- code/litellm branch upgrade-v1.108.0 → image 1.0.0-20261106-9e25578
  (8/8 patches verified in the built image and in a live sandbox run;
  image-gen spend row verified nonzero twice — fake + real Regolo probe;
  36 additive migrations; budget_reset_at + portal API shapes unchanged).
- co-op/librechat-custom branch bump-appstore-1.4.8 → overlay 20261106-c2aec74
  (appstore 1.4.8 = tooling bumps on the same 0.8.8 upstream; all overlay
  anchors verified against the real 1.4.8 image — no porting needed).
Runbook: LiteLLM first, member-scope verification, rollback = previous tag
per app, window estimate 45-60 min.
2026-11-06 04:11:01 +00:00
inference-bot fcd4ac6943 incident: portal's copied LiteLLM DB credential rotted after the 2026-11-05 gateway restore; all-time spend silently read $0 — timeline, fix, the digest spend-consistency guard, and the two-copies-of-one-secret dependency flagged for the next rotation 2026-11-05 19:10:26 +00:00
inference-bot bb10d93412 incident: 2026-11-05 gateway addon loss during multi-app deploy — wiped LiteLLM DB, restored from the pre-deploy snapshot the same hour
Full mechanics, impact, detection and prevention in the file. Portal
member data was never at risk.
2026-11-05 16:36:05 +00:00
inference-bot 4d3f539a84 ops: record the decision to keep the historical ledger test rows (audit L7 — net zero; rewriting the money ledger is worse than the noise) 2026-11-05 16:26:17 +00:00
inference-bot 3bf152b58a ops: record the LibreChat key-feed design decision (audit M2) — kept with monitoring; per-member fetch rejected as the riskier path 2026-11-05 16:21:52 +00:00
inference-bot b1a1c70e8a ops: record the allowance-shortfall manual-remediation ledger
The portal's SHORTFALL_REMEDIATED constant now carries only the OC charge
reference (de-PII'd from the public member-portal repo); the member
identity and the timeline of the manual reset live here, keyed on the
charge, plus the rationale for charging-keyed exclusion.
2026-11-05 15:59:13 +00:00
ops-bot a9edaa3e4b agent-fleet: record the Matrix homeserver accounts moved off the member docs
The member-facing infrastructure page no longer documents who holds room power
or which automation accounts exist. Record it here instead: @inference-admin as
administrator of record, the retired @inference-bot account and its two
un-leavable rooms, and the @ops_audit review account.

Also repairs a heading glitch carried over from the docs page: a line began with
a bare '#infrastructure', which Markdown parsed as an <h1>. The room names are
now written inline so no line starts with '#'.
2026-11-04 21:29:29 +00:00
inference-bot 835aed2852 Record the DNS cutover as complete; flag the old box as an unresolved exposure (#5) 2026-11-04 14:49:04 +00:00
inference-bot 6f2a6d01ed docs: record the DNS cutover as complete; flag the old box as an unresolved internet exposure
- Migration addendum: replace the 'DNS split' wording with the verified state —
  every hostname resolves to the new box (A+AAAA) per Cloudflare's public
  resolver; nothing points at the old box.
- Reframe the old box: not a benign rollback spare but a decommissioned server
  still alive and internet-exposed (22/80/443/587/993 open), holding old data and
  config, serving no member traffic. UNRESOLVED — operator decision to shut it
  down or firewall it. Do not act on it without the operator's word.
- README: add a 'Known open items' section listing the exposure, the CI failure,
  the unpushed CI-agent repo and the unconfirmed member mailbox contents.
2026-11-04 14:48:53 +00:00
inference-bot 6e777be842 Infrastructure audit: app inventory, backups, CI, provider pricing, agent fleet (#4) 2026-11-04 14:47:18 +00:00
33 changed files with 2997 additions and 97 deletions

No files matched your search

+18
View File
@@ -28,8 +28,11 @@ Read it on the web here: <https://git.inference.coop/co-op/ops-docs>
| `agent-fleet.md` | The three agents (steward, infrastructure-bot, socialbot): Unix users, gateway units, teams, and the planned member-bot tier |
| `maintenance/chat-task-models.md` | The small pinned model used for chat titles/tags/suggestions |
| `maintenance/librechat-sandbox.md` | Operating the LibreChat evaluation instance (config, overlay image, key sync, pitfalls) |
| `maintenance/model-transitions.md` | Repoint vs rename when a provider retires or replaces a model: the spend-log measurement that decides it, the aliases and factor keys that must move with the pointer, the picker that only needs touching on a rename, and verification by spend row rather than HTTP 200 |
| `maintenance/backups.md` | The two backup systems (agent-host restic + Cloudron app backup): schedules, retention, the cache split and the grouping fix |
| `maintenance/woodpecker-ci.md` | The self-hosted CI server and agent: build/pin, manual-only trigger, git-lfs, and its not-yet-green state |
| `maintenance/provisioning-boundary.md` | Which Open Collective contributors auto-provision as members and which are deliberately excluded (org-backed, credit-pack, manual, hidden-email), plus the daily paid-but-unprovisioned watchdog |
| `maintenance/2026-11-08-litellm-1.108.0-librechat-1.4.8.md` | The Sunday-evening upgrade-window runbook (gateway → 1.108.0, chat overlay → appstore 1.4.8): candidates, order, exact commands, per-step verification, rollback, window estimate |
| `incidents/` | Post-incident write-ups, one file per incident |
| `migration/` | The Cloudron server-migration record: the plan, the DNS change sheet, and the captured pre-migration state |
| `provider-pricing/` | What each model provider charges, and when it changed (GreenPT, Tinfoil, Regolo, and the decision-model route) |
@@ -56,6 +59,21 @@ answers proves nothing about whether a record exists. At least two listed
records turned out not to exist, and the real record inventory is only visible
in the registrar's own list.
## Known open items — recorded, not hidden
These are genuinely unresolved; a tidy document that omits them would be wrong.
- **The old box `179.199.135.72` is still alive and internet-exposed** (22/80/443/587/993
open), holding old data and config. Nothing in DNS points at it, so it serves no
member traffic — but it needs an operator decision: **shut it down or firewall it**.
Do not act on it without the operator's word. See `migration/cloudron-server-migration.md` (addendum).
- **CI is not green.** The Woodpecker agent is healthy but the server answers its
job-collection stream with HTTP 500, so no pipeline can run. See `maintenance/woodpecker-ci.md`.
- **The CI agent image source (`/home/ubuntu/repos/woodpecker-agent`) has no git
remote** — it exists only on the agent host.
- **Member mailbox contents after the migration** are still unconfirmed (needs a
real IMAP login).
## No secrets here
Audited 2026-11-01, including the full commit history: no credentials, tokens,
+62 -10
View File
@@ -12,6 +12,7 @@ now wrong.
| **Inferencebot** (steward) | `ubuntu` | `hermes-gateway.service` | *(co-op account team)* | per `~/.hermes/config.yaml` | Matrix `@inferencebot:inference.coop`; digests, newsletters, membership/key plumbing |
| **infrastructure-bot** | `infrabot` | `hermes-gateway-infrabot.service` | `agent:infrastructure-bot` ($5/30d) | `greenpt/glm-5.3-flash` | Matrix `#infrastructure` (answers only when mentioned); infrastructure scope |
| **socialbot** | `socialbot` | `hermes-gateway-socialbot.service` | `agent:socialbot` ($5/30d) | `greenpt/glm-5.3-flash` | Matrix `#social-drafts`; drafts the co-op's AT Protocol (Bluesky) account `inference.coop` |
| **designbot** | `designbot` | `hermes-gateway-designbot.service` | `agent:designbot` ($5/30d) | `glm-flash-green` | Matrix `#DesignBot Studio`; Design working group; mention-only |
All three gateways run on the one host; each is a separate process, a separate
`.env`, and a separate set of rooms. There is **one LiteLLM gateway** (the Cloudron
@@ -20,8 +21,9 @@ app) that all three draw on — the agent host runs no gateway of its own.
### Who is who (do not conflate them)
- **Inferencebot** is the **steward** and the fleet administrator: full Cloudron
token, gateway master key, member-data plumbing. It is NOT a member-facing chat
persona.
token, gateway master key, member-data plumbing. Root access is restricted to
the docs/backup service commands in `maintenance/host-access.md`; it is NOT a
member-facing chat persona.
- **infrastructure-bot** is a **lower-privileged** infrastructure agent. Per its
own SOUL it has **no sudo, no Cloudron admin token, and no member data**; when a
task needs more privilege it hands up to the steward rather than working around
@@ -30,16 +32,29 @@ app) that all three draw on — the agent host runs no gateway of its own.
Matrix rooms; its only writable surface is the `#social-drafts` room, and it
**never publishes an unapproved draft** — silence is its correct failure mode.
## Member bots — TIER 2 (planned, not yet provisioned)
## Working-group bots — one Unix user each
The intended path for **member-facing** bots is a second tier: each member bot is a
**Hermes profile under the `infrabot` Unix user**, sharing **one** gateway process
(the infrabot one), with its own gateway team/key. This is tracked as **co-op/support#33**.
**Policy (2026-11-17; supersedes the tier-2 profile plan in co-op/support#33).**
Every working-group bot is provisioned like socialbot: a **dedicated Unix user**,
its own Hermes install, its own gateway unit, its own LiteLLM team and key, and its
**own studio room** — a bot-access room on the server, deliberately **outside the
co-op Space**. Member bots are *not* Hermes profiles under `infrabot`.
**Status (2026-11-04): not yet provisioned.** `/home/infrabot/.hermes/profiles/`
holds only a `.deleted` directory with two probe files — there are **no active
member-bot profiles**. Record this honestly: the design exists, the instances do
not.
Why: sibling Hermes profiles on one Unix user can read each other's `.env`. Sharing
a user would make permission boundaries between working groups nominal.
**designbot** is the first instance:
- Unix user `designbot` (uid 1003, no sudo), unit `hermes-gateway-designbot.service`
- LiteLLM team `agent:designbot` ($5/30d, flash-tier allowlist)
- Matrix `@designbot:inference.coop`, room **#DesignBot Studio**
(`!RqMPii2PDrX0QgBSX4cQTfQFcuW2e78OjQO42IZ1QIk`, alias `#design-wg`):
invite-only, standalone (no `m.space.parent`), power level 100 for Nathan,
Juan Fortun and the bot, mention-only, and no shell/file tools in the room
A studio room is not the working group's public room: the co-op's existing
member-facing Design room is separate, and adding a studio room to the Space is a
mistake, not a convenience.
## Why one Unix user per agent — and the limit of it
@@ -63,3 +78,40 @@ From `GET https://gateway.inference.coop/team/list` (2026-11-04): 97 teams — o
($135/30d, the co-op account), the two `agent:*` teams above, and
`sandbox:librechat-test` ($3). Agent teams carry a **small budget and a flash-tier
model allowlist** enforced at the gateway.
## Matrix homeserver accounts
Beyond the agent bots above, the homeserver carries two automation accounts.
Also recorded here: the room account retired in October 2026, moved out of the
member-facing docs.
- **`@inference-admin:inference.coop` — the room and server administrator.** A
Synapse server admin, used for provisioning rooms, managing membership, and
retiring rooms. It is the administrator of record for the co-op's Matrix rooms
— general, community, design, skillshare, updates and infrastructure. It **never
speaks in a member room**; a message from it is a mistake, not a feature.
- **`@coop-portal:inference.coop` — the portal's member-invite bot (not a server
admin).** Owns `MATRIX_BOT_TOKEN` in the portal env. Room power level **50** in
exactly the eight `MATRIX_INVITE_ROOMS` rooms — enough to invite and kick a
member (invite level is 0–50, kick level 50) and nothing more. It cannot touch
room power levels, server admin APIs, or rooms outside that set. The portal no
longer holds an admin credential.
- **`@inference-bot:inference.coop` is retired (2026-10-29).** It was the
original room-administration account (it created the space and most of the
rooms) and held a Synapse server-admin flag. Its room power passed to
`@inference-admin`; its admin flag was dropped, it was deactivated, and every
device and token was deleted. Nothing should use it again.
- **`@ops_audit:inference.coop` — RETIRED (2026-11-19).** Was a server-admin
account from the October 2026 security review. Its device `OPSAUDITDEV` was
deleted, the admin flag dropped, and the account deactivated. Zero devices
remain; do not recreate it.
Two loose ends, recorded so nobody re-investigates them from scratch: the
retired account remains joined to two rooms it cannot leave (they reject every
write — `500` on leave), and those rooms are also why they can't be deleted; and
its *name* is still the tempting one, so check `whoami` rather than the name
before trusting any account that looks like it.
**House rule: power belongs to `@inference-admin`, voice belongs to `@inferencebot`.**
Don't create an account whose name differs from an existing one by a character or
two — that lookalike confusion is what the rule exists to undo.
+16 -12
View File
@@ -20,19 +20,20 @@ does not hold it.
| FQDN | App id | Label | Image (pin) | Install |
|---|---|---|---|---|
| `inference.coop` | `55f5f904-3233-44de-ad7b-5dc7c8533b75` | — | `cloudron/io.cloudron.surfer:202611021342220000` | store (Surfer — marketing site) |
| `chat.inference.coop` | `4023ccbf-d57a-4500-97df-14de9cf3516e` | AI Chat | `registry.inference.coop/co-op/librechat-custom:20261031-2a98892` | **custom** (LibreChat overlay) |
| `chat-legacy.inference.coop` | `50ae6c97-e851-4d17-b013-51ca7a4e5be0` | Legacy AI Chat | `cloudron/com.openwebui.cloudronapp:202611030420300000` | store (Open WebUI) |
| `portal.inference.coop` | `d4f05e4b-75c6-492e-9faf-7afb0712fc94` | — | `registry.inference.coop/code/member-portal:20261104-d076729` | **custom** |
| `dashboard.inference.coop` | `daf8750e-2683-4104-83ea-f77d1b4601e8` | Dashboard | `registry.inference.coop/code/member-dashboard:20261103-3453131` | **custom** |
| `panel.inference.coop` | `ae187071-7a43-4a6e-8a02-986609a66a1a` | Admin Panel | `local/coop.inference.admin-panel:0.1.0-1793634279942` | **custom** |
| `gateway.inference.coop` | `adababd4-2427-4bdd-9bf7-6bdad0302610` | LiteLLM | `registry.inference.coop/local/ai.coop.litellm:1.0.0-20261103-d6cfe78` | **custom** |
| `chat.inference.coop` | `4023ccbf-d57a-4500-97df-14de9cf3516e` | AI Chat | `registry.inference.coop/co-op/librechat-custom:20261106-c2aec74` | **custom** (LibreChat overlay) |
| `chat-legacy.inference.coop` | `50ae6c97-e851-4d17-b013-51ca7a4e5be0` | Legacy AI Chat | `cloudron/com.openwebui.cloudronapp:202611040420410000` | store (Open WebUI) |
| `portal.inference.coop` | `d4f05e4b-75c6-492e-9faf-7afb0712fc94` | — | `registry.inference.coop/code/member-portal:20261111-58214be0` | **custom** |
| `dashboard.inference.coop` | `daf8750e-2683-4104-83ea-f77d1b4601e8` | Dashboard | `registry.inference.coop/code/member-dashboard:20261111-622982a3` | **custom** |
| `panel.inference.coop` | `ae187071-7a43-4a6e-8a02-986609a66a1a` | Admin Panel | `registry.inference.coop/code/admin-panel:20261111-80acfaed` | **custom** |
| `gateway.inference.coop` | `adababd4-2427-4bdd-9bf7-6bdad0302610` | LiteLLM | `registry.inference.coop/local/ai.coop.litellm:20261109-c43d45c` | **custom** |
| `matrix.inference.coop` | `aa6f4597-6206-4509-b32e-c89750b2c1d8` | Matrix Chat | `cloudron/org.matrix.synapse:202611030719520000` | store (Synapse) |
| `git.inference.coop` | `c91c13aa-30ed-4af9-9599-7a87ab4f221d` | Code | `cloudron/io.gitea.cloudronapp:202611011719500000` | store (Gitea) |
| `registry.inference.coop` | `c257ba3c-6737-4375-ad51-ea19586bf3f0` | — | `cloudron/io.cloudron.container-registry:202610221511140000` | store (container registry) |
| `vault.inference.coop` | `cb838bcf-f2e2-4670-b117-dca04b0ee957` | — | `cloudron/com.github.bitwardenrs:202611020820270000` | store (Vaultwarden) |
| `forum.inference.coop` | `8b1a972c-08af-4e92-852c-d573c37b01ad` | Forum | `cloudron/org.loomio.cloudronapp:202611010321240000` | store (Loomio) |
| `forum.inference.coop` | `8b1a972c-08af-4e92-852c-d573c37b01ad` | Forum | `cloudron/org.loomio.cloudronapp:202611050321160000` | store (Loomio) |
| `newsletter.inference.coop` | `eed2217c-b165-430e-bc29-7ccfef9b11e4` | — | `cloudron/app.listmonk.cloudronapp:202610220221130000` | store (Listmonk) |
| `search.inference.coop` | `d7c73fff-ee42-4db0-98c0-4ce7a8ab35cc` | — | `cloudron/io.github.ascimoo.searx:202611012319290000` | store (SearXNG) |
| `fetch.inference.coop` | `63b95c58-0368-439f-afa7-e8c7736489cc` | Page Fetcher | `registry.inference.coop/coop.inference.fetcher:20261119-5f88ceb` | **custom** (internal page fetch; access restricted to `managers`) |
| `cloud.inference.coop` | `fd261d67-b790-424f-9e82-f74883ee8585` | — | `cloudron/com.nextcloud.cloudronapp:202610211606270000` | store (Nextcloud) |
| `email.inference.coop` | `fbb256b9-ead3-41d8-bee0-d5ea87149436` | — | `cloudron/io.cloudron.mail:202610261602550000` | store (Cloudron mail UI) |
| `docs.inference.coop` | `85b7ce06-e2af-49a4-bd4f-a9c2e692e3ab` | Docs | `cloudron/io.cloudron.surfer:202611021342220000` | store (Surfer) — **NEW 2026-11-03** |
@@ -54,12 +55,15 @@ another app's pattern deploys the wrong (or a missing) image:
| member portal | `registry.inference.coop/code/member-portal` |
| member dashboard | `registry.inference.coop/code/member-dashboard` |
| gateway (LiteLLM) | `registry.inference.coop/local/ai.coop.litellm` |
| admin panel | `local/coop.inference.admin-panel` |
| admin panel | `registry.inference.coop/code/admin-panel` |
**Correcting a stale memory:** the portal is `code/member-portal` (not
`co-op/member-portal`), and the admin panel is `local/coop.inference.admin-panel`
(not `code/admin-panel`). Both were cited wrongly in earlier notes; the values
above are read from the running apps.
**Correcting a stale memory (re-verified against the live system 2026-11-11):**
the portal, dashboard and panel ALL live under the `code/` namespace
(`code/member-portal`, `code/member-dashboard`, `code/admin-panel`) — read from
each running app's `manifest.dockerImage` via the API and confirmed by
successful builds and pulls. An earlier note claimed the panel was
`local/coop.inference.admin-panel`; that path does not match the running
system and is superseded by the verified values above.
## Store vs custom, and what that decides
@@ -0,0 +1,84 @@
# Incident 2026-10-31 — a `customFooter:` key in librechat.yaml kept the chat API from ever starting; the SPA kept serving 200
Backfilled 2026-11-11 (the incident predates ops-docs' incident practice; the
knowledge lived only in the steward skill until the codebase audit flagged the
gap). Written from the skill reference, the git history around the footer work
and the deployed build's own validator. No values, only names.
## What happened
A footer customisation for chat.inference.coop was made by adding a
`customFooter:` top-level key to `/app/data/librechat.yaml` (the persistent
volume) and restarting the app. LibreChat's config loader runs the yaml
through its **strict config schema** (`configSchema.strict()` from
`librechat-data-provider`, in `@librechat/api`'s config load) and exits on an
unrecognized top-level key:
```
logger.error("Exiting due to invalid configuration. Set CONFIG_BYPASS_VALIDATION=true …");
process.exit(1);
```
`customFooter` is not a key of that schema in the deployed build — this build
reads the footer **only** from the `CUSTOM_FOOTER` env var. So the API server
(node `api/server/index.js`) never came up.
## Blast radius
- **Every API route of chat.inference.coop down for members** — login, chat,
/api/config, key checks — from the yaml edit + restart until the key was
removed and the app restarted again.
- The **SPA kept serving HTTP 200**: Cloudron's health check and the homepage
stayed green (the static shell is served regardless of the API process), so
the app looked "up" on every status surface. Any check that scored the app
by a 200 was testing the shell, not the service.
- No data loss (config-only; the yaml was fixed in place).
## Detection gap
Nothing detected it while members hit it. The failure signature —
`/api/config` returning the HTML shell instead of JSON — was only found by a
human-side check, and the recovery was scored by exactly that probe
afterwards. The gap was twofold:
1. No pre-boot validation: the yaml was edited on the volume with nothing
checking it against the schema before the restart.
2. No post-restart behavioural check: a green 200 from a single-page app
proves the vhost, not the app.
## Resolution
- Removed the `customFooter:` key from `/app/data/librechat.yaml`; the footer
was later shipped correctly through `CUSTOM_FOOTER` in `/app/data/env`
(the value channel that actually reaches the node process).
- Restart → `/api/config` returned JSON again → recovery declared on that
evidence, not on the homepage 200.
## The fix that now exists (2026-11-11)
The chat image (overlay `librechat-custom`, tag `20261111-179fd7c`) now
carries a **fail-closed config validator wired at the top of the boot path**:
- `validate_config.py` (canonical copy in `ops-docs/scripts/`, shipped
byte-identical into the image) runs the deployed build's own strict schema —
`configSchema.strict().safeParse()` from the container's
`librechat-data-provider` — against `/app/data/librechat.yaml` **before**
anything starts.
- `patch_start_validator.py` inserts the check into `/app/pkg/start.sh` at
build time (idempotent, non-fatal to apply; fatal at runtime **only** when
the config is actually invalid).
- On an unknown key the boot dies loudly with one line naming the key
(`CONFIG VALIDATION FAILED: customFooter: Unrecognized key(s) …`), instead of
an API server that never starts behind a healthy-looking shell.
Proven before deploy: live yaml passes (7 top-level keys accepted); the
reproduced outage config (live yaml + `customFooter`) fails naming the key,
through both the deployed-schema path and the static fallback; the served
`/api/config` is JSON after the deploy.
## Prevention rules recorded
- Treat any librechat.yaml key as schema-validated: check it against the
deployed build's `configSchema` before writing it to the volume.
- After ANY chat config edit or restart, assert `/api/config` returns JSON —
never score recovery by a 200 from the SPA shell.
@@ -0,0 +1,26 @@
# Allowance shortfall remediation — manual-remediation ledger (2026-11-04/05)
The portal's shortfall mechanism (`derive_shortfalls` in
`member-portal/app/main.py`) credits a member's missing allowance whenever OC
realigned a charge onto the collective billing day and truncated a paid cycle.
Each credit is keyed on the OC charge reference (`tx_…` publicId) so a re-run
never credits twice.
## Entries in `SHORTFALL_REMEDIATED` (code constant, no PII by design)
| OC charge reference | Why it is excluded from automatic shortfall crediting |
|---|---|
| `[redacted member reference]` | The truncated cycle this charge created was already made whole by a **manual allowance reset on 2026-11-04**, performed outside the mechanism (before the automatic path shipped). The member joined mid-October; OC moved their next charge to the 2 Nov common billing day, so their cycle ran ~17 days. The reset re-anchored the allowance to the member's own join day, which is the policy now in code. Later charges of this member form new cycles and are credited normally by the automatic path. |
The member's identity is in the portal `credit_ledger` / `members` tables
(the credit row itself) — the public portal repository deliberately carries
only the charge reference (audit H2, 2026-11-05: the constant used to embed
the member's email and billing timeline; the portal repo is public).
## Why the exclusion is keyed on the charge, not the member
`derive_shortfalls` reads charge history from OC's order list; the charge that
truncated the cycle is the idempotence key everywhere else in the flow
(`credit_reference_exists`). Keying the manual-remediation exclusion on the
same charge means a sweep re-run can neither double-credit the charge nor
skip a genuinely new truncated cycle for the same member.
@@ -0,0 +1,77 @@
# Incident 2026-11-04 — the Loomio sync rehearsal ran against the live services and invited the whole membership
Backfilled 2026-11-11 (self-reported by the audit's missing-write-ups list).
The operator's brief dates this 2026-11-05; the delegation record that fixed it
(fixed the same evening) dates the blast itself to 2026-11-04 — that verified
date is used here.
## What happened
The portal's Loomio integration keeps the co-op's Loomio group in step with the
membership: it adds members who join, removes members who deactivate, and
notifies by email on invite. A **rehearsal** of the sync/deactivation path was
run to verify proposed behaviour. The harness was not made structurally
incapable of a write: the function's dependencies pointed at the **live portal
database** and the **live Loomio API**, and a rehearsed path calls exactly the
path it was given. The rehearsal re-ran a full membership sync against both,
and Loomio issued a **whole-group invite notification — ~83 in-app recipients
(Loomio notification id 744)** — to essentially the entire membership, plus the
invite emails that path sends.
## Blast radius
- ~83 members received a redundant Loomio invite notification and its email
for a group most of them were already in. No member data was changed
destructively (the sync's add path is additive); the damage was a
membership-wide bogus notification, and trust.
- The portal database was not corrupted; the live Loomio group state ended up
correct (the invited people were mostly already members — which is why the
notifications were noise, not access changes).
## Detection gap
Our own code recorded nothing — a rehearsal leaves no "blast" record in the
portal, and the sync had no per-subject send log. The evidence came from the
**third party's own notification log** (Loomio's notification 744), not from
anything we monitor. A rehearsal that touches live services does not announce
itself; only the receiver's records showed it.
## Resolution (same day, deployed and verified)
The fix job (`deleg_8b616d58`, completed 2026-11-04 ~19:00 UTC) re-enabled the
sync with the guard that was missing and deployed portal image
`20261104-c78acf5` (manifest pinned `d945ba1`):
1. **Idempotent add path** — the sync now checks the destination's actual
state before acting: a member already in the Loomio group is never invited
or emailed again, no matter how many times the sync runs. The normal
schedule keeps admitting genuinely new people.
2. **Removal reconciliation preserved** — the guard must not block removals:
a deactivated member still propagates (removals verified idempotent too),
so the invite guard cannot silently strand lapsed members in the group.
3. **Verified by the operation's own class of effect**: 0 notification
deliveries after the deploy, group total 84 vs 94 portal members (the only
roster email not in the portal is `bot@inference.coop`, the allowlist
account, correctly excluded), 26/26 portal tests passing
(`tests/test_loomio_guard.py` among them).
## Root cause
A rehearsal brief that said "test the sync path" without making production
unreachable. "Use a fixture, never the live row" is not a control: any function
whose dependencies point at live services WILL act on them. The harness must be
*structurally incapable* of a write — stub the network layer, copy the
database and point the code at the copy, and **prove the isolation before the
harness runs** (assert the stub recorded the call instead of the service
receiving it).
## The fix that now exists
- The add-path idempotence and preserved removal reconciliation above (in the
portal image since 2026-11-04; guarded by `tests/test_loomio_guard.py`, which
has run green on every push since 2026-11-11 via Woodpecker).
- The standing rule, recorded in the steward skill: a rehearsal brief must make
production unreachable, and the boundary must be verified before the harness
runs — plus a per-subject send record for any path that notifies, seeded from
live state, so a first enabled run cannot re-blast the population it is
meant to leave alone.
@@ -0,0 +1,95 @@
# Incident 2026-11-05 — gateway/panel briefly deployed with the portal's manifest; gateway LiteLLM database wiped and restored
Self-reported by the audit-fix session (inferencebot), 2026-11-05 ~18:00 UTC.
Damage fully recovered the same hour. Nathan: see "What you need to know" at
the end.
## What happened
During the audit fix-order deploys, three apps (member-portal, admin-panel,
gateway) were updated in one shell loop that stayed `cd`'d into the
**member-portal repo**. `cloudron update` reads `CloudronManifest.json` from
the CURRENT DIRECTORY, and the portal manifest carries a `dockerImage` pin —
which wins over any `--image` argument. So:
1. The **admin-panel** app received the portal's manifest (portal image
`20261105-ca3b8db`, portal manifest id `coop.inference.member-portal`,
portal addons) for ~10 minutes.
2. The **gateway** app received the portal's manifest too. The portal manifest
has **no postgresql addon** → Cloudron **dropped the gateway's Postgres
database** (the LiteLLM key/team/spend store). The panel recovery and the
gateway image recovery ran ~10 and ~25 minutes later; the gateway's addon
was re-created on recovery as an EMPTY database with the same name.
3. Result: from ~16:29 to ~17:20 UTC every member key 401'd (184 keys gone
from the gateway's view), chat was down for the membership. The portal app
itself was never affected (its own manifest was the one deployed).
## Impact
- Gateway member inference: **down ~50 minutes** (16:29–17:20 UTC). Master-key
surfaces (/v1/models with the master key) worked, which made the outage look
partial at first glance.
- Gateway LiteLLM Postgres: keys 184→0, teams 100→1, SpendLogs 125k→17 at the
moment of detection.
- Spend rows for live traffic between the 16:28:12 backup and the database
wipe (a few minutes) are unrecoverable; everything after the wipe was
refused calls (no spend to lose).
- Panel: wrong image for ~10 min, no data loss (stateless; no durable addon
data).
- No member data (portal SQLite) was ever at risk — that lives in the portal
app's own localstorage volume, which was never touched.
## Detection
Post-deploy verification battery failed exactly where it should: the
member-scope chat call returned 401, the panel's container md5 matched the
PORTAL's main.py, and `/key/list` returned 0 keys. All three surfaced within
minutes of the recovery deploy.
## Resolution (all verified)
1. Redeployed panel and gateway **from their own repo directories** with their
correct manifests/images (16:47, 16:52 UTC).
2. Gateway database confirmed wiped (0 keys) → located the deploy-time app
snapshot `app_…_v1.0.0_5aad8953` (16:28:12 UTC — taken seconds before the
damage, contains the addon dump).
3. `cloudron restore --app <gateway> --backup …_5aad8953` (17:2x UTC) →
**184 keys, 100 teams, 125,106 spend rows restored**; /v1/models 200.
4. Re-applied the intended gateway image update `1.0.0-20261105-e161db9` from
the litellm repo dir (17:3x UTC) → verified DB still intact after the
redeploy (184/100/125,110 rows — the +4 spend rows are live traffic billing
again), member-scope chat completes for real (tinfoil/glm-5.3, tokens
billed), contactEmail + corrected start.sh live, audio_keepalive scheduler
restored.
5. Panel pin bumped to its own new image `20261105-0713551` and deployed from
its own repo dir; container md5 matches the repo; panel 200.
## Root cause
Running `cloudron update` for multiple apps from a shared shell whose working
directory belonged to a DIFFERENT app's repo. The CLI's behavior (CWD manifest
wins; `--image` silently ignored when a `dockerImage` pin exists) is documented
in the co-op skill, but nothing in the loop enforced "one app, one repo, one
CWD".
## Prevention (recorded in the deploy skill as a hard rule)
**Never batch `cloudron update` for different apps in one shell without
`cd`-ing to each app's own repo per command, and never run an update for an
app while CWD holds another app's `CloudronManifest.json`.** Verify after
EVERY deploy with both facts: the app's own `manifest.dockerImage` from the
API (never the CLI's output) and a container-content check (md5/marker).
Additionally: a manifest change that alters the `addons` block of an
app with a database addon drops/reprovisions that addon's data — treat addon
blocks as data-bearing, not metadata.
## What you need to know (Nathan)
- Chat was down for members ~50 minutes this afternoon (UTC); it is verified
working again with a real member key and real billed tokens.
- The gateway database was restored from the automatic pre-deploy snapshot;
only a few minutes' worth of spend rows from before the outage are missing.
No member key, team, or balance data was lost.
- The portal's member database was never touched.
- The audit fix order otherwise completed; a separate summary has the full
stage-by-stage record.
@@ -0,0 +1,100 @@
# Incident 2026-11-05 — the portal's copied LiteLLM DB credential rotted after the gateway restore; all-time spend silently read $0
Companion to [`2026-11-05-gateway-addon-loss.md`](2026-11-05-gateway-addon-loss.md)
(the deploy mistake that made the gateway restore necessary). This document
covers the second-order failure that restore caused. No spend data was lost at
any point; the failure was in the portal's **read path**, and it failed in a
way that looked like clean data.
## What broke
The portal aggregates all-time spend, model usage and the leaderboard by
querying LiteLLM's Postgres directly, using a **copy** of the gateway's
postgres addon credential: the portal app's `LITELLM_DB_*` env mirrors the
gateway's `CLOUDRON_POSTGRESQL_*` runtime env. Two things then combined:
1. **The copy rotted.** Restoring a Cloudron app re-provisions its postgres
addon and **rotates its credential**. When the gateway was restored
(16:32:35 UTC, see timeline), the gateway got the new credential re-injected
at runtime — but the portal's copy went stale at that exact moment.
2. **The failure degraded silently.** The portal's aggregation catches a DB
auth failure, logs a WARNING, and degrades to an empty result — all-time
spend read `$0.00`. The panel and member dashboard rendered that $0 while
the *cycle* figures (read from LiteLLM's API, unaffected) still looked
plausible, so nothing on screen looked broken. The daily digest had no
spend-consistency check, so it also reported nothing.
## Timeline (UTC, 2026-11-05 — restore/configure times from the platform eventlog)
- **16:29:01** — during the audit-fix deploys, the gateway received the
portal's manifest; its postgres addon was dropped. (Sibling incident.)
- **16:32:35** — the gateway was restored from the pre-deploy snapshot to
recover the sibling incident. The restore re-provisioned the postgres addon
and **rotated its credential** — the moment this incident began.
- **16:32:35 → 18:51** — every portal aggregation query against LiteLLM's
Postgres failed authentication and degraded to empty: panel + dashboard
all-time spend read $0. LiteLLM itself kept serving and billing throughout;
the portal log carried only WARNING lines ("all-time spend query failed"),
easy to read as noise.
- **18:51:22** — the portal's `LITELLM_DB_PASSWORD` was re-synced from the
gateway's runtime env (value staged file→argv through the Cloudron API;
never printed, never committed). Aggregation restored immediately.
- **Same day, verification:** the source of truth (LiteLLM's own Postgres, read
gateway-side) held 125,385 rows / **$655.13** all-time; member teams 97 /
$652.88 — **no gap through the incident window**, because the gateway's own
writes were never affected. The member dashboard was verified restored (a
sample member's all-time figure matched the source exactly).
- **Same day, panel verification (final):** panel running image
`code/admin-panel:20261105-0713551` (matches the repo pin; code marker
confirmed in the container). Its data path is `GET /api/overview` → portal
`GET /admin/overview` (server-side, `X-Admin-Token: ADMIN_TOKEN`) — replayed
live from the panel container, HTTP 200. Displayed all-time total
**$653.08** with the co-op's own-accounts split **$170.73**, both matching an
independent SQL read of the source exactly; four sample members' all-time
figures matched the source to the cent. The full-table total ($655.33–655.41
while verifying — the ledger accrues live) decomposes exactly: members +
operators $653.08 + agent teams $1.18 (shown in the panel's Agents section) +
sandbox/unattributed rows $1.07 (displayed nowhere, accepted knowingly).
## Fix
1. **Immediate:** re-sync the portal's `LITELLM_DB_PASSWORD` from the gateway's
runtime env (18:51:22). Verified by re-reading the portal's aggregation
against the source, not by the absence of log lines.
2. **Standing guard (added the same day):** the daily digest
(cron job `95e5b8fece86`) gained a **SPEND CONSISTENCY** section: it runs
`~/.hermes/scripts/spend_consistency_check.py`, which compares the portal's
reported all-time spend (`/admin/overview` `totals.total_all_time_spend` +
the `agents[]` rows) against LiteLLM's own SpendLogs total — read from the
**gateway** app, the credential owner, so the source does not depend on the
copied credential. A $0 portal figure, a missing field, a mismatch beyond a
$5 tolerance (the deliberately-unattributed sandbox rows are ~$1), or an
unreadable source is a FAILED check reported near the top of the digest —
never as clean. All three failure branches were exercised (unreadable / $0 /
mismatch) and fire with exit 1; the live comparison passes with both numbers
printed. Do not substitute LiteLLM's `/global/spend` for the source: it
returns a ~30-day figure (~$576 when the table holds ~$655), not all-time.
3. **Practice (recorded here because it bit):** after any `app.restore` on this
box, diff the credential **fingerprint** (`sha256`[:8] of the value — never
the value) between the owner app and every app holding a copy, and re-sync
any that differ.
## Architectural dependency — read before rotating anything
**The portal does not hold its own LiteLLM DB credential. It aggregates from
LiteLLM's Postgres using a COPY of the gateway's addon credential.** They are
two copies of one secret with no shared source, and Cloudron rotates the addon
secret on every restore (and on any addon re-provision). Therefore:
- **A gateway DB credential rotation or restore MUST be followed by syncing the
portal's copy.** The rotation itself announces nothing; the only symptoms are
the portal's WARNING lines and $0 figures downstream.
- **Long-term fix (flagged, deliberately not done now):** both apps should
source the credential from ONE place — a shared secret location — or the
portal should not hold a DB credential at all (e.g. the gateway exposes a
read-only aggregation endpoint the portal calls). Either removes the
two-copies-of-one-secret failure mode.
- Until that lands, the digest's SPEND CONSISTENCY check is the drift alarm:
if it ever reports FAILED with a $0 or mismatched portal figure, check the
portal's `LITELLM_DB_PASSWORD` against the gateway's current addon credential
first, before theorising about code.
@@ -0,0 +1,89 @@
# Incident 2026-11-09 — a gateway deploy shipped the previous build's image; every surface said it succeeded
Backfilled 2026-11-11 (self-reported by the audit's missing-write-ups list;
facts from the steward skill's deploy reference, verified there on 2026-11-09,
and re-confirmed by a live recurrence on 2026-11-11 — see the end).
## What happened
During the 2026-11-09 gateway upgrade window, the LiteLLM gateway was updated
expecting the new build. Two distinct mechanisms of this platform's update
path combined to ship the WRONG code while everything reported success:
1. **`cloudron update --image <tag>` was a silent no-op for this app.** The
CLI exited 0, printed `App is updated.`, recreated the container, wrote the
tag into the app record — and the running code was unchanged. The builder
pushes images to the registry (`registry.inference.coop/<repo>`), never
into the host's docker, so a bare `local/…` reference cannot be pulled.
`cloudron status --app` also reported the new tag, so **every surface agreed
with the lie**.
2. **`cloudron update` without `--image` reuses the LAST builder build.** The
update does not build on-server; it takes the previous build package. A
deploy performed before (or without) a fresh build ships the PREVIOUS
commit's image under a fresh manifest. That day: new manifest shipped, old
image ran, both looked like success.
## Blast radius
- The gateway ran the **previous commit's code** after a deploy that was
believed to carry the new code — the deploy's intended change (and any
verification done against it) silently proved nothing.
- No data loss, no downtime: the old image was healthy. The damage was
epistemic — a deploy recorded as done that had not happened, which the next
session would have inherited as fact.
## Detection gap
`App is updated.` and a green health check are the platform's success story,
and they are true even for a wrong deploy. Nothing in the flow forced the
question "is the NEW code actually running?" — the check that catches this
(grep the RUNNING container for something only the new code contains) existed
as a rule but was not wired into the deploy itself.
## Resolution and the fix that now exists
The working deploy order, verified 2026-11-09 and again 2026-11-11:
1. **Commit first** — the build context is the git checkout; an uncommitted
overlay edit silently reverts on rebuild.
2. **Build FIRST**, always, via
`~/.hermes/scripts/cloudron_builder_build.sh <repository> <yyyymmdd>-<gitsha>`
from the app's OWN repo dir (the auth triple is not optional).
3. **Then update**: for an app whose repo manifest pins `dockerImage`
(librechat-custom, member-portal), write the built tag into the manifest,
commit, and `cloudron update --app <id> --force` (no `--image` — the pin
wins). For an app with NO pin (litellm's local/… manifest), update from the
app's own repo dir; a bare `--image` with a non-registry path is a no-op.
4. **Verify two facts, never the CLI's output**: the app record's
`manifest.dockerImage` equals the built tag, AND the running container
contains something only the new build produces (`cloudron exec --app <id> --
grep -c <marker> <path>` / an md5 of a changed file / a boot-log line the
new start path prints).
Rollback is the same command with the previous tag — record the running tag
before any deploy.
## Recurrence caught live (2026-11-11) — the trap is broader than "stale"
The 2026-11-11 validator deploys hit the same mechanism from the other side:
a **bare `cloudron update --app <gateway-id> --force`** (no `--image`, run
from a neutral cwd, with no pin in the gateway manifest) deployed **the last
build package globally — which was a different app's build** (the chat
overlay), replacing the gateway's image AND installed manifest. The app
reported healthy the whole time because the wrong image was itself a healthy
web app; the deploy verification battery (manifest tag check) caught it
within minutes and the gateway was redeployed correctly with an explicit
registry-path `--image` from its own repo dir (downtime ≈ 9 minutes,
03:55–04:04 UTC).
Standing rules this recurrence adds:
- A bare `cloudron update` deploys the LAST BUILD PACKAGE — manifest
included — and the "last build" tracking is **global, not per-app**. Never
run it for an app whose own build was not the immediately preceding build.
- An app whose manifest has no `dockerImage` pin must be updated from its own
repo directory; `--image` takes the full registry path
(`registry.inference.coop/<repo>:<tag>`), never a bare `local/…` reference.
- The two-fact verification (manifest tag + in-container marker) is what turns
this trap from an incident into a caught-in-minutes event; do the second
fact every time.
@@ -0,0 +1,358 @@
# Upgrade window — 2026-11-08 (Sunday evening): LiteLLM 1.103.2 → 1.108.0, LibreChat overlay 1.4.5 → 1.4.8
Both upgrades were **prepared and validated in advance** (2026-11-06); nothing has
been deployed. This runbook is written to be followed by any operator during the
member-watched maintenance window. Read the gotchas in §6 before touching anything —
this app pair has a history of deploys that look successful while changing nothing.
**Candidates (already built and validated, sitting in the registry):**
| App | Candidate | Rollback (currently deployed) |
|---|---|---|
| LiteLLM gateway (`adababd4-2427-4bdd-9bf7-6bdad0302610`, gateway.inference.coop) | branch `upgrade-v1.108.0` in `code/litellm`; prebuilt image `registry.inference.coop/local/ai.coop.litellm:1.0.0-20261106-9e25578` (STALE — see §0 and §3.1) | image `registry.inference.coop/local/ai.coop.litellm:20261107-201000-407e751e2` — the tag running tonight, verified present in the registry. `1.0.0-20261105-e161db9` is two deploys older and is NOT the rollback target |
| LibreChat chat (`4023ccbf-d57a-4500-97df-14de9cf3516e`, chat.inference.coop) | branch `bump-appstore-1.4.8` in `co-op/librechat-custom`; prebuilt overlay `registry.inference.coop/co-op/librechat-custom:20261106-c2aec74` | overlay `registry.inference.coop/co-op/librechat-custom:20261031-2a98892` (verified present) |
**Prep evidence (what was already verified, so Sunday only re-confirms it):**
- LiteLLM 1.108.0 candidate: all 8 build patches verified inside the running candidate
(file markers + build-log markers, zero WARNs); litellm reports 1.108.0.
- `patch_image_cost.py` (image-gen spend): a real image generation through the
candidate produced a **nonzero success SpendLogs row** — twice (fake OpenAI-shaped
endpoint and the real Regolo Qwen-Image API): `spend 0.0011403264` for 256×256 at
`$1.74e-8/px`, `call_type aimage_generation`, `status success`.
- `patch_passthrough_token_cost.py` (Metis metering): a real `/v1/systemone` call
logged `[coop-passthrough-cost] input_tokens=148 rate=1.2e-07 -> response_cost=1.776e-05`
and the SpendLogs row matched exactly (148 × $0.12/1M), tokens recorded.
- Member path: temp key generated with master auth → `/v1/models` (11 models) → real
chat completion (greenpt/glm-5.3-flash, "pong", usage 19/3 tokens, spend row written).
- Migrations: 36 new between 1.103.2 and 1.108.0, **all additive** (no unguarded
DROP/DELETE/UPDATE). A fresh DB ran the full 220-migration chain cleanly; the live
ledger (1.103.2) will apply only the 36 new ones.
- `budget_reset_at`: column unchanged on `LiteLLM_TeamTable`; a direct-DB write
(the portal's exact pattern) plus API read-back verified on the candidate.
- Portal API compatibility: `/team/list` (bare list) and `/key/list`
(`{keys, total_count, …}`) shapes are **unchanged**; a bare `/team/list` call still
returns ALL teams (pagination only applies when `page`/`page_size` are passed —
verified with 11 teams); `/team/update` still drops `budget_reset_at`, so the
portal's direct-DB write remains required. SpendLogs gains only an additive
`billing_agent_id` column — digest queries are unaffected.
- LibreChat 1.4.8 (appstore `ai.librechat.cloudronapp`): changelog 1.4.5 → 1.4.8 is
tooling only — uv 0.13.6/0.13.7 and Node.js 22.23.4 (security fix, 1.4.7); the
LibreChat upstream stays 0.8.8. Every overlay patch anchor (title tag, manifest
link, theme-color metas, webmanifest colors, "MCP Servers" / "Every AI for
Everyone." strings, `index.*.js`, `sw.js`) was verified against the real 1.4.8
image — **no overlay porting needed**; the candidate overlay built with all
markers (UI strings patched in 3 files, index/manifest branding applied).
## 0. State re-check — 2026-11-09 04:15 UTC (read live before the window)
Verified against the live box on the night of the window. Anything here that
contradicts the prep notes above is newer and wins.
- **Gateway:** image `registry.inference.coop/local/ai.coop.litellm:20261107-201000-407e751e2`
(deployed 2026-11-07 20:10 UTC), in-container version **1.103.2**, 8 expected models
+ extras, healthy. **The rollback target is therefore THIS tag, not
`1.0.0-20261105-e161db9`** (see §3.3).
- **Chat:** overlay `registry.inference.coop/co-op/librechat-custom:20261031-2a98892`,
appstore 1.4.5, healthy. `master` is 2 commits ahead of `bump-appstore-1.4.8`, but both
touch only `librechat.yaml` — a persistent-volume file that is NOT baked into the image,
so pinning the Nov-06 candidate does not revert them.
- **Registry:** all four tags this plan needs are present —
`local/ai.coop.litellm:{1.0.0-20261106-9e25578, 20261107-201000-407e751e2}` and
`co-op/librechat-custom:{20261106-c2aec74, 20261031-2a98892}` (listed from the registry
app's own storage).
- **`upgrade-v1.108.0` is 5 commits BEHIND `main`.** main gained
`patch_transcription_response_format.py`, `patch_audio_default_mp3.py` and
`audio_keepalive.py` (Dockerfile RUN/chmod lines) plus the STT/embedding model additions
on 2026-11-06/07, all after the candidate branch was cut. Merging the branch into main
(as §3 does) carries both sides — but the **prebuilt candidate image does NOT contain
them** (see the §3.1 fallback note and the extended marker list).
- **Version target:** the branch pins **1.108.0**; latest stable upstream is **1.108.3**
(2026-11-07). The prep validates 1.108.0 only — ship 1.108.0 tonight unless someone
re-runs the anchor/migration validation against 1.108.3 first.
- **Backups are NOT healthy.** Last successful Cloudron backup: **2026-11-08 21:18 UTC**
(box, encrypted v2, state normal). The scheduled **2026-11-09 04:00 UTC run FAILED**
(`tarPack pipeline error … aborted` — the same signature as the Infomaniak S3 quota
rejections of 2026-11-06/07/08). The pre-flight backups in §2.1 are this window's undo
and must be proven to land before anything is deployed.
## 1. Order: LiteLLM first, then LibreChat
LibreChat's post-upgrade checks (key sync, a real chat completion) run **through the
gateway** — doing the gateway first means those checks also exercise the new
gateway, and each upgrade stays an isolated abort point: if LiteLLM fails, roll it
back and skip LibreChat (chat keeps serving on the old overlay); if LibreChat fails,
the new gateway is already proven.
## 2. Pre-flight (both apps, ~5 min)
```bash
set -a; . ~/.hermes/.env; set +a
CR() { cloudron --server my.inference.coop --token "$CLOUDRON_TOKEN" "$@"; }
# 2.1 Fresh update-rollback backups (DB + volume snapshot each)
CR backup create --app adababd4-2427-4bdd-9bf7-6bdad0302610
CR backup create --app 4023ccbf-d57a-4500-97df-14de9cf3516e
CR backup list --app adababd4-2427-4bdd-9bf7-6bdad0302610 | tail -3 # note newest id
CR backup list --app 4023ccbf-d57a-4500-97df-14de9cf3516e | tail -3
# 2.1b PROVE the backup landed BEFORE deploying. The backup pipeline is failing on the
# Infomaniak S3 plan quota (last success 2026-11-08 21:18 UTC; the 04:00 UTC run on
# 2026-11-09 failed again). Re-run `CR backup list --app <id>` and require a NEW id
# with state normal — an unchanged newest id, or no new entry, means this window has
# NO undo. Decide before deploying, not after.
# 2.2 Record the member-visible baseline for after: number of keys and teams
# (use the MASTER key — it is in /app/data/.master_key inside the gateway:
# CR exec --app gateway.inference.coop -- cat /app/data/.master_key
# then GET /key/list and /team/list with it; count both. NEVER paste the key.)
```
## 3. LiteLLM 1.103.2 → 1.108.0 (~20–35 min)
```bash
cd ~/repos/litellm # ONE APP = ONE REPO DIR. Never run an update
git fetch origin && git checkout main && git pull # for another app from this cwd
git merge upgrade-v1.108.0 # branch is pushed; approve the merge in Gitea
# if you prefer the PR path
git log --oneline -1 # note the sha
```
3.1 **Deploy (on-server build — the repo manifest has no `dockerImage` pin, so
`cloudron update` builds and swaps; do NOT pass `--image`):**
```bash
CR update --app adababd4-2427-4bdd-9bf7-6bdad0302610
```
- The build output must contain **all TEN** patch markers (each is one line in the
build log; a missing line = that patch silently did not apply — STOP and check):
1. `INFO: patched budget-exceeded messages in …/auth_checks.py`
2. `INFO: patched image-cost registration in …/router.py`
3. `[coop-patch] applied to …/cost_calculator.py`
4. `[coop-patch] applied audio shared pricing to …/router.py`
5. `[coop-patch] applied: provider response headers are no longer forwarded …`
6. `expose-cost-headers: appended 20 cost header names to expose_headers …`
7. `[coop-patch] applied: passthrough-key-access -> …/route_checks.py`
8. `[coop-patch] applied: passthrough-token-cost -> …/success_handler.py`
9. `[coop-patch] applied skip-verbose_json to …` (patch_transcription_response_format.py)
10. `[coop-patch] applied TTS default mp3 to …` (patch_audio_default_mp3.py)
- `audio_keepalive.py` must be copied and `chmod +x`'d in the build (start.sh calls it for
the TTS warm path). Markers 9–10 and this file are the 2026-11-06/07 audio work; missing
any of them means that work silently reverts to the pre-Nov-06 behaviour.
- **Boot**: LiteLLM runs `prisma migrate deploy` (the 36 additive migrations) before
binding port 4000. Expect `502`/`ECONNREFUSED` on health checks for a few minutes
(10–20 in the bad case). **Never restart mid-wait** — a restart resets the
migration clock. Once `/health/liveliness` returns 200, continue immediately
("up" ≠ "migrated"; the checks below are the proof).
- **DO NOT use the prebuilt candidate as a flake fallback tonight.** It exists
(`…ai.coop.litellm:1.0.0-20261106-9e25578`, and `--image` would work because the repo
manifest carries no `dockerImage` field), but it was built from the branch tree and
therefore predates `patch_transcription_response_format.py`, `patch_audio_default_mp3.py`,
`audio_keepalive.py` and the STT/embedding model additions. Deploying it reverts the
2026-11-06/07 audio and model work. If the on-server build flakes, fix the build or build
the merged tree — the candidate image is not usable tonight.
3.2 **Verify (in order — a failing early step means stop, not continue):**
```bash
# 1. version inside the running container
CR exec --app gateway.inference.coop -- \
/app/.venv/bin/python3 -c "from importlib.metadata import version; print(version('litellm'))"
# → 1.108.0
# 2. patch markers inside the RUNNING container (not the build log alone)
CR exec --app gateway.inference.coop -- sh -c \
'grep -c "CO-OP PATCH (2026-10-19)" /app/.venv/lib/python3.13/site-packages/litellm/router.py; \
grep -c "x-litellm-response-cost-input" /app/.venv/lib/python3.13/site-packages/litellm/proxy/proxy_server.py'
# → 1 and 1
# 2b. supply-chain IoC check (standing policy on every LiteLLM image change):
CR exec --app gateway.inference.coop -- sh -c \
'ls /app/.venv/lib/python3.13/site-packages/litellm_init.pth 2>/dev/null; \
ls /root/.config/sysmon 2>/dev/null; \
ls /tmp/pglog 2>/dev/null; echo IOC-CLEAN'
# → must print ONLY "IOC-CLEAN" (no such files). Any hit = stop, quarantine, rotate
# the gateway env keys (master + providers live in that env).
# 3. MEMBER-SCOPE key path (master-key tests alone prove nothing — master bypasses
# exactly the tables a broken migration empties):
# POST /key/generate {"alias":"upgrade-verify-temp"} (master auth) → temp key
# GET /v1/models with the TEMP key → 11 models
# POST /v1/chat/completions {"model":"greenpt/glm-5.3-flash",
# "messages":[{"role":"user","content":"Reply with the single word: pong"}],
# "max_tokens":16} → content + usage
# GET /key/list (master) → same count as §2.2
# POST /key/delete {"keys":["<temp>"]} → 200
# 4. CORS preflight (chat origin must be allowed):
# OPTIONS /v1/models with Origin: https://chat.inference.coop → 200 + allow-origin
# 5. Cloudron state
curl -sS -H "Authorization: Bearer $CLOUDRON_TOKEN" \
https://my.inference.coop/api/v1/apps/adababd4-2427-4bdd-9bf7-6bdad0302610 \
| python3 -c "import sys,json; a=json.load(sys.stdin); a=a.get('app',a); print(a['health'], a['runState'], a['manifest'].get('dockerImage'))"
# → healthy running registry.inference.coop/local/ai.coop.litellm:<new tag>
# 6. Watch 10–15 min of real member traffic before closing:
# SpendLogs rows arriving with status 'success' (portal admin panel or
# GET /spend/logs with master auth). Failure rows with call_type = a route
# path and spend 0 are 401-refusals, not duplicates.
```
3.3 **Rollback (one command; the additive migrations make old-code-on-new-schema safe):**
```bash
CR update --app adababd4-2427-4bdd-9bf7-6bdad0302610 \
--image registry.inference.coop/local/ai.coop.litellm:20261107-201000-407e751e2
```
If member keys 401 after any image change, the schema is the suspect: read the
exact error text from a member key call — a missing-relation error names the failing
path; do NOT reissue keys. (Full recipe: `code/litellm` README, "Verify after
upgrading".)
## 4. LibreChat overlay 1.4.5 → 1.4.8 (~10–15 min)
```bash
cd ~/repos/librechat-custom # again: one app = its own repo dir
git fetch origin && git checkout master && git pull
git merge bump-appstore-1.4.8 # overlay code is UNCHANGED apart from the
# FROM pin — appstore 1.4.8 carries the same
# LibreChat 0.8.8; only Node/uv/base bumped
set -a; . ~/.hermes/.env; set +a
# The candidate overlay is already built: pin + deploy via the repo's release tool
./release.sh pin 20261106-c2aec74 # writes dockerImage into CloudronManifest.json, commits, pushes
./release.sh deploy # cloudron update --force from THIS dir, then verify
```
4.1 **Verify** (release.sh verify runs the served-HTML checks; confirm the rest by hand):
```bash
./release.sh verify # title = Inference Co-op, x-coop-build meta present
# key sync task ran (manifest scheduler `librechat_key_sync`, every minute):
CR logs --app chat.inference.coop --lines 100 | grep -i "sync" | tail -5
# → the sync script prints its own md5 prefix each run; it must be the new build's
# RAG service: the appstore package runs rag_api alongside; confirm no crash loop
curl -sS -o /dev/null -w "%{http_code}\n" https://chat.inference.coop/ # 200 (SSO shell)
# login via Cloudron SSO in a browser, then send one real chat completion through
# LibreChat (this exercises chat → NEW gateway → provider end-to-end)
```
4.2 **Rollback:**
```bash
cd ~/repos/librechat-custom
./release.sh pin 20261031-2a98892 && ./release.sh deploy
```
## 5. Window estimate
| Phase | Time |
|---|---|
| Pre-flight + backups | 5 min |
| LiteLLM build+swap (on-server build) | 5–10 min |
| LiteLLM boot migrations + member-scope verification | 10–20 min |
| LibreChat pin+deploy+verify (incl. an SSO login + one chat) | 10–15 min |
| Post-watch on SpendLogs / close-out | 10 min |
| **Total** | **~45–60 min** |
## 6. Gotchas that have each bitten this stack once
1. **One app = one `cd`, immediately before its update.** `cloudron update` reads
`CloudronManifest.json` from the CURRENT directory; updating app B from repo A's
dir ships A's manifest to B — on 2026-11-05 that dropped the gateway's postgres
addon and wiped the LiteLLM DB (~50 min member outage, restored from the
pre-deploy snapshot). The pre-deploy backups in §2 are the undo; addons-block
changes are DATA-BEARING.
2. **A pinned manifest beats `--image`, silently.** LibreChat's repo manifest pins
`dockerImage` — always change the pin (release.sh pin), never pass `--image` to
it. LiteLLM's repo manifest has NO pin — `--image` works there (used for its
rollback and build-flake fallback above).
3. **"App is updated." proves nothing.** Verify the running image tag via the API
AND a container-content marker (§3.2 steps 1–2, §4.1) before trusting any check.
4. **Don't restart the gateway mid-migration-wait** — it resets the boot clock.
5. **Do not "fix" `/team/update` dropping `budget_reset_at` today** — the portal's
direct-DB write is the known, verified workaround; it still works on 1.108.0.
6. After both apps are up, `app-inventory.md` in this repo should be updated with
the new pins in the same session (it mirrors live state).
7. **The prebuilt candidate is not the tree you are deploying.** The branch was cut five
commits behind `main`; the merge supplies the rest, the prebuilt image does not. Verify
the TEN build markers of §3.1 inside the running container, not the old eight.
8. **A stale rollback reference is worse than none** — the runbook pointed at a Nov-05
image while the box was running a Nov-07 build, so "roll back" would have silently
dropped two days of member-visible fixes. Re-read the running tag (§0/§2.2) immediately
before any rollback, and roll back to what was actually running.
9. **The backup pipeline is itself an open incident.** Assume no undo until a pre-flight
backup shows `state: normal` with a new id.
## 7. If something looks wrong
- Member keys 401 with a missing-relation error → schema/migration issue; see
§3.3 and the `code/litellm` README triage section. Restore path: the §2 backup,
then re-pin the old image.
- Chat serves a stale shell after the overlay deploy → wait ~60 s (mid-swap) and
re-check; release.sh verify already retries fetches.
- Anything else: halt at the failing step, note the exact command + output, roll
back that app only, and leave the other app on its new version if it verified.
## 8. Executed — 2026-11-09, 04:41–05:05 UTC (what happened, and where it differed)
Order followed as planned: LiteLLM first, then LibreChat. Two deliberate changes:
1. **Target 1.108.3, not 1.108.0** — latest stable, and it pins the *same*
`litellm-proxy-extras==0.4.110`, so the migration set is exactly the one validated here
(36 new, all additive). All ten build-patch anchors were re-validated against the real
1.108.3 sources first; `patch_expose_cost_headers.py`'s 1.108.x anchor applied.
2. **A pre-built, pre-verified image was deployed, not an on-server build** —
`20261109-c43d45c`, built from `upgrade-v1.108.3` (cut on top of `main`, so it carries the
2026-11-06/07 audio patches the original candidate predated) and exercised first as a
throwaway app (`gateway-dryrun.inference.coop`, its own Postgres/Redis, no member data).
**The one thing that did not go as written — the pre-update snapshot OOMs.**
A default `cloudron update` died at `Backup - Snapshotting app gateway.inference.coop`:
task 1430 → `Task 1430 ran out of memory or terminated`, box log `Memory peak: 401.8M`,
`oom-kill`. Cloudron's app-task service runs with a **hard 400 MB cgroup limit**
(`startTask … "memoryLimit":400` from the system log), and this gateway's snapshot now
exceeds it. Production was never at risk — the app kept serving the old image; only
`installationState` went to `error`.
**Workaround used: `--no-backup`**, with the 04:41 pre-flight app backups as the undo —
which is what §2.1 is for. Next time: take the app backups first, then
`cloudron update … --no-backup`.
**Also learned the hard way:** `--wait-timeout` is a GLOBAL option, so
`cloudron --wait-timeout 45m update …` works and `cloudron update --wait-timeout …` errors out.
### What was verified live afterwards
- **gateway** `…ai.coop.litellm:20261109-c43d45c` — litellm **1.108.3**, extras 0.4.110;
**all ten** patch markers present in the *running* container; `audio_keepalive.py`
executable; IoC check clean; migrations **185 → 221**, none failed or rolled back;
keys 210 / teams 111 unchanged; temp member key → `/v1/models` (15 models) → real
completion → **success SpendLogs row**; CORS preflight 200. Member traffic within ten
minutes: 73 success rows.
- **chat** `…/librechat-custom:20261106-c2aec74` (appstore 1.4.8 / LibreChat 0.8.8) —
`release.sh verify` all checks passed, key sync running every minute (108 member keys,
revision matches the repo), Meili resync normal, served title still `Inference Co‑op`.
### Migrations were rehearsed, not merely run
Before the window, the live gateway database was restored from the 2026-11-08 stopgap
snapshot into a local PostgreSQL **18.6** (prod's exact version) and the image's own
entrypoint (`python -m prisma migrate deploy`) was run against it: **185 → 221 applied in
12 s**, row counts identical (210 keys / 111 teams / 138,422 spend rows), **no table lost**
(90 → 110, the 20 additions all new-feature tables). That is what made `--no-backup`
acceptable on the real box.
### Not rehearsed
The LibreChat leg — a second chat app means ~2 GB of data plus its Meili/rag stack, for a
change that is tooling-only (Node/uv; LibreChat upstream unchanged). Mitigation is the
one-command rollback: `./release.sh pin 20261031-2a98892 && ./release.sh deploy`.
+12 -4
View File
@@ -87,10 +87,18 @@ having failed.
### Other mechanics
- Weekly `restic check` on Sundays (repo metadata); full data check monthly.
- The passphrase (`RESTIC_PASSWORD`) lives in `~/.hermes/.env` **and** the co-op
Vault. A backup whose key exists only on the backed-up box is not a backup.
- S3 credentials come from `SWB_S3_ACCESS_KEY` / `SWB_S3_SECRET_KEY` (mapped to
`AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` in the script).
- Backup credentials (`RESTIC_PASSWORD`, `RESTIC_REPOSITORY`,
`SWB_S3_ACCESS_KEY`, `SWB_S3_SECRET_KEY`) live in **root-only
`/etc/agent-backup.env`** (0600) and in the co-op Vault — never in the
steward agent's `~/.hermes/.env`. The systemd timer runs as root; the agent
can run the backup but cannot read or delete its credentials.
- **Versioning is enabled** on the Swiss Backup S3 bucket (2026-11-20).
Deleting a snapshot object now creates a delete marker; the previous bytes
remain recoverable. This is not object lock: stolen keys can still delete
the current version, and the provider rejected noncurrent-version lifecycle
rules, so old versions accumulate until manually cleaned. Watch the quota.
- **Object lock is unavailable** on this bucket; it was never enabled at
creation and the provider does not offer an append-only policy here.
## 2. Cloudron app backup
+37
View File
@@ -0,0 +1,37 @@
# Agent host root access
The steward agent (`ubuntu`) does **not** have passwordless root for arbitrary commands. The cloud-init `ubuntu ALL=(ALL) NOPASSWD:ALL` rule was removed on 2026-11-20.
## What `ubuntu` may run without a password
`/etc/sudoers.d/90-inferencebot-restricted` allows only:
- `systemctl start|stop|restart docs-deploy-poll.service`
- `systemctl start|restart agent-backup.service`
- `systemctl start|restart agent-backup.timer`
- `journalctl -u docs-deploy-poll.service ...`
Everything else — package installs, user management, file writes under `/etc`, arbitrary shells — requires operator credentials or a new root-owned helper. Do not re-add `NOPASSWD:ALL` to make a task convenient.
## Root-owned execution paths
- The docs publisher is split: `/usr/local/sbin/docs-poll` and `/usr/local/sbin/docs-publish` are root-owned; the build runs as `docsbuild` without credentials.
- The nightly backup runs as root from **`/usr/local/sbin/agent-backup`** via an `agent-backup.service` drop-in. The script is root-owned; the agent's `~/.hermes/scripts/backup.sh` is no longer executed by the unit and must not be treated as root code.
- Backup credentials live in root-only `/etc/agent-backup.env`.
## Residual root-trust gap (operator root required)
The root-owned backup script still resolves `restic` from `/usr/local/bin/restic`, which is owned by `ubuntu`, and it still sources `/home/ubuntu/.hermes/.env`. An agent-writable binary or `PATH` line there is therefore a root code-execution path through the nightly backup timer. Until root fixes it:
- `chown root:root /usr/local/bin/restic` (or install a root-owned copy and call it absolutely)
- remove `/home/ubuntu/.local/bin` from the root script’s `PATH`
- stop sourcing `/home/ubuntu/.hermes/.env` from the root script
- remove the Hermes-python `pip list` diagnostic
This requires root outside the agent; the restricted sudo policy does not grant it. Treat the backup timer as privileged until fixed.
A daily root-trust watchdog (cron `82130f968506`, `check_root_trust.py`) stays silent when healthy and alerts if broad sudo returns, the root backup script starts trusting agent files again, or `/usr/local/bin/restic` is not root-owned.
## Recovery (operator only)
The pre-change cloud-init sudoers file is preserved at `/root/sudoers-cloud-init.bak` (0600). Restoring it requires root access outside the agent, e.g. the provider console. Do not expose it to the agent.
+15
View File
@@ -0,0 +1,15 @@
# Test rows in the credit ledger — deliberately kept (audit L7, 2026-11-05)
The portal `credit_ledger` carries a handful of historical test rows from the
early build ("test credits (will revert)", "admin test - collective expense",
and the matching reverts). They are **net zero** against member balances and
every one is paired with its reversal.
Decision: leave them in place. Rewriting the money ledger — even to remove
test noise — destroys the audit trail's property of "what's in the table is
what happened"; the pollution is cosmetic and far outweighed by the cost of
ever being wrong about a ledger edit. This note is the record; no code or data
change accompanies it.
If the ledger ever grows a reporting consumer that must exclude them, filter
by the `reason` text at query time rather than deleting rows.
+61
View File
@@ -0,0 +1,61 @@
# LibreChat key feed (`/admin/librechat/keys`) — design decision (audit M2)
Audited 2026-11-05. Status: **kept as-is, with monitoring**; a per-member
fetch was considered and deliberately rejected.
## What the route is
`GET https://portal.inference.coop/admin/librechat/keys`, authed by a single
static token (`LIBRECHAT_SYNC_TOKEN`, held by the portal and the LibreChat
sandbox app). It returns every ACTIVE member's decrypted chat key so the
sandbox's in-app key-sync (`librechat_key_sync`, every 10 min inside the
LibreChat app; `sync-keys.js`) can seed LibreChat's per-user key store —
members never see an API-key prompt, and chat bills to each member's own
LiteLLM team/budget.
## Blast radius (why the audit flagged it)
The sync token unlocks every member's chat key in one response. Anyone holding
the token (sandbox compromise, token leak from the sandbox env) reads the whole
membership's keys. It is a deliberate exception to the admin token — members'
key storage is decrypted in the portal only for this feed and for serving a
member's own dashboard.
## Why a per-member fetch was rejected (the riskier path)
The sandbox is the ONLY consumer, and it does not know which member it is
seeding at the API layer — it seeds ALL members in one pass from one identity.
Scoping the feed per member means changing the sandbox's identity model
(per-member credentials or a member list with per-member auth), touching
`sync-keys.js` and the seeding loop. A wrong change there stops key seeding
for every member at once — the exact regression the audit order forbids
("nothing breaks"). The feed also runs on a fixed cadence, so the practical
exposure window is bounded by how fast misuse would show.
## What is in place instead (2026-11-05)
1. **Internal-network restriction**: `/admin/librechat/keys` refuses any
request whose last `X-Forwarded-For` hop is a public address (`403 Internal
network only`). A stolen sync token used from the internet no longer looks
like the sandbox.
2. **Timestamped HMAC**: the sandbox sends `X-Sync-Timestamp` and
`X-Sync-Signature` (HMAC-SHA256 over the timestamp, path and query) using
`KEY_FEED_HMAC_SECRET`; the portal rejects a missing, stale (>60 s) or
wrong signature. The secret lives in the portal app env and the sandbox's
`/app/data/env`. If the secret is absent the portal falls back to token-only
for rollout compatibility; production sets it.
3. **Access logging on the route**: every fetch logs a WARNING line
`librechat key feed served: N member key(s) to <ip>`. Count and client
address only — never key material, never member emails.
4. **Daily-digest watch** (cron job 95e5b8fece86, §7 anomaly list): the
sandbox polls **every minute (~1,440/day) by design**; the old ~144/day
baseline was stale. The digest flags (a) a rate far above ~1/min, (b) any
401/ERROR burst, or (c) any `REFUSED for non-internal address` line —
either is suspected token misuse and becomes a decision item.
## What a real fix looks like (if ever needed)
Move the sandbox to fetch per member: a new portal route keyed by the member
identity the sandbox already knows at seed time, plus a sandbox-side change to
seed from that route. Only worth doing when the sandbox is already being
modified for another reason — never as a standalone risky change.
+69
View File
@@ -0,0 +1,69 @@
# Model transitions (changing what a gateway model serves)
A provider retires or replaces a model we serve. The gateway can absorb this in two
shapes, and picking the right one is the first decision, not a detail.
**Repoint or rename.**
- **Repoint** — keep the `model_name`, change only `litellm_params.model` and
`model_info` prices. No member config breaks. Use this whenever clients may pin the
prefixed id.
- **Rename** — a new `model_name`. Honest about the version, but every client config
pinned to the old id starts returning `400 Invalid model name … Call /v1/models`.
We cannot see those configs.
**Measure before choosing.** Spend logs record the *requested* name in `model_group`
and the upstream string in `model`. Group one page of `/spend/logs` and compare traffic
on the alias vs the prefixed id:
```python
rows = GET https://gateway.inference.coop/spend/logs # master key
Counter((r["model_group"], r["model"]) for r in rows if "deepseek" in r["model_group"])
```
On 2026-11-16 that comparison was 3,014 calls on `greenpt/deepseek-v4.1-flash` against
84 on `deepseek-flash-green` — which settled it in favour of repointing.
## Checklist
1. **`config.yaml` (gateway)** — update the pointer `litellm_params.model` **and** the
`model_info` prices. Do it for **every deployment that carries its own copy**: the
provider-prefixed entry *and* any alias that duplicates the params
(`deepseek-flash-green` is a separate entry with its own pointer and prices — miss
it and the alias keeps billing the old rate). Update the header price comment and the
entry comment, since a repointed name no longer says which snapshot it serves.
2. **`librechat.yaml` (chat picker)** — only needed on a RENAME. The picker is a
hand-maintained list of provider-prefixed ids in two places: `models.default` and
each `modelSpecs` entry's `label` + `preset.model`. A repoint needs no picker change.
(`models.fetch: true` does not add entries to the visible dropdown — verified by
observation, not by reading the config.)
3. **Portal emission factors** — `member-portal/metrics_snapshot.py` keys Wh/1k-out and
gCO2e factors on the model-group name, and `app/main.py` carries a display-name map.
A RENAME requires updating both or Energy/Carbon silently drops from MEASURED to
unmeasured. A repoint needs nothing.
4. **Docs** — `docs/models.md` (default line and the table row: price + which snapshot),
`docs/api-access.md` alias table (only if the id changes), `docs/energy.md` (only if
renamed), `ops-docs/provider-pricing/<provider>.md`.
5. **Validate** — `python3 validate_config.py litellm config.yaml`. Fail-closed: an
unknown top-level key or unresolvable provider prefix refuses the build.
6. **Build, pin, deploy.**
7. **Verify by spend row, not by HTTP 200.** A successful call proves nothing about
what it pointed at. Read the newest `/spend/logs` row: `model_group` must be the name
you called and `model` must be the provider's new upstream string. Confirm aliases
bill under their own name.
8. **Tell members** — append a line to `~/.hermes/cron/updates_notes.jsonl` and it lands
in the next digest's Stewarding section; recommend pinning the alias.
9. **Record** — comment on the originating issue/PR with the shape chosen and why.
## Deprecating a name instead of deleting it
If a rename is eventually wanted, add the versioned id **alongside** the old one (both
pointing at the same upstream), tell members to migrate, and remove the old entry only
when `model_group` traffic on it reads zero for a full cycle. That trigger is measurable,
so retirement is a data decision rather than a judgement call.
## Three independent lists
`config.yaml` (what exists), `librechat.yaml` (what the chat offers), and the docs alias
table (what members are told) are separate lists. A single transition touches all three;
repointing touches one. That asymmetry is the strongest argument for repointing.
+75
View File
@@ -0,0 +1,75 @@
# Member provisioning boundary — who auto-provisions from Open Collective
Which Open Collective contributors become portal members automatically, and
which are deliberately excluded. The portal defines the member set in
`fetch_members()` (member-portal repo, `app/main.py`), acts on it in the
webhook and the nightly `reconcile_memberships()` sweep, and exposes two admin
overrides: `POST /admin/org-link` and `POST /admin/provision`. A daily
watchdog (below) is the net for anything that slips past both.
## Auto-provisioned
**Individual OC accounts holding BACKER/ADMIN on the Membership tier (or no
tier — pre-tier contributors are grandfathered) whose email is visible to the
admin token.** The webhook provisions on first payment; the nightly sweep
(03:00 scheduler task) provisions anything missed within 24h and deactivates
lapsed members. `fetch_members()` matches the tier by NAME
(`"membership"`, case-insensitive): renaming the tier on Open Collective
silently empties the member set — the sweep's fail-safe skips reconciliation
rather than deactivating everyone, but provisioning also stops.
## Deliberately excluded
1. **Org-backed memberships.** An ORGANIZATION account never exposes an email
(the `... on Individual { email }` fragment matches nothing, and OC returns
org emails as null even to collective admins), so reconcile cannot map one
and does not try. Org-backed memberships become members only when LINKED:
`POST /admin/org-link {"org_slug", "email", "name"}` runs the full
provisioning pipeline and stores `members.org_slug`; the sweep keeps linked
accounts active while the org holds BACKER/ADMIN on the Membership tier and
deactivates them when the org's dues lapse (fail-safe: if the org fetch
itself errors, linked accounts stay active). An unlinked org's first
payment emails info@ with the exact linking command.
2. **Non-membership tiers (Credit pack).** A one-time purchase grants BACKER
role but is NOT a membership — `fetch_members()` filters it out. This is
why a contributor can pay, appear in the public backer list, and still have
no portal member row: it is a credit-pack purchase, not a lapsed
provisioning. The money is not lost: the webhook's held-credit-pack flow
records a hold, notifies the buyer, and the operator grants, refunds or
transfers it via `/admin/credit-packs-held`; a hold granted to a named
member auto-applies if that person later becomes a member.
3. **Manual members.** The `MANUAL_MEMBERS` env allowlist (founder/free tier,
the co-op's own accounts) holds members with no OC membership BY DESIGN:
never auto-provisioned from OC, and exempt from lapsed-membership
deactivation. Check for orphaned LiteLLM `member:*` teams after any
`MANUAL_MEMBERS` change.
4. **Hidden-email / anonymous contributors.** An individual whose email is
null even in the ADMIN view cannot be mapped by reconcile. They are not
silently dropped — the daily watchdog reports them with their public dues,
and provisioning is manual: `POST /admin/provision {"email", "name"}` on
the operator's instruction. Incognito accounts publish an
`incognito-xxxxxxxx` slug, but the ADMIN member query usually still reveals
their email — always check the admin view before treating one as
unmappable (that is what resolved the mmoya case).
## The watchdog: `oc_unmapped_check.py`
Daily no-agent cron on the agent host (07:20, job `d0fd1126cc80`), running
`~/.hermes/scripts/oc_unmapped_check.py` — the same silent-until-findings
pattern as the spend-consistency guard. It reads the collective's backer list
through the portal env's admin token and the portal rows read-only via
`cloudron exec`, maps them by email, slug or org_slug, and prints ONLY
member-ish backers (the exact set `fetch_members()` treats as members) with no
portal row at all: slug, display name, whether the admin view sees an email,
dues (amount/frequency/status from the public order list), days as a backer,
and the matching action (org-link vs /admin/provision vs investigate-the-sweep).
Backer nodes with no account object (deleted/incognito-hidden accounts) are
attributed via same-day public orders and stay silent when every same-day
payer is already mapped. Excluded from findings: credit-pack-only backers
(the held-credits flow owns them) and backers matching an inactive portal row
(the sweep re-provisions/reactivates those within 24h). Empty output = clean;
any fetch failure prints FAILED — a check that cannot look never reads as
clean.
@@ -0,0 +1,96 @@
# Shared code: guest state and the OIDC client (2026-11-11 consolidation)
The fragile-framework audit found the guest invited/active state logic
triplicated (portal `app/main.py` admin_overview, dashboard page JS, panel page
JS) and `app/oidc.py` near-duplicated between the dashboard and the panel
(21-line diff: logger name, session cookie, session salt, docstring, one dead
line). This note records how both were consolidated and how to change them
safely from here.
## Guest state — the portal is the single derivation point
`member-portal` computes a guest's display state ONCE, in the `/admin/overview`
row (and the same semantics ride the `/broker/guests` trail):
1. invite not yet accepted (Cloudron `inviteAccepted` false AND no username,
from a SEEN user record) → `state: "invited"` — never "active";
2. otherwise → the guests-ledger status (active / converted / expired /
depleted / cancelled by recipient) — the record of record;
3. no ledger row → the membership state (active/inactive) as fallback.
Tested once, in `member-portal/tests/test_guest_invited_state.py`.
The consumers are pure shims — first served field wins, NO derivation from
flags anywhere:
- **admin panel** (`admin-panel-guests-harness.js` asserts this): `state` →
`guest_status` → nothing (an empty pill; a payload with neither field no
longer exists and must not be re-derived). `guest_status` first keeps the
previous payload shape rendering identically during a portal rollback.
- **member dashboard** (`dashboard-guests-harness.js`): trail pill reads
`state || status` (unchanged behaviour; comment updated).
Changing the derivation means changing the PORTAL + its test, then syncing the
consumer comments/harnesses if the vocabulary changes. Never re-add a
derivation to a consumer.
## OIDC client — one canonical module, byte-identical copies
- **Canonical:** `scripts/shared/oidc_client.py` (this repo).
- **Copies:** `member-dashboard/app/oidc.py`, `admin-panel/app/oidc.py` —
byte-identical to the canonical by sha256. Each app calls
`oidc.configure("<app>", "<cookie>", "<salt>")` in `main.py` at import time
with its HISTORICAL cookie name and salt, so existing sessions survive.
- **Why copies, not a portal-served config:** OIDC is each app's LOGIN path;
making it depend on the portal being up would trade a small duplication for
a cross-app outage coupling. Copies keep every app self-contained; the sync
tooling keeps them identical.
- **Change procedure:** edit the canonical → run
`scripts/sync-oidc-module.sh` (re-copies both, re-pins, py_compiles, runs
the check) → commit all three repos. NEVER hand-edit a repo copy:
- each repo's `tests/test_oidc_sync.py` pins the copy to the canonical
revision's sha256 and goes red on any hand edit;
- `scripts/check-oidc-sync.py` is the pre-deploy gate (run before building
either thin app) and verifies copies, pins and configured identities;
- `scripts/shared/test_oidc_client.py` is the steward-host behaviour harness
(stubs authlib/httpx; needs `pip install itsdangerous`): configure(),
lazy-logger attribution, session roundtrip, cross-app salt isolation.
Woodpecker CI currently runs the panel's guard+harnesses and the portal's 12
suites but does NOT run the new pin tests (CI was out of scope for the
consolidation). Adding `python3 tests/test_oidc_sync.py` to both thin apps'
pipelines is a one-line follow-up; until then the pre-deploy
`check-oidc-sync.py` run is the drift gate.
## Deploy record 2026-11-11 (zero downtime)
Order: portal first (source of truth), then dashboard, then panel; each built
from its own repo dir, verified by running image tag + container md5 + code
marker + health + real payload fetch. Chat/gateway untouched throughout.
| App | New tag (deployed) | Rollback tag (previous) |
|---|---|---|
| member-portal | `code/member-portal:20261111-58214be0` | `code/member-portal:20261108-2954fe60` |
| member-dashboard | `code/member-dashboard:20261111-622982a3` | `code/member-dashboard:20261108-1e6e9e48` |
| admin-panel | `code/admin-panel:20261111-80acfaed` | `code/admin-panel:20261108-b23cc67` |
One-command reverts (run from the app's OWN repo dir; verify by container md5
+ marker afterwards, never by exit code):
- portal / panel (pinned manifests): `git revert --no-edit <pin commit>` then
`cloudron update --app <id> --force`.
- dashboard (no pin): `cloudron update --app daf8750e-2683-4104-83ea-f77d1b4601e8
--image registry.inference.coop/code/member-dashboard:20261108-1e6e9e48 --force`.
Rollback compatibility: any single-app rollback renders correctly — the shims
consume whichever fields the other payload shape serves. The only known nuance
(portal rolled back alone while the new panel stays deployed): an ENDED guest
would pill as `inactive` instead of its ledger status until the portal is
restored; no ended guests existed at consolidation time.
Verification evidence 2026-11-11: all 4 live guest rows byte-identical
pre/post (2 invited, 2 active); member stable-field hash identical across
no-deploy fetches (112 active, 1 in_grace, 2 invited); both apps'
`/auth/openid/login` → 302 to the Cloudron provider with correct
client_id/redirect_uri/scope; dashboard + panel `/` → 302 to the login route;
container `oidc.py` md5 identical in both thin apps (`df23e7a8…`).
+76 -28
View File
@@ -1,8 +1,10 @@
# Woodpecker CI (server + agent)
Self-hosted CI for the co-op's repos. **As of 2026-11-04 the CI is installed but
NOT working end to end** — read the *Current state* section before trusting it for
anything.
Self-hosted CI for the co-op's repos. **As of 2026-11-20 tests are ADVISORY,
not a merge gate** — `co-op/docs` (manual, build+deploy), `code/member-portal`,
`code/admin-panel` and `code/member-dashboard` (push-triggered test runs).
Read
the *Current state* section for what is proven and the traps that remain.
Two Cloudron apps, added 2026-11-03:
@@ -54,41 +56,87 @@ CLI, and a pinned MkDocs toolchain at `/opt/docs-venv`. It **runs as root**
`publishing/requirements.txt`; **keep the two in step** when the docs toolchain
changes.
## Current state (2026-11-11): push-gated test CI is live
- **The server-side gRPC 500 was never the blocker.** The agent's `Next`
long-poll is cut short by the platform proxy every ~10 minutes (nginx
`upstream timed out`, `could not find named location "@grpc_unavailable"`)
and the agent retries — pipelines are collected and executed regardless.
Re-confirmed 2026-11-11: the 500s continue in the log while push-triggered
pipelines run green. Do not chase it.
- **API access:** a personal token for `inference-admin` lives at
`/home/ubuntu/.hermes/woodpecker.key` (mode 600). Repo enablement is
`POST /api/repos?forge_remote_id=<gitea repo id>` (query param, not body);
a manual run is `POST /api/repos/<id>/pipelines` with `{"branch": "..."}`.
- **Enabled repos:** `co-op/docs` (id 1), `code/member-portal` (id 2),
`code/admin-panel` (id 3), `code/member-dashboard` (id 4, enabled
2026-11-13 with the same push gate + `ci/woodpecker/push/woodpecker` status
check as the panel). Note `co-op/member-portal` is a Gitea REDIRECT to
`code/member-portal` — the canonical repo lives in the `code` org (Gitea id 6).
- **Test runs are ADVISORY, not a merge gate (changed 2026-11-20):**
`.woodpecker.yml` on the apps' default branches runs the existing suites on
every push (portal test files; admin-panel guest-guard + oidc/chart sync pins
+ 4 page-JS harnesses; member-dashboard oidc/chart sync pins + 2 page-JS
harnesses). Branch protection no longer requires the
`ci/woodpecker/push/woodpecker` status context: the runner shares one root
container, so a pipeline can forge statuses. Owners review is the trust
boundary; CI failures are visible but do not block a reviewed merge. Do not
turn the status requirement back on until pipelines are isolated.
- **Shared chart module (added 2026-11-13):** `ops-docs/scripts/shared/
coop_chart.js` is the canonical chart rendering + hover-tooltip module;
byte-identical copies live at `app/coop_chart.js` in both UI apps, spliced
into each PAGE_HTML at import time. `tests/test_chart_sync.py` in each app
pins the copy (same pattern as the oidc client);
`scripts/check-chart-sync.py` is the pre-deploy gate and
`scripts/sync-chart-module.sh` re-copies + re-pins both apps in one step.
Since 2026-11-13 the module ALSO owns the chart DEFINITIONS
(`CHART_METRICS` + `renderChart()`): one description per chart, read by both
UIs, so the metric list, the titles, the axis rules and the formatters cannot
drift apart again. Each app keeps only `METRIC_SOURCE` (which fetch feeds a
metric) and its own DOM; Money is a metric of Trends in both, not a tab.
The vendored `tests/check-page-js.sh` in BOTH apps splices the module into
the extracted page JS exactly as the app does — keep the two vendored
copies byte-identical to the skill's script (md5 445cdcf59f193ff875bb634f6f790e73).
- **Proven with real output:** first push runs green (portal tests step: 439
log lines ending "all portal test suites green"; all four harnesses OK on
the panel), and a deliberately broken assertion on a branch (`ci-red-test`)
produced pipeline #2 **failure** with the failing status context on Gitea —
the gate signal works. The branch was deleted after the proof.
- **The agent's python is 3.14** (agent image base) — the portal's PINNED
requirements (pydantic 2.9.2, psycopg2-binary 2.9.9) have no cp314 wheels,
so the portal pipeline installs a bounded-range subset (fastapi/httpx/PyJWT/
slowapi/cryptography) instead of `-r requirements.txt`. See
`code/member-portal/.woodpecker.yml` for the rationale.
## When a pipeline runs (and when it does not)
- **Manual-trigger only.** Nothing here fires on push; a pipeline is started by
hand from the Woodpecker UI.
- **The pipeline is not yet green end to end.**
- `co-op/docs`: **manual-trigger only** by deliberate decision (the poll
watcher remains the live auto-deploy path until the operator says otherwise).
- `code/member-portal`, `code/admin-panel`: fire on every **push** (any
branch) and can also be triggered manually.
- **`git-lfs` is required by the clone step.** Woodpecker runs `git lfs fetch`
after cloning, so a clone step fails with
`git: 'lfs' is not a git command` on any image without it — this was added to
the agent image on 2026-11-04. If a rebuild ever drops it, clones break again.
## Current state (2026-11-04): installed, agent connected, cannot run jobs
## Historical state (2026-11-04): installed, agent connected, could not run jobs
- The server is up — `https://ci.inference.coop/` serves the Woodpecker UI.
- The agent app is `running`/`healthy` and its health endpoint answers — **but
that is liveness, not capability.** The log shows the agent's **gRPC job-collection
long-poll failing continuously**: the server answers the agent's RPC with
**HTTP 500** (an nginx `text/html` 500 body), so the agent retries with backoff
and **never receives work**.
- A healthy agent that cannot collect jobs is the exact trap to avoid reading as
progress. Score a CI worker by **the route that delivers it work**, not by its
health RPC.
Superseded by the section above. Kept because each entry was a lesson:
the health endpoint lied by omission (liveness, not capability), the missing
git-lfs broke every clone, the missing repo secret (`cloudron_token`) made the
config fail to PARSE with the reason visible ONLY in the web UI, and the gRPC
500s were misread twice as the blocker before pipeline #2 proved otherwise.
The repo-enablement login gate (operator completes Gitea OAuth once) was
cleared the same day: the `inference-admin` user exists with admin rights.
**Unresolved / needs an operator:** the server-side gRPC 500. Until the server
answers the agent's stream, no pipeline can execute regardless of repository
configuration. This is a server-side (or platform-proxy) problem, not an agent
image problem.
## Enabling a repo (known gate — cleared 2026-11-04)
## Enabling a repo (known gate)
- Repos are connected through the **Gitea** source (`WOODPECKER_GITEA`). Enabling
a repo requires the repo owner to log in to Woodpecker with **Gitea OAuth** and
activate it. Standing up that OAuth login source is an **operator step**
(creating the Gitea OAuth application needs `write:user`, which the bot's Gitea
token does not have).
- Repos are connected through the **Gitea** source (`WOODPECKER_GITEA`). The
OAuth login source was stood up by the operator and the `inference-admin`
user exists (admin). Enabling further repos is now a pure API call (see
*Current state*), not an operator step.
- Reading run/pipeline state is done from the server's **MySQL** database, not
from a public API.
from a public API, when the API view is thin (the pipeline endpoint does not
expose step logs; `log_entries` in the database does).
- Note: the whole point of this CI is to take the docs build and custom-app builds
off the agent host — see `co-op/support#30` (moving `REGISTRY_BUILD_TOKEN` to CI).
+35 -24
View File
@@ -75,7 +75,7 @@ needed to restore are inside the thing being restored.
the *secret* must be in hand before the window — get it from the Infomaniak console
and store it with the passphrase, off-box.
- [x] The **restic** passphrase is safe: `~/.hermes/scripts/backup.sh` documents that
`RESTIC_PASSWORD` lives in the agent host's `.env` **and** the co-op Vault. The agent
`RESTIC_PASSWORD` lives in root-only `/etc/agent-backup.env` **and** the co-op Vault. The agent
host is not being migrated, so the agent-side backup stays recoverable. (The Vault,
however, is an app on the box being migrated — so the Vault copy alone is not
off-box until it is exported.)
@@ -529,36 +529,47 @@ state at cutover, not today.
| Woodpecker CI server | `ci.inference.coop` | `4984f95e-0c0a-4af3-9ce1-4ca4f3e8483d` |
| Woodpecker CI agent (custom) | `ci-agent.inference.coop` | `5ac63873-cf2c-4ad9-acd6-81dc0e016c83` |
## The DNS "split" is resolved — no hostname is served by the old box
## The DNS cutover is COMPLETE — no hostname is served by the old box
At one point `chat.inference.coop` and `portal.inference.coop` were observed still
resolving to the **old** box (`179.199.135.72`) while `gateway`/`my`/`docs` were on
the **new** box (`179.237.86.116`). **As of 2026-11-04 there is no such split:**
every hostname — `chat`, `portal`, `gateway`, `my`, `docs`, `ci`, `ci-agent`,
`matrix`, `git`, `www` and the apex — resolves to the **new** box.
At one point `chat.inference.coop` and `portal.inference.coop` were *reported* as
still resolving to the **old** box (`179.199.135.72`). **That observation was
stale and the split does not exist.** Verified 2026-11-04 against an external
resolver (Cloudflare, `@1.1.1.1`): **every** hostname — apex, `my`, `chat`,
`portal`, `gateway`, `docs`, `ci`, `newsletter`, `git` — resolves to the **new**
box `179.237.86.116` with **both A and AAAA**
(`2001:1600:18:206::89`). No hostname resolves to the old box, and nothing in DNS
points at it. `chat.inference.coop` serves LibreChat and `portal.inference.coop`
returns the portal from the new box.
The zone is **wildcarded**, so a resolving name proves nothing by itself. The
decisive fact: a **made-up** hostname (`zzznope.inference.coop`) also answers the
**new** box `179.237.86.116` at the authoritative nameservers (`ns1.yoursrs.com`).
That means the **wildcard itself now points at the new box**, so no name is being
served by the old box via the wildcard either.
The zone is **wildcarded**, so a resolving name proves nothing on its own — but a
made-up hostname (`zzznope.inference.coop`) also answers the **new** box at the
authoritative nameservers, so the wildcard itself now points at the new box.
## The old box still exists (rollback), and serves nothing
## ⚠️ UNRESOLVED (operator decision): the old box is still alive and internet-exposed
- `179.199.135.72` is **still powered on** and answers on 22/80/443/587/993, **but
it hosts no running app.** A request with `Host: chat.inference.coop` returns
Cloudron's **"app down / Not Found" fallback page**, and its TLS certificate has
an **empty subject** — the signature of a Cloudron whose vhost's app is stopped,
exactly as documented ("powered on with apps stopped").
- **No DNS reference points at it**, so it receives no real traffic.
- **Decommission is still pending** — this is the one open item from the cutover
that has not happened. Its backup schedule must remain **disabled** while it is
kept (two boxes on one S3 bucket interleave and prune each other's backups).
`179.199.135.72` is **powered on, reachable from the internet, and unaltered.** This
is not "a spare kept for rollback" — it is a **decommissioned server still running
and still exposed.**
- **Open to the internet (verified 2026-11-04):** ports **22, 80, 443, 587, 993**
answer. (3306/5432/8080 are closed.)
- It answers HTTPS **for any Host header** with a **generic Cloudron-served page**
(its fallback / "app down" page, empty-subject certificate) rather than a real
app — because its apps are stopped.
- **It still holds whatever old data and configuration it had** — the old Cloudron
platform, its app data, and its host config are all present on the disk.
- **Nothing in DNS points to it**, so it serves **no member traffic** — the exposure
is the open ports and the retained data/config, not live traffic.
**Decision needed from the operator:** either **shut it down**, or **firewall it**
(close all but what is genuinely needed) if it is being kept as a rollback. It is
NOT the steward's to act on: **do not shut it down or change anything on it without
the operator's word.** Its backup schedule must stay **disabled** while it is kept
(two boxes on one S3 bucket interleave and prune each other's backups).
## Still unresolved / for the operator
- **Decommission the old box** (`179.199.135.72`) when rollback is no longer
wanted, after confirming the new box's backups are proven.
- **The old box's exposure** — see above. Shut down or firewall.
- **Member mailbox contents** — the long-standing unknown from §7 (whether
members' mail is inside the Cloudron backup) still needs a real IMAP login to
confirm.
+7 -10
View File
@@ -46,7 +46,7 @@ table machine-legible — one `YYYY-MM-DD` date per row.
| Gitea token (`inference-bot`) | |
| `WEBHOOK_TOKEN` (portal env + Open Collective webhook URL) | |
| `ADMIN_TOKEN` (portal + admin panel + agent host) | |
| `BROKER_SECRET` and `PORTAL_SECRET` | |
| `BROKER_SECRET` | |
| Matrix tokens — portal `MATRIX_BOT_TOKEN` + agent `MATRIX_ADMIN_TOKEN` (one account, `@inference-admin`) | |
| Matrix token — steward agent `@inferencebot` | |
| Loomio API keys (`LOOMIO_API_KEY`, `LOOMIO_B3_KEY`) | |
@@ -73,7 +73,7 @@ the silent break.
| `GREENPT_API_KEY` (gateway) and `GREENPT_FALLBACK_API_KEY` (agent) | the GreenPT account — the **same value** in both | verified: the "fallback" isolates nothing |
| `REGOLO_API_KEY` | Regolo account | not yet identified |
| Gitea token | `inference-bot` | inferred, not verified |
| `BROKER_SECRET`, `PORTAL_SECRET`, `WEBHOOK_TOKEN`, `ADMIN_TOKEN`, `LOOMIO_*`, `LISTMONK_*` | self-issued / service account | — |
| `BROKER_SECRET`, `WEBHOOK_TOKEN`, `ADMIN_TOKEN`, `LOOMIO_*`, `LISTMONK_*` | self-issued / service account | — |
| Restic passphrase; Infomaniak Swiss Backup S3 keys | self-issued; the Infomaniak account | — |
The two couplings to watch: **one account with several credentials** (the
@@ -191,10 +191,8 @@ addon, declared in each app's `CloudronManifest.json` under `addons.scheduler`:
- **portal**: `membership_sweep` (three times daily — `0 3,11,19 * * *` UTC per
the live manifest; earlier notes said "nightly at 3am" and are stale. Runs
`/app/code/sweep.sh` → `POST /admin/sweep` with the **`ADMIN_TOKEN`** header — NOT `WEBHOOK_TOKEN`,
which returns 403 on `/admin/*` since the 2026-10-28 cutover), `rag_refresh`
(nightly 3:30am, `/app/code/rag_refresh.py` — pulls docs from the Gitea raw
API and refreshes the chat knowledge base; needs `OWUI_API_KEY` +
`DOCS_KNOWLEDGE_ID` in the app env), and `metrics_snapshot` (nightly 3:15am,
which returns 403 on `/admin/*` since the 2026-10-28 cutover), and
`metrics_snapshot` (nightly 3:15am,
`/app/code/metrics_snapshot.py` — writes the day's members / usage / energy /
carbon row into the portal's `metrics_daily` table; `--backfill` rebuilds
history and is idempotent).
@@ -282,12 +280,10 @@ row that names the same credential: several are held by more than one app.
| `WEBHOOK_TOKEN` | Secret in the Open Collective webhook URL | Portal app env, and the webhook URL on Open Collective | GM | Rotating means re-creating the webhook on OC as well |
| `LITELLM_MASTER_KEY` | Create gateway teams and keys for members | Portal app env (copy of the gateway's) | GM | Three holders: portal, gateway, steward agent. Rotate all together |
| `LITELLM_DB_*` | Read spend logs from the gateway database | Portal app env | Cloudron (addon) | Postgres credentials for the gateway's database |
| `MATRIX_BOT_TOKEN` | `@inference-admin:inference.coop` admin account: invites, space membership | Portal app env | GM | The account has no password. Paired with the steward agent's `MATRIX_ADMIN_TOKEN`: same account, separate token on a separate device (verified by homeserver `whoami`, 2026-11-04). Revoke or rotate both together |
| `MATRIX_BOT_TOKEN` | `@coop-portal:inference.coop` room bot: member invites and kicks | Portal app env | GM | NOT a server admin. Room power 50 in exactly the eight `MATRIX_INVITE_ROOMS` rooms (2026-11-19). Independent of the steward agent's `MATRIX_ADMIN_TOKEN`; revoking one does not revoke the other |
| `LOOMIO_API_KEY`, `LOOMIO_B3_KEY` | Forum (Loomio) membership sync | Portal app env | GM | |
| `LISTMONK_API_USER`, `LISTMONK_API_TOKEN` | Newsletter list sync | Portal app env | GM | |
| `OWUI_API_KEY`, `OWUI_JWT_SECRET` | Open WebUI knowledge refresh and SSO | Portal app env | GM | Chat moved to LibreChat in October; confirm whether still needed, and retire if not |
| `BROKER_SECRET` | Shared secret between the portal and the member dashboard | Portal and dashboard app env | GM | Held by both; rotate together |
| `PORTAL_SECRET` | Session signing | Portal app env | GM | |
| `CLOUDRON_MAIL_SMTP_*` | Outbound mail | Cloudron mail addon | Cloudron | Managed by the platform |
### Gateway (`gateway.inference.coop`)
@@ -306,6 +302,7 @@ row that names the same credential: several are held by more than one app.
| Credential | Purpose | Where it lives | Who rotates | Notes |
|---|---|---|---|---|
| LibreChat encryption keys and app secrets | App secrets; the per-member key sync runs in the app's own Cloudron scheduler | App data directory | GM | Not held by the agent |
| `KEENABLE_API_KEY` (fetcher key) | Authenticate page fetches to our own fetcher (`fetch.inference.coop`) | Fetcher app env + LibreChat `/app/data/env` (copy) | GM | Two holders; rotate together. LibreChat reads it as `KEENABLE_API_KEY` alongside `KEENABLE_FETCH_URL` |
| `RAG_OPENAI_API_KEY` (gateway key alias `rag-service-embeddings`) | LibreChat RAG service — embeddings for chat document upload/parse | LibreChat app `/app/data/env` (mode 600), as `RAG_OPENAI_API_KEY` + `RAG_OPENAI_BASEURL` | Gateway master-key holder (`POST /key/regenerate`) | One model only: `tinfoil/nomic-embed-text` (TEE, 768-dim); key budget cap $2 / 30d; on the co-op `info@inference.coop` team, so member keys cannot call it. Live 2026-10-27 (the service had not started since the Cloudron move). Key value recorded in no repository; rotate via the gateway, not a dashboard |
### Agents (on the agent host)
@@ -316,7 +313,7 @@ granularity for the public half. Highest privilege first.
| Credential | Purpose | Where it lives | Who rotates | Notes |
|---|---|---|---|---|
| Gateway master key (`GW_MASTER_KEY`) | Admin over every gateway team, key and spend record | Steward agent `.env` | GM | **Third holder**, with the portal and the gateway. The row most in need of coordinated rotation |
| `MATRIX_ADMIN_TOKEN` | The `@inference-admin:inference.coop` automation account: room administration in every co-op room | Steward agent `.env` | GM | Same account as the portal's `MATRIX_BOT_TOKEN`, but a separate token on a separate device (verified by homeserver `whoami`, 2026-11-04). Revoking one does not revoke the other; revoke or rotate both together |
| `MATRIX_ADMIN_TOKEN` | The `@inference-admin:inference.coop` automation account: room administration in every co-op room | Steward agent `.env` | GM | Server-admin account. The portal no longer uses this account; its `MATRIX_BOT_TOKEN` belongs to `@coop-portal` (2026-11-19) |
| Cloudron agent token | Cloudron API | Steward agent `.env` | GM | See "The two-token split" above |
| `REGISTRY_BUILD_TOKEN` (and its username) | Image build and push for the custom apps | Steward agent `.env` | GM | Moves to CI (co-op/support#30); the agent stops holding it then |
| Gitea token | Commits, issues, PRs as `inference-bot` | Steward agent `.env` | GM | |
+11 -1
View File
@@ -37,8 +37,18 @@ price from a provider's public page (they drift, and some are login-walled).
## A note on currencies
Regolo quotes in **EUR**; our gateway figures convert at **EUR × 1.16 → USD**
Regolo quotes in **EUR**; the gateway converts at the **ECB daily reference rate** at boot
(the rate our numbers use — `regolo.md` documents the derivation). GreenPT's own
listed rates appear in **EUR with the same numerals the gateway carries** —
whether an EUR→USD conversion is intended there is **unverified**; confirm it
against the GreenPT invoice before treating the figures as final.
"
## Automation (2026-11-18)
`eur_prices.json` in `code/litellm` is the EUR source of truth. At gateway boot,
`fx_sync.py` fetches the ECB daily reference rate and rewrites the USD
`model_info` fields (fail-open: feed down = keep last prices). A systemd timer
(`gateway-fx-restart.timer`, 04:30 UTC daily) restarts the gateway so the boot
sync applies the fresh rate. The portal's daily sweep spot-checks ECB vs the
config and emails info@ only if the feed is stale or missing.
+9 -8
View File
@@ -8,16 +8,17 @@ talks to it **directly** (no TEE proxy). Billing across the gateway:
## What we serve, and what it costs
Rates as recorded in the gateway's authorititative config comment, **USD per 1M
tokens** (the gateway's `model_info` carries the per-token equivalents):
GreenPT quotes in **EUR**; EUR is the source of truth. The gateway converts at the **ECB daily reference rate** at boot (fail-open if the feed is down) and stores USD per-token equivalents. The fixed 1.16 figures are fallbacks only.
| our model | input | output | cached input |
|---|---|---|---|
| `greenpt/deepseek-v4.1-flash` **(DEFAULT model)** | $0.22 | $1.10 | $0.011 |
| `greenpt/glm-5.3-flash` | $0.11 | $0.44 | $0.022 |
| `greenpt/glm-5.3` | $1.10 | $4.40 | $0.275 |
| our model | input (EUR) | output (EUR) | cached (EUR) | gateway USD in / out / cached |
|---|---|---|---|---|
| `greenpt/deepseek-v4.1-flash` **(DEFAULT model)** | €0.36 | €1.45 | €0.04 | $0.4176 / $1.682 / $0.0464 |
| `greenpt/glm-5.3-flash` | €0.11 | €0.44 | €0.022 | $0.1276 / $0.5104 / $0.02552 |
| `greenpt/glm-5.3` | €1.10 | €4.40 | €0.275 | $1.276 / $5.104 / $0.319 |
- **`greenpt/deepseek-v4.1-flash` is the gateway's default model.** It is the same
- **`greenpt/deepseek-v4.1-flash` is the gateway's default model, and since 2026-11-16 it serves the
**1017 snapshot** (GreenPT no longer recommends the base release) under the same
name, so member configs needed no change.** It is the same
model family as Tinfoil's `tinfoil/deepseek-v4-1-flash`, but on renewable energy
and **not** marked "Experimental" by the provider (Tinfoil's counterpart is), so
it is the default and Tinfoil's is its private counterpart. The policy trade is
+2
View File
@@ -3,6 +3,8 @@
Source: Regolo's announcement email (link goes to their SSO portal, so the tables below are
entered by hand) plus their public pricing page.
> Regolo quotes EUR. The gateway converts at the **ECB daily reference rate** at boot; the `model_info` values are USD, not raw EUR numerals.
## Effective 2026-11-01 (from the notice email), EUR per 1M tokens
| model | input | output |
+129
View File
@@ -0,0 +1,129 @@
# Reference — Member portal environment-variable manifest
Generated 2026-11-11 from the RUNNING portal container's environment (69 vars,
read as NAMES only — no values were printed or committed), the portal source
(`app/main.py` reads at the line numbers cited), and fingerprint comparison
(`sha256`[:8]) between the portal's copies and each owner app's own
credential. Companion to the incident
[`2026-11-05-portal-alltime-spend-zero.md`](../incidents/2026-11-05-portal-alltime-spend-zero.md),
which is why the copy-pattern secrets carry a warning.
Reading guide:
- **Source** — where the value comes from at runtime:
`platform` = injected by Cloudron (not in any repo, do not set by hand);
`app env` = set on the portal app via the Cloudron env API / dashboard
(42 vars; the authoritative values live in the platform, never in git);
`image` = baked in by the base python image, irrelevant to the app.
- **Class** — `SECRET` (credential: treat as rotation-sensitive),
`IDENT` (identifier/URL: safe-ish, still internal), `CONFIG` (behaviour flag).
- **COPY** — the value is a *copy* of another app's or system's credential.
A rotation or restore on the OWNER side silently rots the copy (proven by the
2026-11-05 incident). After any owner-side restore/rotation, re-sync the copy
and diff fingerprints — never values.
## 1. Platform-injected (27) — never set by hand
| Name | Source | Class | Read by portal | Notes |
|---|---|---|---|---|
| `CLOUDRON_API_ORIGIN` | platform | IDENT | yes (L198) | Cloudron API base the portal calls for OIDC user lookups |
| `CLOUDRON_APP_BRIDGE_ORIGIN` | platform | IDENT | no | platform plumbing |
| `CLOUDRON_APP_DOMAIN` | platform | IDENT | no | portal.inference.coop |
| `CLOUDRON_APP_HOSTNAME` | platform | IDENT | no | platform plumbing |
| `CLOUDRON_APP_ORIGIN` | platform | IDENT | no | platform plumbing |
| `CLOUDRON_MAIL_DOMAIN` | platform | IDENT | no | platform plumbing |
| `CLOUDRON_MAIL_FROM` | platform | IDENT | yes (L474) | From identity for portal mail (default `info@inference.coop`) |
| `CLOUDRON_MAIL_SMTP_PASSWORD` | platform | SECRET | yes (L473) | Cloudron mail addon relay password |
| `CLOUDRON_MAIL_SMTP_PORT` | platform | IDENT | yes (L471) | relay submission port |
| `CLOUDRON_MAIL_SMTP_SERVER` | platform | IDENT | yes (L470) | relay host |
| `CLOUDRON_MAIL_SMTP_USERNAME` | platform | SECRET | yes (L472) | relay user |
| `CLOUDRON_MAIL_SMTPS_PORT` | platform | IDENT | no | platform plumbing |
| `CLOUDRON_MAIL_STARTTLS_PORT` | platform | IDENT | no | platform plumbing |
| `CLOUDRON_OIDC_AUTH_ENDPOINT` | platform | IDENT | no | read via OIDC discovery, not directly |
| `CLOUDRON_OIDC_CLIENT_ID` | platform | IDENT | no | via discovery |
| `CLOUDRON_OIDC_CLIENT_SECRET` | platform | SECRET | no | consumed by the OIDC discovery flow |
| `CLOUDRON_OIDC_DISCOVERY_URL` | platform | IDENT | no | via discovery |
| `CLOUDRON_OIDC_ISSUER` | platform | IDENT | no | via discovery |
| `CLOUDRON_OIDC_KEYS_ENDPOINT` | platform | IDENT | no | via discovery |
| `CLOUDRON_OIDC_PROFILE_ENDPOINT` | platform | IDENT | no | via discovery |
| `CLOUDRON_OIDC_PROVIDER_NAME` | platform | IDENT | no | via discovery |
| `CLOUDRON_OIDC_TOKEN_ENDPOINT` | platform | IDENT | no | via discovery |
| `CLOUDRON_PROXY_IP` | platform | IDENT | no | platform plumbing |
| `CLOUDRON_TOKEN` | platform | **SECRET (high)** | yes (L199) | a Cloudron **API token inside an app env** — the portal calls the Cloudron API for group membership. Scope is broader than the app needs; treat as platform-level credential. Owner: the Cloudron platform |
| `CLOUDRON_WEBADMIN_ORIGIN` | platform | IDENT | no | platform plumbing |
| `GPG_KEY` / `PYTHON_VERSION` / `PYTHON_SHA256` | image | IDENT | no | base python image metadata, not the app's |
## 2. Portal app env (42) — set via the Cloudron env API
**The portal's own secrets:**
| Name | Class | Purpose | Notes |
|---|---|---|---|
| `PORTAL_KEK` | SECRET | key-encryption key wrapping member API keys at rest (L44) | owner: portal. Loss = re-provision every member key |
| `ADMIN_TOKEN` | SECRET | `/admin/*` API auth (L252) | consumed by the panel, dashboard and the daily digest |
| `ADMIN_TOKEN_LEGACY` | CONFIG | accepts the legacy admin token alongside `ADMIN_TOKEN` (L253) | `"0"` disables; delete after the panel/dashboard stop sending the old one |
| `BROKER_SECRET` | SECRET | member-API broker auth (L234) | owner: portal |
| `WEBHOOK_TOKEN` | SECRET | inbound webhook auth (L239) | owner: portal |
**COPIES of another system's credentials — the two-copies-of-one-secret risk:**
| Name | Class | Purpose | COPY of (owner) | Risk |
|---|---|---|---|---|
| `LITELLM_DB_HOST`/`_PORT`/`_USER`/`_NAME`/`_PASSWORD` | SECRET/IDENT | direct Postgres read of LiteLLM's ledger for all-time spend, usage, leaderboard (L496–500) | the **gateway's** `CLOUDRON_POSTGRESQL_*` addon env (fingerprint-verified SAME 2026-11-11) | rotates on every gateway restore; rotted 2026-11-05 → $0 spend shown for 2h20m. After any gateway restore: re-sync + fingerprint-diff. Standing alarm: the digest's SPEND CONSISTENCY check reads the gateway side, not this copy |
| `LITELLM_MASTER_KEY` | SECRET | gateway admin API calls from the portal (key seeding, budget caps) (L201) | the **gateway's** `/app/data/.master_key` (fingerprint-verified SAME 2026-11-11: `2cd3668d`) | same rot rule: re-sync after gateway restores |
| `MATRIX_BOT_TOKEN` | SECRET | portal's Matrix bot: invites, space sync, welcome DMs (L441) | the **Synapse server's** registration of the portal bot (matrix.inference.coop) | rotation lives server-side; the copy rots silently |
| `LIBRECHAT_SYNC_TOKEN` | SECRET | token the **key-sync job shares back** — portal `/admin/librechat/keys` requires it (L7645) | shared with the chat app's `sync-keys.js` (chat.inference.coop) | two holders, one value; rotate both together |
| `LISTMONK_API_TOKEN` / `LISTMONK_API_USER` | SECRET | newsletter list sync (L489–490) | the **Listmonk app's** API credentials (newsletter.inference.coop) | owner-side rotation rots the copy |
| `LOOMIO_API_KEY` / `LOOMIO_B3_KEY` | SECRET | Loomio membership + B3 user API (L420, L425) | the **Loomio app's** API keys (forum.inference.coop) | owner-side rotation rots the copy; the 2026-11-04 invite blast came from this integration running live (see that incident) |
| `OC_PERSONAL_TOKEN` | SECRET | Open Collective GraphQL: payments, orders (L331) | the co-op's **Open Collective** account token (external) | external owner; scope-check on rotation |
**Identifiers and config (non-secret):**
| Name | Class | Purpose |
|---|---|---|
| `ADMIN_INVITER_EMAIL`-adjacent `ADMIN_*` — see above | — | — |
| `LITELLM_BASE` | IDENT | gateway base URL (L200, default `https://gateway.inference.coop`) |
| `MATRIX_HOMESERVER` | IDENT | homeserver base (L440) |
| `MATRIX_SPACE_ID` | IDENT | the co-op Space the sync manages (L442) |
| `MATRIX_GENERAL_ROOM` | IDENT | General room id for welcomes (L443) |
| `MATRIX_INVITE_ROOMS` | CONFIG | rooms every new member is invited to (L451) |
| `MATRIX_EXTRA_ROOMS` | CONFIG | additional rooms the bot watches (L454) |
| `MEMBERS_GROUP_ID` | IDENT | Cloudron group id for active members (L401) |
| `INACTIVE_GROUP_ID` | IDENT | Cloudron group id for deactivated members (L405) |
| `GUESTS_GROUP_ID` / `GUESTS_ENDED_GROUP_ID` | IDENT | guest / ended-guest Cloudron groups (L368, L378) |
| `MEMBER_BUDGET` | CONFIG | monthly member allowance in USD (L336, default 15.0) |
| `MANUAL_MEMBERS` | CONFIG | comma-separated members exempt from payment checks (L413) |
| `ALLOWANCE_POLICY` | CONFIG | allowance lapse policy: `report` (default) / `off` / `on` (L6514) |
| `ALLOWANCE_SHORTFALL_EMAILS` | CONFIG | shortfall mail flag `off`/`dryrun`/`on` (L7147) |
| `BUDGET_NOTICES` | CONFIG | budget-notice mail flag (L7748) |
| `DOCS_KNOWLEDGE_ID` | IDENT | docs-RAG knowledge-base id (L228, has default) |
| `LISTMONK_LIST_ID` | IDENT | "Members" list id (L491, default 3) |
| `LOOMIO_GROUP_ID` | IDENT | the co-op's Loomio group (L455) |
## 3. Read by code but UNSET (20) — behaviour comes from in-code defaults
These never appear in the container env; each has a default in `app/main.py`.
Documented so the defaults are discoverable (this closes the audit's
"undocumented env vars" gap). To change one, ADD it to the portal app env —
the code's `os.environ.get(name, default)` picks it up on restart.
`ADMIN_INVITER_EMAIL`, `ALLOWANCE_DEACTIVATE`, `BUDGET_NOTICE_AT`,
`CREDIT_PACK_URL`, `DB_PATH`, `GUEST_BUDGET`, `GUEST_DAYS`,
`GUEST_PER_INVITER_DAYS`, `LISTMONK_BASE`, `LOOMIO_ALWAYS_KEEP`,
`LOOMIO_BASE`, `LOOMIO_SYNC_ENABLED`, `MAIL_REPLY_TO`,
`MATRIX_EXTRA_MXIDS`, `MONEY_SERIES_TTL`, `OC_COLLECTIVE_SLUG`,
`OPERATOR_EMAILS`, `PAYMENT_GRACE_DAYS`, `PORTAL_BASE`, `REINVITE_AFTER_DAYS`.
## Maintenance rules
1. **No secret value belongs in any repo or doc.** This manifest intentionally
documents names, classes and *fingerprints at a point in time* — nothing else.
2. **Rotation order** (skill: never lock yourself out): prove the NEW credential
works against its owner service, then update the copy, then revoke the old.
3. **After any app restore**: fingerprint-diff every COPY row's owner side
against the portal copy and re-sync what differs (the 2026-11-05 playbook).
4. **De-duplication (flagged, deliberately not done 2026-11-05):** the
`LITELLM_DB_*` + `LITELLM_MASTER_KEY` copies exist because the portal reads
the ledger directly. The long-term fix — one source of truth, or a
gateway-side read-only aggregation endpoint — is recorded in the incident
doc and stays open until someone does it deliberately.
+95
View File
@@ -0,0 +1,95 @@
#!/usr/bin/env python3
"""Verify the shared chart module is single-sourced and byte-identical.
Checks, in order, and exits non-zero naming every failure:
1. canonical ops-docs/scripts/shared/coop_chart.js
== member-dashboard/app/coop_chart.js (byte-identical, sha256)
== admin-panel/app/coop_chart.js (byte-identical, sha256)
2. each repo's tests/test_chart_sync.py pins the CANONICAL revision
(so CI — which has no ops-docs checkout — still goes red when a repo
copy is hand-edited).
3. each repo's app/main.py splices the module into PAGE_HTML
(loader + placeholder replace present).
Run from anywhere: python3 ops-docs/scripts/check-chart-sync.py
This is the pre-deploy gate for either thin app; sync-chart-module.sh runs it
at the end of every sync.
"""
import hashlib
import sys
from pathlib import Path
HERE = Path(__file__).resolve().parent # ops-docs/scripts
REPOS = HERE.parent.parent # ~/repos
CANONICAL = HERE / "shared" / "coop_chart.js"
SPLICE = 'PAGE_HTML = PAGE_HTML.replace("/*@@CHART_MODULE@@*/", CHART_MODULE_JS)'
LOADER = 'CHART_MODULE_JS = (Path(__file__).resolve().parent / "coop_chart.js").read_text()'
APPS = {
"member-dashboard": ("app/coop_chart.js", "tests/test_chart_sync.py", "app/main.py"),
"admin-panel": ("app/coop_chart.js", "tests/test_chart_sync.py", "app/main.py"),
}
def sha256(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
failures: list[str] = []
if not CANONICAL.exists():
print(f"FAILED: canonical module missing: {CANONICAL}")
sys.exit(1)
canonical_sha = sha256(CANONICAL)
print(f"canonical sha256: {canonical_sha}")
for repo, (copy_rel, test_rel, main_rel) in APPS.items():
copy = REPOS / repo / copy_rel
test = REPOS / repo / test_rel
main = REPOS / repo / main_rel
if not copy.exists():
failures.append(f"{repo}: {copy_rel} missing")
else:
got = sha256(copy)
if got == canonical_sha:
print(f"ok - {repo}: {copy_rel} byte-identical to canonical")
else:
failures.append(
f"{repo}: {copy_rel} DRIFTED from the canonical module\n"
f" canonical {canonical_sha}\n"
f" actual {got}\n"
f" fix: edit the canonical module (ops-docs: scripts/shared/coop_chart.js) "
f"and run ops-docs/scripts/sync-chart-module.sh — never hand-edit the copy.")
if not test.exists():
failures.append(f"{repo}: {test_rel} missing")
else:
tsrc = test.read_text()
if canonical_sha in tsrc:
print(f"ok - {repo}: {test_rel} pins the canonical revision")
else:
failures.append(
f"{repo}: {test_rel} does not pin the CURRENT canonical revision "
f"({canonical_sha[:16]}…) — run ops-docs/scripts/sync-chart-module.sh to re-pin.")
if not main.exists():
failures.append(f"{repo}: {main_rel} missing")
else:
msrc = main.read_text()
missing = [name for name, needle in (("loader", LOADER), ("splice", SPLICE)) if needle not in msrc]
if missing:
failures.append(f"{repo}: {main_rel} lacks the chart-module {', '.join(missing)}")
else:
print(f"ok - {repo}: {main_rel} loads and splices the module")
if failures:
print()
for f in failures:
print("FAILED: " + f)
sys.exit(1)
print("chart module sync: OK")
+109
View File
@@ -0,0 +1,109 @@
#!/usr/bin/env python3
"""Verify the OIDC client module is single-sourced and byte-identical.
Checks, in order, and exits non-zero naming every failure:
1. canonical ops-docs/scripts/shared/oidc_client.py
== member-dashboard/app/oidc.py (byte-identical, sha256)
== admin-panel/app/oidc.py (byte-identical, sha256)
2. each repo's tests/test_oidc_sync.py pins the CANONICAL revision
(so CI — which has no ops-docs checkout — still goes red when a repo
copy is hand-edited).
3. each repo's app/main.py calls oidc.configure(...) with THAT repo's
identity literal (cookie name + salt preserved from the pre-consolidation
apps, so existing sessions survive).
Run from anywhere: python3 ops-docs/scripts/check-oidc-sync.py
This is the pre-deploy gate for either thin app; sync-oidc-module.sh runs it
at the end of every sync.
"""
import hashlib
import re
import sys
from pathlib import Path
HERE = Path(__file__).resolve().parent # ops-docs/scripts
REPOS = HERE.parent.parent # ~/repos
CANONICAL = HERE / "shared" / "oidc_client.py"
# repo name -> (copy path, pin-test path, main path, expected configure call)
APPS = {
"member-dashboard": (
"app/oidc.py",
"tests/test_oidc_sync.py",
"app/main.py",
'oidc.configure("member-dashboard", "member_oidc_session", '
'"member-dashboard-oidc-session")',
),
"admin-panel": (
"app/oidc.py",
"tests/test_oidc_sync.py",
"app/main.py",
'oidc.configure("admin-panel", "admin_oidc_session", '
'"admin-panel-oidc-session")',
),
}
def sha256_file(p: Path) -> str:
return hashlib.sha256(p.read_bytes()).hexdigest()
def main() -> int:
failures = []
if not CANONICAL.exists():
print(f"FAIL canonical module missing: {CANONICAL}")
return 1
canon_sha = sha256_file(CANONICAL)
print(f"canonical {CANONICAL.relative_to(REPOS)} sha256={canon_sha[:16]}…")
for repo, (copy_rel, pin_rel, main_rel, expected_configure) in APPS.items():
repo_dir = REPOS / repo
copy = repo_dir / copy_rel
pin = repo_dir / pin_rel
app_main = repo_dir / main_rel
if not copy.exists():
failures.append(f"{repo}: copy missing: {copy}")
continue
copy_sha = sha256_file(copy)
if copy_sha == canon_sha:
print(f"ok - {repo}: {copy_rel} byte-identical to canonical "
f"(sha256={copy_sha[:16]}…)")
else:
failures.append(
f"{repo}: {copy_rel} DRIFTED from canonical\n"
f" canonical sha256={canon_sha}\n"
f" copy sha256={copy_sha}\n"
f" fix: edit the canonical file and run "
f"ops-docs/scripts/sync-oidc-module.sh — never hand-edit the copy.")
if pin.exists() and canon_sha in pin.read_text():
print(f"ok - {repo}: pin test records this canonical revision")
else:
failures.append(
f"{repo}: {pin_rel} does not pin canonical revision {canon_sha[:16]}… "
f"(run sync-oidc-module.sh to re-pin)")
if app_main.exists() and expected_configure in app_main.read_text():
print(f"ok - {repo}: main.py configures the app identity")
else:
failures.append(
f"{repo}: {main_rel} does not call the expected identity literal:\n"
f" {expected_configure}")
if failures:
print()
print(f"FAILED: {len(failures)} problem(s)")
for f in failures:
print(" - " + f)
return 1
print()
print("oidc module sync: all copies byte-identical, pins current, identities wired")
return 0
if __name__ == "__main__":
sys.exit(main())
+421
View File
@@ -0,0 +1,421 @@
/* Inference Cooperative — shared hand-rolled chart module.
*
* Canonical copy: co-op/ops-docs repo, scripts/shared/coop_chart.js.
* Byte-identical copies ship in admin-panel/app/ and member-dashboard/app/
* (each repo's tests/test_chart_sync.py pins its copy to this revision — CI
* has no ops-docs checkout). Editing a copy by hand is a dead end: edit the
* canonical file and run ops-docs/scripts/sync-chart-module.sh, which
* re-copies and re-pins both repos in one step.
*
* No chart library, no CDN (the co-op's no-external-dependency rule applies
* to charts like everything else). Colors come from each app's CSS vars, so a
* chart matches the tables around it. The module exposes ONE global,
* CoOpChart; each app's page JS destructures the pieces it needs, so call
* sites keep their bare function names.
*
* Tooltips — exact values on hover (the panel's registerChartTips contract):
* 1. At render time, stamp each hoverable data element with
* data-tip-host="<hostId>" and data-tip-i="<index into the data>"
* 2. registerChartTips("<hostId>", points) with one point per index:
* { label: "2026-11-07", series: [["Spend", "$12.34"], ...] }
* Values MUST come from the chart's own data arrays (exact), never
* pixel-estimated, and `series` carries EVERY series at that x.
* One delegated listener set on document serves every chart, so innerHTML
* re-renders need no re-binding and new charts join chart-by-chart as they
* render. The box is a fixed-position div with pointer-events:none, clamped
* inside the viewport. NULL points get no stamp and no tooltip (the gap
* rule). Styling lives in each app's .chart-tip CSS block.
*
* Drawing helpers — extracted from the admin panel's chart code so both apps
* produce the same shapes from the same code:
* niceStep(raw, continuous) axis step. continuous=true: the 1/2/5 x 10^k
* rule (money, energy, carbon — ticks read $10,
* not $4.92). false: whole counts rounded up to
* a half power of ten, never below 1 (a
* 2,900-request day reads 3,000; a near-empty
* series still gets an integer axis).
* measuredRuns(vals) contiguous non-null index runs. A NULL metric
* renders as a GAP, never a zero, and the line
* is never drawn through unmeasured history.
* chartFrame(cfg) opens the SVG, draws gridlines + y labels
* (top = one round step x 4 ticks, so labels
* land on round numbers by construction).
* dateMarks(fr, days) 3 x-axis date labels (start/mid/end).
* drawBars(fr, vals, opts) bars; NULLs skipped (no zero bars).
* drawLineRuns(fr, vals, opts) lines broken into measured runs.
* hoverTargets(fr, vals, host) transparent hover circles on measured points.
*
* Definition layer — the ONE place a chart is described (both UIs read it):
* CHART_METRICS the metric list, in order: id, title, kind (line|bar|multi),
* cont (continuous axis), fmt (money|count|wh|g), val(row);
* "multi" carries `series` (the money chart). Anything a
* member may see belongs in this list.
* metricDef(id) the definition for a metric id.
* fmtMoney/fmtMetric/fmtMoneyTick shared value formatters, so both apps'
* labels match byte for byte.
* renderChart({host, def, rows, aria}) -> { svg, legend, empty? }
* one renderer for both UIs: registers the EXACT tooltip
* values, breaks lines at NULLs (a gap is never a zero), and
* returns markup plus legend items. The APP writes the DOM —
* element ids, toggle class names and empty-state markup are
* the only parts that legitimately differ per app.
*/
(function (global) {
"use strict";
// HTML escaping, self-contained: identical mapping to both apps' esc() /
// escapeHtml(), so tooltip output bytes match what each app rendered before.
function esc(s) {
return String(s).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
}
// ---- Chart tooltips: exact values on hover ----
const chartTipData = {}; // hostId -> [{ label, series: [[name, value], ...] }]
let chartTipBox = null; // the singleton tooltip div, created on first use
let chartTipCur = null; // { host, idx } the point currently shown
function registerChartTips(hostId, points) { chartTipData[hostId] = points; }
function chartTipTarget(el) {
return el && el.closest ? el.closest("[data-tip-host]") : null;
}
function hideChartTip() {
chartTipCur = null;
if (chartTipBox) chartTipBox.style.display = "none";
}
function showChartTip(hostId, idx, cx, cy) {
const p = (chartTipData[hostId] || [])[idx];
if (!p) { hideChartTip(); return; }
if (!chartTipBox) {
chartTipBox = global.document.createElement("div");
chartTipBox.className = "chart-tip";
global.document.body.appendChild(chartTipBox);
}
const same = chartTipCur && chartTipCur.host === hostId && chartTipCur.idx === idx;
if (!same) {
let html = '<div class="tip-day">' + esc(p.label) + "</div>";
for (let s = 0; s < p.series.length; s++) {
html += '<div class="tip-row"><span>' + esc(p.series[s][0]) + "</span><b>" + esc(p.series[s][1]) + "</b></div>";
}
chartTipBox.innerHTML = html;
chartTipCur = { host: hostId, idx: idx };
}
chartTipBox.style.display = "block";
moveChartTip(cx, cy);
}
// Position beside the pointer, flipped/clamped so the box stays fully inside
// the viewport at chart edges.
function moveChartTip(cx, cy) {
if (!chartTipBox || chartTipBox.style.display === "none") return;
const pad = 12, m = 4;
const w = chartTipBox.offsetWidth, h = chartTipBox.offsetHeight;
let x = cx + pad, y = cy + pad;
if (x + w > window.innerWidth - m) x = cx - pad - w;
if (x < m) x = m;
if (y + h > window.innerHeight - m) y = cy - pad - h;
if (y < m) y = m;
chartTipBox.style.left = x + "px";
chartTipBox.style.top = y + "px";
}
document.addEventListener("pointerover", (e) => {
const t = chartTipTarget(e.target);
if (!t) return;
showChartTip(t.getAttribute("data-tip-host"), parseInt(t.getAttribute("data-tip-i"), 10), e.clientX, e.clientY);
});
document.addEventListener("pointermove", (e) => {
const t = chartTipTarget(e.target);
if (!t) return;
const host = t.getAttribute("data-tip-host");
const idx = parseInt(t.getAttribute("data-tip-i"), 10);
const cur = chartTipCur;
if (!cur || cur.host !== host || cur.idx !== idx) showChartTip(host, idx, e.clientX, e.clientY);
else moveChartTip(e.clientX, e.clientY);
});
document.addEventListener("pointerout", (e) => {
const from = chartTipTarget(e.target);
if (!from) return;
const to = e.relatedTarget ? chartTipTarget(e.relatedTarget) : null;
if (!to || to.getAttribute("data-tip-host") !== from.getAttribute("data-tip-host")) hideChartTip();
});
// Basic touch: tap/drag shows and follows, release hides it after a beat.
document.addEventListener("pointerup", (e) => {
if (e.pointerType === "touch") setTimeout(hideChartTip, 1600);
});
document.addEventListener("pointercancel", hideChartTip);
// Scrolling or resizing moves the chart under a fixed-position box - hide
// rather than show a tooltip for the wrong point.
window.addEventListener("scroll", hideChartTip, { passive: true });
window.addEventListener("resize", hideChartTip);
// ---- Axis step (see header: continuous vs count rule) ----
function niceStep(raw, continuous) {
if (continuous) {
const mag = Math.pow(10, Math.floor(Math.log10(Math.max(raw, 1e-9))));
const norm = raw / mag;
const nice = norm <= 1 ? 1 : (norm <= 2 ? 2 : (norm <= 5 ? 5 : 10));
return nice * mag;
}
const p = Math.pow(10, Math.floor(Math.log10(Math.max(raw, 1))));
return Math.max(1, Math.ceil(raw / (p / 2)) * (p / 2));
}
// ---- Contiguous measured runs: a NULL day stays a gap ----
function measuredRuns(vals) {
const runs = [];
let run = [];
for (let i = 0; i < vals.length; i++) {
if (vals[i] === null || vals[i] === undefined) { if (run.length) runs.push(run); run = []; }
else run.push(i);
}
if (run.length) runs.push(run);
return runs;
}
// ---- Frame: opens the SVG, draws gridlines + y-tick labels ----
// cfg: { n, top, step, tickLabel(v)->string, aria, W, H, padL, padR, padT,
// padB, gridStroke }. Defaults match the panel's chart geometry
// (W 1000, H 250, padL 62, padR 14, padT 14, padB 30).
// Axis top = one round step times four ticks: labels land on round numbers
// and the peak still clears the frame.
function chartFrame(cfg) {
const W = cfg.W || 1000, H = cfg.H || 250;
const padL = cfg.padL === undefined ? 62 : cfg.padL;
const padR = cfg.padR === undefined ? 14 : cfg.padR;
const padT = cfg.padT === undefined ? 14 : cfg.padT;
const padB = cfg.padB === undefined ? 30 : cfg.padB;
const plotW = W - padL - padR, plotH = H - padT - padB;
const baseY = padT + plotH;
const n = cfg.n;
const xAt = i => padL + (n <= 1 ? plotW / 2 : (plotW * i) / (n - 1));
const yAt = v => baseY - (plotH * v) / cfg.top;
const parts = [];
parts.push('<svg viewBox="0 0 ' + W + ' ' + H + '" role="img" aria-label="' + cfg.aria + '">');
for (let g = 0; g <= 4; g++) {
const yy = baseY - (plotH * g) / 4;
parts.push('<line x1="' + padL + '" y1="' + yy + '" x2="' + (W - padR) + '" y2="' + yy + '" stroke="' + (cfg.gridStroke || "var(--border)") + '"/>');
parts.push('<text x="' + (padL - 8) + '" y="' + (yy + 4) + '" text-anchor="end" font-size="11" fill="var(--muted)">' + cfg.tickLabel(cfg.step * g) + '</text>');
}
return { W, H, padL, padR, baseY, n, xAt, yAt, parts };
}
// ---- X-axis date marks: start / middle / end, day strings YYYY-MM-DD ----
function dateMarks(fr, days) {
const marks = fr.n > 2 ? [0, Math.floor((fr.n - 1) / 2), fr.n - 1] : [0, fr.n - 1];
for (let mi = 0; mi < marks.length; mi++) {
const i = marks[mi];
const anchor = mi === 0 ? "start" : (mi === marks.length - 1 ? "end" : "middle");
fr.parts.push('<text x="' + fr.xAt(i) + '" y="' + (fr.H - 9) + '" text-anchor="' + anchor + '" font-size="11" fill="var(--muted)">' + String(days[i]).slice(5) + '</text>');
}
}
// ---- Bars. opts: { color, host } — host stamps the elements for tooltips.
// NULL values are skipped (no zero bars, no tooltip on an unmeasured day).
function drawBars(fr, vals, opts) {
const bw = Math.max(1, (fr.W - fr.padL - fr.padR) / fr.n - 1);
for (let i = 0; i < fr.n; i++) {
const v = vals[i];
if (v === null || v === undefined) continue;
const yy = fr.yAt(v);
fr.parts.push('<rect x="' + (fr.xAt(i) - bw / 2) + '" y="' + yy + '" width="' + bw + '" height="' + Math.max(0.6, fr.baseY - yy) + '" fill="' + opts.color + '"' + (opts.host ? ' data-tip-host="' + opts.host + '" data-tip-i="' + i + '"' : "") + "></rect>");
}
}
// ---- Lines broken into contiguous measured runs. opts:
// color stroke (and default fill for single-point dots)
// area draw the fill-under-line area path (panel Trends style)
// areaColor / areaOpacity area fill override (defaults: color / 0.10)
// dotSingle draw a dot (r = dotR, default 3) for a 1-point run instead of
// nothing — a single measured day still shows (money style)
function drawLineRuns(fr, vals, opts) {
const runs = measuredRuns(vals);
for (let s = 0; s < runs.length; s++) {
const r0 = runs[s];
if (opts.area) {
fr.parts.push('<path d="M' + fr.xAt(r0[0]) + "," + fr.baseY + " L" + r0.map(i => fr.xAt(i) + "," + fr.yAt(vals[i])).join(" L") + " L" + fr.xAt(r0[r0.length - 1]) + "," + fr.baseY + ' Z" fill="' + (opts.areaColor || opts.color) + '" fill-opacity="' + (opts.areaOpacity === undefined ? "0.10" : opts.areaOpacity) + '"/>');
}
if (r0.length > 1 || opts.area) {
fr.parts.push('<polyline points="' + r0.map(i => fr.xAt(i) + "," + fr.yAt(vals[i])).join(" ") + '" fill="none" stroke="' + opts.color + '" stroke-width="2" stroke-linejoin="round"/>');
} else if (opts.dotSingle) {
// A single measured day (e.g. the first balance snapshot) still shows.
fr.parts.push('<circle cx="' + fr.xAt(r0[0]) + '" cy="' + fr.yAt(vals[r0[0]]) + '" r="' + (opts.dotR === undefined ? 3 : opts.dotR) + '" fill="' + opts.color + '"/>');
}
}
}
// ---- Hover targets: one transparent circle per measured point; the
// tooltip lists every series at that x. NULL points get no stamp.
function hoverTargets(fr, vals, host) {
for (let i = 0; i < fr.n; i++) {
const v = vals[i];
if (v === null || v === undefined) continue;
fr.parts.push('<circle cx="' + fr.xAt(i) + '" cy="' + fr.yAt(v) + '" r="7" fill="transparent" data-tip-host="' + host + '" data-tip-i="' + i + '"></circle>');
}
}
// ==== Chart definitions — the ONE place a chart is described ==============
// A chart is DATA here, not markup: the same metrics, in the same order, with
// the same titles and the same shape in every UI. Each app supplies its own
// data rows and its own DOM (its toggle classes, its empty-state markup, its
// legend element), which is the only thing that legitimately differs.
//
// WHY: the two UIs had drifted while sharing only the drawing primitives —
// the same five metrics shipped with different titles and different chart
// kinds (the panel's "Spend per day" was the dashboard's "What the co-op
// spent (members + the co-op's own accounts)"). Anything a member may see
// belongs in THIS list, so it exists once and cannot drift again.
//
// fmt selects the value formatter: "money" | "count" | "wh" | "g".
// kind is "line" | "bar" | "multi" (multi = N series on one axis, the money
// chart: cumulative revenue, cumulative token spend, and the OC balance,
// which only exists from the day the snapshots began, so it draws as a gap
// before that — never as a zero).
const CHART_METRICS = [
{ id: "members", title: "Members", kind: "line", cont: false, fmt: "count",
val: r => r.members_total },
{ id: "requests", title: "Requests", kind: "bar", cont: false, fmt: "count",
val: r => r.requests },
{ id: "spend", title: "Spend", kind: "bar", cont: true, fmt: "money",
val: r => r.spend_usd },
{ id: "money", title: "Money", kind: "multi", cont: true, fmt: "money",
aria: "Cumulative revenue, token spend and OC balance over time",
series: [
{ name: "Revenue", key: "revenue_cum", color: "var(--green-deep)" },
{ name: "Token spend", key: "spend_cum", color: "#4a6a8a" },
{ name: "OC balance", key: "oc_balance", color: "#a97a2a", dotSingle: true }
] },
{ id: "energy", title: "Energy", kind: "bar", cont: true, fmt: "wh",
val: r => r.energy_wh },
{ id: "co2e", title: "Carbon", kind: "bar", cont: true, fmt: "g",
val: r => r.co2e_g }
];
function metricDef(id) {
for (let i = 0; i < CHART_METRICS.length; i++) if (CHART_METRICS[i].id === id) return CHART_METRICS[i];
return CHART_METRICS[0];
}
// ---- Value formatting (shared so the two apps' labels match byte for byte;
// both already agreed, this only stops them from diverging) ----
function fmtMoney(v) {
const n = Math.abs(Number(v)) < 0.005 ? 0 : (Number(v) || 0);
return "$" + n.toFixed(2);
}
function fmtMetric(def, v) {
if (v === null || v === undefined) return "not measured"; // the gap rule
switch (def && def.fmt) {
case "money": return fmtMoney(v);
case "wh": return Number(v).toLocaleString() + " Wh";
case "g": return Number(v).toLocaleString() + " g";
default: return Number(v).toLocaleString();
}
}
// Money-axis ticks: the 1/2/5 x 10^k rule (niceStep continuous) with integer
// dollars at or above $1 and cents below, so a $0.50 tick does not read "$1".
function fmtMoneyTick(v) {
return v >= 1 ? "$" + Math.round(v).toLocaleString() : "$" + v.toFixed(2);
}
// ---- The chart renderer: one implementation for both UIs ----
// renderChart({ host, def, rows, aria }) -> { svg, legend }
// * registers the EXACT tooltip values (the module's contract) under `host`
// * returns the SVG string and the legend items; the APP writes the DOM,
// because that is the part that differs (element ids, class names)
// * a NULL value stays a GAP: no zero, no bar, and no tooltip stamp
// `rows` for a "multi" chart carry the series keys; otherwise `def.val(row)`.
function renderChart(cfg) {
const def = cfg.def, rows = cfg.rows || [], host = cfg.host;
const legend = [];
if (def.kind === "multi") {
const series = def.series || [];
const vals = series.map(s => rows.map(r => r[s.key]));
const tops = [];
for (let si = 0; si < vals.length; si++) {
for (let i = 0; i < vals[si].length; i++) {
const v = vals[si][i];
if (v !== null && v !== undefined) tops.push(v);
}
}
const maxV = tops.length ? Math.max.apply(null, tops) : 0;
const step = niceStep((maxV <= 0 ? 1 : maxV * 1.08) / 4, true);
const fr = chartFrame({
n: rows.length, top: step * 4, step,
tickLabel: def.fmt === "money" ? fmtMoneyTick : (v => fmtMetric(def, v)),
aria: cfg.aria || def.aria || def.title,
gridStroke: cfg.gridStroke || "var(--border)"
});
registerChartTips(host, rows.map((r, i) => ({
label: r.day,
series: series.map((s, si) => [s.name, fmtMetric(def, vals[si][i])])
})));
for (let si = 0; si < series.length; si++) {
const s = series[si];
drawLineRuns(fr, vals[si], {
color: s.color, dotSingle: s.dotSingle !== false, dotR: 3,
area: !!s.area, areaOpacity: s.areaOpacity
});
hoverTargets(fr, vals[si], host);
legend.push({ color: s.color, name: s.name });
}
dateMarks(fr, rows.map(r => r.day));
fr.parts.push("</svg>");
return { svg: fr.parts.join(""), legend };
}
const vals = rows.map(def.val);
registerChartTips(host, rows.map((r, i) => ({
label: r.day,
series: [[def.title, fmtMetric(def, vals[i])]]
})));
const have = vals.filter(v => v !== null && v !== undefined);
if (have.length < 2) return { svg: "", legend, empty: true };
const maxV = Math.max.apply(null, have);
const step = niceStep((maxV <= 0 ? 1 : maxV * 1.08) / 4, def.cont);
const tickLabel = v => fmtMetric(def, v);
const fr = chartFrame({
n: vals.length, top: step * 4, step, tickLabel,
aria: cfg.aria || (def.title + " over time"),
gridStroke: cfg.gridStroke || "var(--border)"
});
if (def.kind === "bar") {
drawBars(fr, vals, { color: "var(--green-mid)", host });
} else {
drawLineRuns(fr, vals, { color: "var(--green-deep)", area: true });
hoverTargets(fr, vals, host);
}
dateMarks(fr, rows.map(r => r.day));
fr.parts.push("</svg>");
return { svg: fr.parts.join(""), legend };
}
// chartTipData is exported for inspection (harnesses assert on the exact
// registered points); treat it as read-only in page code.
global.CoOpChart = {
chartTipData,
registerChartTips,
chartTipTarget,
hideChartTip,
showChartTip,
moveChartTip,
niceStep,
measuredRuns,
chartFrame,
dateMarks,
drawBars,
drawLineRuns,
hoverTargets,
// the definition layer both UIs read
CHART_METRICS,
metricDef,
fmtMoney,
fmtMetric,
fmtMoneyTick,
renderChart
};
})(typeof globalThis !== "undefined" ? globalThis : window);
+210
View File
@@ -0,0 +1,210 @@
"""OIDC client for Cloudron's OpenID Connect addon — ONE shared module.
This file is the SINGLE SOURCE for the two thin Cloudron apps that implement
the authorization-code flow themselves (admin-panel, member-dashboard). The
copies in those repos' app/oidc.py are byte-identical to this file — verified
by ops-docs/scripts/check-oidc-sync.py and enforced by each repo's
tests/test_oidc_sync.py — so a fix lands here, is synced to both repos, and
can never drift. Do not edit a repo copy directly: sync-oidc-module.sh
overwrites it, and the pin test goes red on any hand edit.
Cloudron exports these env vars (they change on every restart — read per-call,
never cache at import):
CLOUDRON_OIDC_ISSUER e.g. https://my.inference.coop/openid
CLOUDRON_OIDC_AUTH_ENDPOINT authorization endpoint
CLOUDRON_OIDC_TOKEN_ENDPOINT token endpoint
CLOUDRON_OIDC_KEYS_ENDPOINT JWKS endpoint (RS256/EdDSA keys)
CLOUDRON_OIDC_PROFILE_ENDPOINT userinfo endpoint
CLOUDRON_OIDC_CLIENT_ID client id
CLOUDRON_OIDC_CLIENT_SECRET client secret
CLOUDRON_APP_DOMAIN the app's public domain
Identity: Cloudron's `sub` claim is the username (the unique user identifier).
We use `sub` as the identity; each host app decides what it authorizes — the
panel matches it against its ADMIN_USERNAMES allowlist, the dashboard
forwards it to the portal's broker as `X-Member-User` (which resolves
username → email).
Per-app identity: the ONLY differences the two copies used to carry were the
logger name, the session cookie name and the session salt. The host app now
supplies those via configure() at import time (see each app's main.py), which
keeps this file byte-identical everywhere while preserving each app's
existing cookie names and salts (so existing sessions survive a redeploy).
"""
import os
import secrets as _secrets
import logging
import urllib.parse
import httpx
from authlib.jose import JsonWebToken, JsonWebKey
from itsdangerous import URLSafeTimedSerializer, BadSignature, SignatureExpired
# Per-app identity — set by the host app at import time via configure().
# The unset sentinels below are loud on purpose: a copy that reaches a
# request without its host app having configured itself is a sync/setup bug.
APP_NAME = "unset-app"
SESSION_COOKIE = "unset_oidc_session"
_SESSION_SALT = "unset-oidc-session"
SESSION_MAX_AGE = 60 * 60 * 8 # 8 hours, roughly a working day
SCOPES = "openid profile email"
def configure(app_name: str, session_cookie: str, session_salt: str) -> None:
"""Set this app's identity. The host app MUST call this at import time."""
global APP_NAME, SESSION_COOKIE, _SESSION_SALT
APP_NAME = app_name
SESSION_COOKIE = session_cookie
_SESSION_SALT = session_salt
class _LazyLogger:
"""Resolves at CALL time, not import time.
The host app calls configure() AFTER this module is imported (from its
main.py), so an eagerly-created module-level logger would bind the
'unset-app' sentinel name and every OIDC log line would carry the wrong
attribution. Logging through this proxy reads the configured APP_NAME
when the line is actually emitted; logging.getLogger caches by name, so
the per-call lookup is free.
"""
def __getattr__(self, name):
return getattr(logging.getLogger(APP_NAME), name)
logger = _LazyLogger()
def _oidc_env(name: str) -> str:
return os.environ.get(name, "").strip()
def is_oidc_configured() -> bool:
"""True when Cloudron has injected the OIDC addon env vars."""
return bool(
_oidc_env("CLOUDRON_OIDC_CLIENT_ID")
and _oidc_env("CLOUDRON_OIDC_CLIENT_SECRET")
and _oidc_env("CLOUDRON_OIDC_AUTH_ENDPOINT")
)
def _session_serializer() -> URLSafeTimedSerializer:
# Derive a stable, secret signing key from the OIDC client secret (already
# a secret the app holds, and stable across restarts).
secret = _oidc_env("CLOUDRON_OIDC_CLIENT_SECRET") or _secrets.token_urlsafe(32)
return URLSafeTimedSerializer(secret, salt=_SESSION_SALT)
def _redirect_uri(request_host: str) -> str:
domain = _oidc_env("CLOUDRON_APP_DOMAIN")
host = domain or request_host
scheme = "https"
return f"{scheme}://{host}/auth/openid/callback"
def build_login_url(request_host: str) -> tuple[str, str, str]:
"""Return (login_url, state, nonce). Caller stores state+nonce in cookies."""
state = _secrets.token_urlsafe(24)
nonce = _secrets.token_urlsafe(24)
params = {
"response_type": "code",
"client_id": _oidc_env("CLOUDRON_OIDC_CLIENT_ID"),
"redirect_uri": _redirect_uri(request_host),
"scope": SCOPES,
"state": state,
"nonce": nonce,
}
url = f"{_oidc_env('CLOUDRON_OIDC_AUTH_ENDPOINT')}?{urllib.parse.urlencode(params)}"
return url, state, nonce
async def exchange_code(code: str, request_host: str, nonce: str) -> str:
"""Exchange an authorization code for an ID token, returning the username.
Validates the ID token signature (JWKS), issuer, audience, nonce, and
expiry. Returns the `sub` claim (Cloudron = username) on success.
Raises ValueError on any failure.
"""
issuer = _oidc_env("CLOUDRON_OIDC_ISSUER")
client_id = _oidc_env("CLOUDRON_OIDC_CLIENT_ID")
client_secret = _oidc_env("CLOUDRON_OIDC_CLIENT_SECRET")
token_endpoint = _oidc_env("CLOUDRON_OIDC_TOKEN_ENDPOINT")
keys_endpoint = _oidc_env("CLOUDRON_OIDC_KEYS_ENDPOINT")
id_token = None
async with httpx.AsyncClient(timeout=20.0) as client:
# Token exchange (client_secret_post).
token_resp = await client.post(
token_endpoint,
data={
"grant_type": "authorization_code",
"code": code,
"redirect_uri": _redirect_uri(request_host),
"client_id": client_id,
"client_secret": client_secret,
},
)
if token_resp.status_code != 200:
logger.warning("OIDC token exchange failed: %s %s", token_resp.status_code, token_resp.text[:200])
raise ValueError("token exchange failed")
id_token = token_resp.json().get("id_token")
if not id_token:
logger.warning("OIDC token response missing id_token")
raise ValueError("missing id_token")
# Fetch JWKS.
keys_resp = await client.get(keys_endpoint)
if keys_resp.status_code != 200:
logger.warning("OIDC JWKS fetch failed: %s", keys_resp.status_code)
raise ValueError("jwks fetch failed")
jwks = keys_resp.json()
# Validate signature + standard claims (exp/nbf) via claims.validate(),
# and check iss/aud/nonce manually (authlib's JWTClaims.validate() only
# handles exp/nbf; issuer/audience/nonce are checked explicitly).
try:
jwk_set = JsonWebKey.import_key_set(jwks)
jwt = JsonWebToken(["RS256", "EdDSA"])
claims = jwt.decode(id_token, jwk_set)
claims.validate() # validates exp + nbf
# Issuer + audience + nonce (replay protection).
if claims.get("iss") != issuer:
logger.warning("OIDC id_token issuer mismatch: %s", claims.get("iss"))
raise ValueError("issuer mismatch")
if claims.get("aud") != client_id:
logger.warning("OIDC id_token audience mismatch: %s", claims.get("aud"))
raise ValueError("audience mismatch")
if claims.get("nonce") != nonce:
logger.warning("OIDC id_token nonce mismatch")
raise ValueError("nonce mismatch")
except Exception as e:
logger.warning("OIDC id_token validation failed: %s", e)
raise ValueError("id_token validation failed") from e
username = claims.get("sub")
if not username:
logger.warning("OIDC id_token missing sub claim")
raise ValueError("missing sub claim")
return str(username)
def write_session(identity: str) -> str:
"""Create a signed session token for the given identity (username)."""
return _session_serializer().dumps({"identity": identity})
def read_session(token: str) -> str | None:
"""Return the identity from a signed session token, or None if invalid."""
if not token:
return None
try:
data = _session_serializer().loads(token, max_age=SESSION_MAX_AGE)
return data.get("identity") if isinstance(data, dict) else None
except (BadSignature, SignatureExpired):
return None
+118
View File
@@ -0,0 +1,118 @@
#!/usr/bin/env python3
"""Behaviour harness for the shared OIDC client module (steward-host only).
The module's real imports (authlib, itsdangerous, httpx) are not installed on
the steward host, so authlib/httpx are STUBBED and itsdangerous is expected
(pip install itsdangerous). Exercises the parts a copy-edit could break:
1. configure() sets the identity; the lazy logger attributes lines to the
CONFIGURED name even though it was created before configure() ran.
2. write_session/read_session roundtrip on the configured salt, with the
session secret taken from the env (the real derive-from-client-secret
path) — and a DIFFERENT salt cannot read the other app's token.
3. tampered/expired tokens read as None (no exception leaks).
4. the pin check: this file's sibling oidc_client.py must be byte-identical
to both repos' copies (same guarantee as check-oidc-sync.py, so the
harness never validates a drifted copy).
Run: python3 scripts/shared/test_oidc_client.py (from the ops-docs repo)
"""
import hashlib
import logging
import os
import sys
import tempfile
from pathlib import Path
from types import ModuleType
HERE = Path(__file__).resolve().parent
REPOS = HERE.parent.parent.parent
# --- stub authlib + httpx BEFORE importing the module -----------------------
for name in ("authlib", "authlib.jose"):
m = ModuleType(name)
sys.modules.setdefault(name, m)
sys.modules["authlib.jose"].JsonWebToken = object
sys.modules["authlib.jose"].JsonWebKey = object
httpx = ModuleType("httpx")
httpx.AsyncClient = object
sys.modules["httpx"] = httpx
try:
import itsdangerous # noqa: F401
except ImportError:
sys.exit("itsdangerous is required: pip install itsdangerous")
sys.path.insert(0, str(HERE))
oidc = __import__("oidc_client")
failures = []
def check(name, ok, detail=""):
print(("PASS " if ok else "FAIL ") + name + (f" [{detail}]" if detail and not ok else ""))
if not ok:
failures.append(name)
# --- 0. the copies this harness validates are the byte-identical ones -------
canon = hashlib.sha256((HERE / "oidc_client.py").read_bytes()).hexdigest()
for repo in ("member-dashboard", "admin-panel"):
copy = REPOS / repo / "app" / "oidc.py"
check(f"sync: {repo}/app/oidc.py byte-identical to canonical",
hashlib.sha256(copy.read_bytes()).hexdigest() == canon, str(copy))
# --- 1. configure() + lazy logger -------------------------------------------
pre = oidc.logger.name # read BEFORE configure: sentinel, not a crash
oidc.configure("admin-panel", "admin_oidc_session", "admin-panel-oidc-session")
records = []
class _Capture(logging.Handler):
def emit(self, record):
records.append(record)
h = _Capture()
oidc.logger.addHandler(h) # the proxy resolves the configured logger
oidc.logger.setLevel(logging.WARNING)
oidc.logger.warning("probe line")
check("configure: identity is the app's", oidc.APP_NAME == "admin-panel"
and oidc.SESSION_COOKIE == "admin_oidc_session")
check("lazy logger: pre-configure name is the loud sentinel",
pre == "unset-app", pre)
check("lazy logger: lines attribute to the CONFIGURED app",
bool(records) and records[-1].name == "admin-panel",
records[-1].name if records else "no record")
# --- 2/3. session tokens on the configured salt ------------------------------
with tempfile.TemporaryDirectory() as td:
os.environ["CLOUDRON_OIDC_CLIENT_SECRET"] = "unit-test-secret"
token = oidc.write_session("nathan")
check("session: roundtrip returns the identity",
oidc.read_session(token) == "nathan")
check("session: cookie name survived configure",
oidc.SESSION_COOKIE == "admin_oidc_session")
tampered = token[:-3] + ("aaa" if token[-3:] != "aaa" else "bbb")
check("session: tampered token reads None (no exception)",
oidc.read_session(tampered) is None)
check("session: empty token reads None", oidc.read_session("") is None)
# A different salt (the other app's) must NOT read this token.
oidc.configure("member-dashboard", "member_oidc_session",
"member-dashboard-oidc-session")
check("session: the other app's salt cannot read this app's token",
oidc.read_session(token) is None)
d_tok = oidc.write_session("someuser")
check("session: dashboard roundtrip on its own salt",
oidc.read_session(d_tok) == "someuser")
check("session: APP_NAME switched with configure",
oidc.APP_NAME == "member-dashboard")
os.environ.pop("CLOUDRON_OIDC_CLIENT_SECRET")
# back to the panel identity, as the panel's main.py leaves it
oidc.configure("admin-panel", "admin_oidc_session", "admin-panel-oidc-session")
print()
print(f"{len(failures)} failure(s)" + (": " + ", ".join(failures) if failures else ""))
sys.exit(1 if failures else 0)
+116
View File
@@ -0,0 +1,116 @@
#!/usr/bin/env bash
# Sync the shared chart module to both thin apps, and re-pin them.
#
# ops-docs/scripts/sync-chart-module.sh
#
# The canonical module is scripts/shared/coop_chart.js in THIS repo. The two
# consumer repos (member-dashboard, admin-panel) ship BYTE-IDENTICAL copies at
# app/coop_chart.js; each app's main.py splices it into PAGE_HTML at import
# time. Editing a copy by hand is a dead end: this script overwrites it, and
# the repo's tests/test_chart_sync.py goes red on any drift from the pinned
# revision.
#
# What this does:
# 1. copies the canonical module over both repos' app/coop_chart.js
# 2. regenerates each repo's tests/test_chart_sync.py with the CURRENT
# canonical sha256 (the pin CI checks, since CI has no ops-docs checkout)
# 3. node --check's the module
# 4. runs check-chart-sync.py as the gate — a red check leaves the working
# tree dirty so nothing can be silently committed half-synced
#
# After it passes: commit all three repos (ops-docs + both apps).
set -euo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPOS="$(dirname "$(dirname "$HERE")")" # ops-docs/scripts -> ops-docs -> ~/repos
CANONICAL="$HERE/shared/coop_chart.js"
[ -f "$CANONICAL" ] || { echo "canonical module missing: $CANONICAL" >&2; exit 1; }
if command -v node >/dev/null 2>&1; then
node --check "$CANONICAL" && echo "node --check canonical: OK"
else
echo "node not found; skipping node --check (CI runs it)" >&2
fi
SHA="$(sha256sum "$CANONICAL" | cut -d' ' -f1)"
echo "canonical sha256: $SHA"
gen_pin_test() { # <repo>
local repo="$1"
local dir="$REPOS/$repo"
mkdir -p "$dir/tests"
cat > "$dir/tests/test_chart_sync.py" <<EOF
#!/usr/bin/env python3
"""coop_chart.js sync pin — the repo copy is byte-identical to the canonical
module, and main.py splices it into the served page.
WHY THIS EXISTS
app/coop_chart.js is a byte-identical copy of the canonical module
(co-op/ops-docs repo: scripts/shared/coop_chart.js) — the single source for
the hand-rolled chart rendering + hover tooltips both UIs ship. This test
pins the copy to the canonical revision recorded below: ANY hand edit to
app/coop_chart.js breaks the pin and goes red. To change the module, edit
the canonical file and run ops-docs/scripts/sync-chart-module.sh, which
re-copies and re-pins both repos in one step (check-chart-sync.py is the
pre-deploy gate).
Generated by sync-chart-module.sh — do not edit by hand.
Run: python3 tests/test_chart_sync.py
"""
import hashlib
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
CANONICAL_SHA256 = "$SHA"
SPLICE = 'PAGE_HTML = PAGE_HTML.replace("/*@@CHART_MODULE@@*/", CHART_MODULE_JS)'
failures = []
copy = ROOT / "app" / "coop_chart.js"
if not copy.exists():
failures.append("app/coop_chart.js missing")
else:
got = hashlib.sha256(copy.read_bytes()).hexdigest()
if got == CANONICAL_SHA256:
print(f"ok - app/coop_chart.js matches the pinned canonical revision ({got[:16]}…)")
else:
failures.append(
"app/coop_chart.js DRIFTED from the pinned canonical revision\\n"
f" pinned {CANONICAL_SHA256}\\n"
f" actual {got}\\n"
" fix: edit the canonical module (ops-docs: scripts/shared/coop_chart.js) "
"and run ops-docs/scripts/sync-chart-module.sh — never hand-edit the copy.")
main_src = (ROOT / "app" / "main.py")
if not main_src.exists():
failures.append("app/main.py missing")
else:
msrc = main_src.read_text()
if SPLICE not in msrc:
failures.append(
"app/main.py does not splice the shared chart module into PAGE_HTML:\\n"
f" expected literal: {SPLICE}")
if 'parent / "coop_chart.js"' not in msrc:
failures.append("app/main.py does not load app/coop_chart.js")
if failures:
print()
print("FAILED: " + ", ".join(failures))
sys.exit(1)
print("chart sync pin: OK")
EOF
echo "regenerated $repo/tests/test_chart_sync.py"
}
gen_pin_test member-dashboard
gen_pin_test admin-panel
for repo in member-dashboard admin-panel; do
cp "$CANONICAL" "$REPOS/$repo/app/coop_chart.js"
echo "copied canonical -> $repo/app/coop_chart.js"
done
python3 "$HERE/check-chart-sync.py"
+108
View File
@@ -0,0 +1,108 @@
#!/usr/bin/env bash
# Sync the shared OIDC client module to both thin apps, and re-pin them.
#
# ops-docs/scripts/sync-oidc-module.sh
#
# The canonical module is scripts/shared/oidc_client.py in THIS repo. The two
# consumer repos (member-dashboard, admin-panel) ship BYTE-IDENTICAL copies at
# app/oidc.py so their login never depends on another app being up. Editing a
# copy by hand is a dead end: this script overwrites it, and the repo's
# tests/test_oidc_sync.py goes red on any drift from the pinned revision.
#
# What this does:
# 1. copies the canonical module over both repos' app/oidc.py
# 2. regenerates each repo's tests/test_oidc_sync.py with the CURRENT
# canonical sha256 (the pin CI checks, since CI has no ops-docs checkout)
# 3. py_compiles every touched file
# 4. runs check-oidc-sync.py as the gate — a red check leaves the working
# tree dirty so nothing can be silently committed half-synced
#
# After it passes: commit all three repos (ops-docs + both apps).
set -euo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPOS="$(dirname "$(dirname "$HERE")")" # ops-docs/scripts -> ops-docs -> ~/repos
CANONICAL="$HERE/shared/oidc_client.py"
[ -f "$CANONICAL" ] || { echo "canonical module missing: $CANONICAL" >&2; exit 1; }
SHA="$(sha256sum "$CANONICAL" | cut -d' ' -f1)"
echo "canonical sha256: $SHA"
gen_pin_test() { # <repo> <cookie-literal-configure-call>
local repo="$1" configure="$2"
local dir="$REPOS/$repo"
mkdir -p "$dir/tests"
cat > "$dir/tests/test_oidc_sync.py" <<EOF
#!/usr/bin/env python3
"""oidc.py sync pin — the repo copy is byte-identical to the canonical module.
WHY THIS EXISTS
app/oidc.py is a byte-identical copy of the canonical module
(co-op/ops-docs repo: scripts/shared/oidc_client.py) — the single source for
the OIDC client the thin apps ship copies of, so their login never depends
on another app being up. This test pins the copy to the canonical revision
recorded below: ANY hand edit to app/oidc.py breaks the pin and goes red.
To change the module, edit the canonical file and run
ops-docs/scripts/sync-oidc-module.sh, which re-copies and re-pins both
repos in one step (check-oidc-sync.py is the pre-deploy gate).
Generated by sync-oidc-module.sh — do not edit by hand.
Run: python3 tests/test_oidc_sync.py
"""
import hashlib
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
CANONICAL_SHA256 = "$SHA"
EXPECTED_CONFIGURE = '''$configure'''
failures = []
copy = ROOT / "app" / "oidc.py"
if not copy.exists():
failures.append("app/oidc.py missing")
else:
got = hashlib.sha256(copy.read_bytes()).hexdigest()
if got == CANONICAL_SHA256:
print(f"ok - app/oidc.py matches the pinned canonical revision ({got[:16]}…)")
else:
failures.append(
"app/oidc.py DRIFTED from the pinned canonical revision\\n"
f" pinned {CANONICAL_SHA256}\\n"
f" actual {got}\\n"
" fix: edit the canonical module (ops-docs: scripts/shared/oidc_client.py) "
"and run ops-docs/scripts/sync-oidc-module.sh — never hand-edit the copy.")
main_src = (ROOT / "app" / "main.py")
if not main_src.exists():
failures.append("app/main.py missing")
elif EXPECTED_CONFIGURE not in main_src.read_text():
failures.append(
"app/main.py does not configure this app's oidc identity:\\n"
f" expected literal: {EXPECTED_CONFIGURE}")
if failures:
print()
print("FAILED: " + ", ".join(failures))
sys.exit(1)
print("oidc sync pin: OK")
EOF
echo "regenerated $repo/tests/test_oidc_sync.py"
}
gen_pin_test member-dashboard \
'oidc.configure("member-dashboard", "member_oidc_session", "member-dashboard-oidc-session")'
gen_pin_test admin-panel \
'oidc.configure("admin-panel", "admin_oidc_session", "admin-panel-oidc-session")'
for repo in member-dashboard admin-panel; do
cp "$CANONICAL" "$REPOS/$repo/app/oidc.py"
echo "copied canonical -> $repo/app/oidc.py"
python3 -m py_compile "$REPOS/$repo/app/oidc.py" "$REPOS/$repo/tests/test_oidc_sync.py"
done
echo "py_compile: OK (both copies + both pin tests)"
python3 "$HERE/check-oidc-sync.py"
+261
View File
@@ -0,0 +1,261 @@
#!/usr/bin/env python3
"""Fail-closed config validator for the co-op's gateway and chat apps.
ONE script, two modes, shared home in ops-docs/scripts/ and shipped
byte-identical into both app images (litellm repo root, librechat-custom repo
root). Each app's start path calls it before booting the service; a non-zero
exit refuses the boot with a ONE-line error naming the offending key.
Why this exists: the 2026-10-31 chat outage. A `customFooter:` top-level key in
librechat.yaml was rejected by LibreChat's strict config validator and the API
server refused to start, while the SPA kept being served with HTTP 200 — the
app looked up but every API route returned the HTML shell. Nothing had ever
checked the config before boot. This validator closes that gap: invalid config
fails LOUD and EARLY, at the top of the boot log, naming the key.
Modes
-----
litellm Structural check of the gateway's config.yaml:
- top-level keys within LiteLLM's documented config surface;
- model_list present and well-formed (model_name + litellm_params.model);
- the settings blocks are objects; pass_through_endpoints entries have paths.
When the gateway's own litellm package is importable it is additionally
used to resolve every model string to a provider (catches unknown
provider prefixes); the check is skipped with a note where litellm
itself is absent.
librechat Checks librechat.yaml against the DEPLOYED build's own strict schema:
it runs `configSchema.strict().safeParse()` from the container's
librechat-data-provider via node — the same code the API server runs
at boot (its failure mode is `process.exit(1)`, "Exiting due to
invalid configuration"). Unrecognized top-level keys are rejected,
named explicitly. Where node/the package cannot be found (e.g. this
script run from a checkout instead of the image) it falls back to a
static top-level allowlist recorded from the deployed build and says
so on the failure line.
Usage
-----
python3 validate_config.py litellm /app/data/config.yaml
python3 validate_config.py librechat /app/data/librechat.yaml
Exit codes: 0 valid, 1 invalid, 2 usage/environment error (file unreadable,
yaml unparseable). Never prints a value from the config — only key names and
counts, so it is safe to run against files that carry secrets.
"""
import json
import os
import subprocess
import sys
# LiteLLM's documented top-level config surface (proxy config). Unknown keys
# are rejected here — the gateway should never silently ignore a mistyped
# section (a "model-list:" typo would otherwise deploy an EMPTY catalog).
LITELLM_TOP_LEVEL = {
"model_list",
"router_settings",
"litellm_settings",
"general_settings",
"settings",
"environment_variables",
"guardrails",
"files",
}
# Fallback allowlist for librechat mode, recorded 2026-11-11 from the DEPLOYED
# build (chat.inference.coop, overlay 1.4.8) by reading
# configSchema.strict().shape keys. The live schema is always preferred; this
# exists so the validator still fails closed when run outside the container.
LIBRECHAT_TOP_LEVEL_FALLBACK = {
"actions", "balance", "cache", "cloudfront", "endpoints", "fileConfig",
"fileStrategies", "fileStrategy", "filteredTools", "filters",
"imageOutputType", "includedTools", "interface", "langfuse", "mcpServers",
"mcpSettings", "memory", "messageFilter", "modelSpecs", "ocr", "openapi",
"permissions", "rateLimits", "registration", "secureImageLinks",
"skillSync", "speech", "summarization", "transactions", "turnstile",
"version", "webSearch",
}
LC_DATA_PROVIDER_DIST = os.environ.get(
"LC_DATA_PROVIDER_DIST",
"/app/code/librechat/packages/data-provider/dist/index.js")
LC_JS_YAML = os.environ.get(
"LC_JS_YAML", "/app/code/librechat/node_modules/js-yaml")
def fail(key, reason):
"""ONE line, naming the offending key, then a non-zero exit."""
print(f"CONFIG VALIDATION FAILED: {key}: {reason}", flush=True)
sys.exit(1)
def load_yaml(path):
try:
import yaml
except ImportError:
print("CONFIG VALIDATION FAILED: pyyaml not available in this python",
flush=True)
sys.exit(2)
try:
with open(path) as fh:
data = yaml.safe_load(fh)
except FileNotFoundError:
print(f"CONFIG VALIDATION FAILED: config file not found: {path}",
flush=True)
sys.exit(2)
except PermissionError:
print(f"CONFIG VALIDATION FAILED: config file unreadable: {path}",
flush=True)
sys.exit(2)
except yaml.YAMLError as exc:
# Do not echo the raw yaml error: it can quote a secret-bearing line.
print("CONFIG VALIDATION FAILED: (root): yaml does not parse",
flush=True)
sys.exit(2)
if data is None:
data = {}
if not isinstance(data, dict):
fail("(root)", "top level must be a mapping")
return data
def validate_litellm(path):
cfg = load_yaml(path)
unknown = sorted(set(cfg) - LITELLM_TOP_LEVEL)
if unknown:
fail(", ".join(unknown), "unknown top-level key(s) for litellm "
f"(allowed: {', '.join(sorted(LITELLM_TOP_LEVEL))})")
model_list = cfg.get("model_list")
if not isinstance(model_list, list) or not model_list:
fail("model_list", "must be a non-empty list of model entries")
names = set()
for i, entry in enumerate(model_list):
if not isinstance(entry, dict):
fail(f"model_list[{i}]", "entry must be a mapping")
name = entry.get("model_name")
params = entry.get("litellm_params")
if not name or not isinstance(name, str):
fail(f"model_list[{i}].model_name", "missing or empty")
if name in names:
fail(f"model_list[{i}].model_name", f"duplicate model_name {name!r}")
names.add(name)
if not isinstance(params, dict) or not params.get("model"):
fail(f"model_list[{i}].litellm_params.model", "missing or empty")
for block in ("router_settings", "litellm_settings", "general_settings"):
if block in cfg and not isinstance(cfg[block], dict):
fail(block, "must be a mapping")
for ep in (cfg.get("general_settings") or {}).get("pass_through_endpoints") or []:
if not isinstance(ep, dict) or not ep.get("path"):
fail("general_settings.pass_through_endpoints", "each entry needs a path")
# litellm-assisted check (best effort): resolve each model string to a
# provider with the gateway's own package. Skipped where litellm itself
# is not importable (never fatal — the structural checks above ran).
try:
from litellm import get_llm_provider # noqa: WPS433
except Exception:
print("note: litellm not importable here; provider check skipped",
flush=True)
else:
for entry in model_list:
model = entry["litellm_params"]["model"]
try:
get_llm_provider(model=model, custom_llm_provider=None)
except Exception as exc:
short = str(exc).split("\n")[0][:120]
fail(f"model_list.{entry['model_name']}.litellm_params.model",
f"not resolvable to a provider: {short}")
print(f"config OK (litellm): {len(cfg)} top-level key(s), "
f"{len(model_list)} model(s) validated", flush=True)
sys.exit(0)
def validate_librechat(path):
cfg = load_yaml(path)
if not cfg:
print("config OK (librechat): empty config, nothing to validate",
flush=True)
sys.exit(0)
# Preferred: the DEPLOYED build's own strict schema, run through node —
# the exact code path the API server uses at boot (strict() rejects
# unrecognized top-level keys; upstream then exits 1).
node_code = r"""
const fs = require('fs');
let out = {mode: 'schema'};
try {
const yaml = require(JS_YAML_PATH);
const dp = require(DIST_PATH);
const cfg = yaml.load(fs.readFileSync(CONFIG_PATH, 'utf8')) || {};
const result = dp.configSchema.strict().safeParse(cfg);
if (result.success) {
out.ok = true;
out.keys = Object.keys(cfg).length;
} else {
out.ok = false;
out.errors = (result.error && result.error.issues || []).slice(0, 10)
.map(i => ({path: (i.path || []).join('.') || '(root)', msg: i.message}));
}
} catch (e) {
out.mode = 'schema-unavailable';
out.error = String(e && e.message || e).slice(0, 200);
}
console.log('@@' + JSON.stringify(out));
""".replace("JS_YAML_PATH", json.dumps(LC_JS_YAML)) \
.replace("DIST_PATH", json.dumps(LC_DATA_PROVIDER_DIST)) \
.replace("CONFIG_PATH", json.dumps(path))
if os.path.exists(LC_DATA_PROVIDER_DIST):
try:
proc = subprocess.run(["node", "-e", node_code], capture_output=True,
text=True, timeout=60)
for line in (proc.stdout or "").splitlines():
if line.startswith("@@"):
res = json.loads(line[2:])
if res.get("ok"):
print(f"config OK (librechat): {res['keys']} top-level "
"key(s) accepted by the deployed strict schema",
flush=True)
sys.exit(0)
errs = "; ".join(
f"{e['path']}: {e['msg']}" for e in res.get("errors", []))
if errs:
fail(errs, "rejected by the deployed build's strict "
"config schema (configSchema.strict())")
fail("(root)", "strict schema rejected the config")
# No @@ line: schema path unavailable — fall through to fallback.
print("note: deployed schema probe produced no result "
f"(stderr: {(proc.stderr or '')[:120]!r})", flush=True)
except (OSError, subprocess.TimeoutExpired) as exc:
print(f"note: could not run node against the deployed schema "
f"({type(exc).__name__})", flush=True)
else:
print("note: deployed data-provider dist not found; using the static "
"fallback allowlist recorded from the deployed build", flush=True)
# Fallback: static allowlist (still fail-closed).
unknown = sorted(set(cfg) - LIBRECHAT_TOP_LEVEL_FALLBACK)
if unknown:
fail(", ".join(unknown), "unknown top-level key(s) for librechat "
f"(fallback allowlist: {', '.join(sorted(LIBRECHAT_TOP_LEVEL_FALLBACK))})")
print(f"config OK (librechat, fallback allowlist): {len(cfg)} top-level "
"key(s)", flush=True)
sys.exit(0)
def main():
args = sys.argv[1:]
if len(args) != 2 or args[0] not in ("litellm", "librechat"):
print("usage: validate_config.py <litellm|librechat> <config.yaml>",
file=sys.stderr, flush=True)
sys.exit(2)
if args[0] == "litellm":
validate_litellm(args[1])
validate_librechat(args[1])
if __name__ == "__main__":
main()