Compare commits
41
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cd5960f62d | ||
|
|
f63096d4dc | ||
|
|
86012fc879 | ||
|
|
3d4fac124d | ||
|
|
5d1c2a5158 | ||
|
|
e2879dbdc2 | ||
|
|
ec7fa33c77 | ||
|
|
5ad233c612 | ||
|
|
d106f7cf01 | ||
|
|
3044e448cd | ||
|
|
2ea42979b5 | ||
|
|
82eaf274af | ||
|
|
c585cb7228 | ||
|
|
b792198b36 | ||
|
|
4525142e0b | ||
|
|
2fda1bcc29 | ||
|
|
c2a9029d00 | ||
|
|
02a75a1868 | ||
|
|
4a7a4be1a7 | ||
|
|
3008a02553 | ||
|
|
8557f636f8 | ||
|
|
e6d27b3775 | ||
|
|
65e3726d90 | ||
|
|
23d2fc0eb2 | ||
|
|
206c3d5379 | ||
|
|
2c38f4d2c3 | ||
|
|
52e3c9d502 | ||
|
|
5a4492e725 | ||
|
|
0f40dcc519 | ||
|
|
816961fb2d | ||
|
|
fcd4ac6943 | ||
|
|
bb10d93412 | ||
|
|
4d3f539a84 | ||
|
|
3bf152b58a | ||
|
|
b1a1c70e8a | ||
|
|
a9edaa3e4b | ||
|
|
835aed2852 | ||
|
|
6f2a6d01ed | ||
|
|
6e777be842 | ||
|
|
2eb88f55b4 | ||
|
|
8b33d823c1 |
No files matched your search
@@ -24,11 +24,19 @@ Read it on the web here: <https://git.inference.coop/co-op/ops-docs>
|
||||
| Path | Contents |
|
||||
|---|---|
|
||||
| `operator-token-runbook.md` | The Cloudron token model (agent vs portal, admin vs webhook), how to rotate each without breaking the stack |
|
||||
| `app-inventory.md` | Every Cloudron app: id, fqdn, registry image path and pin (read from the running apps) |
|
||||
| `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/host-access.md` | Agent-host privilege model: bot accounts, steward bot access, key-only operator root, root-trust watchdog, and safe-mode recovery |
|
||||
| `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 our model providers charge, and when it changed |
|
||||
| `provider-pricing/` | What each model provider charges, and when it changed (GreenPT, Tinfoil, Regolo, and the decision-model route) |
|
||||
|
||||
## The migration material
|
||||
|
||||
@@ -52,6 +60,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,
|
||||
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
# The agent fleet
|
||||
|
||||
The co-op runs **more than one agent**, each as its **own Unix user** on the agent
|
||||
host (`ov-0f018e`, `179.237.103.165`) with its **own Hermes gateway unit** and its
|
||||
**own LiteLLM team**. Any document that describes "the agent" as a single thing is
|
||||
now wrong.
|
||||
|
||||
## The three agents today
|
||||
|
||||
| Agent | Unix user | systemd unit | Gateway team (budget) | Model | Presence |
|
||||
|---|---|---|---|---|---|
|
||||
| **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
|
||||
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 can act inside the bot
|
||||
accounts (`sudo -iu socialbot`, and so on) and run the docs/backup service
|
||||
commands in `maintenance/host-access.md`, but it has **no root**. Root belongs
|
||||
to the separate `operator` account; 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
|
||||
it. Its gateway key has a small monthly budget and a flash-tier allowlist.
|
||||
- **socialbot** has **no Cloudron, portal or member-data access** and no power over
|
||||
Matrix rooms; its only writable surface is the `#social-drafts` room, and it
|
||||
**never publishes an unapproved draft** — silence is its correct failure mode.
|
||||
|
||||
## Fleet access
|
||||
|
||||
- **Bots have no sudo.** Each bot account carries `ALL=(ALL) !ALL`; its home is
|
||||
mode `0700` and owned by the bot.
|
||||
- **The steward can enter bot accounts**, and that is how fleet maintenance
|
||||
happens: `sudo -iu <bot> ...`. It cannot enter root.
|
||||
- **Root is a human door.** SSH as `operator` with a key, then `sudo -i`. Root
|
||||
SSH login stays closed, and no account has a password login. The account and
|
||||
its sudoers rules are documented in `maintenance/host-access.md`.
|
||||
|
||||
## Working-group bots — one Unix user each
|
||||
|
||||
**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`.
|
||||
|
||||
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
|
||||
|
||||
**Profile isolation is organizational, not security.** Run one OS user (or a
|
||||
rootless container) per agent from day one: **on a shared Unix user, sibling
|
||||
Hermes profiles can read each other's `.env`.** So tier-2 member bots sharing the
|
||||
`infrabot` user are isolated from *members* but **not from each other** — that
|
||||
sharing is accepted for member bots, not extended to the privileged agents.
|
||||
|
||||
## Backup coverage is automatic — but prove it
|
||||
|
||||
The nightly restic run (see `maintenance/backups.md`) enumerates `/home/*` **as
|
||||
root** and stages every agent home, so a new agent is covered without editing any
|
||||
list. Coverage is still **unproven until that agent's files show up in a
|
||||
snapshot**.
|
||||
|
||||
## Gateway teams (member vs agent)
|
||||
|
||||
From `GET https://gateway.inference.coop/team/list` (2026-11-04): 97 teams — one
|
||||
`member:<email>` team per member (mostly $15/30d), `member:info@inference.coop`
|
||||
($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.
|
||||
@@ -0,0 +1,86 @@
|
||||
# Cloudron app inventory
|
||||
|
||||
The co-op's Cloudron server carries **19 apps**. Before 2026-11-02 it carried 16;
|
||||
the three added since the migration are the docs site, the CI server and the CI
|
||||
agent (marked **NEW** below).
|
||||
|
||||
**Source of truth:** read it from the running apps, not from memory or a sibling
|
||||
deploy. `GET https://my.inference.coop/api/v1/apps` returns every app with its
|
||||
`id`, `fqdn`, install state and — inside `manifest` — `dockerImage`. The app
|
||||
record's own top-level `image` field is **null**; the CLI's `list` output does
|
||||
not carry the image at all. The registry paths are **per-app and not uniform**
|
||||
(there are three different namespaces in use — see below), and a path copied from
|
||||
a remembered deploy of a *different* app points the update at a repository that
|
||||
does not hold it.
|
||||
|
||||
*Verified against the live API 2026-11-04.*
|
||||
|
||||
## The 19 apps
|
||||
|
||||
| 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: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: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** |
|
||||
| `ci.inference.coop` | `4984f95e-0c0a-4af3-9ce1-4ca4f3e8483d` | Woodpecker | `cloudron/org.woodpecker_ci.cloudronapp:202610300219490000` | store (Woodpecker server) — **NEW 2026-11-03** |
|
||||
| `ci-agent.inference.coop` | `5ac63873-cf2c-4ad9-acd6-81dc0e016c83` | — | `registry.inference.coop/co-op/woodpecker-agent:20261104-e070275` | **custom** (Woodpecker agent) — **NEW 2026-11-03** |
|
||||
|
||||
(`my.inference.coop` is the Cloudron dashboard hostname — the platform itself, not
|
||||
an app object — so it does not appear here.)
|
||||
|
||||
## Registry namespaces — they are NOT uniform
|
||||
|
||||
Five custom apps pull from four different namespaces. Deriving one path from
|
||||
another app's pattern deploys the wrong (or a missing) image:
|
||||
|
||||
| App | Registry path |
|
||||
|---|---|
|
||||
| chat (LibreChat overlay) | `registry.inference.coop/co-op/librechat-custom` |
|
||||
| CI agent | `registry.inference.coop/co-op/woodpecker-agent` |
|
||||
| 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 | `registry.inference.coop/code/admin-panel` |
|
||||
|
||||
**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
|
||||
|
||||
Six apps are **custom** installs (packaged by us, `appStoreId == ""`): chat,
|
||||
CI agent, portal, dashboard, panel, gateway. Custom apps get **no automatic
|
||||
update** (Cloudron says "not available for custom apps") — their protection is the
|
||||
`manifest.dockerImage` pin, which an update deploys, so a custom app must never be
|
||||
pinned to a floating tag. The rest carry a real `appStoreId` and update through
|
||||
the store.
|
||||
|
||||
## Notes that are easy to get wrong
|
||||
|
||||
- **`enableAutomaticUpdate` exists on every app object and means nothing for a
|
||||
custom one.** Judge update behaviour by the install SOURCE (`appStoreId`), not
|
||||
by that flag.
|
||||
- **Public collectives reach `co-op/*` and `code/*` repos; the only private repos
|
||||
are `ops/inferencebot` and `ops/security`.**
|
||||
- **`info@inference.coop` is the co-op's gateway team account** (`member:info@inference.coop`,
|
||||
budget $135/30d) and also the owner account of several provider keys — see the
|
||||
token runbook.
|
||||
@@ -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`.
|
||||
@@ -0,0 +1,152 @@
|
||||
# Backups
|
||||
|
||||
There are **two independent backup systems**, on two different machines, with two
|
||||
different targets and two different passphrases. Confusing them is the most likely
|
||||
mistake — they do not back each other up, and neither one covers the other's host.
|
||||
|
||||
| | Agent-host backup | Cloudron app backup |
|
||||
|---|---|---|
|
||||
| What | The agent host's state (all agent homes, `~/.hermes`, `~/.ssh`, `~/repos`, gateway unit files) | Every Cloudron app's `/app/data` + addon databases, plus platform config |
|
||||
| Machine | Agent host `ov-0f018e` (`179.237.103.165`) | The Cloudron server `179.237.86.116` |
|
||||
| Tool | `restic` (client-side encrypted, run nightly by a systemd timer) | Cloudron's built-in backup (dashboard-configured) |
|
||||
| Target | Infomaniak **Swiss Backup** (S3-compatible) | Infomaniak **Swiss Backup** (S3-compatible, `s3-v4-compat`) |
|
||||
| Schedule | 04:30 UTC + up to 5 min jitter (`agent-backup.timer`) | daily 23:00 UTC (`00 00 23 * * *`) |
|
||||
| Retention | 7 daily / 4 weekly / 3 monthly, no grouping | 7 days (`keepWithinSecs: 604800`) |
|
||||
| Config lives | installed as `/usr/local/sbin/agent-backup` (root-owned) from `~/.hermes/scripts/backup.sh`; unit at `/etc/systemd/system/agent-backup.*` | Cloudron dashboard (no write API — see below) |
|
||||
| Last verified | 2026-11-04 (13 snapshots in the repo) | 2026-11-02 (runs 2026-10-30 → 11-03 all `normal`, ~5.4 GB) |
|
||||
|
||||
Nothing on the Cloudron **host OS** is backed up by either system (netplan, sshd,
|
||||
`authorized_keys`, hand-edited `/etc`) — build the box, do not expect to restore
|
||||
it. This was the migration's central caveat and it still holds.
|
||||
|
||||
---
|
||||
|
||||
## 1. Agent-host backup (restic)
|
||||
|
||||
`agent-backup.timer` → `agent-backup.service` → `/usr/local/sbin/agent-backup`,
|
||||
a root-owned installed copy of `~/.hermes/scripts/backup.sh`.
|
||||
|
||||
- **The unit runs as `User=root` on purpose.** The agent homes under `/home/*`
|
||||
are mode `0700`, so only root can enumerate them; `ubuntu` sees `EACCES` and a
|
||||
non-root `[ -d .../.hermes ]` test reports **false for a home that exists** —
|
||||
which would silently skip that agent. The script therefore discovers agents by
|
||||
enumerating `/home/*` **as root** and stages each one; a new agent is covered
|
||||
without editing any list. Coverage is still unproven until its files show up in
|
||||
a snapshot.
|
||||
- **It backs up:** `/home/ubuntu/.hermes` (config, `.env`, skills, cron, memory,
|
||||
logs, state DBs), `/home/ubuntu/.ssh`, `/home/ubuntu/repos`, every other
|
||||
agent's `/home/<agent>/.hermes`, and `/etc/systemd/system/hermes-gateway*.service`.
|
||||
It **excludes** rebuildable bulk (`tools/`, `hermes-agent/`, `installs/`,
|
||||
`cache/`, `lsp/`, model caches) and the live SQLite files — consistent copies of
|
||||
those are staged first with `sqlite3 .backup`.
|
||||
- **Failure is visible, not silent.** On failure the script appends a note to
|
||||
`~/.hermes/cron/updates_notes.jsonl`, which the daily stewarding digest reads.
|
||||
Exit codes: 0 ok, 1 config, 2 backup, 3 prune.
|
||||
- **Root trust.** The installed copy runs with root-owned `restic`, does not put
|
||||
`/home/ubuntu/.local/bin` on `PATH`, and does not source
|
||||
`/home/ubuntu/.hermes/.env`. Credentials come only from root-only
|
||||
`/etc/agent-backup.env`, so no agent-writable file is executed as root.
|
||||
Verified 2026-11-21: `check_root_trust.py` is silent and a manual timer run
|
||||
completed with `backup: ok`.
|
||||
|
||||
### Deliberate-but-surprising: the PER-USER restic cache split
|
||||
|
||||
`RESTIC_CACHE_DIR` defaults to **`/var/cache/restic`** (root's run), while manual
|
||||
runs by `ubuntu` use **`~/.cache/restic-manual`**. This is intentional — **do not
|
||||
"tidy" it back into one shared `~/.cache/restic`.**
|
||||
|
||||
A shared cache directory let each user create files the other could not read;
|
||||
restic then **retried every snapshot with exponential backoff** (30s, 1m25s, …)
|
||||
until the run crawled or timed out. The visible symptom (2026-11-03) was a prune
|
||||
that "failed" **three nights running** — which looked exactly like retention being
|
||||
broken, when it was a permissions/retry storm. Splitting the cache per user ended
|
||||
it. The lock and log also live **under `$HOME/.hermes/`** (not `/tmp`): with
|
||||
`fs.protected_regular`, a root run is denied a sticky-dir file owned by another
|
||||
user (`EACCES`), and under `set -e` that killed the root run *silently*.
|
||||
|
||||
### Deliberate-but-surprising: `--group-by ""` on retention
|
||||
|
||||
Retention is:
|
||||
|
||||
```
|
||||
restic forget --tag nightly --group-by "" \
|
||||
--keep-daily 7 --keep-weekly 4 --keep-monthly 3 --prune
|
||||
```
|
||||
|
||||
**`--group-by ""` (no grouping) is required, not cosmetic.** restic's default is
|
||||
`--group-by host,paths`, which splits the nightly snapshots into one group per
|
||||
distinct **paths set**. The backup glob `/etc/systemd/system/hermes-gateway*.service`
|
||||
grew from one unit to three when the infrabot and socialbot gateways were added
|
||||
(2026-10-30), so the paths set changed mid-history: snapshots before 2026-10-30
|
||||
formed one group and snapshots after formed another. Each group then sat **under**
|
||||
the keep-7-daily limit *on its own*, so **nothing was ever expired and the repo
|
||||
could never shrink**. Empty grouping applies one policy across all nightly
|
||||
snapshots. `--group-by host` would also collapse today's groups, but the box has
|
||||
already migrated once and a hostname change would reintroduce the same split — no
|
||||
grouping is immune to both path-set drift and a hostname change.
|
||||
|
||||
**Current state (honest):** the repo still holds **13 snapshots** — the pre-fix
|
||||
accumulation. The script on disk carries the fix, and a `--dry-run` (2026-11-04)
|
||||
confirms it **keeps 8 and removes 5**. The next timer run (2026-11-05 04:31 UTC)
|
||||
applies it. Until it runs, treat "13 snapshots" as expected, not as the fix
|
||||
having failed.
|
||||
|
||||
### Other mechanics
|
||||
|
||||
- Weekly `restic check` on Sundays (repo metadata); full data check monthly.
|
||||
- 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
|
||||
|
||||
- Configured in the **dashboard** (*Settings → Backups*). There is **no write
|
||||
API**: `GET /api/v1/backup_sites` works, but `PUT`/`POST` on it and
|
||||
`POST /backups` all 404. Schedule and retention are dashboard-only.
|
||||
- **Two sites exist:** the live one (`s3-v4-compat`, daily 23:00, 7-day
|
||||
retention, id `03cfbdca-88fc-4ccc-97c3-7e1b58cf892d`) and an inactive
|
||||
`filesystem` site with schedule `never`. Do not be alarmed by the second one.
|
||||
- **A run reads `state=normal` even when it failed.** The failure's real error
|
||||
text is in `GET /api/v1/tasks` (task id `backup_<siteId>`, field `error.message`),
|
||||
not in the run list. `/events` needs a `?since=` range and `/system/logs` does
|
||||
not exist — a 404 there is not "no failures".
|
||||
- `/backup_sites` carries `schedule` as a 6-field cron and `retention.keepWithinSecs`.
|
||||
Check retention **before** claiming it needs changing.
|
||||
- **Quota math:** a failure whose upload pushed the retained set over the
|
||||
provider ceiling is the signature. The old box's `EntityTooLarge` failures came
|
||||
from a 4.82 GB run twice daily against the ceiling; the ceiling was raised and
|
||||
the schedule moved to once daily. Per-run size still grows (mostly registry
|
||||
image blobs) — watch the number.
|
||||
- **Two boxes on one S3 bucket interleave and prune each other's backups.** The
|
||||
old box's schedule must stay **disabled** while it is kept for rollback.
|
||||
- **Cross-check `siteId` per run:** runs on an old site id are pre-migration
|
||||
leftovers, kept `state=normal` forever and never pruned by the current site's
|
||||
retention.
|
||||
|
||||
## Restoring
|
||||
|
||||
- **Cloudron** restores apps per-app, from the **newest** box-backup entry:
|
||||
`GET /apps/:id/backups` → pick by `creationTime` → `POST /apps/:id/restore`
|
||||
with `{"backupId": ...}`. Restore apps **sequentially** (parallel restores
|
||||
exhaust disk). `repair` recreates a container but restores **no data** — a
|
||||
repaired app comes up empty.
|
||||
- Full procedure, triage and the post-restore checker: the `cloudron-ops` skill
|
||||
and `migration/cloudron-server-migration.md`.
|
||||
- **Agent host:** `restic restore latest --target /` (or a specific snapshot) with
|
||||
`RESTIC_PASSWORD` and the S3 keys in the environment, run as root.
|
||||
|
||||
## The credential that carries the backups
|
||||
|
||||
The agent-host `RESTIC_PASSWORD` and the Cloudron backup passphrase are **two
|
||||
different secrets**, both held by the GM and recorded in the token runbook's
|
||||
inventory. The Cloudron backup passphrase + S3 `secretAccessKey` are the
|
||||
chicken-and-egg pair a bare-metal rebuild needs first — they must be held off-box.
|
||||
@@ -0,0 +1,145 @@
|
||||
# Agent host access
|
||||
|
||||
The agent host (`ov-0f018e`, an Infomaniak VPS Lite instance) separates three
|
||||
levels of privilege: the bots, the steward, and the human operator.
|
||||
|
||||
## The model
|
||||
|
||||
| Account | Role | Privilege |
|
||||
|---|---|---|
|
||||
| `socialbot`, `infrabot`, `designbot`, future working-group bots | agents | own Unix user, own gateway unit, **no sudo at all** |
|
||||
| `ubuntu` | steward agent (Inferencebot) | may act inside the bot accounts and run the docs/backup service commands; **no root** |
|
||||
| `operator` | human operator | own SSH key, full `sudo` (`NOPASSWD:ALL`); root SSH login stays closed |
|
||||
|
||||
The steward is the fleet administrator, not a root user. Root belongs to a
|
||||
person: the operator signs in as `operator` with an SSH key and escalates
|
||||
deliberately with `sudo -i`.
|
||||
|
||||
### sudoers files
|
||||
|
||||
- `/etc/sudoers.d/91-bot-access`
|
||||
`ubuntu ALL=(socialbot,infrabot,designbot) NOPASSWD: ALL`
|
||||
- `/etc/sudoers.d/90-inferencebot-restricted`
|
||||
`ubuntu` may only start/stop/restart `docs-deploy-poll.service` and
|
||||
`agent-backup.service`/`.timer`, and read `docs-deploy-poll` logs.
|
||||
- `/etc/sudoers.d/90-operator`
|
||||
`operator ALL=(ALL) NOPASSWD:ALL`
|
||||
- `/etc/sudoers.d/90-<bot>-nosudo`
|
||||
`<bot> ALL=(ALL) !ALL` — each bot is denied sudo, including via its own
|
||||
account.
|
||||
|
||||
Do not re-add the old cloud-init `ubuntu ALL=(ALL) NOPASSWD:ALL` rule. The
|
||||
steward must not regain root, and the operator account is the root door.
|
||||
|
||||
### No passwords
|
||||
|
||||
- `ubuntu` and the bot accounts are password-locked (cloud image
|
||||
`lock_passwd: True`); SSH password authentication is disabled
|
||||
(`/etc/ssh/sshd_config.d/60-cloudimg-settings.conf`).
|
||||
- Access is SSH public keys only. Do not set a password on `ubuntu`, a bot, or
|
||||
`operator` as a convenience.
|
||||
- `operator`'s key is copied from `/home/ubuntu/.ssh/authorized_keys` when the
|
||||
account is created. If the operator's key rotates, update **both**
|
||||
`/home/ubuntu/.ssh/authorized_keys` and
|
||||
`/home/operator/.ssh/authorized_keys`.
|
||||
- Root SSH login is not authorized; do not add root authorized keys.
|
||||
|
||||
## Root-owned execution paths
|
||||
|
||||
- **Docs publisher.** `/usr/local/sbin/docs-poll` and `/usr/local/sbin/docs-publish`
|
||||
are root-owned; the build runs as `docsbuild` with a scrubbed environment.
|
||||
- **Nightly backup.** `agent-backup.service` runs as root with
|
||||
`ExecStart=/usr/local/sbin/agent-backup`, a root-owned copy of
|
||||
`~/.hermes/scripts/backup.sh`. The source script stays editable by `ubuntu`,
|
||||
but the unit executes the installed root-owned copy.
|
||||
`/usr/local/bin/restic` is `root:root`.
|
||||
- **Backup credentials.** `RESTIC_PASSWORD`, `RESTIC_REPOSITORY`,
|
||||
`SWB_S3_ACCESS_KEY`, `SWB_S3_SECRET_KEY` live only in root-only
|
||||
`/etc/agent-backup.env` (0600). The root script must not source
|
||||
`/home/ubuntu/.hermes/.env` and must not put `/home/ubuntu/.local/bin` on its
|
||||
`PATH`; either would make an agent-writable file a root code-execution path.
|
||||
- **Watchdog.** `check_root_trust.py` (daily cron) stays silent when healthy and
|
||||
alerts if broad sudo returns, `sudo -n true` succeeds, a root-executed binary
|
||||
is agent-owned, or a root script trusts agent files. It is silent as of
|
||||
2026-11-21.
|
||||
|
||||
Any new root-executed script that reads an agent-writable file is a root path.
|
||||
Audit it before installing it as root code.
|
||||
|
||||
## Verification
|
||||
|
||||
Run from an operator session:
|
||||
|
||||
```bash
|
||||
# steward: bot access, no root
|
||||
sudo -iu socialbot id # uid=1002
|
||||
sudo -iu infrabot id # uid=1001
|
||||
sudo -iu designbot id # uid=1003
|
||||
sudo -n true # must fail: interactive authentication required
|
||||
sudo -n /usr/bin/id # must fail
|
||||
|
||||
# operator: root door
|
||||
sudo -n true && echo root-ok # root-ok
|
||||
sudo -i
|
||||
|
||||
# root-trust watchdog: silence is the pass
|
||||
python3 ~/.hermes/scripts/check_root_trust.py
|
||||
```
|
||||
|
||||
## Recovery when root is unreachable
|
||||
|
||||
If sudo policy or the operator key is wrong, or no in-band root remains, use the
|
||||
provider's rescue environment. On Infomaniak VPS Lite it is called **Safe mode**,
|
||||
not "Rescue".
|
||||
|
||||
1. Manager → **VPS** → the server → **MANAGE** → **Restart the server (Safe
|
||||
mode)**. Services stop while it is booted.
|
||||
2. Connect to the rescue image as user `infomaniak` (temporary rescue password
|
||||
from the panel if SSH asks). The rescue image has a different host key, so
|
||||
use `-o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no` for this
|
||||
session only. Then `sudo -i`; confirm `id -u` is `0`.
|
||||
3. Identify the disks with `lsblk -f`. The rescue system is the first disk
|
||||
(root partition hostname `ik-rescue`). The cloud disk is the second disk; its
|
||||
root partition is labelled `cloudimg-rootfs`, usually `/dev/sdb1`. Mount it:
|
||||
|
||||
```bash
|
||||
mount /dev/sdb1 /mnt
|
||||
cat /mnt/etc/hostname # must print ov-0f018e
|
||||
```
|
||||
|
||||
If it prints `ik-rescue` or the file is missing, unmount and mount the
|
||||
`cloudimg-rootfs` partition instead.
|
||||
4. Run the staged recovery script, kept on the cloud disk:
|
||||
|
||||
```bash
|
||||
less /mnt/home/ubuntu/recover.sh # inspect first
|
||||
bash /mnt/home/ubuntu/recover.sh
|
||||
```
|
||||
|
||||
It backs up the current sudoers files to
|
||||
`/mnt/root/pre-recovery-YYYYMMDD/`, writes the bot-access and operator rules,
|
||||
ensures the operator user and key, closes the backup root path, and runs
|
||||
`visudo -c`. Do not unmount `/mnt` while it runs.
|
||||
5. `umount /mnt`, then **MANAGE → Restart the server (Classic mode)**.
|
||||
6. Verify with the commands above. The normal SSH host key returns after the
|
||||
classic boot.
|
||||
|
||||
A narrative handoff of the same procedure, with no credentials, is kept at
|
||||
`/home/ubuntu/recovery-context.txt` on the host.
|
||||
|
||||
### Rollback
|
||||
|
||||
- Previous sudoers files: `/root/pre-recovery-YYYYMMDD/` on the cloud disk.
|
||||
- Original cloud-init sudoers: `/root/sudoers-cloud-init.bak` (0600).
|
||||
- Provider snapshots are the outer rollback.
|
||||
- Restoring the broad cloud-init rule is **not** the intended end state; it is
|
||||
only a temporary recovery step while a narrower rule is installed.
|
||||
|
||||
## Things not to do
|
||||
|
||||
- Do not restore `ubuntu ALL=(ALL) NOPASSWD:ALL`.
|
||||
- Do not set a password on any account; keep access key-based.
|
||||
- Do not use the backup unit's agent-owned binary, `PATH`, or `.env` as a
|
||||
shortcut to root; that is the hole, not a recovery channel.
|
||||
- Do not run a root-owned unit against agent-writable files without a root-trust
|
||||
review.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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…`).
|
||||
@@ -0,0 +1,142 @@
|
||||
# Woodpecker CI (server + agent)
|
||||
|
||||
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:
|
||||
|
||||
| App | FQDN | Cloudron id | Image |
|
||||
|---|---|---|---|
|
||||
| Woodpecker **server** | `ci.inference.coop` | `4984f95e-0c0a-4af3-9ce1-4ca4f3e8483d` | `cloudron/org.woodpecker_ci.cloudronapp:202610300219490000` (store, v2.22.1 / upstream 3.20.1) |
|
||||
| Woodpecker **agent** | `ci-agent.inference.coop` | `5ac63873-cf2c-4ad9-acd6-81dc0e016c83` | `registry.inference.coop/co-op/woodpecker-agent:20261104-e070275` (**custom**) |
|
||||
|
||||
- The **server** is the stock Cloudron app. It uses the `mysql` addon for storage
|
||||
and exposes `GRPC_PORT` 9000 to the agent. Its config lives in
|
||||
`/app/data/env.sh` (`WOODPECKER_GITEA`, `WOODPECKER_ADMIN`,
|
||||
`WOODPECKER_AGENT_SECRET`, `WOODPECKER_OPEN`, …). **No env vars are set through
|
||||
the app's Cloudron env** (`env-keys` is empty) — everything is in that file.
|
||||
- The **agent** is a custom app. Its config is set as Cloudron env (names only):
|
||||
`WOODPECKER_SERVER` = `ci.inference.coop:9000`, `WOODPECKER_GRPC_SECURE=true`,
|
||||
`WOODPECKER_BACKEND=local`, `WOODPECKER_MAX_WORKFLOWS=2`,
|
||||
`WOODPECKER_AGENT_CONFIG_FILE=/app/data/agent.conf`, plus the shared
|
||||
`WOODPECKER_AGENT_SECRET`.
|
||||
|
||||
## Why the agent image is custom (and why the backend is `local`)
|
||||
|
||||
Cloudron apps have **no Docker socket**, so the default `docker` backend cannot
|
||||
run and the agent uses the **`local` backend**: each pipeline step executes as a
|
||||
shell command *inside the agent container*, and a step's `image:` field selects
|
||||
the **shell**, not a container image. Consequence: **every tool a pipeline step
|
||||
needs must be baked into the agent image**, and the Cloudron rootfs is read-only
|
||||
at run time, so nothing can install at run time.
|
||||
|
||||
The image is `FROM woodpeckerci/woodpecker-agent:v3.20.1-alpine` (the **alpine**
|
||||
variant — the default `scratch` image has no shell). It adds `bash`, `git`,
|
||||
**`git-lfs`**, `tar`, `ca-certificates`, `python3`, `node`/`npm`, the `cloudron`
|
||||
CLI, and a pinned MkDocs toolchain at `/opt/docs-venv`. It **runs as root**
|
||||
(`/app/data` on this Cloudron is root-owned, as for the other custom apps here).
|
||||
|
||||
## Building and pinning the agent image
|
||||
|
||||
- **Source repo:** `/home/ubuntu/repos/woodpecker-agent` on the agent host.
|
||||
⚠️ **This repo has no git remote and has never been pushed to Gitea** — the CI
|
||||
agent's build source exists only on the agent host. Treat that as a gap to close.
|
||||
- **Tag convention:** `<yyyymmdd>-<gitsha>` (e.g. `20261104-e070275`). Never a
|
||||
floating tag.
|
||||
- **Build:** `~/.hermes/scripts/cloudron_builder_build.sh registry.inference.coop/co-op/woodpecker-agent <tag> <dir>`
|
||||
(the script carries the registry auth triple, which is not optional).
|
||||
- **Deploy:** write the new tag into `CloudronManifest.json`'s `dockerImage`,
|
||||
commit, build `--no-cache`, then `cloudron update --app 5ac63873-…` **without**
|
||||
`--image` (the manifest's pin wins). Verify by the running image tag **and**
|
||||
something only the new build produces — never by exit code alone.
|
||||
- `publishing-requirements.txt` mirrors the docs repo's
|
||||
`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)
|
||||
|
||||
- `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.
|
||||
|
||||
## Historical state (2026-11-04): installed, agent connected, could not run jobs
|
||||
|
||||
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.
|
||||
|
||||
## Enabling a repo (known gate — cleared 2026-11-04)
|
||||
|
||||
- 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, 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).
|
||||
@@ -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.)
|
||||
@@ -508,3 +508,68 @@ access removed 2026-11-02 — retirement begun; app restored and safe in backups
|
||||
**Outstanding:** tonight 23:00 UTC first backup (verify `normal`, ~4.9 GiB); Cloudron subscription
|
||||
page check on the new dashboard; my primary model route re-heals on its own (fallback worked all
|
||||
night); old box keep powered-on/apps-stopped/backups-disabled for a few days, then decommission.
|
||||
|
||||
---
|
||||
|
||||
# POST-MIGRATION ADDENDUM — 2026-11-04
|
||||
|
||||
Recorded by the infra-docs audit. This section is current state; everything above
|
||||
is the as-it-happened record.
|
||||
|
||||
## App count: 16 → 19 (three apps added since cutover)
|
||||
|
||||
The migration restored **16 apps**. Since then the server carries **19** — the
|
||||
three new ones are the docs site, the CI server and the CI agent. See
|
||||
`app-inventory.md` for the full list. Anywhere above that says "16 apps" is the
|
||||
state at cutover, not today.
|
||||
|
||||
| New since 2026-11-02 | FQDN | Cloudron id |
|
||||
|---|---|---|
|
||||
| Docs site (Surfer) | `docs.inference.coop` | `85b7ce06-e2af-49a4-bd4f-a9c2e692e3ab` |
|
||||
| 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 cutover is COMPLETE — no hostname is served by the old 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 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.
|
||||
|
||||
## ⚠️ UNRESOLVED (operator decision): the old box is still alive and internet-exposed
|
||||
|
||||
`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
|
||||
|
||||
- **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.
|
||||
+10
-12
@@ -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
|
||||
@@ -188,12 +188,11 @@ container). The `PYTHONPATH` env survives restores (it's in app config).
|
||||
The portal and gateway run their own housekeeping via the Cloudron scheduler
|
||||
addon, declared in each app's `CloudronManifest.json` under `addons.scheduler`:
|
||||
|
||||
- **portal**: `membership_sweep` (nightly 3am, `/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,
|
||||
- **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), 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).
|
||||
@@ -281,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`)
|
||||
@@ -305,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)
|
||||
@@ -315,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 | |
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
# Provider pricing
|
||||
|
||||
What our model providers charge, and where the authoritative numbers live.
|
||||
|
||||
## The authority
|
||||
|
||||
**The gateway's own per-model costs are the authority** — they are what the
|
||||
response headers (`x-litellm-response-cost`) and member billing both read. They
|
||||
live in the LiteLLM config on the gateway's persistent volume
|
||||
(`/app/data/config.yaml`), under each model's `model_info`, as **USD per token**
|
||||
(the comments in that file quote per-1M rates). Read them live with
|
||||
`GET https://gateway.inference.coop/model/info` (master key), or read the config
|
||||
straight from the running app.
|
||||
|
||||
**The member-facing mirror** is `co-op/docs/models.md`. When a rate changes,
|
||||
update **both** the gateway config and `models.md` — the config is authoritative,
|
||||
`models.md` is the mirror.
|
||||
|
||||
A missing cost field makes a paid feature free; a stale one bills wrong; a missing
|
||||
`cache_read_input_token_cost` bills cache hits at the full input rate. All three
|
||||
have happened here.
|
||||
|
||||
## The pages
|
||||
|
||||
| File | Provider | Notes |
|
||||
|---|---|---|
|
||||
| `greenpt.md` | GreenPT | renewable energy; the default model lives here |
|
||||
| `tinfoil.md` | Tinfoil | TEE; the local-proxy architecture lives here |
|
||||
| `regolo.md` | Regolo | renewable + ZDR; includes our measured usage |
|
||||
| `decision-model.md` | GreenPT "Metis" via `/v1/systemone` | a pass-through **route**, not a chat model |
|
||||
|
||||
## The routing rule
|
||||
|
||||
Members reach models through one gateway, which fronts all providers. The
|
||||
per-request cost the gateway records is the number to trust; do not re-derive a
|
||||
price from a provider's public page (they drift, and some are login-walled).
|
||||
|
||||
## A note on currencies
|
||||
|
||||
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.
|
||||
@@ -0,0 +1,58 @@
|
||||
# The decision-model route — GreenPT "Metis" (`/v1/systemone`)
|
||||
|
||||
The gateway exposes a **decision model** — GreenPT's **Metis** (System One API) —
|
||||
as a **pass-through route**, not a chat model.
|
||||
|
||||
## What it is, and why it is a route and not a model
|
||||
|
||||
Metis is a **decision** endpoint, not a chat completion: it takes a `state` plus up
|
||||
to 32 typed questions and returns **probabilities / choices / scores**. It
|
||||
generates no text (`output_tokens` is always 0), so **it cannot be a `model_list`
|
||||
entry** — LiteLLM's chat pipeline has nothing to parse. It is therefore exposed as
|
||||
a pass-through:
|
||||
|
||||
```
|
||||
path: /v1/systemone
|
||||
target: https://api.greenpt.ai/v1/systemone
|
||||
auth: true # members call it with their normal co-op API key
|
||||
```
|
||||
|
||||
- **It is API-only and deliberately NOT a chat-picker model.** It never appears in
|
||||
the chat model list. Do not add it there.
|
||||
- **Members authenticate with their own co-op key**, never the provider key — the
|
||||
route's `Authorization` header injects the provider key server-side.
|
||||
- Hosted by GreenPT (policy-based privacy, EU, 100% renewable), same
|
||||
`GREENPT_API_KEY` the green chat models use.
|
||||
|
||||
## Pricing and the metering fix
|
||||
|
||||
- **$0.12 per 1M input tokens; output is free.**
|
||||
|
||||
Metering is **exact, from the token count GreenPT reports back**. Because Metis is
|
||||
not a `model_list` entry, it is priced through the
|
||||
`coop_passthrough_cost_per_token` map, keyed by the route path
|
||||
(`/v1/systemone: 0.00000012`). `patch_passthrough_token_cost.py` (built into the
|
||||
image) reads `usage.input_tokens` from the Metis response body at logging time and
|
||||
writes the exact figure to member spend.
|
||||
|
||||
**Why this exists — record it, it will recur:** **generic pass-through routes
|
||||
originally logged nothing.** A route that is not a `model_list` entry gets no
|
||||
automatic pricing, so its calls were metered as $0 — a paid feature silently free.
|
||||
The pass-through accounting had to be fixed so spend lands against the **calling
|
||||
member's key**. If another pass-through route is ever added, it needs the same
|
||||
treatment or it bills nothing.
|
||||
|
||||
`cost_per_request: 0.0001` on the route is now only a **fallback** — it applies if
|
||||
a response arrives without a usable token count, so a call is never silently free.
|
||||
Keep the two in sync.
|
||||
|
||||
## Access control gotcha (community edition)
|
||||
|
||||
The route is opened to any authenticated member key via
|
||||
`coop_passthrough_open_to_keys` (consumed at build time by
|
||||
`patch_passthrough_key_access.py`). **LiteLLM's own gate for `auth=true`
|
||||
pass-through routes (`allowed_passthrough_routes`) is an Enterprise-only field**,
|
||||
so on this community-edition proxy it can never be granted to member keys. The
|
||||
only alternative, `auth: false`, would expose the route publicly and forward the
|
||||
co-op's GreenPT key to anonymous callers. **Authentication is unchanged** — the
|
||||
endpoint still requires a valid key.
|
||||
@@ -0,0 +1,45 @@
|
||||
# GreenPT pricing
|
||||
|
||||
GreenPT is OpenAI-compatible, EU-hosted on **100% renewable energy**. LiteLLM
|
||||
talks to it **directly** (no TEE proxy). Billing across the gateway:
|
||||
|
||||
- `api_base`: `https://api.greenpt.ai/v1`
|
||||
- key: `GREENPT_API_KEY` (gateway app env)
|
||||
|
||||
## What we serve, and what it costs
|
||||
|
||||
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 (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, 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
|
||||
**policy-based privacy (GreenPT) vs TEE (Tinfoil)** — say so plainly rather than
|
||||
implying GreenPT is confidential computing.
|
||||
- `greenpt/glm-5.3` is the strongest **agentic** model in the green tier (1M context).
|
||||
- Note the **dotted slug** `glm-5.3-flash` on GreenPT, distinct from Tinfoil's
|
||||
`glm-5-3-flash` (hyphenated). Getting a model slug wrong is a silent 404 at call
|
||||
time.
|
||||
|
||||
## Historical
|
||||
|
||||
- **Removed 2026-10:** `green-l` / `green-r` — GreenPT now marks them "not
|
||||
recommended".
|
||||
- The config comment previously read "€0.22 in / €1.10 out" alongside the dollar
|
||||
figures — see the currency note in `README.md`; the intended FX is unverified.
|
||||
|
||||
## The fallback key
|
||||
|
||||
`GREENPT_FALLBACK_API_KEY` (agent host) is the **same value** as the gateway's
|
||||
`GREENPT_API_KEY` — verified by hash comparison. It powers the steward agent's
|
||||
direct-to-provider fallback during a gateway outage. **Rotating one without the
|
||||
other silently breaks the fallback** (a dedicated key is the cleaner end state).
|
||||
See the token runbook.
|
||||
@@ -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 |
|
||||
@@ -97,3 +99,21 @@ At these volumes the mispricing is small: apertus's input roughly 2.5x-ing on a
|
||||
**$0.82 lifetime** is about **$1/month** of exposure, and qwen's cut moves ~$0.6/month in members'
|
||||
favour. So this is **billing accuracy, not urgency** — but accuracy still matters, because the same
|
||||
numbers feed the cost headers members can now read.
|
||||
|
||||
## UPDATE 2026-11-04 — the gateway was updated; both stale sections above are now resolved
|
||||
|
||||
Checked against the live gateway config (`/app/data/config.yaml`, `model_info`):
|
||||
|
||||
- `regolo/apertus-70b` = **1.16e-06 / 3.944e-06** per token
|
||||
($1.16 / $3.94 per 1M) — the new 2026-11-01 rate. The "~70 cent/M loss while the
|
||||
gateway still bills $0.46" paragraph above no longer applies.
|
||||
- `regolo/qwen3.5-122b` = **6.96e-07 / 3.944e-06** ($0.70 / $3.94 per 1M) — the new
|
||||
rate. The "over-bills members by ~46 cents/M" paragraph no longer applies.
|
||||
- `regolo/qwen-image` now carries **`input_cost_per_pixel: 1.74e-8`** — the EUR
|
||||
figure converted at ×1.16, i.e. the "image model is priced in EUR-as-USD" open
|
||||
inconsistency above is **fixed**. It is no longer priced at the raw EUR number.
|
||||
|
||||
So the two "Until the gateway is updated" tables and the image-model section above
|
||||
are **historical**. The usage measurement ($4.38/month, ~1.1% of inference spend)
|
||||
and the subscription analysis stand. Keep this file dated-section-per-change; do
|
||||
not delete the history, it shows the reasoning.
|
||||
@@ -0,0 +1,84 @@
|
||||
# Tinfoil pricing and architecture
|
||||
|
||||
Tinfoil serves models inside **TEE-protected enclaves**. The co-op does not
|
||||
self-host it — Tinfoil is a hosted cloud service; models run in Tinfoil's TEEs.
|
||||
Tinfoil is the co-op's **architecturally-private** tier (contrast: GreenPT and
|
||||
Regolo are the renewable tier, with policy-based privacy, not TEE).
|
||||
|
||||
## The architecture — read this before touching the Tinfoil route
|
||||
|
||||
LiteLLM does **not** talk to Tinfoil's enclave directly. Every Tinfoil model in the
|
||||
gateway config points at:
|
||||
|
||||
```
|
||||
api_base: http://127.0.0.1:3301/v1
|
||||
```
|
||||
|
||||
That is a **local proxy** running **inside the gateway container**
|
||||
(`/app/data/tinfoil-proxy -b 127.0.0.1 -p 3301`). LiteLLM speaks **plaintext
|
||||
OpenAI** to the proxy; the proxy **verifies the enclave attestation and wraps the
|
||||
request/response bodies in EHBP (HPKE)** before forwarding to the Tinfoil
|
||||
enclave. The provider key is set via the environment variable `TINFOIL_API_KEY`.
|
||||
|
||||
Consequences:
|
||||
|
||||
- **The proxy is load-bearing.** If it is not running, every Tinfoil model fails;
|
||||
LiteLLM's own config still looks correct. Check the process, not just the config.
|
||||
- **`http://127.0.0.1:3301` is intentional, not a misconfiguration.** Do not
|
||||
"fix" it to a public Tinfoil URL — the encryption happens in the proxy.
|
||||
- The proxy binary lives on the persistent volume (`/app/data/tinfoil-proxy`), so
|
||||
it survives restarts; it is started by the app's `start.sh`.
|
||||
|
||||
## What we serve, and what it costs
|
||||
|
||||
Rates as recorded in the gateway config, **USD per 1M tokens** unless noted:
|
||||
|
||||
| our model | input | output | cached input |
|
||||
|---|---|---|---|
|
||||
| `tinfoil/deepseek-v4-1-flash` | $0.65 | $1.45 | $0.13 |
|
||||
| `tinfoil/gpt-oss-120b` | $0.15 | $0.60 | — |
|
||||
| `tinfoil/glm-5.3` | $1.80 | $5.75 | $0.45 |
|
||||
| `tinfoil/whisper-large-v3-turbo` (STT) | $0 / 1M | — | **$0.01 per request** |
|
||||
| `tinfoil/voxtral-tts` (TTS) | $0 / 1M | — | **$0.002 per request** |
|
||||
| `tinfoil/nomic-embed-text` (embeddings) | $0.05 | $0 | — |
|
||||
|
||||
- **`tinfoil/glm-5.3` replaced `tinfoil/glm-5-3-flash`** (Tinfoil deprecated the
|
||||
flash variant on 2026-10-09). Text-only (no vision), reasoning + tool calling.
|
||||
- **`tinfoil/deepseek-v4-1-flash` and the glm-flash variant carry an
|
||||
"Experimental: may be deprecated with minimal notice" flag from Tinfoil** —
|
||||
which is part of why the GreenPT counterpart is the default.
|
||||
|
||||
### Audio is billed per REQUEST, and needs a build-time patch
|
||||
|
||||
Tinfoil bills the audio models **per request** (its model list carries a
|
||||
`requestPrice`), not per token. Reading only the two token prices made TTS look
|
||||
free and left STT billed off an older catalog. **LiteLLM cannot price per request
|
||||
on the audio paths**, so `patch_audio_request_cost.py` (built into the image via
|
||||
the Dockerfile) makes the cost calculator honour `input_cost_per_request`.
|
||||
**Re-check that build-log line after every LiteLLM upgrade.**
|
||||
|
||||
One non-obvious load-bearing detail: for TTS, `input_cost_per_character: 0` is
|
||||
**required**. Without it the TTS cost branch raises `ValueError("cost for tts call
|
||||
is None")` and aborts the whole calculation, so the spend write is skipped and
|
||||
speech bills nothing — whatever `input_cost_per_request` says.
|
||||
|
||||
**Audio keep-alive** (the Cloudron scheduler task `audio_keepalive`, every 10 min)
|
||||
pings the Tinfoil audio models so voice mode does not pay the ~24s TEE cold-start
|
||||
after idle. It is **TTS-only by design**: the STT warm ping was disabled
|
||||
2026-10-11 because it costs $0.01/request — roughly $52/month at 6 pings/hour.
|
||||
`docs.inference.coop`-style "keep-alive economics" detail is in the script.
|
||||
|
||||
### The embedding model is operator-only
|
||||
|
||||
`tinfoil/nomic-embed-text` (768-dim) is **not** a member-facing model — it is
|
||||
scoped to the co-op's own admin team (`model_info.team_id`) for the docs-RAG, so
|
||||
member keys cannot call it. The portal also filters it out of the chat-facing
|
||||
model list by its `mode: embedding`.
|
||||
|
||||
## Fallbacks
|
||||
|
||||
The router treats `tinfoil/deepseek-v4-1-flash` as the fallback for
|
||||
`greenpt/deepseek-v4.1-flash`, and `tinfoil/gpt-oss-120b` as the fallback for
|
||||
`tinfoil/deepseek-v4-1-flash`. The timeout is deliberately generous (180s) with
|
||||
`TimeoutErrorRetries: 0` — DeepSeek generations routinely exceed 30s, and a
|
||||
timed-out generation is **already billed** by Tinfoil, so re-hitting it re-bills.
|
||||
@@ -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.
|
||||
Executable
+95
@@ -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")
|
||||
Executable
+109
@@ -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())
|
||||
Binary file not shown.
@@ -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 => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[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);
|
||||
@@ -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
|
||||
@@ -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)
|
||||
Executable
+116
@@ -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"
|
||||
Executable
+108
@@ -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"
|
||||
@@ -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()
|
||||
Reference in new issue
Block a user