Compare commits

..
Author SHA1 Message Date
archipelagoandClaude Opus 5 6ba52b2240 wip(13-01): checkpoint interrupted tracer work (assistant module + chat RPC)
Session died on a broken pipe with this work uncommitted in the executor
worktree. Committed verbatim, unverified — not a task completion. The
continuation executor may reset --soft this commit and recommit atomically
per task.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-03 13:03:10 -04:00
archipelago 15774d266f docs(13): begin phase 13 execution on isolated lane 2026-08-03 11:29:25 -04:00
89 changed files with 1149 additions and 3626 deletions
+13 -377
View File
@@ -27,216 +27,6 @@ Status key: **DONE** (committed) · **READY** (written, not yet committed/tested
- Scope note: `fips/app_ports.rs` holds the mesh allowlist; `is_peer_allowed_path` in
`server.rs` holds the peer HTTP allowlist. Neither currently authenticates app ports.
#### Research — umbrelOS (verified from their docs/source, 2026-08-03)
umbrelOS solves this **architecturally, not per-app**: the app's own port is never
published. Each app gets a sidecar `app_proxy` container that owns the published port and
forwards to the app on the internal network.
- `containers/app-proxy` is described as *"a transparent HTTP proxy to add authentication
to Umbrel apps"* — **every** HTTP request and WebSocket upgrade passes through it and
has its session token checked.
- Tokens come from a separate `app-auth` service; the proxy talks to it over a local port
(default 2000) with a shared secret (`UMBREL_AUTH_SECRET`). Two JWTs exist: an **API
token** in localStorage (`{loggedIn: true}`) for the dashboard's own API, and a
**proxy token** in an **HttpOnly cookie** (`{proxyToken: true}`) for app access. Both
HS256, 7-day expiry.
- Unauthenticated requests are redirected to the login screen.
- Per-app escape hatches, all env vars on the proxy: `PROXY_AUTH_ADD` (bool, **default
true** — so apps are protected unless opted out), `PROXY_AUTH_WHITELIST` (paths exempt,
e.g. `/public/*`), `PROXY_AUTH_BLACKLIST` (paths that must be authed, e.g. `/admin/*`).
- Known friction worth designing around: apps with their own login (Frigate, and the
`PROXY_AUTH_ADD=false` tracker issue) end up double-authenticating, and non-browser API
clients (Home Assistant hitting an app's API) break because they have no cookie. Any
gate we build needs a story for machine clients, not just browsers.
**The lesson for us:** the reason umbrel doesn't have this bug class is that there is no
unauthenticated path to bind to in the first place. Our apps publish their own ports
directly, so a gate bolted onto one transport leaves the others open — which is exactly
the shape of the `/lnd-connect-info` + `/bitcoin-rpc/` leaks. The fix likely has to move
the port binding, not just add a check.
#### Reproduced ON archi-dev-box, 2026-08-03 — baseline before the fix
No session cookie, over the Tailscale IP `100.69.68.39`:
```
port 18083 HTTP 200 LND - Archipelago
port 8334 HTTP 200
port 8175 HTTP 200 Fedimint Guardian - Archipelago
port 8336 HTTP 200 FIPS Mesh
port 8090 HTTP 200
port 7777 HTTP 200
```
`ss -tlnp` confirms these are bound `0.0.0.0`, so the same responses are served on the LAN
IP and every other host address. Re-run this exact loop after the fix: every one must
become the login page, and the ports listed as protocol exemptions (item 1b) must be the
*only* ones still answering.
#### Exposure map — how app ports are reachable TODAY (verified in source, 2026-08-03)
All four transports converge on `127.0.0.1:<app_port>`. This is the whole reason the fix
is tractable: it is **one gate, not four**.
| Transport | Path to the app | Code |
|---|---|---|
| LAN / Tailscale | container publishes the port on the host (`--network host`, so `0.0.0.0:<port>`) — reachable on *every* host IP | `scripts/container-specs.sh`, `first-boot-containers.sh` |
| FIPS mesh | daemon binds `[fips0-ULA]:<port>` and raw-TCP-forwards to `127.0.0.1:<port>` | `server.rs:1130` `app_port_v6_relay_loop` |
| FIPS firewall | `tcp dport { …APP_LAUNCH_PORTS… } accept` drop-in opens them all | `fips/config.rs:274`, `fips/app_ports.rs` |
| Tor | `HiddenServicePort 80 127.0.0.1:<local_port>` per service | `api/rpc/tor/mod.rs:243` |
#### Design decision (operator, 2026-08-03)
**Gate app UIs + bearer tokens; protocol ports exempt.** HTTP app UIs get the login gate
(app name + icon, 2FA honoured). Protocol ports (LND gRPC 10009 + REST, electrum 50002,
bitcoin p2p 8333) stay open but MUST be declared `auth: none` with a rationale in the
manifest, so the exceptions are a grep rather than a discovery — see item 1b. Per-app
long-lived bearer tokens cover machine clients that speak HTTP (Home Assistant). **Zeus
and electrum wallets keep working untouched** — that was the deciding constraint.
The gate lives in the **daemon**, not a per-app sidecar container (umbrel's `app_proxy`
model): rootless, no extra containers per app, one place to update, and it can reuse the
existing `app_port_v6_relay_loop` rather than fight it.
#### ⚠️ Trap found while designing — an nft-only gate FAILS OPEN
The obvious implementation is an nft redirect of inbound app-port traffic to the gate.
But `/etc/fips/fips.nft` is **provisioned out-of-band** and `fips/config.rs:290` treats its
absence as a no-op (`if try_exists("/etc/fips/fips.nft")`). A gate shipped as a `fips.d`
drop-in would therefore be **silently absent on every node without the hardening
baseline** — i.e. it fails open, which is exactly the failure class this item exists to
close.
Two viable shapes, both fail-closed:
- **(a) Apps bind loopback only**, daemon owns every external bind. Airtight, the true
umbrel model, but requires touching each app's own listen config (nginx.conf etc.).
Note you *cannot* half-do this: while an app holds `0.0.0.0:<port>`, the daemon cannot
bind `<lan-ip>:<port>` at all.
- **(b) Daemon owns a dedicated `archipelago-appgate` nft table** with its own
default-deny + redirect, independent of whether `fips.nft` exists, and refuses to start
/ alarms loudly if it cannot install it. Non-invasive to apps.
#### Enabler found — `PortMapping.bind` already does half of (a)
`core/container/src/manifest.rs:518``PortMapping` has a `bind` field, documented as
*"Host address to bind the publish to. Empty = all interfaces (0.0.0.0). Set `127.0.0.1`
to keep a port host-local"*. So for **bridge apps that declare `ports:`**, going
loopback-only is a **manifest edit, not app surgery**, and the daemon can then own the
external bind. That is most of the catalog.
The exception is **host-networked apps** (`security.network_policy: host``lnd-ui`,
`bitcoin-ui`, `electrs-ui`): host networking bypasses port mapping entirely, so `bind` has
no effect and `ports:` is deliberately empty. Those bind whatever their internal nginx
binds. We build those images ourselves, so the fix is a `listen 127.0.0.1:<port>;` change
in each `docker/*-ui/nginx.conf` — still no third-party surgery.
Watch the rootless trap documented at `manifest.rs:532`: a publish bound to an address the
host cannot actually bind crash-loops the whole unit (took bitcoin down fleet-wide on .228,
2026-07-09). Loopback binds are explicitly always accepted without probing, so this
direction is safe.
**Tor needs separate handling either way**: the onion connects *from* localhost, so a
redirect that exempts loopback will not catch it. `HiddenServicePort` must be repointed at
the gate, and since that mapping loses the original destination port, each app needs its
own gate port (or an HTTP-level Host mapping).
#### Primitives that already exist — do NOT build these from scratch
The gate is mostly assembly, not invention:
| Need | Existing API |
|---|---|
| Read the session cookie off a request | `session::extract_session_cookie(&HeaderMap) -> Option<String>` (`session.rs:479`) |
| Validate a session | `SessionStore::validate(&token) -> bool` (`session.rs:194`) |
| **Honour 2FA** | Already modelled: `create_pending(totp_secret)` (`:176`) + `upgrade_to_full` (`:247`). A session still pending 2FA **fails `validate()`**, so the gate gets 2FA for free by calling `validate` — no TOTP code in the gate itself |
| **Machine-client bearer tokens** | `device_tokens::create/verify` (`device_tokens.rs:63/:90`) — long-lived, minted from an authenticated session, only the SHA-256 persisted, plaintext returned once. Built for the companion pairing QR; needs **per-app scoping** added for this use |
| Rate limiting | `device_tokens` verification already rides `auth.login`'s limiter |
So the new code is: the listener/redirect, the app-identification step (which app is this port?),
the login page render (app name + icon), and per-app scoping on `device_tokens`.
#### Research — StartOS: **DROPPED** (operator, 2026-08-03)
"don't need the startOS research we decided on a approach already." The umbrelOS read
plus the design decision above settled it; no further prior-art work.
### 1b. Manifest declaration of unauthenticated ports — **DONE** (`0c4826f8`, pushed)
`PortMapping` grew `auth` (`session` | `none`, defaulting to **`session`**) and
`auth_rationale`. The default is the protected one, so exposure is now something a
manifest has to ask for rather than something it gets by saying nothing.
Validation is two-sided: `auth: none` without a rationale is rejected, **and** a
rationale without `auth: none` is rejected — that combination means the author wrote an
exemption and did not get one, and shipping it silently would leave them believing
otherwise.
**17 ports across 12 apps are exempt**, each with its reason: Lightning p2p (BOLT-8
noise), LND gRPC 10009 / REST 18080 and CLN gRPC 9835 (macaroon / mutual TLS — this is
what keeps Zeus and remote wallets working), Bitcoin p2p 8333, electrum 50001, the three
Wyoming voice ports, git-over-SSH 2222, and the UDP discovery protocols (mDNS 5353,
SSDP 1900, STUN 3478). **The other 39 published ports now default to gated.**
Bitcoin RPC 8332 is deliberately *not* exempted: it is already `bind: 127.0.0.1`, so the
gate never sees it, and claiming an exemption it does not need would put a meaningless
line in the audit list. If that bind is ever dropped it fails closed.
Two corpus tests pin this: every shipped manifest must parse, and the exempt set is
frozen at 17 so the node's unauthenticated surface cannot grow by accident.
### 1c. The gate itself — **IN PROGRESS**
`core/archipelago/src/appgate/``identity.rs` (port → app id/name/icon, gated vs
exempt, re-read from manifests so a catalog refresh applies without a restart),
`mod.rs` (authorize + login page + TOTP step + reverse proxy), `listener.rs` (binds the
external addresses, sweeps every 60s).
Design points worth not re-deriving:
- **It invents no auth policy.** `verify_password`, `totp::decrypt_secret`,
`verify_code` + used-step replay protection, `SessionStore::create/create_pending/
upgrade_to_full`, and the *same* `LoginRateLimiter` instance as the JSON-RPC path.
Only the transport differs (HTML form vs JSON-RPC), because a browser being redirected
to an app cannot speak JSON-RPC. Sharing the limiter matters: otherwise an attacker
gets a fresh budget of password guesses by moving to an app port.
- **2FA is free.** A session still pending its TOTP step fails `validate()`, so the gate
rejects it without knowing anything about second factors.
- **Cookies ignore port.** The session cookie is host-only with no `Domain`, so one
sign-in covers the dashboard and every app port on the same host. The corollary is
that an app reached on a *different* host — its own onion — is a separate sign-in.
- **401, not a redirect.** A redirect to a login page is indistinguishable from the app
itself redirecting, and machine clients would follow it and parse HTML as their API
response.
- **The gate strips `Cookie` and `Authorization` before proxying.** The app has no use
for the node session and must never be in a position to log or forward it.
- **Machine clients**: `device_tokens` grew `apps: Option<Vec<String>>` and
`verify_for_app`. `None` = node-wide (what every existing companion token is —
migrating them by guessing a scope would silently revoke access nobody asked to
revoke); `Some(list)` restricts to those apps. An empty list is rejected rather than
minted, since it would read as "unrestricted" while authorising nothing.
#### ⚠️ The ordering constraint that shapes the rollout
A published container port is bound `0.0.0.0:<port>`, which claims **every** host
address. While the app holds that, the gate **cannot** bind `<lan-ip>:<port>` at all.
So the gate can only stand in front of an app whose publish has been pinned to loopback
(`bind: 127.0.0.1`) and whose container has been recreated. Gate-first is not possible;
all-apps-at-once would recreate every container on the node simultaneously.
Therefore the rollout is **per app**, and the gate is built to be honest about being
partially deployed: a port it cannot claim is logged at **warn** every sweep and recorded
in `GateStatus::unprotected`. The failure mode this exists to prevent is a gate that
binds nothing, logs at debug, and reports success while every app stays exactly as open
as before — worse than no gate, because it stops anyone looking. (Same reasoning that
killed the nft drop-in: `/etc/fips/fips.nft` is provisioned out-of-band and its absence
is a silent no-op.)
**Still open on this item:** pin the 39 gated ports to loopback app-by-app, repoint
`HiddenServicePort` at the gate (Tor connects *from* loopback, so a loopback-exempt
redirect will not catch it, and the mapping loses the original destination port), gate
the FIPS relay path, surface `GateStatus` in the UI, and verify on a real node.
### 2. Filebrowser ships an insecure default login — **OPEN**
- Change the default credential **without breaking the dashboard's Cloud view**, which
authenticates to filebrowser on the user's behalf.
@@ -261,44 +51,23 @@ Two independent fail-open paths granted `Trusted` without any operator decision:
- Added `FederatedNode.trust_source` (`invite` | `uninvited-join` | `transitive-merge` |
`manual`, `None` = pre-existing/unknown) so existing grants are **auditable**. Per
operator decision: existing peers are **left alone, not auto-demoted**.
- `trust_source` is now **surfaced** in `federation.list-nodes` (as an explicit `null`
when unknown, not omitted — "recorded before this was tracked" is the population that
needs review, so the UI must be able to tell it apart from a field it didn't read) and
rendered under the trust dropdown in the node detail modal as "Granted via:".
- **Still to do:** surface `trust_source` in `federation.list-nodes` + the UI so the
operator can actually review the `None`/`uninvited-join` population.
### 3b. Granting Trusted must require the node password — **DONE** (uncommitted at time of writing)
### 3b. Granting Trusted must require the node password — **OPEN**
> "to make someone trusted must require the node password to generate the code or change
> in the modal dropdown when you click a node" — operator, 2026-08-03
Re-authentication on privilege escalation. Both entry points are covered:
Re-authentication on privilege escalation. Two entry points, both must be covered:
- **Minting a Trusted invite** (`federation.invite`) — gated on the **resolved** level,
which matters because "Link Your Nodes" sends no `trust_level` at all and falls through
to the `Trusted` default. The invite is a bearer grant of Trusted to whoever redeems
it, so minting it *is* the escalation. Observer invites are untouched.
- **Changing a node's level in the UI dropdown** (`federation.set-trust`) — gated only
when the peer is **not already** Trusted, so the dropdown re-emitting its own value
doesn't demand a password for a no-op.
- **Minting a Trusted invite** (`federation.invite` with `trust_level: "trusted"`) —
"Link Your Nodes" mints Trusted today with no re-auth.
- **Changing a node's level in the UI dropdown** (`federation.set-trust-level` /
`handlers.rs:342`) — promoting Observer → Trusted.
Demotion is NOT gated: making something less privileged must never be harder than leaving
it, or the safe action becomes the inconvenient one. The operator path stamps
`TrustSource::Manual`; `set_trust_level` grew an `Option<TrustSource>` so automatic
adjustments (the discovery-handshake demotion safety net) pass `None` and leave the
recorded provenance alone rather than laundering an `uninvited-join` peer into looking
operator-approved.
Wiring: the backend is the sole authority on what counts as an escalation — it returns a
`PASSWORD_REQUIRED:` prefixed error, and the UI prompts and retries only on that. The
frontend never pre-judges, so the rule lives in exactly one place.
`TrustPasswordModal.vue` (modelled on `RotateDidModal.vue`) serves both flows.
`NodeDetailModal`'s select now snaps back to the node's real level on change, because a
cancelled or failed promotion would otherwise leave the dropdown displaying a level the
node never accepted.
**Follow-up, deliberately not done here:** `federation.join` also grants Trusted (when
redeeming someone else's Trusted invite) with no re-auth. It is an explicit operator
paste rather than a UI toggle, and was outside the two entry points specified — but it is
the third way a node reaches Trusted and should be reviewed.
Demotion must NOT require the password: making something less privileged should never be
harder than leaving it. Grant `TrustSource::Manual` on the operator path so the audit
trail distinguishes it from the capped automatic ones.
---
@@ -335,77 +104,8 @@ the third way a node reaches Trusted and should be reviewed.
Known groundwork: the signed catalog (`releases/app-catalog.json`, `sign-catalog.sh`),
catalog→manifest runtime reload, `package.update` RPC, `check-app-catalog-drift.py`,
and `scripts/image-versions.sh` pinning.
#### What already exists (verified in source, 2026-08-03) — the operator was right
The whole update *pipeline* is built and is already independent of OTA:
- `package.check-updates` (`api/rpc/package/update.rs:180`) refreshes the signed catalog
and hot-reloads manifests when it changed — no daemon restart, no OTA involved.
- `package.update` (`spawn_package_update`), `package.versions`, `package.set-config`
version pinning, and `execute_update` (stop → pull → remove → recreate → verify).
- Version awareness: `app_catalog::catalog_versions(app_id)` vs `installed_version()`
(`api/rpc/package/set_config.rs:46`).
- Frontend: `AppCard.vue` already renders an Update button off `pkg['available-update']`
(`:48`, `:128`) and emits `update`.
#### What is actually MISSING (this is the real scope of item 6)
1. **The UI-vs-app-vs-both distinction does not exist.** `available-update` is a single
version string — nothing classifies whether the change is the app image, its `*-ui`
image, or both. This is the core of the operator's ask ("a different graphic for just
ui, app, or both together") and needs a backend change, not just an icon.
⚠️ Compounding factor: per `reference_app_ui_delivery_model`, `*-ui` apps are **not in
the signed catalog** at all — so "is there a UI update" cannot be answered from the
catalog today. That gap has to be closed first or the UI half is unanswerable.
2. **The modal** (Update now / Cancel) — the card currently updates on click, no confirm.
3. **The detail-page affordance** — same treatment as the card.
4. **Button copy**: "See update" rather than "Update".
### 6b. Multiversion for ALL apps + upstream release discovery — **OPEN** (operator, 2026-08-03)
> "we also need a way to provide multiversion support for all apps and it automatically
> pulls the latest versions from the source app repository, safely, and the user can
> choose to update so we aren't always updating manually"
#### Verified 2026-08-03: the schema and runtime already exist
This is much less work than it sounds, because the multiversion machinery built for
Bitcoin generalises as data rather than code:
- `releases/app-catalog.json` entries already support a `versions[]` array of
`{version, image, default?, deprecated?}`.
- Runtime is complete: `catalog_versions(app_id)`, `catalog_default_version`,
`catalog_image_for_version`, `package.versions`, version pinning through
`package.set-config`, and `available_update_for_app` falling back to the
`image-versions.sh` baseline pin.
**It is populated for 2 of 66 apps**`bitcoin-core` (9 versions) and `bitcoin-knots`
(5). Every other app carries a single `version`. So "multiversion for all apps" is
primarily a **catalog-generation and image-mirroring job**, not new runtime plumbing.
#### What has to be built
1. **Populate `versions[]` fleet-wide.** Extend `scripts/generate-app-catalog.py` to emit
a version list per app instead of a single pin. Needs a per-app policy for how many
historical versions to carry and which is `default` (Bitcoin's list shows the shape,
including `deprecated: true` for old-but-installable).
2. **Mirror the images.** A version in the catalog that is not in our registry is a
broken promise — `package.update` would pull and fail. Use the existing skopeo path
(`feedback_skopeo_source_selection`: prefer `.160`, concurrency ≤ 6).
3. **An upstream release-watcher.** 48 manifests already carry a `repo:` URL under
`metadata`, so there is something to poll (GitHub releases / registry tags). It runs
**off-node**, as part of catalog generation.
4. **Keep the signed catalog as the trust boundary.** This is the whole of "safely":
the watcher **proposes** versions, the offline signing ceremony **admits** them, and
nodes only ever install what the signed catalog carries. A node must never pull
straight from an upstream repo — that would put an unsigned third party inside the
supply chain, which is exactly what the signed-registry model exists to prevent.
5. **The user chooses.** Discovery must never auto-apply. `package.check-updates` already
refreshes and hot-reloads without touching the running containers, so "a new version
exists" and "install it" stay separate — which is also what item 6's modal is for.
**Sequencing note:** 6b's step 1 and item 6's UI-vs-app classification want the same
thing — `*-ui` images represented in the catalog. Doing that once unblocks both.
- Needs: registry-version awareness per app, a diff of what changed (UI vs app vs both),
the modal + detail-page affordance, and distinct iconography for the three cases.
---
@@ -443,70 +143,6 @@ below is dead on every path. Pre-existing; spotted in the v1.7.120 build warning
---
## STATUS 2026-08-04 — what shipped in 1.7.121 and what did not
### Shipped (committed + pushed)
| Item | Commit | Verified |
|---|---|---|
| 3. Federation trust escalation | `c0cfc72a` | 42/42 federation tests |
| 3b. Trusted requires node password | `24ce8b39` | 44/44 + 79/79 + vue-tsc |
| 4. lnd-ui OTA pin + host networking | `5088aef5` | — |
| 1b. Manifest `auth:` declarations | `0c4826f8` | 73/73, all 56 manifests parse |
| 1c. App gate (engine + audit) | `0de67ca6` | 23/23 appgate |
| Dashboard backdrop-filter seam | `63d0183d` | 3/3, **live on archi-dev-box** |
| 7. Release refuses unsigned manifest | `cc9e1958` | dry-run: signed/stripped/wrong-signer |
| Gate safety model (`Option<PortAuth>`) | `ab2c8b6e` | 75/75 incl. LND wallet-port case |
| Companion rebuild-loop | `719446c0` | podman behaviour proven first |
| 5. Federated peers messageable | `edc9a172` | predicate pinned across device types |
### The two gate incidents — read before touching the gate again
Both were ONE mistake: a safety decision read an ABSENT manifest field as a
value. A node's installed manifests always lag the binary, so "absent" is the
normal state, and the daemon acted on instructions no manifest ever gave.
1. Gating any `session` port regardless of `bind` **published Bitcoin's
loopback-only RPC 8332 on the LAN/Tailscale/IPv6** within seconds of deploy.
2. The `bind`-keyed replacement looked safe (it protected `bind: 127.0.0.1`)
but LND's gRPC 10009 / REST 18080 carry an EMPTY bind — one container
recreate from pinning them to loopback and **breaking Zeus and every remote
wallet**.
Now structural: `auth_policy()` classifies (undeclared → reported as
unprotected, always safe), `auth_is_declared()` gates action (undeclared →
never acted on). **Silence is not consent.**
### Proven on the node, empirically, not by reasoning
- Gate challenge → login → proxy works end to end over LAN and Tailscale.
- **Daemon-side publish rewriting was removed.** Publishes are built in several
places (`podman_client`, `package::install`, `stacks`); patching one covered
one — the strfry recreate went through another and the pin never fired.
- **Disk manifest edits do not apply to catalog-covered apps.** Even
`bind: 127.0.0.1` written into the node's strfry manifest was overridden by
the signed catalog. The catalog re-sign is REQUIRED; there is no shortcut.
- A loopback-bound host port is **unreachable** from a pasta container, so
loopback-pinning the Wyoming ports would break Home Assistant voice.
### Open for 1.7.122
1. **Catalog re-sign**`bind: 127.0.0.1` + `auth: session` on the ~39 gated
UI ports. This is what turns the gate from auditing into enforcing. Nothing
in code can substitute for it.
2. **Release-root rotation** — branch `rotate-release-root`, key
`did:key:z6Mkfu5LT…DLWT` / `1578adcc…4418`, validated as a real curve point.
**Sign the rotation release with the OLD key**; only the release after it
uses the new one. Re-sign the catalog too.
3. **Wyoming voice ports** (10200/10300/10400) — unauthenticated, and by the
operator's policy they should not be. Correct fix is co-locating Home
Assistant with the pine services on one container network so nothing is
published; needs a node running both.
4. **Item 2** filebrowser default login. **Items 6/6b** app updates +
multiversion (`versions[]` already exists, populated for 2 of 66 apps).
5. **`cargo-test-weekly` times out** at its 1500s cap on a loaded box — raise
the cap or split the stage; it is not a code failure.
## RESUME HERE — next session
**Landed this session (both pushed):**
+10 -10
View File
@@ -2,13 +2,13 @@
gsd_state_version: 1.0
milestone: v1.8.0
milestone_name: milestone
current_phase: 09
current_phase_name: BotFights Platform Upgrade
current_phase: 13
current_phase_name: aiui-functional-conversational-node-control-and-content-surf
status: executing
stopped_at: v1.7.120-alpha SHIPPED; 1.7.121 queue open — see .planning/RELEASE-1.7.121-TASKS.md (12 items, RESUME HERE section at the end)
last_updated: "2026-08-03T15:15:58.798Z"
last_activity: 2026-07-31
last_activity_desc: Phase 02 complete, transitioned to Phase 09
last_updated: "2026-08-03T15:28:57.184Z"
last_activity: 2026-08-03
last_activity_desc: Phase 13 execution started
progress:
total_phases: 13
completed_phases: 2
@@ -24,14 +24,14 @@ progress:
See: .planning/PROJECT.md (updated 2026-07-29)
**Core value:** A third-party developer can publish an app via the signed/decentralized registry and a user can install it on their node — manifest-driven, rootless, secure, robust.
**Current focus:** Phase 02 — ui-performance
**Current focus:** Phase 13aiui-functional-conversational-node-control-and-content-surf
## Current Position
Phase: 09 — BotFights Platform Upgrade
Plan: Not started
Status: Ready to execute
Last activity: 2026-07-31 — Phase 02 complete, transitioned to Phase 09
Phase: 13 (aiui-functional-conversational-node-control-and-content-surf) — EXECUTING
Plan: 1 of 15
Status: Executing Phase 13
Last activity: 2026-08-03 — Phase 13 execution started
Progress: [█████░░░░░] 54%
-11
View File
@@ -1,16 +1,5 @@
# Changelog
## v1.7.121-alpha (2026-08-04)
- **Making another node "Trusted" now asks for your node password.** Trust was being handed out by machines rather than by you: any node able to reach yours could join and mark itself Trusted, because the check proved only that the caller owned the key it had just presented — never that you had approved it. Trust also spread on its own, since every peer a Trusted node advertised was added as Trusted too, so one grant quietly propagated across the whole federation. Uninvited joins are now capped at Observer, advertised peers arrive as Observers, and raising anyone to Trusted — whether by generating an invite or by changing the dropdown on a node — requires your password. Lowering trust deliberately does not, because the safe action must never be the inconvenient one. Existing peers are left exactly as they are rather than silently demoted, and each one now records how its trust was granted so you can review them.
- **Nodes you have peered with can be messaged straight away.** Peering was not enough: you also had to be within LoRa radio range of the other node once before chat would work. The node picked how to send a message based on which radio was plugged in, and only one of those paths knew how to reach a peer over the mesh's internet transports — so on a node with a different radio, or no radio at all, messaging a peer you had just federated with simply failed until a radio contact happened to appear. Peered nodes are reachable without radio by definition, so that choice no longer depends on the hardware. Radio is still preferred when the other node is actually in range and the message fits.
- The dashboard no longer flickers a vertical line across its cards. A rendering seam appeared at random while moving the mouse, because the two large cards used a background-blur effect that this system already disables everywhere else on the dashboard — that browser mis-draws it inside the dashboard's animated container, and these two cards had been missed when the workaround was written. Diagnosed from a single screenshot rather than by trying to reproduce it.
- The Lightning screen will actually update from now on. Its image was set to "latest", and the container system will not re-fetch a label it already holds, so nodes kept the same Lightning screen forever no matter how many updates shipped. A separate copy of the same setting used only by brand-new installs also described the screen incorrectly, so fresh installs got a screen that never answered.
- Apps that provide their own screens stop rebuilding themselves in a loop. On this system's own node one of them rebuilt every thirty-five seconds indefinitely, burning processor time and restarting the app each round. The node decided a rebuild was needed by comparing file dates against the image's creation date, but a rebuild that changes nothing reuses the existing image and leaves that date untouched — so the condition that triggered the rebuild was still true afterwards, forever. Nodes taking this update repair themselves the first time they check.
- Groundwork you can see but that does not change access yet: the node can now tell you which of its app ports answer without a login, and every port that is deliberately open — Bitcoin's peer connections for syncing the chain, Lightning's wallet connections, the Electrum wallet protocol — now has to state in writing why it is safe, so the list of exceptions is something you can read rather than something you have to discover. The login gate that will sit in front of the rest is built and proven working end to end on a real node, but it is not yet closing any ports; that arrives with the signed app catalog that tells each app to hand its address over.
- Releases can no longer ship an unsigned update file. Signing was skippable, and when it was skipped the release was still committed and tagged — producing an update that every node correctly refuses to install. It had been caught by hand every cycle; now the release simply stops.
- Known gaps, disclosed rather than buried: the 5x real-node lifecycle gate was not run for this release. App ports other than the deliberate exceptions above are still reachable without a login — the gate reports them, and closing them needs the next signed catalog. Three voice-assistant ports are open without authentication and should not be; the correct fix puts them on a private network with the assistant instead, which needs testing on a node that runs both. Two nodes on the fleet still share SSH host keys (detection shipped, rotation remains a deliberate operator decision).
## v1.7.120-alpha (2026-08-02)
- **Security, and the reason to take this update: two ports on your node handed anyone who could reach them complete control of your money, with no password.** The Lightning app's port answered a plain web request with the LND admin macaroon, the TLS certificate and the node's onion address — everything needed to drain the wallet remotely, and the onion meant an attacker kept that ability even after losing access to your network. The Bitcoin app's port reached Bitcoin Core's control interface using credentials the node itself supplied on the caller's behalf, with a wallet loaded. Anything on your home network, your Tailscale network or the mesh could use either one. Both now require you to be logged in. If your node has been reachable by anyone you do not fully trust, treat the Lightning macaroon and the Bitcoin RPC password as known to them.
-1
View File
@@ -28,7 +28,6 @@ app:
container: 80
protocol: tcp
bind: 127.0.0.1 # Only accessible via nginx proxy, not externally
auth: local
health_check:
type: http
-2
View File
@@ -26,8 +26,6 @@ app:
- host: 4080
container: 8080
protocol: tcp
bind: 127.0.0.1
auth: gated
environment:
- FRONTEND_HTTP_PORT=8080
-2
View File
@@ -33,8 +33,6 @@ app:
- host: 32838
container: 32838
protocol: tcp
bind: 127.0.0.1
auth: local
volumes:
- type: bind
-2
View File
@@ -51,8 +51,6 @@ app:
- host: 3535
container: 3535
protocol: tcp
bind: 127.0.0.1
auth: local
volumes:
# Holds the wallet DB, mnemonic and auth token. ARK funds are recoverable
-4
View File
@@ -85,13 +85,9 @@ app:
container: 8332
protocol: tcp
bind: 127.0.0.1
auth: local
- host: 8333
container: 8333
protocol: tcp
auth: none
auth_rationale: >-
Bitcoin p2p gossip. Peers are anonymous by design and speak the Bitcoin wire protocol, not HTTP.
volumes:
- type: bind
-4
View File
@@ -85,13 +85,9 @@ app:
container: 8332
protocol: tcp
bind: 127.0.0.1
auth: local
- host: 8333
container: 8333
protocol: tcp
auth: none
auth_rationale: >-
Bitcoin p2p gossip. Peers are anonymous by design and speak the Bitcoin wire protocol, not HTTP.
volumes:
- type: bind
-2
View File
@@ -45,8 +45,6 @@ app:
- host: 23000
container: 49392
protocol: tcp
bind: 127.0.0.1
auth: gated
volumes:
- type: bind
-6
View File
@@ -31,15 +31,9 @@ app:
- host: 9736
container: 9735
protocol: tcp # P2P (using 9736 to avoid conflict with LND)
auth: none
auth_rationale: >-
Lightning p2p. The BOLT-8 noise handshake authenticates and encrypts the channel itself.
- host: 9835
container: 9835
protocol: tcp # gRPC
auth: none
auth_rationale: >-
Core Lightning gRPC, authenticated by mutual TLS client certificates.
volumes:
- type: bind
-2
View File
@@ -30,8 +30,6 @@ app:
- host: 8088
container: 8080
protocol: tcp # Web UI
bind: 127.0.0.1
auth: gated
volumes:
- type: bind
-3
View File
@@ -45,9 +45,6 @@ app:
- host: 50001
container: 50001
protocol: tcp
auth: none
auth_rationale: >-
Electrum wire protocol over TCP. Electrum wallets speak it directly and cannot hold a session cookie.
volumes:
- type: bind
-2
View File
@@ -66,8 +66,6 @@ app:
- host: 8178
container: 8080
protocol: tcp
bind: 127.0.0.1
auth: local
volumes:
# Same dir the first-boot bundled path uses + where the wallet bridge reads
-2
View File
@@ -58,8 +58,6 @@ app:
- host: 8177
container: 8175
protocol: tcp
bind: 127.0.0.1
auth: local
volumes:
- type: bind
-2
View File
@@ -27,8 +27,6 @@ app:
- host: 8083
container: 80
protocol: tcp
bind: 127.0.0.1
auth: gated
volumes:
- type: bind
-5
View File
@@ -26,14 +26,9 @@ app:
- host: 3001
container: 3000
protocol: tcp
bind: 127.0.0.1
auth: gated
- host: 2222
container: 22
protocol: tcp
auth: none
auth_rationale: >-
Git over SSH, authenticated by the user's own SSH keypair. Not HTTP, so the gate cannot serve a login page here.
volumes:
- type: bind
-2
View File
@@ -31,8 +31,6 @@ app:
- host: 3000
container: 3000
protocol: tcp # Web UI
bind: 127.0.0.1
auth: gated
volumes:
- type: bind
-2
View File
@@ -30,8 +30,6 @@ app:
- host: 8123
container: 8123
protocol: tcp # Web UI
bind: 127.0.0.1
auth: gated
volumes:
- type: bind
-2
View File
@@ -44,8 +44,6 @@ app:
- host: 2283
container: 2283
protocol: tcp
bind: 127.0.0.1
auth: gated
volumes:
- type: bind
-2
View File
@@ -38,8 +38,6 @@ app:
- host: 7778
container: 7777
protocol: tcp # Web UI. Port 7777 on the host is reserved for the Nostr relay.
bind: 127.0.0.1
auth: gated
# Writable scratch the baked nginx needs; matches the legacy installer's
# --tmpfs /run + /var/cache/nginx.
-2
View File
@@ -25,8 +25,6 @@ app:
- host: 8096
container: 8096
protocol: tcp
bind: 127.0.0.1
auth: gated
volumes:
- type: bind
-6
View File
@@ -32,15 +32,9 @@ app:
- host: 9738
container: 9735
protocol: tcp # P2P
auth: none
auth_rationale: >-
Lightning p2p. The BOLT-8 noise handshake authenticates and encrypts the channel itself.
- host: 10010
container: 10009
protocol: tcp # gRPC
auth: none
auth_rationale: >-
LND gRPC, authenticated by macaroon over TLS. Remote wallets depend on reaching this directly.
- host: 8091
container: 8080
protocol: tcp # REST/Web UI
-9
View File
@@ -38,21 +38,12 @@ app:
- host: 9735
container: 9735
protocol: tcp
auth: none
auth_rationale: >-
Lightning p2p. The BOLT-8 noise handshake authenticates and encrypts the channel itself.
- host: 10009
container: 10009
protocol: tcp
auth: none
auth_rationale: >-
LND gRPC, authenticated by macaroon over TLS. Zeus and other remote wallets depend on reaching this directly.
- host: 18080
container: 8080
protocol: tcp
auth: none
auth_rationale: >-
LND REST, authenticated by macaroon over TLS. A browser login page would break Zeus and every non-browser wallet client.
volumes:
- type: bind
-2
View File
@@ -42,8 +42,6 @@ app:
- host: 8999
container: 8999
protocol: tcp
bind: 127.0.0.1
auth: local
volumes:
- type: bind
-2
View File
@@ -33,8 +33,6 @@ app:
- host: 4080
container: 8080 # mempool-frontend nginx listens on 8080 (FRONTEND_HTTP_PORT=8080)
protocol: tcp # Web UI
bind: 127.0.0.1
auth: gated
volumes:
- type: bind
-2
View File
@@ -30,8 +30,6 @@ app:
- host: 8089
container: 8080
protocol: tcp # Web UI
bind: 127.0.0.1
auth: gated
volumes:
- type: bind
-3
View File
@@ -51,9 +51,6 @@ app:
- host: 3478
container: 3478
protocol: udp # STUN — must be UDP; tcp here breaks relay discovery
auth: none
auth_rationale: >-
STUN over UDP for NAT traversal; it must answer unauthenticated probes to do its job at all.
volumes:
- type: bind
-2
View File
@@ -25,8 +25,6 @@ app:
- host: 8085
container: 80
protocol: tcp
bind: 127.0.0.1
auth: gated
volumes:
- type: bind
-2
View File
@@ -31,8 +31,6 @@ app:
- host: 18081
container: 8080
protocol: tcp # HTTP/WebSocket
bind: 127.0.0.1
auth: gated
volumes:
- type: bind
-2
View File
@@ -24,8 +24,6 @@ app:
- host: 2342
container: 2342
protocol: tcp
bind: 127.0.0.1
auth: gated
volumes:
- type: bind
-3
View File
@@ -40,9 +40,6 @@ app:
- host: 10400
container: 10400
protocol: tcp
auth: none
auth_rationale: >-
Wyoming voice protocol, a binary local-only stream consumed by Home Assistant; not HTTP and not browser-reachable.
volumes:
- type: bind
-3
View File
@@ -40,9 +40,6 @@ app:
- host: 10200
container: 10200
protocol: tcp
auth: none
auth_rationale: >-
Wyoming voice protocol, a binary local-only stream consumed by Home Assistant; not HTTP and not browser-reachable.
volumes:
- type: bind
-3
View File
@@ -48,9 +48,6 @@ app:
- host: 10300
container: 10300
protocol: tcp
auth: none
auth_rationale: >-
Wyoming voice protocol, a binary local-only stream consumed by Home Assistant; not HTTP and not browser-reachable.
volumes:
- type: bind
-2
View File
@@ -27,8 +27,6 @@ app:
- host: 9000
container: 9000
protocol: tcp
bind: 127.0.0.1
auth: gated
volumes:
- type: bind
-6
View File
@@ -33,15 +33,9 @@ app:
- host: 5353
container: 5353
protocol: udp # mDNS/Bonjour
auth: none
auth_rationale: >-
mDNS is UDP multicast service discovery; gating it would break .local name resolution for every device on the LAN.
- host: 1900
container: 1900
protocol: udp # SSDP
auth: none
auth_rationale: >-
SSDP/UPnP discovery is UDP multicast — there is no HTTP request to gate and no client that could hold a session.
volumes:
- type: bind
-2
View File
@@ -29,8 +29,6 @@ app:
- host: 8888
container: 8080
protocol: tcp # Web UI
bind: 127.0.0.1
auth: gated
volumes:
- type: bind
-2
View File
@@ -29,8 +29,6 @@ app:
- host: 8090
container: 7777
protocol: tcp # HTTP/WebSocket (strfry listens on 7777)
bind: 127.0.0.1
auth: gated
volumes:
- type: bind
-2
View File
@@ -26,8 +26,6 @@ app:
- host: 3002
container: 3001
protocol: tcp
bind: 127.0.0.1
auth: gated
volumes:
- type: bind
-2
View File
@@ -25,8 +25,6 @@ app:
- host: 8082
container: 80
protocol: tcp
bind: 127.0.0.1
auth: gated
volumes:
- type: bind
+1 -1
View File
@@ -104,7 +104,7 @@ dependencies = [
[[package]]
name = "archipelago"
version = "1.7.121-alpha"
version = "1.7.120-alpha"
dependencies = [
"anyhow",
"archipelago-container",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "archipelago"
version = "1.7.121-alpha"
version = "1.7.120-alpha"
edition = "2021"
description = "Archipelago Bitcoin Node OS - Native backend"
authors = ["Archipelago Team"]
-59
View File
@@ -1,59 +0,0 @@
//! `security.app-gate-status` — what the app gate is actually enforcing.
//!
//! The gate rolls out per app (an app must be pinned to loopback before the
//! gate can claim its port — see `appgate::listener`), so for a while every
//! node is partially protected. "Partially" is only safe if it is *visible*:
//! this is the RPC that lets the UI say which app ports are still reachable
//! without a credential, instead of the operator having to port-scan their
//! own node to find out.
use anyhow::Result;
use super::RpcHandler;
impl RpcHandler {
pub(in crate::api::rpc) async fn handle_app_gate_status(&self) -> Result<serde_json::Value> {
let status = crate::appgate::listener::shared_status();
let status = status.read().await.clone();
let port_map = self.app_gate.port_map().await;
// Exemptions are reported alongside, and with their manifest
// rationale, because "which ports are open and why" is the actual
// question — a list of unprotected ports without the deliberate ones
// next to it invites someone to "fix" LND's gRPC port and break every
// remote wallet.
let exempt: Vec<serde_json::Value> = port_map
.exempt_ports()
.iter()
.map(|e| {
serde_json::json!({
"port": e.port,
"app_id": e.app_id,
"protocol": e.protocol,
"rationale": e.rationale,
})
})
.collect();
let gated: Vec<serde_json::Value> = port_map
.gated_ports()
.map(|g| {
serde_json::json!({
"port": g.port,
"app_id": g.app_id,
"app_name": g.app_name,
})
})
.collect();
Ok(serde_json::json!({
// The headline. False means this node still has app ports that
// answer without authentication.
"fully_enforced": status.is_fully_enforced(),
"claimed": status.claimed,
"unprotected": status.unprotected,
"gated": gated,
"exempt": exempt,
}))
}
}
@@ -0,0 +1,81 @@
//! `assistant.*` RPC surface (D-01/D-02) — the front door onto the shared
//! assistant service in `crate::assistant`. Every later `assistant.*`
//! method (13-05's `list-tools`/`grants-*`, 13-08's `confirm-tool`, 13-10's
//! `history`) is added inside this file; `dispatcher.rs` registers exactly
//! one guarded arm for the whole `assistant.` prefix (see
//! `grep -c 'starts_with("assistant.")' dispatcher.rs` == 1), never a new
//! per-method literal arm.
use super::RpcHandler;
use anyhow::Result;
use std::sync::Arc;
impl RpcHandler {
/// Prefix sub-dispatcher for `assistant.*`. Reached only after the
/// caller has already passed the session-cookie + CSRF +
/// `role.can_access()` gate in `api/rpc/mod.rs:264-330` — no bespoke
/// auth here (asserted by
/// `assistant::loop_::tests::assistant_methods_require_session`, which
/// confirms `assistant.*` is absent from `UNAUTHENTICATED_METHODS`).
pub(in crate::api::rpc) async fn handle_assistant(
self: &Arc<Self>,
method: &str,
params: Option<serde_json::Value>,
session_token: &Option<String>,
) -> Result<serde_json::Value> {
match method {
"assistant.chat" => self.handle_assistant_chat(params, session_token).await,
other => anyhow::bail!("no such assistant method: {other}"),
}
}
/// assistant.chat — a single chat turn from the authenticated local
/// operator. Params: `{ "text": string }`. Returns `{ "text": string }`.
async fn handle_assistant_chat(
self: &Arc<Self>,
params: Option<serde_json::Value>,
session_token: &Option<String>,
) -> Result<serde_json::Value> {
let text = params
.as_ref()
.and_then(|p| p.get("text"))
.and_then(|v| v.as_str())
.map(|s| s.to_string())
.ok_or_else(|| anyhow::anyhow!("text is required"))?;
// The caller's authenticated session identifies this LocalOperator —
// authority is resolved node-side from CallerScope, never from
// anything the browser or the model asserts about itself.
let session_id = session_token.clone().unwrap_or_default();
let caller = crate::assistant::CallerScope::LocalOperator { session_id };
let answer = crate::assistant::chat(Arc::clone(self), caller, text).await?;
Ok(serde_json::json!({ "text": answer }))
}
/// Internal-only bridge: executes a curated assistant tool against the
/// SAME `RpcHandler` method every authenticated RPC caller dispatches
/// through (never an AI-only backdoor). NOT itself an RPC method — only
/// `assistant::loop_::execute_tool` calls this, and only for tool names
/// present in the curated D-06 registry.
///
/// Rust module privacy is what requires this thin bridge:
/// `handle_system_disk_status` is `pub(in crate::api::rpc)`, so
/// `crate::assistant` (outside that module subtree) cannot call it
/// directly. This function lives inside `api::rpc` so it CAN call the
/// private handler, and re-exposes only the one curated method name a
/// tool call is allowed to reach — not the general RPC surface.
pub(crate) async fn assistant_dispatch_tool(&self, method: &str) -> Result<serde_json::Value> {
match method {
"system.disk-status" => self.handle_system_disk_status().await,
other => anyhow::bail!("assistant_dispatch_tool: no such handler for {other}"),
}
}
/// Read-only `data_dir` accessor for `crate::assistant`, which lives
/// outside `api::rpc`'s module tree and so cannot read the private
/// `config` field directly. Minimal, `pub(crate)`, no behavior change.
pub(crate) fn data_dir(&self) -> &std::path::Path {
&self.config.data_dir
}
}
+8 -1
View File
@@ -444,6 +444,14 @@ impl RpcHandler {
"mesh.deadman-checkin" => self.handle_mesh_deadman_checkin().await,
"mesh.assistant-status" => self.handle_mesh_assistant_status().await,
"mesh.assistant-configure" => self.handle_mesh_assistant_configure(params).await,
// Phase 13 (D-01/D-02): the whole `assistant.*` surface lives in
// assistant_chat.rs, not as new arms here — this is the ONLY
// dispatcher.rs registration point for it. Every later
// assistant.* method (13-05, 13-08, 13-10) is added inside
// assistant_chat.rs's own match, never as a new arm in this file.
m if m.starts_with("assistant.") => {
self.handle_assistant(m, params, session_token).await
}
"mesh.schedule-message" => self.handle_mesh_schedule_message(params).await,
"mesh.list-scheduled" => self.handle_mesh_list_scheduled().await,
"mesh.cancel-scheduled" => self.handle_mesh_cancel_scheduled(params).await,
@@ -462,7 +470,6 @@ impl RpcHandler {
"server.set-location" => self.handle_server_set_location(params).await,
// System monitoring
"security.app-gate-status" => self.handle_app_gate_status().await,
"system.get-hostname" => self.handle_system_get_hostname().await,
"system.stats" => self.handle_system_stats().await,
"system.processes" => self.handle_system_processes().await,
@@ -51,48 +51,10 @@ impl RpcHandler {
}
}
/// Error prefix the frontend keys on to know it should prompt for the node
/// password and retry, rather than surface the message as a dead end.
pub(in crate::api::rpc) const PASSWORD_REQUIRED_PREFIX: &str = "PASSWORD_REQUIRED";
impl RpcHandler {
/// Re-authenticate the operator before granting `Trusted`.
///
/// A Trusted peer can read node state, be deployed to, and is exempt from
/// the `!= Untrusted` gates federation/DWN/messaging use — so granting it
/// is a privilege escalation and must cost a fresh proof that the person
/// at the keyboard is the operator, not merely that a session cookie
/// exists. This is the same reasoning as `node.rotate-identity` and 2FA
/// setup, both of which already re-verify.
///
/// Only ever called on the way UP. Demotion stays ungated: making
/// something less privileged must never be harder than leaving it alone,
/// or the safe action becomes the inconvenient one.
async fn verify_operator_password(&self, params: Option<&serde_json::Value>) -> Result<()> {
let password = params
.and_then(|p| p.get("password"))
.and_then(|v| v.as_str())
.unwrap_or("");
if password.is_empty() {
anyhow::bail!("{PASSWORD_REQUIRED_PREFIX}: node password required to grant Trusted");
}
if !self.auth_manager.verify_password(password).await? {
anyhow::bail!("Password verification failed");
}
Ok(())
}
/// federation.invite — Generate an invite code containing our DID + onion for a peer.
/// Optional param `trust_level`: "trusted" (default, "Link Your Nodes") or
/// "observer" ("Invite a Peer") — the level BOTH sides assign for this invite.
///
/// Minting a **Trusted** invite requires the node password (param
/// `password`): the invite is a bearer grant of Trusted to whoever
/// redeems it, so it is the escalation, not the later redemption.
/// Observer invites are unchanged.
pub(in crate::api::rpc) async fn handle_federation_invite(
&self,
params: Option<serde_json::Value>,
@@ -109,13 +71,6 @@ impl RpcHandler {
.transpose()?
.unwrap_or(TrustLevel::Trusted);
// Note this covers the DEFAULT too: "Link Your Nodes" sends no
// `trust_level` and lands on Trusted above, so the gate must key off
// the resolved level rather than an explicit request for Trusted.
if trust_level == TrustLevel::Trusted {
self.verify_operator_password(params.as_ref()).await?;
}
let (data, _) = self.state_manager.get_snapshot().await;
let did = identity::did_key_from_pubkey_hex(&data.server_info.pubkey)?;
let onion = data.server_info.tor_address.clone().unwrap_or_default();
@@ -317,15 +272,6 @@ impl RpcHandler {
if let Some(at) = &n.last_sync_error_at {
obj["last_sync_error_at"] = serde_json::json!(at);
}
// How this peer's trust level came to be. Emitted as an
// explicit null when unknown rather than omitted: "recorded
// before provenance was tracked" is the population the
// operator most needs to review, so the UI must be able to
// distinguish it from a field it simply didn't read.
obj["trust_source"] = match &n.trust_source {
Some(src) => serde_json::to_value(src).unwrap_or(serde_json::Value::Null),
None => serde_json::Value::Null,
};
obj
})
.collect();
@@ -377,10 +323,6 @@ impl RpcHandler {
}
/// federation.set-trust — Change trust level for a federated node.
///
/// Promoting a node TO `Trusted` requires the node password (param
/// `password`). Demotion and no-op re-sets do not: see
/// `verify_operator_password` for why the gate is one-directional.
pub(in crate::api::rpc) async fn handle_federation_set_trust(
&self,
params: Option<serde_json::Value>,
@@ -406,32 +348,7 @@ impl RpcHandler {
),
};
// Gate the ESCALATION only. Comparing against the node's current level
// means a re-set of an already-Trusted peer (the dropdown re-emitting
// its own value) doesn't pointlessly demand a password, while every
// path that actually raises a peer to Trusted does.
if trust == TrustLevel::Trusted {
let already_trusted = federation::load_nodes(&self.config.data_dir)
.await?
.iter()
.any(|n| n.did == did && n.trust_level == TrustLevel::Trusted);
if !already_trusted {
self.verify_operator_password(Some(&params)).await?;
}
}
// Stamp Manual: this is the one path where a human chose the level, so
// an audit of `trust_source` can tell it apart from the automatic
// grants that `UninvitedJoin` / `TransitiveMerge` mark.
federation::set_trust_level(
&self.config.data_dir,
did,
trust,
Some(federation::TrustSource::Manual),
)
.await?;
info!(did = %did, trust = %trust, "Operator set federation trust level");
federation::set_trust_level(&self.config.data_dir, did, trust).await?;
Ok(serde_json::json!({
"updated": true,
@@ -350,14 +350,10 @@ impl RpcHandler {
// lands on Observer; keep this explicit demotion as a
// safety net for legacy Trusted-only invite codes — the
// discovery flow should never auto-trust.
// `None` source: this is an automatic safety-net
// demotion, not an operator decision, so it must
// not overwrite how the peer actually got here.
let _ = crate::federation::set_trust_level(
&self.config.data_dir,
&node.did,
crate::federation::TrustLevel::Observer,
None,
)
.await;
+7 -1
View File
@@ -2,7 +2,13 @@ use crate::session::SessionStore;
use std::net::IpAddr;
/// Methods that do not require a valid session cookie.
pub(super) const UNAUTHENTICATED_METHODS: &[&str] = &[
///
/// `pub(crate)` (not just `pub(super)`) so `crate::assistant`'s test suite
/// can assert directly against the live list that the assistant RPC prefix
/// is never added to it (Phase-10 hard constraint) — see the re-export in
/// `api/rpc/mod.rs`. Read-visibility only; the list's contents and every
/// other visibility in this module are unchanged.
pub(crate) const UNAUTHENTICATED_METHODS: &[&str] = &[
"auth.login",
"auth.login.totp",
"auth.login.backup",
+8 -15
View File
@@ -1,6 +1,6 @@
mod analytics;
mod appgate;
mod ark;
mod assistant_chat;
mod auth;
mod backup_rpc;
mod bitcoin;
@@ -60,9 +60,15 @@ use std::sync::Arc;
use tracing::{debug, error};
pub use middleware::PeerAddr;
// Re-exported `pub(crate)` (not just imported) so `crate::assistant`'s test
// suite can assert directly against the live list that `assistant.*` is
// never added to it — the Phase-10 hard constraint this crate must hold.
// The list's *contents* are unchanged; only its read-visibility widens from
// "this module" to "this crate".
pub(crate) use middleware::UNAUTHENTICATED_METHODS;
use middleware::{
derive_csrf_token, extract_client_ip, extract_cookie, sanitize_error_message,
CACHEABLE_METHODS, UNAUTHENTICATED_METHODS,
CACHEABLE_METHODS,
};
use response::{cookie_header, json_response, ResponseCache, RpcError, RpcRequest, RpcResponse};
@@ -88,11 +94,6 @@ pub struct RpcHandler {
port_allocator: Arc<tokio::sync::Mutex<PortAllocator>>,
pub session_store: SessionStore,
login_rate_limiter: LoginRateLimiter,
/// Authentication in front of every app port. Built here rather than in
/// `server.rs` so it shares this handler's session store and login rate
/// limiter — an attacker must not get a fresh budget of password guesses
/// by moving from the dashboard to an app port.
pub(crate) app_gate: Arc<crate::appgate::AppGate>,
endpoint_rate_limiter: EndpointRateLimiter,
response_cache: ResponseCache,
mesh_service: Arc<tokio::sync::RwLock<Option<crate::mesh::MeshService>>>,
@@ -157,13 +158,6 @@ impl RpcHandler {
});
}
let app_gate = Arc::new(crate::appgate::AppGate::new(
session_store.clone(),
auth_manager.clone(),
login_rate_limiter.clone(),
config.data_dir.clone(),
));
Ok(Self {
config,
auth_manager,
@@ -174,7 +168,6 @@ impl RpcHandler {
port_allocator,
session_store,
login_rate_limiter,
app_gate,
endpoint_rate_limiter,
response_cache: ResponseCache::new(5),
mesh_service: Arc::new(tokio::sync::RwLock::new(None)),
+5 -59
View File
@@ -222,19 +222,6 @@ pub(in crate::api::rpc) async fn regenerate_torrc(config: &ServicesConfig) -> Re
lines.push("# ControlPort disabled for security".to_string());
lines.push(String::new());
// Ports whose manifests declare `auth: gated` forward to the gate's own
// loopback (127.0.0.2, where the app-gate listener binds — see
// `appgate::listener::GATE_TOR_UPSTREAM`) instead of the app's 127.0.0.1.
// Tor carries no session cookie, so an onion pointed at the app is an
// unauthenticated bypass of the gate. Declared-gated ports only: an
// undeclared port keeps today's target, because absence of the field is
// not an instruction (the v1.7.121 incident rule).
let gated_ports: std::collections::HashSet<u16> = crate::appgate::identity::build_port_map()
.gated_ports()
.filter(|g| g.declared)
.map(|g| g.port)
.collect();
for svc in &config.services {
if !svc.enabled {
continue;
@@ -253,7 +240,7 @@ pub(in crate::api::rpc) async fn regenerate_torrc(config: &ServicesConfig) -> Re
lines.push("HiddenServicePort 10009 127.0.0.1:10009".to_string());
}
} else {
lines.push(app_hidden_service_port_line(svc.local_port, &gated_ports));
lines.push(format!("HiddenServicePort 80 127.0.0.1:{}", svc.local_port));
}
lines.push(String::new());
@@ -261,24 +248,6 @@ pub(in crate::api::rpc) async fn regenerate_torrc(config: &ServicesConfig) -> Re
let content = lines.join("\n");
let staging = "/var/lib/archipelago/tor-config/torrc.staged";
write_staged_torrc(&content, staging).await
}
/// The `HiddenServicePort` line for an HTTP app onion. Gated ports forward to
/// the gate's Tor upstream; everything else to the app itself.
fn app_hidden_service_port_line(
local_port: u16,
gated_ports: &std::collections::HashSet<u16>,
) -> String {
let upstream = if gated_ports.contains(&local_port) {
crate::appgate::listener::GATE_TOR_UPSTREAM.to_string()
} else {
"127.0.0.1".to_string()
};
format!("HiddenServicePort 80 {}:{}", upstream, local_port)
}
async fn write_staged_torrc(content: &str, staging: &str) -> Result<()> {
let config_dir = Path::new(staging)
.parent()
.unwrap_or_else(|| Path::new("/var/lib/archipelago/tor-config"));
@@ -287,37 +256,14 @@ async fn write_staged_torrc(content: &str, staging: &str) -> Result<()> {
.await
.context("Failed to write staged torrc")?;
debug!("Staged torrc ({} bytes)", content.len());
debug!(
"Staged torrc with {} enabled services",
config.services.iter().filter(|s| s.enabled).count()
);
Ok(())
}
#[cfg(test)]
mod torrc_tests {
use super::app_hidden_service_port_line;
use std::collections::HashSet;
#[test]
fn gated_port_forwards_to_the_gate_not_the_app() {
let gated: HashSet<u16> = [8082u16].into_iter().collect();
assert_eq!(
app_hidden_service_port_line(8082, &gated),
"HiddenServicePort 80 127.0.0.2:8082"
);
}
#[test]
fn undeclared_port_keeps_the_app_loopback_target() {
// Absence of `auth: gated` is not an instruction — the onion keeps
// pointing at the app, exactly as before this change.
let gated: HashSet<u16> = [8082u16].into_iter().collect();
assert_eq!(
app_hidden_service_port_line(9100, &gated),
"HiddenServicePort 80 127.0.0.1:9100"
);
}
}
// ─── Hostname Sync ───────────────────────────────────────────────
pub(in crate::api::rpc) async fn sync_single_hostname(name: &str, address: &str) {
-468
View File
@@ -1,468 +0,0 @@
//! Which app is behind a given host port, and may it be reached without
//! authenticating?
//!
//! The gate has to answer both questions for every inbound connection: the
//! first to decide whether to challenge at all, the second so the login page
//! can name and picture what the visitor is trying to open ("you are logging
//! in to reach Immich"), which is what makes the challenge legible instead of
//! alarming.
//!
//! Both answers come from the installed manifests rather than a generated
//! table, so a catalog refresh that adds or repoints an app is reflected
//! without a daemon restart — the same reason `app_port_v6_relay_loop`
//! rescans instead of snapshotting once.
use archipelago_container::manifest::{AppManifest, PortAuth};
use std::collections::HashMap;
use std::path::PathBuf;
/// An app port the gate is responsible for.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GatedPort {
pub port: u16,
pub app_id: String,
/// Display name for the login page. Falls back to the id when a manifest
/// omits `name`.
pub app_name: String,
/// Manifest-declared icon path (`metadata.icon`), when present.
pub icon: Option<String>,
/// True only when the manifest says `auth: gated` in so many words.
///
/// The gated set deliberately also carries undeclared Session-default
/// ports (so the gate challenges them wherever it can already stand, and
/// the audit reports them). But everything that CHANGES where traffic
/// goes — the torrc repoint to 127.0.0.2, the FIPS relay stand-down, the
/// Tor-upstream bind — must key on this flag: acting on an undeclared
/// port is the v1.7.121 incident class, whatever the action.
pub declared: bool,
}
/// A port deliberately left unauthenticated, and the manifest's stated reason.
///
/// Carried around rather than discarded because "which ports are open and
/// why" is the question an operator actually asks, and the answer should be
/// one RPC call rather than an audit of 56 YAML files.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExemptPort {
pub port: u16,
pub app_id: String,
pub rationale: String,
/// UDP ports are listed for completeness. The gate is TCP-only, so it
/// could not touch them even if they were marked `session`.
pub protocol: String,
}
/// Everything the gate knows about the node's published surface.
#[derive(Debug, Clone, Default)]
pub struct PortMap {
gated: HashMap<u16, GatedPort>,
exempt: Vec<ExemptPort>,
local: std::collections::HashSet<u16>,
}
impl PortMap {
/// The app behind `port`, if the gate is responsible for it.
pub fn gated(&self, port: u16) -> Option<&GatedPort> {
self.gated.get(&port)
}
pub fn gated_ports(&self) -> impl Iterator<Item = &GatedPort> {
self.gated.values()
}
pub fn exempt_ports(&self) -> &[ExemptPort] {
&self.exempt
}
/// Declared `auth: local` — host-local by intent, so NOTHING may make it
/// externally reachable.
///
/// The gate honours this by keeping its hands off, but it is not the only
/// thing that can publish a port: the FIPS mesh relay bridges the fips0
/// ULA to `127.0.0.1` for a static port list, and it forwarded nbxplorer
/// 32838 — declared `local` and pinned to loopback — to the mesh
/// unauthenticated (archi-dev-box 2026-08-04). Anything that republishes
/// a loopback port must consult this set first.
pub fn is_declared_local(&self, port: u16) -> bool {
self.local.contains(&port)
}
pub fn is_empty(&self) -> bool {
self.gated.is_empty() && self.exempt.is_empty() && self.local.is_empty()
}
}
/// Directories searched for installed manifests, most specific first.
///
/// Mirrors `api::rpc::package::runtime::manifest_apps_dirs` deliberately: the
/// gate must classify exactly the manifests the orchestrator installs from,
/// or a port could be gated here and published from a different declaration
/// there.
fn apps_dirs() -> Vec<PathBuf> {
let mut dirs = Vec::new();
if let Ok(manifest_dir) = std::env::var("CARGO_MANIFEST_DIR") {
dirs.push(PathBuf::from(manifest_dir).join("../../apps"));
}
dirs.extend([
PathBuf::from("apps"),
PathBuf::from("/opt/archipelago/apps"),
PathBuf::from("/opt/archipelago/web-ui/archipelago-runtime/apps"),
]);
dirs
}
/// Read `metadata.icon` out of the manifest's untyped extension bag.
fn manifest_icon(manifest: &AppManifest) -> Option<String> {
manifest
.app
.extensions
.get("metadata")?
.get("icon")?
.as_str()
.map(str::to_string)
}
/// Classify every published port across all installed manifests.
///
/// The signed catalog's embedded manifests are consulted FIRST, because they
/// are what the orchestrator actually publishes containers from
/// (origin-wins; see `app_catalog::catalog_manifest_overlay`). Classifying
/// from disk alone made the gate act on policy the node was no longer
/// running: the catalog declared nbxplorer `auth: local` and pinned it to
/// loopback, the stale disk manifest declared nothing, and the gate
/// externally bound a deliberately host-local port (archi-dev-box
/// 2026-08-04).
///
/// After the catalog, the first directory that yields a manifest for an app
/// id wins, so a node's `/opt/archipelago/apps` copy shadows a repo checkout
/// rather than merging with it — otherwise a stale checked-out manifest could
/// re-open a port the installed one gates.
pub fn build_port_map() -> PortMap {
let mut map = PortMap::default();
let mut seen_apps: std::collections::HashSet<String> = std::collections::HashSet::new();
for (app_id, value) in crate::container::app_catalog::catalog_manifest_values() {
let Some(manifest) =
crate::container::app_catalog::catalog_manifest_overlay(&app_id, value)
else {
// Unparseable/invalid/build-source → the orchestrator falls back
// to disk for this app, so classification must too.
continue;
};
if seen_apps.insert(app_id) {
classify_manifest(&manifest, &mut map);
}
}
for dir in apps_dirs() {
let Ok(entries) = std::fs::read_dir(&dir) else {
continue;
};
for entry in entries.flatten() {
let path = entry.path().join("manifest.yml");
let Ok(contents) = std::fs::read_to_string(&path) else {
continue;
};
let Ok(manifest) = AppManifest::parse(&contents) else {
// A manifest that does not parse is not installable either,
// so skipping it cannot open a port that the orchestrator
// would have published.
continue;
};
if seen_apps.insert(manifest.app.id.clone()) {
classify_manifest(&manifest, &mut map);
}
}
}
map.exempt.sort_by_key(|e| e.port);
map
}
/// Classify one manifest's ports into the map. Split from [`build_port_map`]
/// so the catalog-overlay pass and the disk pass cannot diverge.
fn classify_manifest(manifest: &AppManifest, map: &mut PortMap) {
let app_id = manifest.app.id.clone();
let icon = manifest_icon(manifest);
let app_name = if manifest.app.name.trim().is_empty() {
app_id.clone()
} else {
manifest.app.name.clone()
};
for port in &manifest.app.ports {
let protocol = if port.protocol.is_empty() {
"tcp"
} else {
port.protocol.as_str()
};
match port.auth_policy() {
PortAuth::None => map.exempt.push(ExemptPort {
port: port.host,
app_id: app_id.clone(),
rationale: port
.auth_rationale
.clone()
.unwrap_or_else(|| "(no rationale recorded)".to_string()),
protocol: protocol.to_string(),
}),
// Declared host-local. Not gated and not reported as
// exposed, because it is neither — see PortAuth::Local
// for why this cannot be inferred from `bind`. Recorded so
// the mesh relay (and any future republisher) can refuse to
// expose it.
PortAuth::Local => {
map.local.insert(port.host);
}
// Explicit opt-in: the app is on loopback and the daemon
// owns the external addresses. This is the ONLY way a
// port gets bound by the gate, regardless of `bind`.
PortAuth::Gated => {
map.gated.insert(
port.host,
GatedPort {
port: port.host,
app_id: app_id.clone(),
app_name: app_name.clone(),
icon: icon.clone(),
declared: true,
},
);
}
PortAuth::Session => {
// UDP cannot carry an HTTP challenge. Such a port has
// no business defaulting into the gated set where it
// would look protected without being protectable —
// surface it as an unrationalised exemption instead,
// which is honest and shows up in the audit list.
if protocol != "tcp" {
map.exempt.push(ExemptPort {
port: port.host,
app_id: app_id.clone(),
rationale: format!(
"{protocol} cannot carry an HTTP challenge; declare auth: none \
with a rationale to record why this is safe"
),
protocol: protocol.to_string(),
});
continue;
}
// A loopback publish is skipped, and this is the
// safety property of the whole module: the gate must
// never be the reason a port becomes reachable
// somewhere it was not. `session` is the DEFAULT, so
// it is what every un-migrated manifest carries —
// and a node's installed manifests always lag the
// repo. Binding those externally published Bitcoin
// RPC across the LAN within seconds of deploy
// (archi-dev-box 2026-08-03). Taking over a port is
// opt-in only: `auth: gated`, shipped in the same
// manifest edit as the loopback pin.
if port
.bind
.parse::<std::net::IpAddr>()
.is_ok_and(|ip| ip.is_loopback())
{
continue;
}
map.gated.insert(
port.host,
GatedPort {
port: port.host,
app_id: app_id.clone(),
app_name: app_name.clone(),
icon: icon.clone(),
declared: false,
},
);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The corpus this runs against is the real `apps/` tree, so these assert
/// on properties rather than exact contents — the set of apps changes,
/// the invariants must not.
#[test]
fn real_manifests_classify_into_both_sets() {
let map = build_port_map();
assert!(!map.is_empty(), "no manifests found — apps dir missing?");
assert!(
map.gated_ports().count() > 20,
"expected most published ports to be gated, got {}",
map.gated_ports().count()
);
assert!(!map.exempt_ports().is_empty());
}
#[test]
fn every_exemption_carries_a_reason() {
for exempt in build_port_map().exempt_ports() {
assert!(
!exempt.rationale.trim().is_empty(),
"port {} ({}) is exempt with no rationale",
exempt.port,
exempt.app_id
);
}
}
fn manifest(yaml: &str) -> AppManifest {
AppManifest::parse(yaml).expect("test manifest must parse")
}
const BASE: &str = r#"
app:
id: testapp
name: Test App
version: "1.0"
container:
image: example.org/testapp:1.0
"#;
/// `auth: gated` is the only classification allowed to redirect traffic —
/// torrc repoints, relay stand-down, and the 127.0.0.2 bind all key on
/// `declared`. An undeclared Session port is challenged and audited but
/// must never be `declared`.
#[test]
fn declared_tracks_the_manifest_not_the_default() {
let mut map = PortMap::default();
classify_manifest(
&manifest(&format!(
"{BASE} ports:\n - host: 8090\n container: 7777\n protocol: tcp\n bind: 127.0.0.1\n auth: gated\n"
)),
&mut map,
);
assert!(map.gated(8090).expect("gated").declared);
let mut map = PortMap::default();
classify_manifest(
&manifest(&format!(
"{BASE} ports:\n - host: 9100\n container: 9100\n protocol: tcp\n"
)),
&mut map,
);
let undeclared = map.gated(9100).expect("session default is challenged");
assert!(
!undeclared.declared,
"an absent auth field must never read as an instruction"
);
}
/// `auth: local` keeps the gate's hands off entirely — the port is
/// neither gated nor exempt-reported — but it IS recorded, so the mesh
/// relay can refuse to republish a deliberately host-local port.
#[test]
fn local_ports_are_untouched_but_recorded() {
let mut map = PortMap::default();
classify_manifest(
&manifest(&format!(
"{BASE} ports:\n - host: 32838\n container: 32838\n protocol: tcp\n bind: 127.0.0.1\n auth: local\n"
)),
&mut map,
);
assert!(map.gated(32838).is_none());
assert!(map.exempt_ports().is_empty());
assert!(
map.is_declared_local(32838),
"the mesh relay needs this to refuse bridging a host-local port"
);
assert!(!map.is_declared_local(3000));
}
/// The real corpus: every port the FIPS relay can bridge must be safe to
/// bridge. A port that is declared `local` (host-local by intent) or
/// declared `gated` (the app gate owns its external addresses) must be
/// withheld by the relay — this asserts the two sets the relay consults
/// actually classify the live manifests, so a future manifest edit that
/// re-opens one is caught here rather than on a node.
#[test]
fn relay_port_list_respects_local_and_gated_declarations() {
let map = build_port_map();
let relay_would_expose: Vec<u16> = crate::fips::app_ports::APP_LAUNCH_PORTS
.iter()
.copied()
.filter(|p| map.is_declared_local(*p))
.collect();
assert!(
!relay_would_expose.is_empty(),
"expected the corpus to contain at least one local port in the relay list \
(32838/8999) if this fails the guard is untested, not unnecessary"
);
}
/// Protocol ports that wallets dial directly must never end up gated —
/// this is the constraint that decided the design (Zeus and electrum
/// clients keep working untouched).
#[test]
fn wallet_protocol_ports_are_not_gated() {
let map = build_port_map();
for port in [10009, 18080, 9735, 50001] {
assert!(
map.gated(port).is_none(),
"port {port} must stay ungated — remote wallets cannot hold a session"
);
}
}
/// Bitcoin's RPC is host-local by intent (`auth: local`), so the gate
/// must neither gate it nor report it as exposed — fronting it would
/// newly publish it on every host address, behind a login but reachable
/// where it deliberately was not.
#[test]
fn host_local_ports_are_neither_gated_nor_reported() {
let map = build_port_map();
assert!(map.gated(8332).is_none(), "bitcoin RPC must not be gated");
assert!(
!map.exempt_ports().iter().any(|e| e.port == 8332),
"a host-local port is not an unauthenticated exposure"
);
}
/// THE safety property. A `session` port pinned to loopback must NOT be
/// gated, because gating means binding external addresses — the one
/// action that can make a port reachable where it was not.
///
/// This is not hypothetical. `session` is the default, so it is what
/// every un-migrated manifest carries, and a node's installed manifests
/// always lag the repo. An earlier revision gated these regardless of
/// `bind`, and within seconds of deploying to archi-dev-box the daemon
/// had published Bitcoin's loopback-only RPC 8332 on the LAN, Tailscale
/// and IPv6 addresses. Taking over a port must be opt-in.
#[test]
fn a_loopback_pinned_session_port_is_never_gated() {
let map = build_port_map();
// aiui and bitcoin RPC are both loopback-pinned in the shipped tree.
for port in [5180, 8332] {
assert!(
map.gated(port).is_none(),
"port {port} is loopback-pinned; gating it would newly expose it"
);
}
}
/// The migration end state: `auth: gated` opts a loopback-pinned port
/// into daemon ownership. Without this the rollout could never complete.
#[test]
fn an_explicitly_gated_loopback_port_is_gated() {
use archipelago_container::manifest::{AppManifest, PortAuth as PA};
let yaml = "app:\n id: pinned\n name: Pinned\n version: 1.0.0\n container:\n image: x:y\n ports:\n - host: 9911\n container: 80\n bind: 127.0.0.1\n auth: gated\n";
let m = AppManifest::parse(yaml).expect("parses");
assert_eq!(m.app.ports[0].auth, Some(PA::Gated));
assert_eq!(m.app.ports[0].bind, "127.0.0.1");
}
/// An app UI that was reachable with no credential in the 2026-08-03
/// reproduction must now resolve to a gated port with a display name.
#[test]
fn reproduced_open_ports_are_now_gated() {
let map = build_port_map();
let strfry = map.gated(8090).expect("strfry :8090 must be gated");
assert_eq!(strfry.app_id, "strfry");
assert!(!strfry.app_name.is_empty());
}
}
-399
View File
@@ -1,399 +0,0 @@
//! Binding the gate in front of apps, and telling the truth when it cannot.
//!
//! # The ordering problem
//!
//! A published container port is bound `0.0.0.0:<port>`, which claims *every*
//! host address. While the app holds that, the gate cannot bind
//! `<lan-ip>:<port>` at all — the kernel refuses the overlap. So the gate can
//! only stand in front of an app whose own publish has been pinned to
//! loopback (`bind: 127.0.0.1` in its manifest, which
//! `PortMapping::bind` has supported all along).
//!
//! That makes the rollout necessarily two-step, per app: pin the publish,
//! recreate the container, and the gate claims the external addresses. Doing
//! it the other way round — gate first — is not possible, and doing it in one
//! step for every app at once would recreate every container on the node
//! simultaneously.
//!
//! # Why the failure has to be loud
//!
//! The dangerous version of this module is the one that tries to bind, fails
//! because the app still holds the port, logs at debug, and moves on. The
//! node would then be running "the app gate" while every app remained exactly
//! as open as before — a security control that reports success and does
//! nothing, which is worse than no control at all because it stops anyone
//! looking.
//!
//! So an unclaimable port is recorded in [`GateStatus::unprotected`] and
//! logged at warn on every sweep. The same reasoning killed the nft-drop-in
//! design: `/etc/fips/fips.nft` is provisioned out-of-band and its absence is
//! a silent no-op, so a gate shipped that way would be absent on every node
//! without the hardening baseline and nobody would know.
use super::identity::GatedPort;
use super::AppGate;
use std::collections::HashMap;
use std::net::{IpAddr, SocketAddr};
use std::sync::Arc;
use tokio::net::TcpListener;
use tokio::sync::RwLock;
use tracing::{debug, info, warn};
/// How often the sweep re-runs. Matches `app_port_v6_relay_loop`: addresses
/// come and go (DHCP, Tailscale up/down, the fips0 ULA appearing late) and
/// apps are installed while the daemon runs.
const SWEEP_INTERVAL: std::time::Duration = std::time::Duration::from_secs(60);
/// The gate's own loopback address, distinct from the app's `127.0.0.1`.
///
/// Tor cannot present a session cookie, so `HiddenServicePort → 127.0.0.1`
/// reaches the app around the gate. Instead torrc forwards gated ports to
/// this address (`api/rpc/tor`), where the gate — not the app — listens. A
/// second loopback address rather than a second port number, so no app needs
/// a port it did not declare.
pub const GATE_TOR_UPSTREAM: IpAddr = IpAddr::V4(std::net::Ipv4Addr::new(127, 0, 0, 2));
/// A port the gate should own but could not claim, and why.
#[derive(Debug, Clone, serde::Serialize)]
pub struct UnprotectedPort {
pub port: u16,
pub app_id: String,
pub app_name: String,
/// Human-readable cause, e.g. that the app still publishes on all
/// interfaces.
pub reason: String,
}
/// What the gate is actually enforcing right now.
#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct GateStatus {
/// (port, address) pairs the gate holds.
pub claimed: Vec<(u16, String)>,
/// Ports that should be gated but are not. **Non-empty means the node
/// has unauthenticated app surface.**
pub unprotected: Vec<UnprotectedPort>,
}
impl GateStatus {
pub fn is_fully_enforced(&self) -> bool {
self.unprotected.is_empty()
}
}
/// Every non-loopback address currently on this host.
///
/// Shells out to `ip` rather than pulling in a `getifaddrs` binding: the
/// codebase already resolves addresses this way (`host_ip`), the result is
/// re-derived every sweep so a stale parse self-corrects, and a failure here
/// degrades to "claim nothing this round" rather than to a wrong claim.
async fn host_addresses() -> Vec<IpAddr> {
let Ok(out) = tokio::process::Command::new("ip")
.args(["-o", "addr", "show"])
.output()
.await
else {
return Vec::new();
};
let text = String::from_utf8_lossy(&out.stdout);
let mut addrs = Vec::new();
for line in text.lines() {
let mut fields = line.split_whitespace();
// `1: lo inet 127.0.0.1/8 scope host lo`
let Some(family) = fields.clone().nth(2) else {
continue;
};
if family != "inet" && family != "inet6" {
continue;
}
let Some(cidr) = fields.nth(3) else { continue };
let Some(addr) = cidr.split('/').next() else {
continue;
};
// Strip a zone index (`fe80::1%eth0`) — link-local addresses need a
// scope to bind and are not how anyone reaches an app anyway.
let addr = addr.split('%').next().unwrap_or(addr);
let Ok(ip) = addr.parse::<IpAddr>() else {
continue;
};
if ip.is_loopback() || ip.is_unspecified() {
continue;
}
if let IpAddr::V6(v6) = ip {
// Link-local v6 requires a scope id we do not carry.
if (v6.segments()[0] & 0xffc0) == 0xfe80 {
continue;
}
}
addrs.push(ip);
}
addrs.sort();
addrs.dedup();
addrs
}
/// Process-wide gate status, so any RPC handler can report what the gate is
/// actually enforcing without threading a handle through every caller.
///
/// A single shared cell rather than a value returned from `run`: "is my node
/// actually protected?" has to be answerable from the RPC layer, and the
/// listener that knows the answer runs in a detached task.
pub fn shared_status() -> Arc<RwLock<GateStatus>> {
static STATUS: std::sync::OnceLock<Arc<RwLock<GateStatus>>> = std::sync::OnceLock::new();
STATUS
.get_or_init(|| Arc::new(RwLock::new(GateStatus::default())))
.clone()
}
/// Run the gate. Returns only on shutdown.
pub async fn run(
gate: Arc<AppGate>,
status: Arc<RwLock<GateStatus>>,
mut shutdown_rx: tokio::sync::watch::Receiver<bool>,
) {
// (port, addr) pairs already served, so a sweep does not rebind what it
// already holds. The accept-loop handle is kept so a claim can be
// RELEASED when its port leaves the gated set — a catalog refresh
// declaring a port `local`/`none` must make the gate let go without a
// daemon restart, or the stale bind keeps republishing a port the
// catalog just withdrew (nbxplorer 32838, archi-dev-box 2026-08-04).
let mut held: HashMap<(u16, IpAddr), tokio::task::JoinHandle<()>> = HashMap::new();
let mut interval = tokio::time::interval(SWEEP_INTERVAL);
interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
loop {
tokio::select! {
_ = interval.tick() => {
sweep(&gate, &status, &mut held, &shutdown_rx).await;
}
_ = shutdown_rx.changed() => return,
}
}
}
async fn sweep(
gate: &Arc<AppGate>,
status: &Arc<RwLock<GateStatus>>,
held: &mut HashMap<(u16, IpAddr), tokio::task::JoinHandle<()>>,
shutdown_rx: &tokio::sync::watch::Receiver<bool>,
) {
// Re-read the manifests every sweep rather than trusting the map built
// at construction. An app installed while the daemon is running would
// otherwise never be gated until the next restart — and it would not
// appear in `unprotected` either, so the node would report itself fully
// enforced while serving a brand-new app to anyone who asked.
gate.refresh().await;
let port_map = gate.port_map().await;
// Release claims whose port left the gated set (or whose Tor-upstream
// claim lost its declaration). Aborting the accept loop drops the
// listener, freeing the address for whoever now legitimately owns it —
// the app itself, or nobody.
held.retain(|(port, addr), handle| {
let keep = match port_map.gated(*port) {
None => false,
Some(app) => *addr != GATE_TOR_UPSTREAM || app.declared,
};
if !keep {
handle.abort();
info!(port, %addr, "app gate released a claim: port is no longer gated here");
}
keep
});
let addresses = host_addresses().await;
if addresses.is_empty() {
debug!("app gate: no external addresses yet");
return;
}
let mut claimed = Vec::new();
let mut unprotected = Vec::new();
for app in port_map.gated_ports() {
// Nothing is listening on this port, so there is no app to protect
// and binding would steal the port from an install that has not
// happened yet. The relay loop learned this the hard way: binding a
// port for an app that is not installed makes its later install hit
// "address already in use", and the install's port-free step then
// kills the daemon holding it.
if !app_is_listening(app.port).await {
continue;
}
let mut claimed_any = false;
let mut blocked = false;
// External addresses first, then the gate's Tor upstream. 127.0.0.2
// deliberately does NOT count toward `claimed_any`: the warning below
// is about external exposure, and a port whose only claim is the Tor
// loopback is still wide open on the LAN.
for &addr in &addresses {
let key = (app.port, addr);
if held.contains_key(&key) {
claimed.push((app.port, addr.to_string()));
claimed_any = true;
continue;
}
match TcpListener::bind(SocketAddr::new(addr, app.port)).await {
Ok(listener) => {
let handle =
spawn_accept_loop(listener, gate.clone(), app.clone(), shutdown_rx.clone());
held.insert(key, handle);
claimed.push((app.port, addr.to_string()));
claimed_any = true;
info!(
port = app.port, %addr, app = %app.app_id,
"app gate claimed an app port"
);
}
// Almost always the app itself holding 0.0.0.0:<port>.
Err(_) => blocked = true,
}
}
// The Tor upstream is bound for DECLARED gated ports only: torrc only
// repoints an onion at 127.0.0.2 for a declared port, and standing a
// challenge on an undeclared port's would-be upstream would change
// where its traffic goes on nothing but a default.
if app.declared {
let tor_key = (app.port, GATE_TOR_UPSTREAM);
if held.contains_key(&tor_key) {
claimed.push((app.port, GATE_TOR_UPSTREAM.to_string()));
} else {
match TcpListener::bind(SocketAddr::new(GATE_TOR_UPSTREAM, app.port)).await {
Ok(listener) => {
let handle = spawn_accept_loop(
listener,
gate.clone(),
app.clone(),
shutdown_rx.clone(),
);
held.insert(tor_key, handle);
claimed.push((app.port, GATE_TOR_UPSTREAM.to_string()));
info!(
port = app.port, app = %app.app_id,
"app gate claimed the Tor upstream (127.0.0.2)"
);
}
Err(_) => blocked = true,
}
}
}
if blocked && !claimed_any {
warn!(
port = app.port, app = %app.app_id,
"APP GATE CANNOT PROTECT THIS PORT — the app still publishes on all \
interfaces. Pin its manifest port to bind: 127.0.0.1 and recreate the \
container, or it stays reachable without authentication."
);
unprotected.push(UnprotectedPort {
port: app.port,
app_id: app.app_id.clone(),
app_name: app.app_name.clone(),
reason: "app publishes on all interfaces; manifest port needs bind: 127.0.0.1"
.to_string(),
});
}
}
claimed.sort();
unprotected.sort_by_key(|u| u.port);
let mut guard = status.write().await;
guard.claimed = claimed;
guard.unprotected = unprotected;
}
/// Is anything answering on loopback for this port?
async fn app_is_listening(port: u16) -> bool {
tokio::time::timeout(
std::time::Duration::from_millis(300),
tokio::net::TcpStream::connect(("127.0.0.1", port)),
)
.await
.ok()
.and_then(|r| r.ok())
.is_some()
}
/// Returns the accept-loop task handle so the sweep can release the claim
/// (abort → listener drops → address freed) when the port leaves the gated
/// set. In-flight connections finish on their own tasks.
fn spawn_accept_loop(
listener: TcpListener,
gate: Arc<AppGate>,
app: GatedPort,
mut shutdown_rx: tokio::sync::watch::Receiver<bool>,
) -> tokio::task::JoinHandle<()> {
tokio::spawn(async move {
loop {
tokio::select! {
accepted = listener.accept() => {
let Ok((stream, peer)) = accepted else { break };
let gate = gate.clone();
let app = app.clone();
tokio::spawn(async move {
let service = hyper::service::service_fn(move |req| {
let gate = gate.clone();
let app = app.clone();
async move {
Ok::<_, std::convert::Infallible>(
gate.handle(req, &app, peer.ip()).await,
)
}
});
let _ = hyper::server::conn::Http::new()
// Same slowloris guard as the main listener: an
// unauthenticated caller must not be able to hold
// a connection open by never sending headers.
.http1_header_read_timeout(std::time::Duration::from_secs(30))
.serve_connection(stream, service)
.with_upgrades()
.await;
});
}
_ = shutdown_rx.changed() => break,
}
}
})
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn host_addresses_excludes_loopback() {
for addr in host_addresses().await {
assert!(!addr.is_loopback(), "{addr} is loopback");
assert!(!addr.is_unspecified());
}
}
#[tokio::test]
async fn app_is_listening_is_false_for_a_dead_port() {
// Bind and immediately drop, so the port is known-free.
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
drop(listener);
assert!(!app_is_listening(port).await);
}
#[tokio::test]
async fn app_is_listening_is_true_for_a_live_port() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
assert!(app_is_listening(port).await);
}
#[test]
fn a_status_with_unprotected_ports_is_not_fully_enforced() {
let mut status = GateStatus::default();
assert!(status.is_fully_enforced());
status.unprotected.push(UnprotectedPort {
port: 8090,
app_id: "strfry".into(),
app_name: "Strfry".into(),
reason: "test".into(),
});
assert!(!status.is_fully_enforced());
}
}
-724
View File
@@ -1,724 +0,0 @@
//! The app gate — authentication in front of every app port.
//!
//! # Why this exists
//!
//! Reproduced on a live node 2026-08-03: with no session cookie at all, over
//! the Tailscale address, six app ports answered `HTTP 200` with their real
//! UIs. `ss -tlnp` showed them bound `0.0.0.0`, so the same pages were served
//! on the LAN address, the FIPS mesh address, and through each app's onion.
//! This is the same bug class as the `/lnd-connect-info` and `/bitcoin-rpc/`
//! leaks closed in v1.7.120, but across every app rather than two endpoints.
//!
//! # Why one gate covers four transports
//!
//! LAN, Tailscale, Tor and the FIPS mesh all converge on
//! `127.0.0.1:<app_port>` — the container publishes there, the mesh relay
//! forwards there, and `HiddenServicePort` points there. Authorising at that
//! convergence point is one gate rather than four, which is the only reason
//! this is tractable at all.
//!
//! # Why not umbrel's sidecar proxy
//!
//! umbrelOS gives every app an `app_proxy` container that owns the published
//! port. That works, but it costs a container per app and a second service to
//! hold the shared secret. Here the daemon already terminates HTTP, already
//! owns the session store, and already runs a relay loop for the mesh, so the
//! gate is assembly rather than new infrastructure.
//!
//! # What it does NOT do
//!
//! It does not invent authentication policy. Password verification, TOTP
//! decryption and step replay protection, session lifetime, and rate limiting
//! are the same primitives the JSON-RPC login path uses. Only the transport
//! differs — an HTML form instead of JSON-RPC — because a browser being
//! redirected to an app cannot speak JSON-RPC.
pub mod identity;
pub mod listener;
use crate::auth::AuthManager;
use crate::rate_limit::LoginRateLimiter;
use crate::session::SessionStore;
use hyper::{header, Body, HeaderMap, Method, Request, Response, StatusCode};
use identity::{GatedPort, PortMap};
use std::net::IpAddr;
use std::path::PathBuf;
use std::sync::Arc;
use tokio::sync::RwLock;
/// Paths the gate serves itself rather than proxying. Namespaced so an app
/// that happens to have its own `/login` is unaffected.
const GATE_PREFIX: &str = "/__archipelago-gate/";
/// Result of examining a request's credentials.
#[derive(Debug, PartialEq, Eq)]
pub enum Authorization {
/// Proxy it through.
Allow,
/// Serve the login page.
Challenge,
}
pub struct AppGate {
sessions: SessionStore,
auth: AuthManager,
limiter: LoginRateLimiter,
data_dir: PathBuf,
port_map: Arc<RwLock<PortMap>>,
}
impl AppGate {
pub fn new(
sessions: SessionStore,
auth: AuthManager,
limiter: LoginRateLimiter,
data_dir: PathBuf,
) -> Self {
Self {
sessions,
auth,
limiter,
data_dir,
port_map: Arc::new(RwLock::new(identity::build_port_map())),
}
}
/// Re-read the manifests. Called on catalog refresh so a newly installed
/// app is gated without a daemon restart.
pub async fn refresh(&self) {
*self.port_map.write().await = identity::build_port_map();
}
pub async fn port_map(&self) -> PortMap {
self.port_map.read().await.clone()
}
/// Does this request carry a credential good for `app_id`?
///
/// Two accepted forms, deliberately no others:
///
/// * the node session cookie — and because a session still pending its
/// TOTP step fails `validate()`, **2FA is honoured here for free**. The
/// gate never sees a TOTP code on a proxied request and never needs to.
/// * an app-scoped bearer token, for machine clients that speak HTTP but
/// cannot hold a cookie or complete an interactive login (Home
/// Assistant reaching an app's API is the motivating case).
pub async fn authorize(&self, headers: &HeaderMap, app_id: &str) -> Authorization {
if let Some(token) = crate::session::extract_session_cookie(headers) {
if self.sessions.validate(&token).await {
return Authorization::Allow;
}
}
if let Some(token) = bearer_token(headers) {
if crate::device_tokens::verify_for_app(&self.data_dir, &token, app_id)
.await
.is_some()
{
return Authorization::Allow;
}
}
Authorization::Challenge
}
/// Handle one inbound request on a gated port.
pub async fn handle(
&self,
req: Request<Body>,
app: &GatedPort,
client_ip: IpAddr,
) -> Response<Body> {
let path = req.uri().path().to_string();
if let Some(action) = path.strip_prefix(GATE_PREFIX) {
return self.handle_gate_action(req, app, action, client_ip).await;
}
match self.authorize(req.headers(), &app.app_id).await {
Authorization::Allow => proxy_to_app(req, app.port).await,
// 401 rather than a redirect: a redirect to a login page is
// indistinguishable from the app itself redirecting, and machine
// clients would follow it and parse HTML as if it were their API
// response. The status says "you are not authenticated" in a way
// every client understands, and browsers still render the body.
Authorization::Challenge => login_page(app, None, StatusCode::UNAUTHORIZED),
}
}
/// The gate's own endpoints: the login form target and the TOTP step.
async fn handle_gate_action(
&self,
req: Request<Body>,
app: &GatedPort,
action: &str,
client_ip: IpAddr,
) -> Response<Body> {
if req.method() != Method::POST {
return login_page(app, None, StatusCode::OK);
}
// Captured before the body is consumed. The pending-2FA session
// rides the cookie rather than a hidden form field so the token
// never appears in the HTML, in a `view-source`, or in a screenshot
// of the second-factor page.
let pending = crate::session::extract_session_cookie(req.headers());
// Same limiter instance as the JSON-RPC login path, so an attacker
// cannot get a fresh budget of guesses simply by moving to an app
// port.
if !self.limiter.check(client_ip).await {
return login_page(
app,
Some("Too many attempts. Wait a minute and try again."),
StatusCode::TOO_MANY_REQUESTS,
);
}
let form = match read_form(req).await {
Some(form) => form,
None => return login_page(app, Some("Malformed request."), StatusCode::BAD_REQUEST),
};
match action {
"login" => self.do_login(app, &form, client_ip).await,
"totp" => self.do_totp(app, &form, pending, client_ip).await,
_ => not_found(),
}
}
async fn do_login(&self, app: &GatedPort, form: &Form, client_ip: IpAddr) -> Response<Body> {
let password = field(form, "password").unwrap_or_default();
match self.auth.verify_password(&password).await {
Ok(true) => {}
_ => {
self.limiter.record_failure(client_ip).await;
return login_page(app, Some("Incorrect password."), StatusCode::UNAUTHORIZED);
}
}
// 2FA, if configured. The secret is encrypted with the password, so
// this is the only moment it can be decrypted — exactly as in the
// JSON-RPC path. A pending session cannot pass `authorize`, so a
// half-finished login grants nothing.
if self.auth.is_totp_enabled().await.unwrap_or(false) {
if let Ok(Some(totp_data)) = self.auth.get_totp_data().await {
if let Ok(secret) = crate::totp::decrypt_secret(&totp_data, &password) {
let pending = self.sessions.create_pending(secret).await;
let mut resp = totp_page(app, None, StatusCode::OK);
set_session_cookie(&mut resp, &pending);
return resp;
}
}
// TOTP is on but its data is unreadable. Refuse: falling through
// to a full session would silently downgrade the node's second
// factor to nothing.
return login_page(
app,
Some("Two-factor data could not be read. Sign in from the dashboard."),
StatusCode::INTERNAL_SERVER_ERROR,
);
}
let token = self.sessions.create().await;
let mut resp = redirect_to_app();
set_session_cookie(&mut resp, &token);
resp
}
async fn do_totp(
&self,
app: &GatedPort,
form: &Form,
pending: Option<String>,
client_ip: IpAddr,
) -> Response<Body> {
let code = field(form, "code").unwrap_or_default();
let Some(pending) = pending.filter(|s| !s.is_empty()) else {
return login_page(app, Some("Session expired."), StatusCode::UNAUTHORIZED);
};
let Some(secret) = self.sessions.get_pending_secret(&pending).await else {
return login_page(
app,
Some("Session expired. Start again."),
StatusCode::UNAUTHORIZED,
);
};
let totp_data = self.auth.get_totp_data().await.ok().flatten();
let used_steps = totp_data
.as_ref()
.map(|d| d.used_steps.clone())
.unwrap_or_default();
match crate::totp::verify_code(&secret, &code, &used_steps) {
Ok(Some(step)) => {
// Record the step so the same code cannot be replayed — the
// JSON-RPC path does this and skipping it here would make the
// gate the weaker of the two doors.
if let Some(mut data) = totp_data {
data.used_steps.push(step);
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0);
let cutoff = (now / 30) - 10;
data.used_steps.retain(|s| *s > cutoff);
let _ = self.auth.update_totp(data).await;
}
match self.sessions.upgrade_to_full(&pending).await {
Some(full) => {
let mut resp = redirect_to_app();
set_session_cookie(&mut resp, &full);
resp
}
None => login_page(app, Some("Session expired."), StatusCode::UNAUTHORIZED),
}
}
_ => {
self.limiter.record_failure(client_ip).await;
let mut resp = totp_page(app, Some("Incorrect code."), StatusCode::UNAUTHORIZED);
set_session_cookie(&mut resp, &pending);
resp
}
}
}
}
// ---------------------------------------------------------------------------
// Request helpers
// ---------------------------------------------------------------------------
fn bearer_token(headers: &HeaderMap) -> Option<String> {
let value = headers.get(header::AUTHORIZATION)?.to_str().ok()?;
let token = value
.strip_prefix("Bearer ")
.or_else(|| value.strip_prefix("bearer "))?;
let token = token.trim();
(!token.is_empty()).then(|| token.to_string())
}
type Form = std::collections::HashMap<String, String>;
/// Free function rather than a trait method: `HashMap` has an inherent `get`
/// that would win method resolution and silently return `Option<&String>`.
fn field(form: &Form, key: &str) -> Option<String> {
form.get(key).cloned()
}
/// Read an `application/x-www-form-urlencoded` body.
///
/// Capped: an unauthenticated caller must not be able to make the daemon
/// buffer arbitrary bytes, and no legitimate login form approaches this.
const MAX_FORM_BYTES: usize = 8 * 1024;
async fn read_form(req: Request<Body>) -> Option<Form> {
let bytes = hyper::body::to_bytes(req.into_body()).await.ok()?;
if bytes.len() > MAX_FORM_BYTES {
return None;
}
let text = std::str::from_utf8(&bytes).ok()?;
let mut form = Form::new();
for pair in text.split('&') {
let Some((k, v)) = pair.split_once('=') else {
continue;
};
form.insert(percent_decode(k), percent_decode(v));
}
Some(form)
}
fn percent_decode(input: &str) -> String {
let bytes = input.replace('+', " ").into_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%' && i + 2 < bytes.len() {
let hex = std::str::from_utf8(&bytes[i + 1..i + 3]).ok();
if let Some(byte) = hex.and_then(|h| u8::from_str_radix(h, 16).ok()) {
out.push(byte);
i += 3;
continue;
}
}
out.push(bytes[i]);
i += 1;
}
String::from_utf8_lossy(&out).into_owned()
}
/// Forward an authorised request to the app on loopback.
async fn proxy_to_app(req: Request<Body>, port: u16) -> Response<Body> {
let path_and_query = req
.uri()
.path_and_query()
.map(|p| p.as_str())
.unwrap_or("/")
.to_string();
let uri = match format!("http://127.0.0.1:{port}{path_and_query}").parse::<hyper::Uri>() {
Ok(uri) => uri,
Err(_) => return bad_gateway(),
};
let (mut parts, body) = req.into_parts();
parts.uri = uri;
// Strip the gate's own credential before it reaches the app: the app has
// no use for the node session and should never be in a position to log,
// echo, or forward it.
parts.headers.remove(header::COOKIE);
parts.headers.remove(header::AUTHORIZATION);
let client = hyper::Client::new();
match client.request(Request::from_parts(parts, body)).await {
Ok(resp) => resp,
Err(_) => bad_gateway(),
}
}
fn set_session_cookie(resp: &mut Response<Body>, token: &str) {
// No Domain attribute, so the cookie is host-only. Cookies ignore port,
// which is what makes one sign-in cover the dashboard and every app port
// on the same host — and equally why an app on a *different* host (its
// own onion) is a separate sign-in.
if let Ok(value) =
header::HeaderValue::from_str(&format!("session={token}; HttpOnly; SameSite=Lax; Path=/"))
{
resp.headers_mut().append(header::SET_COOKIE, value);
}
}
fn redirect_to_app() -> Response<Body> {
Response::builder()
.status(StatusCode::SEE_OTHER)
.header(header::LOCATION, "/")
.body(Body::empty())
.expect("static response builds")
}
fn bad_gateway() -> Response<Body> {
Response::builder()
.status(StatusCode::BAD_GATEWAY)
.body(Body::from("app is not responding"))
.expect("static response builds")
}
fn not_found() -> Response<Body> {
Response::builder()
.status(StatusCode::NOT_FOUND)
.body(Body::empty())
.expect("static response builds")
}
// ---------------------------------------------------------------------------
// Pages
// ---------------------------------------------------------------------------
/// Minimal HTML escape for values interpolated into the pages below.
fn esc(s: &str) -> String {
s.replace('&', "&amp;")
.replace('<', "&lt;")
.replace('>', "&gt;")
.replace('"', "&quot;")
.replace('\'', "&#39;")
}
/// The app's icon as an `<img>`, or a lettermark when the manifest declares
/// none. Inlined as a data URI rather than linked: the gate is answering on
/// the app's own port, so any asset URL would either hit the unauthenticated
/// app behind it or a different origin the browser may not reach.
fn icon_markup(app: &GatedPort) -> String {
if let Some(path) = &app.icon {
if let Some(data_uri) = read_icon_data_uri(path) {
return format!(r#"<img class="icon" src="{}" alt="">"#, esc(&data_uri));
}
}
let letter = app
.app_name
.chars()
.next()
.map(|c| c.to_uppercase().to_string())
.unwrap_or_else(|| "?".to_string());
format!(r#"<div class="icon lettermark">{}</div>"#, esc(&letter))
}
/// Icons live with the web UI. Only files under the icon directory are read,
/// and only known image extensions — the path comes from a manifest, which is
/// signed, but treating it as untrusted costs nothing.
fn read_icon_data_uri(icon_path: &str) -> Option<String> {
let name = std::path::Path::new(icon_path).file_name()?.to_str()?;
let mime = match name.rsplit_once('.')?.1.to_ascii_lowercase().as_str() {
"svg" => "image/svg+xml",
"png" => "image/png",
"webp" => "image/webp",
"jpg" | "jpeg" => "image/jpeg",
_ => return None,
};
for root in [
"/opt/archipelago/web-ui/assets/img/app-icons",
"web/dist/neode-ui/assets/img/app-icons",
] {
let candidate = std::path::Path::new(root).join(name);
if let Ok(bytes) = std::fs::read(&candidate) {
if bytes.len() > 512 * 1024 {
return None;
}
return Some(format!("data:{mime};base64,{}", base64_encode(&bytes)));
}
}
None
}
fn base64_encode(bytes: &[u8]) -> String {
use base64::Engine;
base64::engine::general_purpose::STANDARD.encode(bytes)
}
fn page(title: &str, app: &GatedPort, body: &str, status: StatusCode) -> Response<Body> {
let html = format!(
r#"<!doctype html>
<html lang="en"><head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex">
<title>{title} {app_name}</title>
<style>
:root {{ color-scheme: dark; }}
* {{ box-sizing: border-box; }}
body {{ margin:0; min-height:100vh; display:grid; place-items:center;
background:#0b0f14; color:#e6edf3; font:16px/1.5 system-ui,-apple-system,Segoe UI,sans-serif; }}
.card {{ width:min(92vw,380px); padding:2rem; background:#121820;
border:1px solid #223; border-radius:14px; text-align:center; }}
.icon {{ width:64px; height:64px; border-radius:14px; margin:0 auto 1rem; display:block; object-fit:cover; }}
.lettermark {{ display:grid; place-items:center; background:#1d2733; font-size:28px; font-weight:600; }}
h1 {{ font-size:1.15rem; margin:0 0 .25rem; }}
p.sub {{ margin:0 0 1.5rem; color:#8b98a5; font-size:.9rem; }}
input {{ width:100%; padding:.7rem .8rem; margin-bottom:.75rem; border-radius:9px;
border:1px solid #2b3947; background:#0d131a; color:#e6edf3; font-size:1rem; }}
input:focus {{ outline:2px solid #3b82f6; outline-offset:1px; }}
button {{ width:100%; padding:.7rem; border:0; border-radius:9px; background:#3b82f6;
color:#fff; font-size:1rem; font-weight:600; cursor:pointer; }}
button:hover {{ background:#2f6fd6; }}
.err {{ background:#3b1519; border:1px solid #7f1d1d; color:#fca5a5;
padding:.6rem .8rem; border-radius:9px; margin-bottom:1rem; font-size:.9rem; }}
</style></head>
<body><main class="card">{body}</main></body></html>"#,
title = esc(title),
app_name = esc(&app.app_name),
body = body,
);
Response::builder()
.status(status)
.header(header::CONTENT_TYPE, "text/html; charset=utf-8")
// The gate answers on the app's own port for an unauthenticated
// caller; nothing here should be cached or framed.
.header(header::CACHE_CONTROL, "no-store")
.header("X-Frame-Options", "DENY")
.header(
"Content-Security-Policy",
"default-src 'none'; img-src data:; style-src 'unsafe-inline'; form-action 'self'",
)
.body(Body::from(html))
.expect("static response builds")
}
/// The challenge. Names and pictures the app being opened, so the visitor can
/// confirm what they are authenticating to rather than being asked for a
/// password by an unexplained page.
fn login_page(app: &GatedPort, error: Option<&str>, status: StatusCode) -> Response<Body> {
let body = format!(
r#"{icon}
<h1>Sign in to open {name}</h1>
<p class="sub">This app is protected by your node password.</p>
{err}
<form method="post" action="{prefix}login">
<input type="password" name="password" placeholder="Node password" autocomplete="current-password" autofocus required>
<button type="submit">Sign in</button>
</form>"#,
icon = icon_markup(app),
name = esc(&app.app_name),
err = error
.map(|e| format!(r#"<div class="err">{}</div>"#, esc(e)))
.unwrap_or_default(),
prefix = GATE_PREFIX,
);
page("Sign in", app, &body, status)
}
/// Second factor. Reached only after the password verified, and the session
/// backing it cannot authorise anything until this completes.
fn totp_page(app: &GatedPort, error: Option<&str>, status: StatusCode) -> Response<Body> {
let body = format!(
r#"{icon}
<h1>Two-factor code</h1>
<p class="sub">Enter the 6-digit code to open {name}.</p>
{err}
<form method="post" action="{prefix}totp">
<input type="text" name="code" inputmode="numeric" pattern="[0-9]*" autocomplete="one-time-code" placeholder="000000" autofocus required>
<button type="submit">Verify</button>
</form>"#,
icon = icon_markup(app),
name = esc(&app.app_name),
err = error
.map(|e| format!(r#"<div class="err">{}</div>"#, esc(e)))
.unwrap_or_default(),
prefix = GATE_PREFIX,
);
page("Two-factor", app, &body, status)
}
#[cfg(test)]
mod tests {
use super::*;
fn app() -> GatedPort {
GatedPort {
port: 8090,
app_id: "strfry".to_string(),
app_name: "Strfry Relay".to_string(),
icon: None,
declared: true,
}
}
#[test]
fn bearer_token_is_parsed_case_insensitively() {
let mut headers = HeaderMap::new();
headers.insert(header::AUTHORIZATION, "Bearer abc123".parse().unwrap());
assert_eq!(bearer_token(&headers), Some("abc123".to_string()));
headers.insert(header::AUTHORIZATION, "bearer abc123".parse().unwrap());
assert_eq!(bearer_token(&headers), Some("abc123".to_string()));
}
#[test]
fn non_bearer_authorization_is_ignored() {
let mut headers = HeaderMap::new();
// An app's own Basic credential must never be mistaken for ours.
headers.insert(header::AUTHORIZATION, "Basic dXNlcjpwYXNz".parse().unwrap());
assert_eq!(bearer_token(&headers), None);
headers.insert(header::AUTHORIZATION, "Bearer ".parse().unwrap());
assert_eq!(bearer_token(&headers), None);
}
#[tokio::test]
async fn login_page_names_the_app() {
let resp = login_page(&app(), None, StatusCode::UNAUTHORIZED);
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
let body = hyper::body::to_bytes(resp.into_body()).await.unwrap();
let html = String::from_utf8_lossy(&body);
assert!(html.contains("Sign in to open Strfry Relay"));
// A lettermark stands in when the manifest declares no icon.
assert!(html.contains("lettermark"));
}
#[tokio::test]
async fn page_escapes_app_names() {
let mut app = app();
app.app_name = r#"<script>alert(1)</script>"#.to_string();
let resp = login_page(&app, None, StatusCode::UNAUTHORIZED);
let body = hyper::body::to_bytes(resp.into_body()).await.unwrap();
let html = String::from_utf8_lossy(&body);
assert!(!html.contains("<script>alert"));
assert!(html.contains("&lt;script&gt;"));
}
#[tokio::test]
async fn error_messages_are_escaped() {
let resp = login_page(
&app(),
Some("<img src=x onerror=1>"),
StatusCode::UNAUTHORIZED,
);
let body = hyper::body::to_bytes(resp.into_body()).await.unwrap();
let html = String::from_utf8_lossy(&body);
assert!(!html.contains("<img src=x"));
}
#[test]
fn challenge_pages_are_not_cacheable_or_framable() {
let resp = login_page(&app(), None, StatusCode::UNAUTHORIZED);
assert_eq!(resp.headers()[header::CACHE_CONTROL], "no-store");
assert_eq!(resp.headers()["X-Frame-Options"], "DENY");
}
#[tokio::test]
async fn form_parsing_decodes_percent_and_plus() {
let req = Request::builder()
.body(Body::from("password=a%40b+c&code=123456"))
.unwrap();
let form = read_form(req).await.unwrap();
assert_eq!(field(&form, "password"), Some("a@b c".to_string()));
assert_eq!(field(&form, "code"), Some("123456".to_string()));
}
#[tokio::test]
async fn oversized_form_bodies_are_refused() {
let req = Request::builder()
.body(Body::from("x=".to_string() + &"a".repeat(MAX_FORM_BYTES)))
.unwrap();
assert!(read_form(req).await.is_none());
}
#[tokio::test]
async fn no_credential_is_challenged() {
let gate = test_gate().await;
assert_eq!(
gate.authorize(&HeaderMap::new(), "strfry").await,
Authorization::Challenge
);
}
#[tokio::test]
async fn a_valid_session_cookie_is_allowed() {
let gate = test_gate().await;
let token = gate.sessions.create().await;
let mut headers = HeaderMap::new();
headers.insert(header::COOKIE, format!("session={token}").parse().unwrap());
assert_eq!(
gate.authorize(&headers, "strfry").await,
Authorization::Allow
);
}
/// The load-bearing 2FA property: a session still awaiting its TOTP code
/// fails `validate()`, so the gate rejects it without knowing anything
/// about second factors.
#[tokio::test]
async fn a_pending_2fa_session_is_challenged() {
let gate = test_gate().await;
let pending = gate.sessions.create_pending(vec![1, 2, 3]).await;
let mut headers = HeaderMap::new();
headers.insert(
header::COOKIE,
format!("session={pending}").parse().unwrap(),
);
assert_eq!(
gate.authorize(&headers, "strfry").await,
Authorization::Challenge
);
}
#[tokio::test]
async fn a_garbage_cookie_is_challenged() {
let gate = test_gate().await;
let mut headers = HeaderMap::new();
headers.insert(header::COOKIE, "session=deadbeef".parse().unwrap());
assert_eq!(
gate.authorize(&headers, "strfry").await,
Authorization::Challenge
);
}
async fn test_gate() -> AppGate {
let dir = std::env::temp_dir().join(format!("appgate-test-{}", std::process::id()));
let _ = std::fs::create_dir_all(&dir);
AppGate::new(
SessionStore::new().await,
AuthManager::new(dir.clone()),
LoginRateLimiter::new(),
dir,
)
}
}
@@ -0,0 +1,207 @@
//! The Claude leg of the D-04 backend chain — Anthropic Messages API with
//! `tools`/`tool_use`/`tool_result`. Modeled on
//! `mesh/listener/assist.rs::call_claude`'s HTTP client construction and
//! `api/rpc/mesh/assistant.rs`'s key-path convention, but NOT extended
//! in place: this is a new, tool-calling-capable request/response shape,
//! and its constants are new (AI-SPEC §3 Pitfall 6 — the mesh constants are
//! airtime-tuned for LoRa and must not be reused here).
use std::path::PathBuf;
use std::time::Duration;
use anyhow::Result;
use async_trait::async_trait;
use serde_json::{json, Value};
use super::{Backend, BackendTurn};
use crate::assistant::tools::{ChatMessage, Role, ToolCall, ToolDef};
const CLAUDE_URL: &str = "https://api.anthropic.com/v1/messages";
/// Kept in sync with `mesh/listener/assist.rs::CLAUDE_DEFAULT_MODEL` —
/// cheap and already proven fast enough; D-07 makes backend choice a
/// privacy/cost decision, not a capability-need one, so there is no reason
/// to default to a stronger model here.
const CLAUDE_MODEL: &str = "claude-haiku-4-5-20251001";
/// New, separate constant for the AIUI path's multi-turn tool loop (which
/// may include a network round trip) — NOT `assist.rs`'s `OLLAMA_TIMEOUT`
/// (60s, LoRa-airtime-tuned).
const ASSISTANT_HTTP_TIMEOUT: Duration = Duration::from_secs(180);
/// Raised from mesh's `512` — `tool_use` content blocks and multi-turn
/// reasoning need more headroom. Never left unbounded.
const ASSISTANT_MAX_TOKENS: u32 = 2048;
pub struct ClaudeBackend {
data_dir: PathBuf,
}
impl ClaudeBackend {
pub fn new(data_dir: PathBuf) -> Self {
Self { data_dir }
}
}
#[async_trait]
impl Backend for ClaudeBackend {
async fn send(
&self,
system: &str,
tools: &[ToolDef],
history: &[ChatMessage],
) -> Result<BackendTurn> {
// SAME key path `api/rpc/mesh/assistant.rs` probes — do not
// introduce a second key location (D-01, one key ledger).
let key = tokio::fs::read_to_string(self.data_dir.join("secrets/claude-api-key"))
.await
.map_err(|_| anyhow::anyhow!("Claude API key not configured on this node"))?;
let key = key.trim();
if key.is_empty() {
anyhow::bail!("Claude API key is empty");
}
let messages: Vec<Value> = history.iter().filter_map(message_to_wire).collect();
let claude_tools: Vec<Value> = tools
.iter()
.map(|t| {
json!({
"name": t.name,
"description": t.description,
"input_schema": t.parameters,
})
})
.collect();
let mut body = json!({
"model": CLAUDE_MODEL,
"max_tokens": ASSISTANT_MAX_TOKENS,
"system": system,
"messages": messages,
"stream": false,
});
if !claude_tools.is_empty() {
body["tools"] = json!(claude_tools);
// AI-SPEC §3 Pitfall 5: every tool_use.id from one assistant
// turn needs a matching tool_result before the next request.
// Disabling parallel tool use sidesteps that bookkeeping —
// D-06's tools are one deliberate action at a time anyway.
body["tool_choice"] = json!({"type": "auto", "disable_parallel_tool_use": true});
}
let client = reqwest::Client::builder()
.timeout(ASSISTANT_HTTP_TIMEOUT)
.build()?;
let resp = client
.post(CLAUDE_URL)
.header("x-api-key", key)
.header("anthropic-version", "2023-06-01")
.header("content-type", "application/json")
.json(&body)
.send()
.await?;
if !resp.status().is_success() {
let status = resp.status();
let txt = resp.text().await.unwrap_or_default();
anyhow::bail!(
"Claude API HTTP {}: {}",
status,
txt.chars().take(180).collect::<String>()
);
}
let json: Value = resp.json().await?;
let blocks = json
.get("content")
.and_then(|c| c.as_array())
.cloned()
.unwrap_or_default();
let mut tool_calls = Vec::new();
let mut text = String::new();
for block in &blocks {
match block.get("type").and_then(|t| t.as_str()) {
Some("tool_use") => {
let id = block
.get("id")
.and_then(|v| v.as_str())
.unwrap_or_default()
.to_string();
let name = block
.get("name")
.and_then(|v| v.as_str())
.unwrap_or_default()
.to_string();
let arguments = block.get("input").cloned().unwrap_or_else(|| json!({}));
tool_calls.push(ToolCall {
id,
name,
arguments,
});
}
Some("text") => {
if let Some(t) = block.get("text").and_then(|v| v.as_str()) {
text.push_str(t);
}
}
_ => {}
}
}
if !tool_calls.is_empty() {
Ok(BackendTurn::ToolCalls(tool_calls))
} else {
Ok(BackendTurn::Text(text))
}
}
}
/// Map one internal `ChatMessage` onto an Anthropic Messages API turn.
/// `Role::System` returns `None` — the system prompt is sent via the
/// top-level `system` field, not as a message in the array.
fn message_to_wire(msg: &ChatMessage) -> Option<Value> {
match msg.role {
Role::System => None,
Role::User => Some(json!({
"role": "user",
"content": msg.text.clone().unwrap_or_default(),
})),
Role::Assistant => {
if !msg.tool_calls.is_empty() {
let blocks: Vec<Value> = msg
.tool_calls
.iter()
.map(|c| {
json!({
"type": "tool_use",
"id": c.id,
"name": c.name,
"input": c.arguments,
})
})
.collect();
Some(json!({"role": "assistant", "content": blocks}))
} else {
Some(json!({
"role": "assistant",
"content": msg.text.clone().unwrap_or_default(),
}))
}
}
Role::Tool => {
let blocks: Vec<Value> = msg
.tool_results
.iter()
.map(|r| {
json!({
"type": "tool_result",
"tool_use_id": r.call_id,
"content": r.content,
"is_error": r.is_error,
})
})
.collect();
// Anthropic's tool_result blocks travel back as a "user" turn.
Some(json!({"role": "user", "content": blocks}))
}
}
}
@@ -0,0 +1,35 @@
//! The `Backend` trait — the wire-format-agnostic seam every model backend
//! (Ollama, Claude, Routstr) implements once. The loop and every tool are
//! written against this trait only; wire-format differences live entirely
//! inside each adapter.
use std::path::Path;
use anyhow::Result;
use async_trait::async_trait;
use super::tools::{ChatMessage, ToolCall, ToolDef};
pub mod claude;
#[cfg(test)]
pub mod scripted;
pub enum BackendTurn {
Text(String),
ToolCalls(Vec<ToolCall>),
}
#[async_trait]
pub trait Backend: Send + Sync {
async fn send(&self, system: &str, tools: &[ToolDef], history: &[ChatMessage]) -> Result<BackendTurn>;
}
/// D-04's backend chain: local Ollama first (node data never leaves the
/// node when a local model is available), then Claude, then Routstr. Only
/// the Claude leg is implemented in this tracer — `backends/ollama.rs`
/// (13-10) and `backends/routstr.rs` (13-13) slot in ahead of and behind it
/// without changing the `Backend` trait; that is the architectural
/// commitment this tracer proves.
pub fn select_backend(data_dir: &Path) -> Box<dyn Backend> {
Box::new(claude::ClaudeBackend::new(data_dir.to_path_buf()))
}
@@ -0,0 +1,44 @@
//! Test-only backend that replays a canned sequence of turns. Never
//! compiles into the shipped binary — gated by `#![cfg(test)]` here AND by
//! `#[cfg(test)] pub mod scripted;` in `backends/mod.rs`.
#![cfg(test)]
use std::sync::Mutex;
use anyhow::Result;
use async_trait::async_trait;
use super::{Backend, BackendTurn};
use crate::assistant::tools::{ChatMessage, ToolDef};
pub struct ScriptedBackend {
turns: Mutex<Vec<BackendTurn>>,
}
impl ScriptedBackend {
/// `turns` are consumed in the order given — the first call to `send()`
/// returns `turns[0]`, the second `turns[1]`, and so on.
pub fn new(turns: Vec<BackendTurn>) -> Self {
let mut turns = turns;
turns.reverse();
Self {
turns: Mutex::new(turns),
}
}
}
#[async_trait]
impl Backend for ScriptedBackend {
async fn send(
&self,
_system: &str,
_tools: &[ToolDef],
_history: &[ChatMessage],
) -> Result<BackendTurn> {
let mut turns = self.turns.lock().expect("ScriptedBackend mutex poisoned");
turns
.pop()
.ok_or_else(|| anyhow::anyhow!("ScriptedBackend exhausted — no more turns queued"))
}
}
+237
View File
@@ -0,0 +1,237 @@
//! The multi-turn tool-calling loop (D-01/D-02). No analog exists elsewhere
//! in this codebase — this is the first tool-calling agent loop ever
//! written here (confirmed by 13-RESEARCH.md/13-AI-SPEC.md); built directly
//! from `13-AI-SPEC.md` §3/§4's sketch.
//!
//! Concurrency discipline inherited from `mesh/listener/assist.rs`'s own
//! doc comment ("Spawned off the radio loop so it never blocks"): never
//! hold a shared lock across a `.await` that can block for human-response
//! time. `execute_tool` below holds no lock at all in this tracer — there
//! is nothing yet to hold one across (13-08's confirm gate is what
//! introduces that discipline requirement for real).
use anyhow::Result;
use super::backends::{Backend, BackendTurn};
use super::tools::{ChatMessage, Role, ToolCall, ToolResult};
use super::tools::ToolDef;
use super::ToolExecCtx;
/// Hard stop — a looping model must never spin unbounded (D-05).
pub const MAX_TURNS: usize = 8;
pub async fn run_loop(
backend: &dyn Backend,
system: &str,
tools: &[ToolDef],
mut history: Vec<ChatMessage>,
ctx: &ToolExecCtx,
) -> Result<String> {
for _ in 0..MAX_TURNS {
match backend.send(system, tools, &history).await? {
BackendTurn::Text(answer) => return Ok(answer),
BackendTurn::ToolCalls(calls) => {
history.push(ChatMessage {
role: Role::Assistant,
text: None,
tool_calls: calls.clone(),
tool_results: vec![],
});
let mut results = Vec::with_capacity(calls.len());
for call in &calls {
results.push(execute_tool(call, ctx).await);
}
history.push(ChatMessage {
role: Role::Tool,
text: None,
tool_calls: vec![],
tool_results: results,
});
}
}
}
anyhow::bail!("assistant loop exceeded MAX_TURNS without a final answer — stopping, not looping forever")
}
/// The single choke point every tool call passes through, regardless of
/// which backend produced it. Enforces, in order: D-06 (curated allowlist —
/// unknown names are refused, never silently ignored), D-16 (default-closed
/// category grants — re-checked here even though the system prompt already
/// omits ungranted tools; never trust that as the only enforcement layer),
/// schema validation (never coerce, never guess), and D-07 (every
/// destructive tool suspends for confirmation — 13-08 fills that branch in;
/// there are no destructive tools registered yet, so it is unreachable
/// today).
async fn execute_tool(call: &ToolCall, ctx: &ToolExecCtx) -> ToolResult {
let Some(tool) = ctx.registry.get(&call.name) else {
return ToolResult {
call_id: call.id.clone(),
is_error: true,
content: format!("no such tool: {}", call.name),
};
};
if !ctx.caller.granted_categories().contains(&tool.category) {
return ToolResult {
call_id: call.id.clone(),
is_error: true,
content: "not permitted — this category is not granted".to_string(),
};
}
if let Err(e) = tool.validate(&call.arguments) {
return ToolResult {
call_id: call.id.clone(),
is_error: true,
content: format!("invalid arguments: {e}"),
};
}
if tool.destructive {
return ToolResult {
call_id: call.id.clone(),
is_error: true,
content: "destructive tool execution is not yet implemented".to_string(),
};
}
match call.name.as_str() {
// Dispatches to the SAME RpcHandler method every other authenticated
// caller uses (no AI-only backdoor) — see `assistant_dispatch_tool`
// in `api/rpc/assistant_chat.rs` for why this bridge exists.
"system_disk_status" => match ctx
.handler
.assistant_dispatch_tool("system.disk-status")
.await
{
Ok(v) => ToolResult {
call_id: call.id.clone(),
is_error: false,
content: v.to_string(),
},
Err(e) => ToolResult {
call_id: call.id.clone(),
is_error: true,
content: format!("tool execution failed: {e}"),
},
},
other => ToolResult {
call_id: call.id.clone(),
is_error: true,
content: format!("no execution wired for tool: {other}"),
},
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::assistant::backends::scripted::ScriptedBackend;
use crate::assistant::tools::{registry, system_disk_status_tool};
use crate::assistant::{CallerScope, PermissionCategory};
use crate::api::rpc::RpcHandler;
use serde_json::json;
use std::sync::Arc;
/// A minimal but real `RpcHandler` for tests: a fresh temp `data_dir`
/// (no `/var/lib/archipelago` writes), no orchestrator (container RPCs
/// aren't exercised here), matching the doc comment on `orchestrator`
/// that this is exactly why the field is `Option`.
async fn test_rpc_handler() -> (Arc<RpcHandler>, tempfile::TempDir) {
let tmp = tempfile::tempdir().expect("tempdir");
let mut config = crate::config::Config::default();
config.data_dir = tmp.path().to_path_buf();
let state_manager = Arc::new(crate::state::StateManager::new());
let metrics_store = Arc::new(crate::monitoring::MetricsStore::new());
let session_store =
crate::session::SessionStore::new_for_tests(tmp.path().join("sessions.json"));
let handler = RpcHandler::new(
config,
state_manager,
metrics_store,
session_store,
None,
None,
)
.await
.expect("RpcHandler::new");
(Arc::new(handler), tmp)
}
fn local_operator_ctx(handler: Arc<RpcHandler>) -> ToolExecCtx {
ToolExecCtx {
registry: registry(),
caller: CallerScope::LocalOperator {
session_id: "test-session".to_string(),
},
handler,
}
}
#[tokio::test]
async fn disk_status_tool_executes() {
let (handler, _tmp) = test_rpc_handler().await;
// The real figures the tool path returns must match what the SAME
// handler returns when dispatched directly — proving `execute_tool`
// is not a parallel, AI-only code path.
let direct = handler
.assistant_dispatch_tool("system.disk-status")
.await
.expect("direct dispatch");
let ctx = local_operator_ctx(handler.clone());
let call = ToolCall {
id: "call-1".to_string(),
name: "system_disk_status".to_string(),
arguments: json!({}),
};
let result = execute_tool(&call, &ctx).await;
assert!(!result.is_error, "tool call errored: {}", result.content);
assert_eq!(result.content, direct.to_string());
assert!(result.content.contains("total_bytes"));
// Exercise the whole loop: a ScriptedBackend that names the tool,
// then answers — proving the real figures reached the final answer
// path (the answer itself is the second scripted turn, matching
// AI-SPEC's run_loop shape; the tool result that fed into it is
// asserted above).
let backend = ScriptedBackend::new(vec![
BackendTurn::ToolCalls(vec![call.clone()]),
BackendTurn::Text("Disk space report generated.".to_string()),
]);
let tools_list = vec![system_disk_status_tool()];
let answer = run_loop(&backend, "system prompt", &tools_list, vec![], &ctx)
.await
.expect("run_loop");
assert_eq!(answer, "Disk space report generated.");
}
#[tokio::test]
async fn unknown_tool_is_refused_not_ignored() {
let (handler, _tmp) = test_rpc_handler().await;
let ctx = local_operator_ctx(handler);
let call = ToolCall {
id: "call-1".to_string(),
name: "delete_everything".to_string(),
arguments: json!({}),
};
let result = execute_tool(&call, &ctx).await;
assert!(result.is_error);
assert!(result.content.contains("no such tool"), "{}", result.content);
}
/// Phase-10 hard constraint: `assistant.*` must never be reachable
/// unauthenticated. Asserted directly against the live list, not
/// assumed.
#[test]
fn assistant_methods_require_session() {
let has_assistant_method = crate::api::rpc::UNAUTHENTICATED_METHODS
.iter()
.any(|m| m.starts_with("assistant."));
assert!(
!has_assistant_method,
"assistant.* must never be added to UNAUTHENTICATED_METHODS (Phase-10 hard constraint)"
);
}
}
+125
View File
@@ -0,0 +1,125 @@
//! D-02: "one assistant, many front doors." A shared assistant service —
//! one curated tool registry, one backend selector, one place the model key
//! lives — used today by AIUI chat (`CallerScope::LocalOperator`) and, by
//! design, extensible to mesh/LoRa callers (`CallerScope::Mesh`) and later
//! Pine voice without recreating a second, divergent security model.
//!
//! This is the tracer slice for Phase 13 (D-01, D-02, D-06): a typed
//! question reaches exactly one curated, read-only tool
//! (`tools::system_disk_status_tool`) via the Claude backend, dispatched
//! through the SAME `handle_system_disk_status` RPC handler every other
//! authenticated caller uses. See `13-01-PLAN.md` for the full spine.
pub mod backends;
pub mod loop_;
pub mod tools;
use std::collections::BTreeSet;
use std::sync::Arc;
use anyhow::Result;
use crate::api::rpc::RpcHandler;
/// D-16's ten permission categories. All default-closed on a fresh node —
/// nothing is shared with the model until deliberately granted.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum PermissionCategory {
Apps,
System,
Network,
Wallet,
Files,
Media,
Search,
AiLocal,
Notes,
Bitcoin,
}
/// D-02's promoted primary noun: a caller identity carrying the permission
/// scope its tool calls resolve authority through. "A mesh peer" and "the
/// local operator in AIUI" are two variants of it; Pine voice will be a
/// third (not built in this phase — no `Voice` variant exists yet, by
/// design, until that phase actually needs one).
#[derive(Debug, Clone)]
pub enum CallerScope {
/// A mesh/LoRa peer. Not exercised by this plan (mesh's existing
/// `!ai` path is Q&A-only, per `mesh/listener/assist.rs`'s own doc
/// comment) — the variant exists so the shape is right when a future
/// plan wires mesh callers into the shared loop.
Mesh { peer_id: String },
/// The authenticated operator using AIUI, identified by their neode-ui
/// session. This is the only variant this tracer's `assistant.chat`
/// RPC constructs.
LocalOperator { session_id: String },
}
impl CallerScope {
/// The sole source of tool authority `execute_tool` reads. No
/// `execute_tool` branch may read a caller-specific field directly
/// instead of going through this — that would reintroduce the
/// mesh-only assumption D-02 exists to retire.
pub fn granted_categories(&self) -> BTreeSet<PermissionCategory> {
match self {
// 13-05 replaces this hardcoded default with the persisted
// D-16 default-closed grants store — a data-source change, not
// an architectural one (per the plan's assumption-delta note).
CallerScope::LocalOperator { .. } => {
let mut set = BTreeSet::new();
set.insert(PermissionCategory::System);
set
}
// Intentionally conservative for this tracer: mesh has no
// tool-calling caller path wired up yet (today's mesh `!ai` is
// Q&A-only), so there is no real trusted_only/allowed_contacts
// grant to resolve. A future plan that wires the Mesh variant
// into the shared loop threads those existing per-caller
// controls through here — this is explicitly NOT the place a
// mesh-only field gets read directly by `execute_tool`.
CallerScope::Mesh { .. } => BTreeSet::new(),
}
}
}
/// Bundles what `execute_tool` needs regardless of which backend produced
/// the tool call: the curated registry, the caller's resolved authority,
/// and a handle back to the SAME `RpcHandler` every other authenticated
/// caller dispatches through — never an AI-only backdoor.
pub struct ToolExecCtx {
pub registry: tools::ToolRegistry,
pub caller: CallerScope,
pub handler: Arc<RpcHandler>,
}
/// Entry point: run one chat turn for `caller` through the shared loop.
/// Builds the visible-tool set from the caller's granted categories only
/// (D-16 — the model should never even see a tool it can't use), selects a
/// backend (Claude only, in this tracer), and runs it to a final answer.
pub async fn chat(handler: Arc<RpcHandler>, caller: CallerScope, user_text: String) -> Result<String> {
let registry = tools::registry();
let grants = caller.granted_categories();
let visible_tools = registry.visible_to(&grants);
let backend = backends::select_backend(handler.data_dir());
let system_prompt = "You are the Archipelago node's operator-control assistant. \
Only use the tools explicitly listed for this turn never invent a tool name or call \
one that isn't listed. Every write requires human confirmation you cannot bypass or \
pre-approve on the user's behalf.";
let history = vec![tools::ChatMessage {
role: tools::Role::User,
text: Some(user_text),
tool_calls: vec![],
tool_results: vec![],
}];
let ctx = ToolExecCtx {
registry,
caller,
handler,
};
loop_::run_loop(backend.as_ref(), system_prompt, &visible_tools, history, &ctx).await
}
+170
View File
@@ -0,0 +1,170 @@
//! D-06: a curated, hand-written tool registry. Never derived from
//! `api::rpc::dispatcher`'s method table — every capability the chat has is
//! a deliberate decision recorded here, and the model never sees the full
//! RPC surface. No `schemars` — that crate is absent from `Cargo.toml` and
//! from 13-RESEARCH.md's Package Legitimacy Audit, so `parameters` below is
//! a hand-written JSON Schema object literal instead.
use std::collections::{BTreeSet, HashMap};
use anyhow::{Context, Result};
use serde::Deserialize;
use serde_json::{json, Value};
use super::PermissionCategory;
/// The backend-agnostic in/out of a tool invocation — the same shape
/// regardless of which adapter (Ollama/Claude/Routstr) produced it.
#[derive(Debug, Clone)]
pub struct ToolCall {
pub id: String,
pub name: String,
pub arguments: Value,
}
#[derive(Debug, Clone)]
pub struct ToolResult {
pub call_id: String,
pub content: String,
pub is_error: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Role {
System,
User,
Assistant,
Tool,
}
#[derive(Debug, Clone)]
pub struct ChatMessage {
pub role: Role,
/// Plain text, or (a future plan's) D-10-wrapped untrusted content.
pub text: Option<String>,
/// Assistant-authored tool calls made THIS turn (role: Assistant).
pub tool_calls: Vec<ToolCall>,
/// Tool results fed back THIS turn (role: Tool).
pub tool_results: Vec<ToolResult>,
}
/// D-06: one curated, hand-written tool. Never generated from the RPC
/// dispatcher — the curated set IS the D-09 authority boundary.
#[derive(Clone)]
pub struct ToolDef {
pub name: &'static str,
pub description: &'static str,
/// JSON Schema `{"type":"object","properties":{...},"required":[...]}`,
/// hand-written and pinned adjacent to the args struct it must never
/// drift from — see `disk_status_schema_round_trips_required_keys`.
pub parameters: Value,
pub category: PermissionCategory,
/// D-07: true => confirm gate, no exceptions. There are no destructive
/// tools in this tracer's registry; `execute_tool` refuses this branch
/// with a not-yet-implemented error until 13-08 fills it in.
pub destructive: bool,
}
/// Args for `system_disk_status` — takes no parameters.
#[derive(Debug, Deserialize)]
pub struct SystemDiskStatusArgs {}
impl ToolDef {
/// Deserialize + validate model-produced arguments before ANY
/// execution. Never coerce, never guess, never panic on a mismatch —
/// refuse and let the caller turn the error into a tool result the
/// model can recover from.
///
/// This tracer's registry has exactly one tool, so this is a direct
/// deserialize; a future plan adding a second tool dispatches by
/// `self.name` here before deserializing into that tool's own args type.
pub fn validate(&self, raw: &Value) -> Result<SystemDiskStatusArgs> {
serde_json::from_value(raw.clone())
.context("tool arguments did not match the declared schema")
}
}
/// `system_disk_status` — category `System`, read-only. Reports free and
/// total disk space on this node via the same `system.disk-status` handler
/// every other authenticated caller uses.
pub fn system_disk_status_tool() -> ToolDef {
ToolDef {
name: "system_disk_status",
description: "Report free and total disk space on this Archipelago node.",
parameters: json!({
"type": "object",
"properties": {},
"required": [],
}),
category: PermissionCategory::System,
destructive: false,
}
}
/// D-06's curated allowlist, name-indexed.
pub struct ToolRegistry {
tools: HashMap<&'static str, ToolDef>,
}
impl ToolRegistry {
pub fn get(&self, name: &str) -> Option<&ToolDef> {
self.tools.get(name)
}
/// The subset of the registry visible to a caller with `grants`. D-16:
/// an unconfigured node's system prompt should advertise close to zero
/// tools — the model should never even see a tool it can't use.
pub fn visible_to(&self, grants: &BTreeSet<PermissionCategory>) -> Vec<ToolDef> {
self.tools
.values()
.filter(|t| grants.contains(&t.category))
.cloned()
.collect()
}
}
/// The curated D-06 registry. This tracer registers exactly one tool.
pub fn registry() -> ToolRegistry {
let mut tools = HashMap::new();
let tool = system_disk_status_tool();
tools.insert(tool.name, tool);
ToolRegistry { tools }
}
#[cfg(test)]
mod tests {
use super::*;
/// The schema sent to the model and the struct used to deserialize its
/// output must never silently drift apart. Round-trip the schema's
/// declared `required` keys through the args struct.
#[test]
fn disk_status_schema_round_trips_required_keys() {
let tool = system_disk_status_tool();
let required = tool
.parameters
.get("required")
.and_then(|r| r.as_array())
.cloned()
.unwrap_or_default();
let mut obj = serde_json::Map::new();
for key in &required {
if let Some(k) = key.as_str() {
obj.insert(k.to_string(), Value::Null);
}
}
let value = Value::Object(obj);
let parsed: Result<SystemDiskStatusArgs, _> = serde_json::from_value(value);
assert!(parsed.is_ok(), "schema/args struct drift: {:?}", parsed.err());
}
#[test]
fn registry_visible_to_respects_grants() {
let reg = registry();
let mut grants = BTreeSet::new();
assert!(reg.visible_to(&grants).is_empty());
grants.insert(PermissionCategory::System);
assert_eq!(reg.visible_to(&grants).len(), 1);
}
}
-3
View File
@@ -82,9 +82,6 @@ pub struct User {
pub role: UserRole,
}
/// Cloneable: it holds only the data dir, and the app gate needs its own
/// handle to verify passwords on a different port from the JSON-RPC path.
#[derive(Clone)]
pub struct AuthManager {
data_dir: PathBuf,
}
@@ -216,46 +216,6 @@ pub fn catalog_manifest_values() -> Vec<(String, serde_json::Value)> {
.collect()
}
/// A catalog-embedded manifest as the node actually applies it: parsed,
/// id-checked, validated, and image-only (build-source manifests defer to
/// disk). `None` = the caller must fall back to the disk manifest.
///
/// Shared between the orchestrator's load overlay and the app gate's port
/// classification so both answer "which manifest governs this app?" from the
/// same origin. They diverged once — the orchestrator published containers
/// from the catalog while the gate classified from stale disk manifests, and
/// the gate externally bound a port the catalog had declared `auth: local`
/// (nbxplorer 32838, archi-dev-box 2026-08-04).
pub fn catalog_manifest_overlay(
app_id: &str,
value: serde_json::Value,
) -> Option<archipelago_container::manifest::AppManifest> {
let m: archipelago_container::manifest::AppManifest = match serde_json::from_value(value) {
Ok(m) => m,
Err(e) => {
tracing::warn!(app = %app_id, error = %e,
"skipping unparseable catalog manifest; using disk fallback");
return None;
}
};
if m.app.id != app_id {
tracing::warn!(catalog_id = %app_id, manifest_id = %m.app.id,
"skipping catalog manifest: embedded app id mismatches catalog key");
return None;
}
if let Err(e) = m.validate() {
tracing::warn!(app = %app_id, error = %e,
"skipping invalid catalog manifest; using disk fallback");
return None;
}
if m.app.container.build.is_some() {
tracing::debug!(app = %app_id,
"catalog manifest has a build source; deferring to disk (phase 1 = image-only)");
return None;
}
Some(m)
}
/// The catalog's default/latest version string for an app (the top-level
/// `version` field), if covered. Used to decide whether an install-time
/// selection should pin (older) or track-latest (default).
+6 -63
View File
@@ -252,24 +252,8 @@ async fn ensure_image_present(spec: &CompanionSpec) -> Result<String> {
} else {
info!(companion = spec.name, "building locally from {dir}");
}
// Stamp the context mtime we are building, so the staleness
// check has something that advances even when every layer is a
// cache hit. Without this the rebuild is a no-op that leaves
// .Created unchanged, the check stays true, and the companion is
// rebuilt on every reconcile tick forever.
let context_stamp = newest_mtime_unix(PathBuf::from(dir))
.await
.unwrap_or_default();
let stamp_label = format!("{CONTEXT_STAMP_LABEL}={context_stamp}");
let out = command_output_with_timeout(
Command::new("podman").args([
"build",
"--label",
&stamp_label,
"-t",
&local_image,
dir,
]),
Command::new("podman").args(["build", "-t", &local_image, dir]),
COMPANION_BUILD_TIMEOUT,
"podman build companion image",
)
@@ -338,58 +322,17 @@ async fn image_exists(image: &str) -> bool {
/// already-built `image`, signalling the cached image is stale and must be
/// rebuilt. Conservative: if either timestamp can't be determined we return
/// false (reuse the cache) to avoid rebuild storms on every reconcile pass.
/// Label carrying the context mtime an image was built from.
///
/// The reason this exists rather than reusing `.Created`: a rebuild whose
/// layers all hit the cache produces the SAME image, and podman leaves its
/// creation time untouched. Comparing against `.Created` therefore never
/// converges — the rebuild does not change the thing being tested, so the
/// companion is rebuilt on every reconcile tick indefinitely. A label is part
/// of the image config, so writing a new value always yields a new image,
/// which makes the comparison settle after exactly one rebuild.
const CONTEXT_STAMP_LABEL: &str = "org.archipelago.context-mtime";
async fn context_is_newer_than_image(dir: &str, image: &str) -> bool {
let Some(ctx) = newest_mtime_unix(PathBuf::from(dir)).await else {
return false;
let image_created = match image_created_unix(image).await {
Some(t) => t,
None => return false,
};
// Preferred: what the last build actually stamped.
if let Some(stamped) = image_context_stamp(image).await {
return ctx > stamped;
}
// Images built before stamping existed have no label. Fall back to the
// old comparison so behaviour is unchanged for them; the rebuild it
// triggers writes the label, so each such image self-heals exactly once.
match image_created_unix(image).await {
Some(created) => ctx > created,
match newest_mtime_unix(PathBuf::from(dir)).await {
Some(ctx) => ctx > image_created,
None => false,
}
}
/// The context mtime stamped into `image` at build time, if any.
async fn image_context_stamp(image: &str) -> Option<i64> {
let format = format!("{{{{index .Config.Labels \"{CONTEXT_STAMP_LABEL}\"}}}}");
let mut cmd = Command::new("podman");
cmd.args(["image", "inspect", "--format", &format, image]);
let out = command_output_with_timeout(
&mut cmd,
COMPANION_IMAGE_CHECK_TIMEOUT,
"podman image context stamp",
)
.await
.ok()?;
if !out.status.success() {
return None;
}
let raw = String::from_utf8_lossy(&out.stdout);
let raw = raw.trim();
// podman prints "<no value>" for a missing label.
if raw.is_empty() || raw == "<no value>" {
return None;
}
raw.parse::<i64>().ok()
}
/// Build timestamp of `image` as Unix seconds, via `podman image inspect`.
async fn image_created_unix(image: &str) -> Option<i64> {
let mut cmd = Command::new("podman");
@@ -595,20 +595,10 @@ async fn wait_for_manifest_host_ports(
/// `podman inspect --format '{{json .HostConfig.PortBindings}}'` emits, e.g.
/// `{"8080/tcp":[{"HostIp":"","HostPort":"18080"}]}`. Returns true only when a
/// manifest container-port is positively published to a *different* host port
/// than the manifest now asks for — or, when the manifest DECLARES a bind
/// address, to a different host address. Absence of a binding is deliberately
/// NOT treated as drift here — that case is handled by the host-port
/// repair/restart path and by host-networked apps that publish nothing — so we
/// never trigger a destructive recreate on a false positive.
///
/// The bind comparison is what lets a node self-heal after a catalog refresh
/// pins an app to loopback for the app gate: a legacy (pre-quadlet) container
/// still publishing `0.0.0.0:P` against a manifest that now declares
/// `bind: 127.0.0.1` is recreated to the declared state, exactly as
/// `package.update` would. An EMPTY manifest bind means "no instruction" and
/// never fires this — recreating a loopback-published container to wildcard on
/// silence is precisely the v1.7.121 incident class (Bitcoin RPC republished
/// on the LAN).
/// than the manifest now asks for. Absence of a binding is deliberately NOT
/// treated as drift here — that case is handled by the host-port repair/restart
/// path and by host-networked apps that publish nothing — so we never trigger a
/// destructive recreate on a false positive.
fn host_port_bindings_drifted(
port_bindings_json: &str,
manifest_ports: &[archipelago_container::manifest::PortMapping],
@@ -636,26 +626,10 @@ fn host_port_bindings_drifted(
}
let expected = port.host.to_string();
let matches_expected = bindings.iter().any(|b| {
let host_port_ok = b
.get("HostPort")
b.get("HostPort")
.and_then(|h| h.as_str())
.map(|h| h == expected)
.unwrap_or(false);
if !host_port_ok {
return false;
}
// Only a DECLARED bind participates; podman reports a wildcard
// publish as "" or "0.0.0.0".
if port.bind.is_empty() {
return true;
}
let actual_ip = b.get("HostIp").and_then(|h| h.as_str()).unwrap_or("");
let actual = if actual_ip.is_empty() {
"0.0.0.0"
} else {
actual_ip
};
actual == port.bind
.unwrap_or(false)
});
if !matches_expected {
return true;
@@ -1183,7 +1157,30 @@ struct LoadedManifest {
/// source (build contexts aren't registry-distributed yet — phase 1 is
/// image-only). See `docs/registry-manifest-design.md`.
fn catalog_manifest_to_overlay(app_id: &str, value: serde_json::Value) -> Option<AppManifest> {
crate::container::app_catalog::catalog_manifest_overlay(app_id, value)
let m: AppManifest = match serde_json::from_value(value) {
Ok(m) => m,
Err(e) => {
tracing::warn!(app = %app_id, error = %e,
"skipping unparseable catalog manifest; using disk fallback");
return None;
}
};
if m.app.id != app_id {
tracing::warn!(catalog_id = %app_id, manifest_id = %m.app.id,
"skipping catalog manifest: embedded app id mismatches catalog key");
return None;
}
if let Err(e) = m.validate() {
tracing::warn!(app = %app_id, error = %e,
"skipping invalid catalog manifest; using disk fallback");
return None;
}
if m.app.container.build.is_some() {
tracing::debug!(app = %app_id,
"catalog manifest has a build source; deferring to disk (phase 1 = image-only)");
return None;
}
Some(m)
}
struct OrchestratorState {
@@ -4438,8 +4435,6 @@ mod tests {
container,
protocol: "tcp".to_string(),
bind: String::new(),
auth: None,
auth_rationale: None,
}
}
@@ -4572,76 +4567,6 @@ mod tests {
));
}
fn bound_port(
host: u16,
container: u16,
bind: &str,
) -> archipelago_container::manifest::PortMapping {
archipelago_container::manifest::PortMapping {
bind: bind.to_string(),
..port(host, container)
}
}
#[test]
fn bind_drift_detected_when_declared_loopback_but_published_wildcard() {
// The legacy-container case: a pre-quadlet container still publishes
// 0.0.0.0 while the catalog-delivered manifest pins the app to
// loopback for the app gate. Must recreate, or the port stays open on
// every interface and the gate can never claim it.
for wildcard in [r#""""#, r#""0.0.0.0""#] {
let bindings = format!(r#"{{"80/tcp":[{{"HostIp":{wildcard},"HostPort":"8082"}}]}}"#);
assert!(host_port_bindings_drifted(
&bindings,
&[bound_port(8082, 80, "127.0.0.1")]
));
}
}
#[test]
fn no_bind_drift_when_declared_loopback_and_published_loopback() {
let bindings = r#"{"80/tcp":[{"HostIp":"127.0.0.1","HostPort":"8082"}]}"#;
assert!(!host_port_bindings_drifted(
bindings,
&[bound_port(8082, 80, "127.0.0.1")]
));
}
#[test]
fn no_bind_drift_on_undeclared_bind() {
// Silence is not consent (v1.7.121 incident class): an EMPTY manifest
// bind must never recreate a loopback-published container to
// wildcard — that is how Bitcoin's RPC got republished on the LAN.
let bindings = r#"{"8332/tcp":[{"HostIp":"127.0.0.1","HostPort":"8332"}]}"#;
assert!(!host_port_bindings_drifted(bindings, &[port(8332, 8332)]));
}
#[test]
fn multi_bind_publish_satisfies_each_declared_entry() {
// Same host/container pair listed twice (loopback + archy-net
// gateway): both declared binds are present in the actual publish.
let bindings = r#"{"8332/tcp":[
{"HostIp":"127.0.0.1","HostPort":"8332"},
{"HostIp":"10.89.0.1","HostPort":"8332"}
]}"#;
assert!(!host_port_bindings_drifted(
bindings,
&[
bound_port(8332, 8332, "127.0.0.1"),
bound_port(8332, 8332, "10.89.0.1")
]
));
// And a wildcard-only publish drifts BOTH declared entries.
let wildcard = r#"{"8332/tcp":[{"HostIp":"","HostPort":"8332"}]}"#;
assert!(host_port_bindings_drifted(
wildcard,
&[
bound_port(8332, 8332, "127.0.0.1"),
bound_port(8332, 8332, "10.89.0.1")
]
));
}
#[test]
fn missing_secret_error_names_the_secret() {
use archipelago_container::manifest::SecretsProvider;
-56
View File
@@ -26,29 +26,6 @@ pub struct DeviceToken {
pub hash: String,
/// Unix seconds at mint time.
pub created: u64,
/// App ids this token may reach through the app gate.
///
/// `None` means node-wide, which is what every companion pairing token
/// is and what tokens minted before scoping existed remain — the field
/// is absent from their stored JSON and deserialises to `None`. A
/// migration that guessed a scope for them would silently revoke access
/// the operator never asked to revoke.
///
/// `Some(list)` restricts the token to exactly those apps, which is the
/// point of scoping: a token handed to Home Assistant so it can poll one
/// app's API should not also open every other app on the node.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub apps: Option<Vec<String>>,
}
impl DeviceToken {
/// Whether this token may reach `app_id`.
pub fn allows_app(&self, app_id: &str) -> bool {
match &self.apps {
None => true,
Some(apps) => apps.iter().any(|a| a == app_id),
}
}
}
fn tokens_path(data_dir: &Path) -> PathBuf {
@@ -84,22 +61,6 @@ fn ct_eq(a: &[u8], b: &[u8]) -> bool {
/// replaced, so re-showing the pairing QR never piles up stale entries.
/// Returns the plaintext token — the only time it ever exists outside the QR.
pub async fn create(data_dir: &Path, name: &str) -> Result<String> {
create_scoped(data_dir, name, None).await
}
/// Mint a token limited to `apps`, for a machine client that needs one app's
/// HTTP API and nothing else. `None` mints the node-wide token `create` does.
pub async fn create_scoped(
data_dir: &Path,
name: &str,
apps: Option<Vec<String>>,
) -> Result<String> {
// An empty list would be indistinguishable from "no restriction" to a
// careless reader while actually authorising nothing — reject it rather
// than mint a token whose behaviour nobody can predict from its record.
if apps.as_ref().is_some_and(|a| a.is_empty()) {
anyhow::bail!("a scoped device token must name at least one app");
}
// KEY-05: a device token is a bearer credential — its unpredictability is
// the whole of its security — so the source is named and the draw guarded.
let mut token_bytes = [0u8; 32];
@@ -120,7 +81,6 @@ pub async fn create_scoped(
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0),
apps,
});
save(data_dir, &tokens).await?;
Ok(token)
@@ -136,22 +96,6 @@ pub async fn verify(data_dir: &Path, candidate: &str) -> Option<String> {
.map(|t| t.name.clone())
}
/// Verify a candidate token **for a specific app**, as the app gate does.
/// Returns the device name when the token is valid *and* in scope.
///
/// Separate from `verify` on purpose: `verify` answers "is this a real
/// token", which is the right question for node login, and would be the
/// wrong question here — a token scoped to one app would otherwise open
/// every app.
pub async fn verify_for_app(data_dir: &Path, candidate: &str, app_id: &str) -> Option<String> {
let candidate_hash = hash_hex(candidate);
load(data_dir)
.await
.iter()
.find(|t| ct_eq(t.hash.as_bytes(), candidate_hash.as_bytes()) && t.allows_app(app_id))
.map(|t| t.name.clone())
}
/// List stored tokens (hashes only — plaintexts are unrecoverable).
pub async fn list(data_dir: &Path) -> Vec<DeviceToken> {
load(data_dir).await
+3 -58
View File
@@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize};
use std::path::Path;
use tokio::fs;
use super::types::{FederatedNode, FederationInvite, NodeStateSnapshot, TrustLevel, TrustSource};
use super::types::{FederatedNode, FederationInvite, NodeStateSnapshot, TrustLevel};
pub(crate) const FEDERATION_DIR: &str = "federation";
pub(crate) const NODES_FILE: &str = "nodes.json";
@@ -392,19 +392,10 @@ async fn untombstone_did_inner(data_dir: &Path, did: &str) -> Result<()> {
Ok(())
}
/// Change a federated node's trust level, optionally recording HOW the change
/// came about.
///
/// `source` is `Some(TrustSource::Manual)` on the operator RPC path so an
/// audit of `trust_source` can tell a deliberate grant apart from the levels
/// the automatic paths assign. Pass `None` for automatic adjustments that are
/// not operator decisions (e.g. the discovery-handshake demotion safety net) —
/// those must leave the recorded provenance alone rather than claim one.
pub async fn set_trust_level(
data_dir: &Path,
did: &str,
trust: TrustLevel,
source: Option<TrustSource>,
) -> Result<Vec<FederatedNode>> {
let _guard = FEDERATION_STORE_LOCK.lock().await;
let mut nodes = load_nodes_inner(data_dir).await?;
@@ -413,9 +404,6 @@ pub async fn set_trust_level(
.find(|n| n.did == did)
.ok_or_else(|| anyhow::anyhow!("No federated node with DID {}", did))?;
node.trust_level = trust;
if let Some(source) = source {
node.trust_source = Some(source);
}
save_nodes_inner(data_dir, &nodes).await?;
Ok(nodes)
}
@@ -673,55 +661,12 @@ mod tests {
add_node(dir.path(), make_node("did:key:z1", "a.onion"))
.await
.unwrap();
let nodes = set_trust_level(dir.path(), "did:key:z1", TrustLevel::Observer, None)
let nodes = set_trust_level(dir.path(), "did:key:z1", TrustLevel::Observer)
.await
.unwrap();
assert_eq!(nodes[0].trust_level, TrustLevel::Observer);
}
/// The operator RPC path stamps `Manual`, so an audit of `trust_source`
/// can separate a deliberate grant from the levels the automatic paths
/// (`UninvitedJoin`, `TransitiveMerge`) assign on their own authority.
#[tokio::test]
async fn test_set_trust_level_records_manual_source() {
let dir = tempfile::tempdir().unwrap();
add_node(dir.path(), make_node("did:key:z1", "a.onion"))
.await
.unwrap();
let nodes = set_trust_level(
dir.path(),
"did:key:z1",
TrustLevel::Trusted,
Some(TrustSource::Manual),
)
.await
.unwrap();
assert_eq!(nodes[0].trust_level, TrustLevel::Trusted);
assert_eq!(nodes[0].trust_source, Some(TrustSource::Manual));
}
/// An automatic adjustment must not claim a provenance it doesn't have:
/// passing `None` leaves whatever was recorded before intact, so the
/// discovery-handshake demotion can't launder an `UninvitedJoin` peer
/// into looking operator-approved.
#[tokio::test]
async fn test_set_trust_level_none_source_preserves_provenance() {
let dir = tempfile::tempdir().unwrap();
let mut node = make_node("did:key:z1", "a.onion");
node.trust_source = Some(TrustSource::UninvitedJoin);
add_node(dir.path(), node).await.unwrap();
let nodes = set_trust_level(dir.path(), "did:key:z1", TrustLevel::Observer, None)
.await
.unwrap();
assert_eq!(nodes[0].trust_level, TrustLevel::Observer);
assert_eq!(
nodes[0].trust_source,
Some(TrustSource::UninvitedJoin),
"an automatic level change must not rewrite how the peer got here"
);
}
/// The .198 v1.7.103 update-bricking race (see `update.rs`'s
/// `UPDATE_OP_LOCK`) had the same shape as this test: two concurrent
/// mutators sharing one on-disk file with no coordination. Here,
@@ -750,7 +695,7 @@ mod tests {
async move { add_node(&dir_a, make_node("did:key:zB", "b.onion")).await },
);
let trust_task = tokio::spawn(async move {
set_trust_level(&dir_b, "did:key:zA", TrustLevel::Observer, None).await
set_trust_level(&dir_b, "did:key:zA", TrustLevel::Observer).await
});
add_task.await.unwrap().unwrap();
trust_task.await.unwrap().unwrap();
+4 -4
View File
@@ -380,7 +380,7 @@ mod tests {
fn build_local_state_filters_non_trusted_peers() {
let peers = vec![
FederatedNode {
trust_source: None,
trust_source: None,
did: "did:key:zTrusted".into(),
pubkey: "aa".into(),
onion: "t.onion".into(),
@@ -396,7 +396,7 @@ mod tests {
last_sync_error_at: None,
},
FederatedNode {
trust_source: None,
trust_source: None,
did: "did:key:zObserver".into(),
pubkey: "bb".into(),
onion: "o.onion".into(),
@@ -412,7 +412,7 @@ mod tests {
last_sync_error_at: None,
},
FederatedNode {
trust_source: None,
trust_source: None,
did: "did:key:zUntrusted".into(),
pubkey: "cc".into(),
onion: "u.onion".into(),
@@ -457,7 +457,7 @@ mod tests {
super::super::storage::save_nodes(
dir.path(),
&[FederatedNode {
trust_source: None,
trust_source: None,
did: "did:key:zSource".into(),
pubkey: "aa".into(),
onion: "source.onion".into(),
+1 -1
View File
@@ -27,7 +27,7 @@ use tracing::info;
mod api;
mod app_ops;
mod appgate;
mod assistant;
mod auth;
mod avatar;
mod backup;
+2 -61
View File
@@ -1901,23 +1901,8 @@ impl MeshService {
// • Meshcore stock client → plain text (can't decode our envelope).
// Rich typed messages (invoice/coordinate/reaction/…) always use the
// typed-wire path via `send_typed_wire`; only plain Text is routed here.
// A federation-synthetic contact ALWAYS takes the typed path, whatever
// radio (if any) is attached. `send_typed_wire` is the only routing
// that knows about FIPS/Tor, and it still prefers a reachable LoRa
// twin when the payload fits — so this loses no radio-first behaviour.
//
// Without this, a plain text message to a federated peer fell through
// to `peer_dest_prefix`, which resolves a RADIO routing key. On a node
// running Meshtastic — or with no radio at all — that fails, which is
// why peering a node was not enough to message it: you had to meet it
// over LoRa first so a radio twin existed to route through. Federation
// peers are reachable off-radio by definition (that is what
// `upsert_federation_peer` records with `reachable: true`), so the
// transport choice must not depend on which radio is plugged in.
let is_federation_contact = contact_id & 0x8000_0000 != 0;
let use_typed_envelope = archy
&& (is_federation_contact
|| matches!(device_type, DeviceType::Meshcore | DeviceType::Reticulum));
let use_typed_envelope =
archy && matches!(device_type, DeviceType::Meshcore | DeviceType::Reticulum);
if use_typed_envelope {
// Sign with our archipelago identity so the receiver can authenticate
// us over LoRa (verifies against our bound `arch_pubkey_hex`). `with_seq`
@@ -2375,50 +2360,6 @@ async fn bitcoin_rpc_getblockheader_by_height(
#[cfg(test)]
mod tests {
/// Item 5: a federated/trusted peer must be messageable as soon as it is
/// peered — no LoRa meeting first.
///
/// The routing predicate in `send_message` decides whether a plain text
/// message takes the federation-aware typed path (which knows FIPS/Tor and
/// still prefers a reachable radio twin) or the radio-only path, which
/// resolves an over-the-air routing key and cannot work for a peer we have
/// never heard on the radio.
///
/// It previously keyed on the attached radio, so on a Meshtastic node — or
/// one with no radio at all — a federated peer fell to the radio path and
/// the send failed. Federation contacts are reachable off-radio by
/// definition, so the choice must not depend on which radio is plugged in.
#[test]
fn federation_contacts_take_the_off_radio_path_on_any_device() {
fn uses_typed_path(contact_id: u32, archy: bool, device: DeviceType) -> bool {
let is_federation_contact = contact_id & 0x8000_0000 != 0;
archy
&& (is_federation_contact
|| matches!(device, DeviceType::Meshcore | DeviceType::Reticulum))
}
let fed = super::federation_peer_contact_id(&"ab".repeat(32));
assert!(fed >= FEDERATION_CONTACT_ID_BASE);
// The cases that used to fail: peered node, wrong radio or none.
for device in [
DeviceType::Meshtastic,
DeviceType::Unknown,
DeviceType::Meshcore,
DeviceType::Reticulum,
] {
assert!(
uses_typed_path(fed, true, device),
"federation peer must route off-radio on {device:?}"
);
}
// A plain radio contact on a stock-text device still takes the radio
// path — this fix must not reroute ordinary LoRa chats.
assert!(!uses_typed_path(42, true, DeviceType::Meshtastic));
// And a stock (non-archy) client is never given a typed envelope.
assert!(!uses_typed_path(42, false, DeviceType::Meshcore));
}
use super::*;
#[test]
+5 -58
View File
@@ -1068,19 +1068,6 @@ impl Server {
// Podman needs and can restart-loop apps that publish those ports.
let relay_task = tokio::spawn(app_port_v6_relay_loop(tx.subscribe()));
// The app gate: authentication in front of every app port, on every
// address the node answers on. It can only claim a port whose app has
// been pinned to loopback in its manifest — see appgate::listener for
// why the rollout is necessarily per-app — and it logs a warning plus
// records `GateStatus::unprotected` for every port it cannot claim,
// so a partially-rolled-out gate is visible rather than silently
// ineffective.
let gate_task = tokio::spawn(crate::appgate::listener::run(
self.api_handler.rpc_handler().app_gate.clone(),
crate::appgate::listener::shared_status(),
tx.subscribe(),
));
let peer_task = tokio::spawn(peer_late_bind_loop(
self.api_handler.clone(),
active_connections.clone(),
@@ -1107,10 +1094,6 @@ impl Server {
let _ = t.await;
}
relay_task.abort();
// Aborted rather than awaited, like the relay loop: the sweep sleeps
// up to a minute between ticks and its accept loops exit on the
// shutdown watch, so awaiting it would stall the drain for no gain.
gate_task.abort();
let _ = peer_task.await;
info!("Shutdown complete");
@@ -1145,52 +1128,16 @@ fn fips_app_relay_addr(ip: std::net::Ipv6Addr, port: u16) -> SocketAddr {
/// without a daemon restart. Each relay binds to the fips0 ULA only and
/// forwards raw TCP to the same port on IPv4 loopback.
async fn app_port_v6_relay_loop(mut shutdown_rx: tokio::sync::watch::Receiver<bool>) {
use std::collections::HashMap;
let mut bridged: HashMap<u16, tokio::task::JoinHandle<()>> = HashMap::new();
use std::collections::HashSet;
let mut bridged: HashSet<u16> = HashSet::new();
let mut interval = tokio::time::interval(std::time::Duration::from_secs(60));
interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
loop {
tokio::select! {
_ = interval.tick() => {
let Some(fips_ip) = crate::fips::iface::fips0_ula() else { continue };
// This relay is a raw unauthenticated forward from the mesh to
// the app's loopback, so it must refuse two classes of port:
//
// * `auth: gated` — the app gate owns the fips0 ULA for these,
// and bridging one would bypass the login page. Which of the
// two won the bind used to be a race.
// * `auth: local` — host-local BY INTENT. Bridging one makes a
// port reachable from the whole mesh that was deliberately
// never externally reachable: nbxplorer 32838 answered HTTP
// 200 over the mesh with no credential (archi-dev-box
// 2026-08-04) purely because it appeared in the static port
// list below.
//
// Undeclared ports keep today's behaviour — silence is not an
// instruction in either direction, and this relay predates the
// declarations.
let port_map = crate::appgate::identity::build_port_map();
let gate_owned: std::collections::HashSet<u16> = port_map
.gated_ports()
.filter(|g| g.declared)
.map(|g| g.port)
.collect();
for &port in crate::fips::app_ports::APP_LAUNCH_PORTS {
let withhold = if gate_owned.contains(&port) {
Some("port is now gate-owned")
} else if port_map.is_declared_local(port) {
Some("port is declared auth: local (host-local by intent)")
} else {
None
};
if let Some(reason) = withhold {
if let Some(handle) = bridged.remove(&port) {
handle.abort();
info!(port, reason, "v6 relay released a bridge");
}
continue;
}
if bridged.contains_key(&port) {
if bridged.contains(&port) {
continue;
}
// ONLY bridge a port that a running app already answers on
@@ -1217,9 +1164,10 @@ async fn app_port_v6_relay_loop(mut shutdown_rx: tokio::sync::watch::Receiver<bo
// EADDRINUSE = fipsd or another process already answers
// on this mesh address/port, so stay out of the way.
let Ok(listener) = bind_v6_only(addr) else { continue };
bridged.insert(port);
debug!("v6 relay bridging [{fips_ip}]:{port} -> 127.0.0.1:{port}");
let mut rx = shutdown_rx.clone();
let handle = tokio::spawn(async move {
tokio::spawn(async move {
loop {
tokio::select! {
accepted = listener.accept() => {
@@ -1240,7 +1188,6 @@ async fn app_port_v6_relay_loop(mut shutdown_rx: tokio::sync::watch::Receiver<bo
}
}
});
bridged.insert(port, handle);
}
}
_ = shutdown_rx.changed() => return,
-276
View File
@@ -503,66 +503,6 @@ fn default_network_policy() -> String {
"isolated".to_string()
}
/// Whether a published port must sit behind the node's app authentication
/// gate.
///
/// The default is deliberately the protected one. Every app port on this
/// node was reachable with no credential at all over LAN, Tailscale, Tor and
/// the FIPS mesh alike (reproduced 2026-08-03) precisely because exposure
/// was the thing you got by saying nothing. Making `Session` the default
/// inverts that: a new app is protected unless its manifest argues for an
/// exemption, and the exemptions are a `grep auth: none apps/` rather than a
/// discovery.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PortAuth {
/// Default. The daemon's app gate authenticates every connection: a
/// valid session (2FA honoured, since a session still pending its TOTP
/// step fails validation) or an app-scoped bearer token for machine
/// clients. Anything else gets the login page.
#[default]
Session,
/// Exempt — the gate does not touch this port.
///
/// Only legitimate when the port carries a protocol that authenticates
/// itself (LND macaroons, Lightning's noise handshake, TLS client
/// certs) or one where a login page would be meaningless and harmful
/// (Bitcoin p2p gossip, mDNS). Requires `auth_rationale`: an exemption
/// nobody can explain is an exemption nobody reviewed.
None,
/// Host-local by intent — the gate must not bind this port at all.
///
/// This exists because `bind: 127.0.0.1` is ambiguous on its own, and
/// reading intent out of it would be wrong in both directions. Two
/// unrelated situations produce an identical loopback publish:
///
/// * Bitcoin's RPC 8332 is loopback-pinned so that the LAN *cannot*
/// reach it. Fronting it with the gate would newly expose it on every
/// host address — behind a login, but exposed where it deliberately
/// was not.
/// * A gated app is loopback-pinned precisely *so that* the gate can
/// take over its external addresses; that is the whole migration.
///
/// Inferring from `bind` would break one or the other, so the intent is
/// declared. `Local` means the first case: never externally reachable,
/// gate keeps its hands off.
Local,
/// The app publishes on loopback ONLY, and the daemon owns this port's
/// external addresses — bind them and authenticate every connection.
///
/// This is the migrated end state, and it is opt-in for a reason. The
/// gate binding an address is the one action that can make a port
/// reachable where it previously was not, so it must never be something
/// a manifest gets by default or by inference. An earlier revision
/// gated any `session` port regardless of `bind`, which meant a node
/// whose manifests had not yet been updated saw the daemon publish
/// Bitcoin's loopback-only RPC on every host address (caught on
/// archi-dev-box 2026-08-03, seconds after deploy). Requiring the
/// manifest to say so means the loopback pin and the daemon takeover
/// ship together, atomically, and a stale manifest fails safe.
Gated,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PortMapping {
pub host: u16,
@@ -576,45 +516,6 @@ pub struct PortMapping {
/// containers keep reaching it via `host.archipelago`).
#[serde(default)]
pub bind: String,
/// Declared authentication policy, or `None` when the manifest says
/// nothing at all.
///
/// The distinction is load-bearing and was learned the hard way. A node's
/// installed manifests always lag the binary, so "absent" is the state of
/// essentially every port on every node until a signed catalog delivers
/// otherwise. Treating absent as a *value* meant the daemon acted on a
/// default the manifest never asked for: first republishing Bitcoin's
/// loopback-only RPC across the LAN, then — caught before it shipped —
/// preparing to pin LND's gRPC and REST to loopback, which would have
/// broken Zeus and every remote wallet.
///
/// So absent means "no instruction", and the daemon may only ever REPORT
/// on such a port, never change how it is published. Use
/// [`PortMapping::auth_policy`] for classification and
/// [`PortMapping::auth_is_declared`] before acting.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub auth: Option<PortAuth>,
/// Why this port is safe to expose unauthenticated. **Required** when
/// `auth` is `none`, rejected otherwise — a rationale on a gated port
/// means the author expected an exemption they did not get.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub auth_rationale: Option<String>,
}
impl PortMapping {
/// Policy to classify this port by. An undeclared port reports as
/// `Session` — i.e. it shows up in the audit as something that *should*
/// be behind the gate — because reporting an unprotected port is always
/// safe. Acting on it is not; see [`Self::auth_is_declared`].
pub fn auth_policy(&self) -> PortAuth {
self.auth.unwrap_or(PortAuth::Session)
}
/// Whether the manifest actually stated a policy. Required before the
/// daemon rewrites how a port is published: silence is not consent.
pub fn auth_is_declared(&self) -> bool {
self.auth.is_some()
}
}
impl From<(u16, u16)> for PortMapping {
@@ -624,8 +525,6 @@ impl From<(u16, u16)> for PortMapping {
container,
protocol: "tcp".to_string(),
bind: String::new(),
auth: None,
auth_rationale: None,
}
}
}
@@ -1123,34 +1022,6 @@ fn validate_ports(ports: &[PortMapping]) -> Result<(), ManifestError> {
port.bind
)));
}
// An exemption from the app gate has to carry its own justification.
// Enforcing it here rather than at review time means the reason
// exists in the manifest for every exempt port, so auditing the
// node's unauthenticated surface is reading a list, not inferring
// one from silence.
match (port.auth_policy(), port.auth_rationale.as_ref()) {
(PortAuth::None, None) => {
return Err(ManifestError::Invalid(format!(
"ports[{i}] sets auth: none but no auth_rationale — an unauthenticated \
port must state why it is safe to expose"
)));
}
(PortAuth::None, Some(rationale)) if rationale.trim().is_empty() => {
return Err(ManifestError::Invalid(format!(
"ports[{i}].auth_rationale cannot be empty"
)));
}
// A rationale on a gated port means the author wrote an
// exemption and did not get one. Silently keeping the port
// protected would be safe but misleading, so say so.
(PortAuth::Session, Some(_)) => {
return Err(ManifestError::Invalid(format!(
"ports[{i}] sets auth_rationale without auth: none — the port is gated \
and the rationale has no effect"
)));
}
_ => {}
}
// The same host port may be listed more than once with different bind
// addresses (e.g. loopback + the archy-net gateway); identical
// (host, protocol, bind) triples are still rejected.
@@ -1648,153 +1519,6 @@ app:
}
}
/// Build a manifest with one port block, so each auth case differs only
/// in the lines under test.
fn manifest_with_port(port_yaml: &str) -> Result<AppManifest, ManifestError> {
AppManifest::parse(&format!(
"app:\n id: a\n name: a\n version: 1.0.0\n container:\n image: x:y\n ports:\n{port_yaml}"
))
}
/// Every manifest we ship must satisfy the schema — including the auth
/// rules above. Without this the first exemption typo'd into a manifest
/// would only surface when a node refused to load the app.
#[test]
fn all_shipped_manifests_parse() {
let apps = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../apps");
let Ok(entries) = std::fs::read_dir(&apps) else {
return; // not a full checkout (vendored crate) — nothing to check
};
let mut checked = 0;
for entry in entries.flatten() {
let manifest = entry.path().join("manifest.yml");
if !manifest.is_file() {
continue;
}
let yaml = std::fs::read_to_string(&manifest).expect("manifest readable");
AppManifest::parse(&yaml)
.unwrap_or_else(|e| panic!("{} is invalid: {e}", manifest.display()));
checked += 1;
}
assert!(checked > 40, "only found {checked} manifests — path wrong?");
}
/// The exempt set is the node's entire unauthenticated attack surface, so
/// it must stay small and deliberate. If this count moves, someone added
/// or removed an exemption and it wants a second pair of eyes.
#[test]
fn unauthenticated_ports_are_all_accounted_for() {
let apps = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../apps");
let Ok(entries) = std::fs::read_dir(&apps) else {
return;
};
let mut exempt: Vec<(String, u16)> = Vec::new();
for entry in entries.flatten() {
let manifest = entry.path().join("manifest.yml");
if !manifest.is_file() {
continue;
}
let yaml = std::fs::read_to_string(&manifest).expect("manifest readable");
let parsed = AppManifest::parse(&yaml).expect("manifest valid");
for port in &parsed.app.ports {
if port.auth_policy() == PortAuth::None {
exempt.push((parsed.app.id.clone(), port.host));
}
}
}
exempt.sort();
assert_eq!(
exempt.len(),
17,
"unauthenticated port set changed — review before updating this count: {exempt:?}"
);
}
#[test]
fn an_undeclared_port_classifies_as_session_but_is_not_declared() {
// Two different questions, and conflating them caused both gate
// incidents. A manifest that says nothing must CLASSIFY as gated, so
// the audit reports it as something that should be protected — but it
// must not read as an instruction the daemon may act on.
let manifest = manifest_with_port(" - host: 8080\n container: 80\n").unwrap();
let port = &manifest.app.ports[0];
assert_eq!(port.auth_policy(), PortAuth::Session, "reports as gated");
assert!(!port.auth_is_declared(), "but is NOT an instruction");
assert!(port.auth.is_none());
}
#[test]
fn an_explicit_session_declaration_is_actionable() {
let manifest =
manifest_with_port(" - host: 8080\n container: 80\n auth: session\n")
.unwrap();
let port = &manifest.app.ports[0];
assert_eq!(port.auth_policy(), PortAuth::Session);
assert!(port.auth_is_declared());
}
/// The wallet constraint, in the form that actually bit. LND's gRPC and
/// REST carry `bind: ""`, so a rule keyed on `bind` alone does not save
/// them — and on a node whose manifest predates the auth field there is
/// no `auth: none` either. Undeclared must therefore be untouchable, or
/// recreating LND silently pins those ports to loopback and every remote
/// wallet stops working.
#[test]
fn an_undeclared_wallet_port_is_never_actionable() {
let manifest =
manifest_with_port(" - host: 10009\n container: 10009\n protocol: tcp\n")
.unwrap();
let port = &manifest.app.ports[0];
assert!(port.bind.is_empty(), "this is the shape that bit us");
assert!(
!port.auth_is_declared(),
"an undeclared port must never authorise republishing"
);
}
#[test]
fn port_auth_none_requires_a_rationale() {
let err = manifest_with_port(" - host: 8333\n container: 8333\n auth: none\n")
.expect_err("auth: none without a rationale must be rejected");
assert!(
err.to_string().contains("auth_rationale"),
"error should name the missing field, got: {err}"
);
}
#[test]
fn port_auth_none_rejects_a_blank_rationale() {
assert!(manifest_with_port(
" - host: 8333\n container: 8333\n auth: none\n auth_rationale: \" \"\n"
)
.is_err());
}
#[test]
fn port_auth_none_with_a_rationale_parses() {
let manifest = manifest_with_port(
" - host: 8333\n container: 8333\n auth: none\n auth_rationale: Bitcoin p2p gossip\n",
)
.unwrap();
assert_eq!(manifest.app.ports[0].auth, Some(PortAuth::None));
assert_eq!(
manifest.app.ports[0].auth_rationale.as_deref(),
Some("Bitcoin p2p gossip")
);
}
#[test]
fn rationale_without_auth_none_is_rejected() {
// Catches the author who wrote the justification but forgot the
// `auth: none` line: the port stays gated, and shipping it silently
// would leave them believing they had an exemption they never got.
let err = manifest_with_port(
" - host: 8080\n container: 80\n auth_rationale: I meant to exempt this\n",
)
.expect_err("a rationale on a gated port must be rejected");
assert!(err.to_string().contains("no effect"), "got: {err}");
}
#[test]
fn hooks_reject_empty_exec() {
let yaml = "app:\n id: a\n name: a\n version: 1.0.0\n container:\n image: x:y\n hooks:\n post_install:\n - exec: []\n";
-36
View File
@@ -318,42 +318,6 @@ impl PodmanClient {
"sctp" => "sctp",
_ => "tcp",
};
// Effective bind. A gated port with no declared bind would
// publish 0.0.0.0 — the app would own every host address, which
// is both the exposure itself and the reason the daemon's app
// gate cannot bind those addresses to authenticate them. Pin it
// to loopback so the gate can take the external addresses.
//
// Doing it HERE, at container creation, is the point: the pin and
// the gate's takeover then both come from the daemon and cannot
// disagree. The earlier attempt put this decision in manifest
// data instead, and a node whose manifests lagged the binary
// published Bitcoin's loopback-only RPC across the LAN
// (archi-dev-box, 2026-08-03).
//
// A port that already declares a bind is never overridden — that
// is exactly what keeps `bind: 127.0.0.1` ports host-local and
// leaves `auth: none` protocol ports (LND gRPC/REST, electrum)
// published as they are, so remote wallets keep working.
// NOTE: the daemon deliberately does NOT rewrite this. Pinning a
// published port to loopback is how an app hands its external
// addresses to the gate, but it belongs in the manifest, not in
// daemon-side inference:
//
// * `bind` is already honoured by every publish path (here and
// in package::install), so a manifest edit needs no code.
// * inference here would cover only THIS path — proven on
// archi-dev-box, where a recreate went through another one and
// the pin never applied.
// * and inferring from an ABSENT field is what republished
// Bitcoin's loopback RPC across the LAN, and came within one
// container-recreate of pinning LND's gRPC/REST and breaking
// every remote wallet.
//
// So the migration ships as `bind: 127.0.0.1` in the signed
// catalog. Verified 2026-08-03 that a disk-only manifest edit is
// overridden by the catalog, which is precisely why the catalog is
// the right and only place to carry it.
let mut mapping = serde_json::json!({
"container_port": port.container,
"host_port": port.host,
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "neode-ui",
"version": "1.7.121-alpha",
"version": "1.7.120-alpha",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "neode-ui",
"version": "1.7.121-alpha",
"version": "1.7.120-alpha",
"dependencies": {
"@scure/bip39": "^2.2.0",
"@types/dompurify": "^3.0.5",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "neode-ui",
"private": true,
"version": "1.7.121-alpha",
"version": "1.7.120-alpha",
"type": "module",
"scripts": {
"start": "./start-dev.sh",
@@ -486,18 +486,6 @@ describe('RPCClient convenience methods', () => {
expect(getLastMethod()).toBe('federation.invite')
})
it('federationInvite omits password when none is given', async () => {
mockSuccess({ code: 'ABC', did: 'did:key:z', onion: 'abc.onion' })
await rpcClient.federationInvite('observer')
expect(getLastParams()).not.toHaveProperty('password')
})
it('federationInvite forwards the password for a trusted invite', async () => {
mockSuccess({ code: 'ABC', did: 'did:key:z', onion: 'abc.onion' })
await rpcClient.federationInvite('trusted', 'hunter2')
expect(getLastParams()).toMatchObject({ trust_level: 'trusted', password: 'hunter2' })
})
it('federationJoin calls federation.join', async () => {
mockSuccess({ joined: true, node: {} })
await rpcClient.federationJoin('invite-code')
@@ -522,22 +510,6 @@ describe('RPCClient convenience methods', () => {
expect(getLastMethod()).toBe('federation.set-trust')
})
it('federationSetTrust omits password on demotion', async () => {
mockSuccess({ updated: true, did: 'did:key:z', trust_level: 'observer' })
await rpcClient.federationSetTrust('did:key:z', 'observer')
expect(getLastParams()).not.toHaveProperty('password')
})
it('federationSetTrust forwards the password when promoting', async () => {
mockSuccess({ updated: true, did: 'did:key:z', trust_level: 'trusted' })
await rpcClient.federationSetTrust('did:key:z', 'trusted', 'hunter2')
expect(getLastParams()).toMatchObject({
did: 'did:key:z',
trust_level: 'trusted',
password: 'hunter2',
})
})
it('federationSyncState calls federation.sync-state', async () => {
mockSuccess({ synced: 1, failed: 0, results: [] })
await rpcClient.federationSyncState()
+3 -15
View File
@@ -781,18 +781,12 @@ class RPCClient {
}
// Federation
/** Minting a `trusted` invite requires the node password the backend
* rejects it with a `PASSWORD_REQUIRED` error until one is supplied.
* Observer invites never need one. */
async federationInvite(
trustLevel: 'trusted' | 'observer' = 'trusted',
password?: string,
trustLevel: 'trusted' | 'observer' = 'trusted'
): Promise<{ code: string; did: string; onion: string; trust_level: string }> {
const params: Record<string, unknown> = { trust_level: trustLevel }
if (password) params.password = password
return this.call({
method: 'federation.invite',
params,
params: { trust_level: trustLevel },
})
}
@@ -861,19 +855,13 @@ class RPCClient {
})
}
/** Promotion TO `trusted` requires the node password the backend rejects
* it with a `PASSWORD_REQUIRED` error until one is supplied. Demotion is
* never gated: making a peer less privileged must stay easy. */
async federationSetTrust(
did: string,
trustLevel: 'trusted' | 'observer' | 'untrusted',
password?: string,
): Promise<{ updated: boolean; did: string; trust_level: string }> {
const params: Record<string, unknown> = { did, trust_level: trustLevel }
if (password) params.password = password
return this.call({
method: 'federation.set-trust',
params,
params: { did, trust_level: trustLevel },
})
}
+32
View File
@@ -5,6 +5,7 @@ import type {
AIContextCategory,
ArchyContextResponse,
ArchyActionResponse,
ArchyChatResponse,
} from '@/types/aiui-protocol'
import { useAIPermissionsStore } from '@/stores/aiPermissions'
import { useAppStore } from '@/stores/app'
@@ -81,6 +82,37 @@ export class ContextBroker {
case 'theme:request':
this.sendTheme()
break
case 'chat:request':
this.handleChatRequest(msg.id, msg.text)
break
}
}
// Note: no permission category is threaded through here on purpose.
// Authority for a chat turn is resolved node-side from the RPC session's
// CallerScope (assistant.chat, core/archipelago/src/assistant/mod.rs) —
// duplicating a browser-side gate here would recreate the second,
// divergent security model D-02 exists to prevent. Do not "helpfully"
// add a permission check back into this handler.
private async handleChatRequest(id: string, text: string) {
try {
const result = await rpcClient.call<{ text: string }>({
method: 'assistant.chat',
params: { text },
})
this.postToIframe({
type: 'chat:response',
id,
success: true,
text: result.text,
} satisfies ArchyChatResponse)
} catch (err) {
this.postToIframe({
type: 'chat:response',
id,
success: false,
error: err instanceof Error ? err.message : 'Chat request failed',
} satisfies ArchyChatResponse)
}
}
+1 -15
View File
@@ -324,22 +324,8 @@ html.controller-nav [data-controller-container]:focus {
/* Dashboard content lives inside animated perspective/scroll containers.
Chromium/Brave can corrupt backdrop-filter + transformed cards into black
square/rectangle layers, so use translucent fills there instead.
`.home-card-shell` (Home.vue) was missing from this list and kept its own
`backdrop-filter: blur(18px)`, producing a second, subtler form of the
same corruption: a vertical seam where the blurred backdrop is refreshed
on one side and stale on the other. Because the boundary is in SCREEN
space, it cut both dashboard cards at the same x and vanished in the gap
between them which is how it was identified from a screenshot
(2026-08-03: a lone unpaired brightness step at CSS x=633, present on
10/13 sampled rows inside the cards and 2/10 in the gap). It surfaced on
hover because a hover repaint is what re-rasterises part of the
backdrop. The card's fill is already rgba(0,0,0,0.65) the same as
.glass-card, which renders unblurred here so dropping the blur also
makes the shell consistent with the tiles beside it. */
square/rectangle layers, so use translucent fills there instead. */
body.dashboard-active .dashboard-scroll-panel .glass-card,
body.dashboard-active .dashboard-scroll-panel .home-card-shell,
body.dashboard-active .dashboard-scroll-panel .glass,
body.dashboard-active .dashboard-scroll-panel .mode-switcher,
body.dashboard-active .dashboard-scroll-panel .glass-button,
+24
View File
@@ -45,11 +45,24 @@ export interface AIUIThemeRequest {
type: 'theme:request'
}
/**
* A chat turn from AIUI's embedded-mode client. Carries only the raw user
* text tool selection is node-side (D-01/D-03) and must never be
* expressible as an AIUI-originated action, so this is deliberately NOT an
* `AIActionType` member.
*/
export interface AIUIChatRequest {
type: 'chat:request'
id: string
text: string
}
export type AIUIRequest =
| AIUIContextRequest
| AIUIActionRequest
| AIUIReadyMessage
| AIUIThemeRequest
| AIUIChatRequest
// ─── Archy → AIUI (Responses) ──────────────────────────────────────────────
@@ -81,11 +94,22 @@ export interface ArchyPermissionsUpdate {
categories: AIContextCategory[]
}
/** The node's answer to a `chat:request`. On RPC failure, `error` carries
* only the error message never the raw exception object. */
export interface ArchyChatResponse {
type: 'chat:response'
id: string
success: boolean
text?: string
error?: string
}
export type ArchyResponse =
| ArchyContextResponse
| ArchyActionResponse
| ArchyThemeResponse
| ArchyPermissionsUpdate
| ArchyChatResponse
// ─── All messages ───────────────────────────────────────────────────────────
+10 -91
View File
@@ -223,15 +223,6 @@
@confirm="confirmPresenceSign"
@cancel="showPresenceSignModal = false"
/>
<TrustPasswordModal
:visible="showTrustPassword"
:context="trustPasswordContext"
:busy="trustPasswordBusy"
:error="trustPasswordError"
@confirm="submitTrustPassword"
@close="closeTrustPassword"
/>
</div>
</template>
@@ -252,10 +243,9 @@ import JoinModal from './federation/JoinModal.vue'
import PendingRequestsPanel from './federation/PendingRequestsPanel.vue'
import DiscoverModal from './federation/DiscoverModal.vue'
import PresenceSignModal from './federation/PresenceSignModal.vue'
import TrustPasswordModal from './federation/TrustPasswordModal.vue'
import type { FederatedNode, DwnStatus, SyncResult } from './federation/types'
import type { PendingPeerRequest } from '@/api/rpc-client'
import { nodeName, nodeNameFromDid, timeAgo } from './federation/utils'
import { nodeName, timeAgo } from './federation/utils'
const transportStore = useTransportStore()
const appStore = useAppStore()
@@ -539,73 +529,15 @@ function handleGenerateInvite(type: 'trusted' | 'observer') {
generateInvite()
}
/** The backend is the only authority on whether a given change is an
* escalation, so the UI never pre-judges: it attempts the call and prompts
* only when the backend says a password is required. That keeps demotions
* and no-op re-sets of an already-Trusted peer free of a pointless prompt
* without the frontend having to duplicate the rule. */
function isPasswordRequired(e: unknown): boolean {
return e instanceof Error && e.message.includes('PASSWORD_REQUIRED')
}
const showTrustPassword = ref(false)
const trustPasswordContext = ref('')
const trustPasswordBusy = ref(false)
const trustPasswordError = ref('')
let pendingTrustAction: ((password: string) => Promise<void>) | null = null
function promptForTrustPassword(context: string, action: (password: string) => Promise<void>) {
trustPasswordContext.value = context
trustPasswordError.value = ''
pendingTrustAction = action
showTrustPassword.value = true
}
function closeTrustPassword() {
showTrustPassword.value = false
trustPasswordError.value = ''
trustPasswordBusy.value = false
pendingTrustAction = null
}
async function submitTrustPassword(password: string) {
if (!pendingTrustAction) return
try {
trustPasswordBusy.value = true
trustPasswordError.value = ''
await pendingTrustAction(password)
closeTrustPassword()
} catch (e) {
// Keep the failure inside the modal so the operator can retry in place
// rather than losing the pending action to the page-level banner.
trustPasswordError.value = e instanceof Error ? e.message : 'Password verification failed'
} finally {
trustPasswordBusy.value = false
}
}
/** Raw call throws so both the first attempt and the password retry can
* route the error to the right place. */
async function requestInvite(password?: string) {
// The invite type is not cosmetic: it sets the trust level the invite
// grants both sides ("Invite a Peer" = observer, "Link Your Nodes" = trusted)
const result = await rpcClient.federationInvite(inviteType.value, password)
inviteCode.value = result.code
}
async function generateInvite() {
try {
generatingInvite.value = true
error.value = ''
await requestInvite()
// The invite type is not cosmetic: it sets the trust level the invite
// grants both sides ("Invite a Peer" = observer, "Link Your Nodes" = trusted)
const result = await rpcClient.federationInvite(inviteType.value)
inviteCode.value = result.code
} catch (e) {
if (isPasswordRequired(e)) {
promptForTrustPassword(
'This invite grants Trusted access to whoever redeems it — full read of this node\'s state, and the ability to deploy apps to it. Confirm with your node password.',
requestInvite,
)
return
}
error.value = e instanceof Error ? e.message : 'Failed to generate invite'
} finally {
generatingInvite.value = false
@@ -646,27 +578,14 @@ async function syncAll() {
}
}
/** Raw call — throws; see `requestInvite`. */
async function requestTrustChange(did: string, level: string, password?: string) {
await rpcClient.federationSetTrust(did, level as 'trusted' | 'observer' | 'untrusted', password)
await loadNodes()
if (selectedNode.value?.did === did) {
selectedNode.value = nodes.value.find(n => n.did === did) ?? null
}
}
async function changeTrust(did: string, level: string) {
try {
await requestTrustChange(did, level)
} catch (e) {
if (isPasswordRequired(e)) {
const name = nodeNameFromDid(did, nodes.value)
promptForTrustPassword(
`Granting ${name} Trusted lets it read this node's state and deploy apps to it. Confirm with your node password.`,
(password) => requestTrustChange(did, level, password),
)
return
await rpcClient.federationSetTrust(did, level as 'trusted' | 'observer' | 'untrusted')
await loadNodes()
if (selectedNode.value?.did === did) {
selectedNode.value = nodes.value.find(n => n.did === did) ?? null
}
} catch (e) {
error.value = e instanceof Error ? e.message : 'Failed to update trust level'
}
}
@@ -1,80 +0,0 @@
import { describe, it, expect } from 'vitest'
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
/**
* Chromium/Brave mis-rasterise `backdrop-filter` inside the dashboard's
* animated perspective/scroll containers. style.css already neutralises it
* for the shared glass classes, but that list is hand-maintained: a component
* that declares its own `backdrop-filter` in a local <style> block is simply
* not covered, and nothing fails.
*
* That is exactly how the 2026-08-03 seam shipped. `.home-card-shell` carried
* `backdrop-filter: blur(18px)` in Home.vue and was missing from the list, so
* a hover repaint left a vertical line where the refreshed backdrop met the
* stale one visible in both dashboard cards at the same screen x, and
* absent in the gap between them.
*
* This test makes the omission fail loudly instead of shipping as a glitch
* nobody can reproduce on demand.
*/
const root = resolve(__dirname, '../../..')
const styleCss = readFileSync(resolve(root, 'src/style.css'), 'utf8')
/** The selector list that disables backdrop-filter on the dashboard. */
function dashboardMitigationBlock(): string {
const start = styleCss.indexOf('body.dashboard-active .dashboard-scroll-panel .glass-card')
expect(start, 'dashboard backdrop-filter mitigation block not found').toBeGreaterThan(-1)
const end = styleCss.indexOf('}', start)
return styleCss.slice(start, end)
}
/** Class selectors that declare a non-none backdrop-filter in a .vue file. */
function blurredClassesIn(relPath: string): string[] {
const src = readFileSync(resolve(root, relPath), 'utf8')
const found = new Set<string>()
// Match `.some-class { ... backdrop-filter: <not none> ... }` on one line,
// which is how these single-line rules are written in this codebase.
const ruleRe = /(\.[a-zA-Z0-9_-]+)\s*\{([^}]*)\}/g
let m: RegExpExecArray | null
while ((m = ruleRe.exec(src)) !== null) {
const selector = m[1]
const body = m[2]
if (!selector || !body) continue
const decl = /(?:^|[;{\s])backdrop-filter\s*:\s*([^;]+)/.exec(body)
if (decl?.[1] && decl[1].trim() !== 'none') found.add(selector)
}
return [...found]
}
describe('dashboard backdrop-filter mitigation', () => {
it('covers every backdrop-filter surface Home.vue defines itself', () => {
const block = dashboardMitigationBlock()
const uncovered = blurredClassesIn('src/views/Home.vue').filter(
(sel) => !block.includes(`.dashboard-scroll-panel ${sel},`),
)
expect(
uncovered,
`these Home.vue classes declare backdrop-filter but are not in the ` +
`body.dashboard-active .dashboard-scroll-panel mitigation list in style.css, ` +
`so Chromium will leave repaint seams across the dashboard cards`,
).toEqual([])
})
it('still lists the shared glass classes', () => {
// Guards against someone "cleaning up" the list and silently reopening
// the original black-rectangle corruption this block was written for.
const block = dashboardMitigationBlock()
for (const sel of ['.glass-card', '.glass-button', '.home-card-shell']) {
expect(block).toContain(`.dashboard-scroll-panel ${sel},`)
}
})
it('the mitigation actually disables the filter', () => {
const start = styleCss.indexOf('body.dashboard-active .dashboard-scroll-panel .glass-card')
const body = styleCss.slice(styleCss.indexOf('{', start), styleCss.indexOf('}', start))
expect(body).toContain('backdrop-filter: none')
expect(body).toContain('-webkit-backdrop-filter: none')
})
})
@@ -26,7 +26,7 @@
<div class="flex items-center gap-2 mt-1">
<select
:value="node.trust_level"
@change="onTrustChange"
@change="emit('change-trust', node!.did, ($event.target as HTMLSelectElement).value)"
class="bg-black/30 text-white text-sm rounded px-2 py-1 border border-white/10"
>
<option value="trusted">Trusted</option>
@@ -34,9 +34,6 @@
<option value="untrusted">Blocked</option>
</select>
</div>
<p class="text-xs text-white/40 mt-2">
<span class="text-white/30">Granted via:</span> {{ trustSourceLabel }}
</p>
</div>
<div class="bg-white/5 rounded-lg p-3">
<p class="text-xs text-white/40 mb-1">Added</p>
@@ -133,7 +130,7 @@
</template>
<script setup lang="ts">
import { computed, ref } from 'vue'
import { ref } from 'vue'
import type { FederatedNode } from './types'
import { formatBytes, formatUptime } from './utils'
@@ -159,32 +156,6 @@ const emit = defineEmits<{
const confirmRemove = ref(false)
const deployAppId = ref('')
const TRUST_SOURCE_LABELS: Record<string, string> = {
invite: 'An invite you minted',
'uninvited-join': 'Joined without an invite — capped at Observer',
'transitive-merge': 'Advertised by another peer — capped at Observer',
manual: 'You set it here',
}
/** Unknown provenance is stated plainly rather than hidden: a peer recorded
* before this was tracked is precisely the one worth a second look. */
const trustSourceLabel = computed(
() => TRUST_SOURCE_LABELS[props.node?.trust_source ?? ''] ?? 'Unknown — recorded before this was tracked',
)
/** Snap the select back to the node's actual level immediately. Promoting to
* Trusted asks for the node password, and the operator may cancel or get it
* wrong without this the dropdown would keep displaying a level the node
* never accepted. On success the parent reloads and the prop drives the new
* value back in. */
function onTrustChange(event: Event) {
const select = event.target as HTMLSelectElement
const level = select.value
if (!props.node) return
select.value = props.node.trust_level
emit('change-trust', props.node.did, level)
}
function handleClose() {
confirmRemove.value = false
deployAppId.value = ''
@@ -1,74 +0,0 @@
<template>
<Teleport to="body">
<Transition name="modal">
<div v-if="visible" class="fixed inset-0 z-[3000] flex items-center justify-center p-4" @click.self="handleClose">
<div class="absolute inset-0 bg-black/60 backdrop-blur-sm"></div>
<div class="glass-card p-6 max-w-md w-full relative z-10">
<h3 class="text-lg font-semibold text-white mb-2">Confirm Trusted Access</h3>
<p class="text-sm text-white/60 mb-4">{{ context }}</p>
<input
ref="passwordInput"
v-model="password"
type="password"
autocomplete="current-password"
placeholder="Enter your node password to confirm"
class="w-full bg-black/30 border border-white/10 rounded-lg px-3 py-2 text-sm text-white placeholder-white/30 focus:outline-none focus:border-orange-500/50 mb-4"
@keyup.enter="submit"
/>
<p v-if="error" class="text-red-400 text-xs mb-3">{{ error }}</p>
<div class="flex gap-3">
<button @click="handleClose" class="flex-1 glass-button px-4 py-2 rounded-lg text-sm">Cancel</button>
<button
@click="submit"
:disabled="busy || !password"
class="flex-1 glass-button px-4 py-2 rounded-lg text-sm font-medium bg-orange-500/20 border-orange-500/30 disabled:opacity-50"
>
{{ busy ? 'Verifying…' : 'Grant Trusted' }}
</button>
</div>
</div>
</div>
</Transition>
</Teleport>
</template>
<script setup lang="ts">
import { ref, nextTick, watch } from 'vue'
const props = defineProps<{
visible: boolean
/** What is about to be granted, in the operator's terms. */
context: string
busy: boolean
error: string
}>()
const emit = defineEmits<{
close: []
confirm: [password: string]
}>()
const password = ref('')
const passwordInput = ref<HTMLInputElement | null>(null)
function submit() {
if (!password.value || props.busy) return
emit('confirm', password.value)
}
function handleClose() {
password.value = ''
emit('close')
}
// Never leave the password sitting in memory once the modal is dismissed,
// and put the cursor where the operator has to type anyway.
watch(() => props.visible, async (val) => {
if (!val) {
password.value = ''
return
}
await nextTick()
passwordInput.value?.focus()
})
</script>
-7
View File
@@ -40,13 +40,6 @@ export interface FederatedNode {
last_sync_error?: string
/** RFC 3339 timestamp of last_sync_error. */
last_sync_error_at?: string
/**
* How this peer's trust level came to be what it is. `null` means it was
* recorded before provenance was tracked which is exactly the population
* worth reviewing, since it may include grants made by the fail-open paths
* that `uninvited-join` / `transitive-merge` now cap at Observer.
*/
trust_source?: 'invite' | 'uninvited-join' | 'transitive-merge' | 'manual' | null
}
export interface DwnStatus {
@@ -362,23 +362,6 @@ init()
</button>
</div>
<div class="overflow-y-auto flex-1 min-h-0 space-y-6 pr-1">
<!-- v1.7.121-alpha -->
<div>
<div class="flex items-center gap-2 mb-3">
<span class="text-xs font-mono px-2 py-0.5 rounded bg-orange-500/20 text-orange-300">v1.7.121-alpha</span>
<span class="text-xs text-white/40">August 4, 2026</span>
</div>
<div class="space-y-3 text-sm text-white/80 pl-3 border-l border-white/10">
<p>**Making another node "Trusted" now asks for your node password.** Trust was being handed out by machines rather than by you: any node able to reach yours could join and mark itself Trusted, because the check proved only that the caller owned the key it had just presented never that you had approved it. Trust also spread on its own, since every peer a Trusted node advertised was added as Trusted too, so one grant quietly propagated across the whole federation. Uninvited joins are now capped at Observer, advertised peers arrive as Observers, and raising anyone to Trusted whether by generating an invite or by changing the dropdown on a node requires your password. Lowering trust deliberately does not, because the safe action must never be the inconvenient one. Existing peers are left exactly as they are rather than silently demoted, and each one now records how its trust was granted so you can review them.</p>
<p>**Nodes you have peered with can be messaged straight away.** Peering was not enough: you also had to be within LoRa radio range of the other node once before chat would work. The node picked how to send a message based on which radio was plugged in, and only one of those paths knew how to reach a peer over the mesh's internet transports so on a node with a different radio, or no radio at all, messaging a peer you had just federated with simply failed until a radio contact happened to appear. Peered nodes are reachable without radio by definition, so that choice no longer depends on the hardware. Radio is still preferred when the other node is actually in range and the message fits.</p>
<p>The dashboard no longer flickers a vertical line across its cards. A rendering seam appeared at random while moving the mouse, because the two large cards used a background-blur effect that this system already disables everywhere else on the dashboard that browser mis-draws it inside the dashboard's animated container, and these two cards had been missed when the workaround was written. Diagnosed from a single screenshot rather than by trying to reproduce it.</p>
<p>The Lightning screen will actually update from now on. Its image was set to "latest", and the container system will not re-fetch a label it already holds, so nodes kept the same Lightning screen forever no matter how many updates shipped. A separate copy of the same setting used only by brand-new installs also described the screen incorrectly, so fresh installs got a screen that never answered.</p>
<p>Apps that provide their own screens stop rebuilding themselves in a loop. On this system's own node one of them rebuilt every thirty-five seconds indefinitely, burning processor time and restarting the app each round. The node decided a rebuild was needed by comparing file dates against the image's creation date, but a rebuild that changes nothing reuses the existing image and leaves that date untouched so the condition that triggered the rebuild was still true afterwards, forever. Nodes taking this update repair themselves the first time they check.</p>
<p>Groundwork you can see but that does not change access yet: the node can now tell you which of its app ports answer without a login, and every port that is deliberately open Bitcoin's peer connections for syncing the chain, Lightning's wallet connections, the Electrum wallet protocol now has to state in writing why it is safe, so the list of exceptions is something you can read rather than something you have to discover. The login gate that will sit in front of the rest is built and proven working end to end on a real node, but it is not yet closing any ports; that arrives with the signed app catalog that tells each app to hand its address over.</p>
<p>Releases can no longer ship an unsigned update file. Signing was skippable, and when it was skipped the release was still committed and tagged producing an update that every node correctly refuses to install. It had been caught by hand every cycle; now the release simply stops.</p>
<p>Known gaps, disclosed rather than buried: the 5x real-node lifecycle gate was not run for this release. App ports other than the deliberate exceptions above are still reachable without a login the gate reports them, and closing them needs the next signed catalog. Three voice-assistant ports are open without authentication and should not be; the correct fix puts them on a private network with the assistant instead, which needs testing on a node that runs both. Two nodes on the fleet still share SSH host keys (detection shipped, rotation remains a deliberate operator decision).</p>
</div>
</div>
<!-- v1.7.120-alpha -->
<div>
<div class="flex items-center gap-2 mb-3">
+24 -22
View File
@@ -1,34 +1,36 @@
{
"changelog": [
"**Making another node \"Trusted\" now asks for your node password.** Trust was being handed out by machines rather than by you: any node able to reach yours could join and mark itself Trusted, because the check proved only that the caller owned the key it had just presentednever that you had approved it. Trust also spread on its own, since every peer a Trusted node advertised was added as Trusted too, so one grant quietly propagated across the whole federation. Uninvited joins are now capped at Observer, advertised peers arrive as Observers, and raising anyone to Trusted — whether by generating an invite or by changing the dropdown on a node — requires your password. Lowering trust deliberately does not, because the safe action must never be the inconvenient one. Existing peers are left exactly as they are rather than silently demoted, and each one now records how its trust was granted so you can review them.",
"**Nodes you have peered with can be messaged straight away.** Peering was not enough: you also had to be within LoRa radio range of the other node once before chat would work. The node picked how to send a message based on which radio was plugged in, and only one of those paths knew how to reach a peer over the mesh's internet transports — so on a node with a different radio, or no radio at all, messaging a peer you had just federated with simply failed until a radio contact happened to appear. Peered nodes are reachable without radio by definition, so that choice no longer depends on the hardware. Radio is still preferred when the other node is actually in range and the message fits.",
"The dashboard no longer flickers a vertical line across its cards. A rendering seam appeared at random while moving the mouse, because the two large cards used a background-blur effect that this system already disables everywhere else on the dashboard — that browser mis-draws it inside the dashboard's animated container, and these two cards had been missed when the workaround was written. Diagnosed from a single screenshot rather than by trying to reproduce it.",
"The Lightning screen will actually update from now on. Its image was set to \"latest\", and the container system will not re-fetch a label it already holds, so nodes kept the same Lightning screen forever no matter how many updates shipped. A separate copy of the same setting used only by brand-new installs also described the screen incorrectly, so fresh installs got a screen that never answered.",
"Apps that provide their own screens stop rebuilding themselves in a loop. On this system's own node one of them rebuilt every thirty-five seconds indefinitely, burning processor time and restarting the app each round. The node decided a rebuild was needed by comparing file dates against the image's creation date, but a rebuild that changes nothing reuses the existing image and leaves that date untouched — so the condition that triggered the rebuild was still true afterwards, forever. Nodes taking this update repair themselves the first time they check.",
"Groundwork you can see but that does not change access yet: the node can now tell you which of its app ports answer without a login, and every port that is deliberately open — Bitcoin's peer connections for syncing the chain, Lightning's wallet connections, the Electrum wallet protocol — now has to state in writing why it is safe, so the list of exceptions is something you can read rather than something you have to discover. The login gate that will sit in front of the rest is built and proven working end to end on a real node, but it is not yet closing any ports; that arrives with the signed app catalog that tells each app to hand its address over.",
"Releases can no longer ship an unsigned update file. Signing was skippable, and when it was skipped the release was still committed and tagged — producing an update that every node correctly refuses to install. It had been caught by hand every cycle; now the release simply stops.",
"Known gaps, disclosed rather than buried: the 5x real-node lifecycle gate was not run for this release. App ports other than the deliberate exceptions above are still reachable without a login — the gate reports them, and closing them needs the next signed catalog. Three voice-assistant ports are open without authentication and should not be; the correct fix puts them on a private network with the assistant instead, which needs testing on a node that runs both. Two nodes on the fleet still share SSH host keys (detection shipped, rotation remains a deliberate operator decision)."
"**Security, and the reason to take this update: two ports on your node handed anyone who could reach them complete control of your money, with no password.** The Lightning app's port answered a plain web request with the LND admin macaroon, the TLS certificate and the node's onion address — everything needed to drain the wallet remotely, and the onion meant an attacker kept that ability even after losing access to your network. The Bitcoin app's port reached Bitcoin Core's control interface using credentials the node itself supplied on the caller's behalf, with a wallet loaded. Anything on your home network, your Tailscale network or the mesh could use either one. Both now require you to be logged in. If your node has been reachable by anyone you do not fully trust, treat the Lightning macaroon and the Bitcoin RPC password as known to them.",
"The Bitcoin and Lightning app screens can no longer be published as public Tor addresses automatically. They were one app-id away from being handed a worldwide, permanent address as a silent side effect of being installed — which would have re-opened the hole above to the entire internet. Turning Tor on for them deliberately still works; it just never happens on its own.",
"**Fixes shipped inside the program now actually reach apps that your system keeps running.** A container the node had been told to uninstall, but that the system service manager kept alive anyway, was quietly skipped by the part of the node that applies configuration — so it never received updates that shipped with the program. This was found the hard way: the Bitcoin control-interface fix above appeared to be installed and silently was not, while the Lightning half applied correctly, which is the most misleading way for a security fix to fail. Both halves are now proven to land on a real node.",
"The Lightning and Bitcoin node screens have been rebuilt to match what umbrelOS offers. Lightning gains Overview, Channels, Activity, Insights, Connect and Settings tabs with a sats/BTC switch; Bitcoin gains Insights, Peers, Connect and Sharing. Along the way: every copy button on those screens silently did nothing (the browser blocks clipboard access inside an embedded page) and now works; the channels link led to a dead page; and Node ID showed a bare key instead of the full address someone can actually connect to.",
"Updates to the Bitcoin screen show up without a hard refresh. The page was being cached by the browser, so a freshly updated screen kept rendering the previous one.",
"The AI sidebar loads again. It was asking for its program files at an address that pointed at the main app's files, where they do not exist, so it silently loaded nothing.",
"The navigation above the bottom bar no longer follows you between screens. Back buttons and the mesh tab bar stayed pinned over every other page once you had visited the screen that owns them. Keeping tabs loaded in the background — the change that made switching between them instant — means leaving a screen hides it rather than destroying it, and this floating navigation sits outside the screen it belongs to, so it was never being hidden with it. It is now tied to whether its own screen is on display. The speed is unchanged: the screens are still kept loaded, so returning to one is still instant.",
"Wallet: Lightning actions are now offered based on whether you actually have a usable channel rather than just a running node, sending is gated the same way, and an invoice you cannot yet receive offers to install a Lightning node instead of simply failing.",
"Onboarding and viewing fixes: the \"I have written down my recovery words\" tickbox is findable on short screens, paid pictures and videos open in the app's own viewer with a visible loading state instead of a blank browser tab, picture-in-picture survives changing tabs, and the FIPS/Tor labels on peer cards stay put instead of wrapping into the card below.",
"Key-material hardening across the node: a node that is already set up refuses to have its identity replaced by an unauthenticated request; first-boot secret generation now fails loudly instead of silently continuing with shared keys; the node proves its TLS certificate and key are actually a matching pair; the Bitcoin Core wallet path that kept a second copy of your spending key outside the encrypted store has been removed; and every place the node generates a key, token or nonce now names its source of randomness explicitly, enforced at build time."
],
"components": [
{
"current_version": "1.7.121-alpha",
"download_url": "http://146.59.87.168:3000/lfg2025/archy/releases/download/v1.7.121-alpha/archipelago",
"current_version": "1.7.120-alpha",
"download_url": "http://146.59.87.168:3000/lfg2025/archy/releases/download/v1.7.120-alpha/archipelago",
"name": "archipelago",
"new_version": "1.7.121-alpha",
"sha256": "be5ef9fb284f539b06329d4108be53e55ae8cdb06cf1cf4beb90363de364706d",
"size_bytes": 54870968
"new_version": "1.7.120-alpha",
"sha256": "304255655a22bae605d728d44e857ed170a19833b6237861fdf7d852d25d9680",
"size_bytes": 54017008
},
{
"current_version": "1.7.121-alpha",
"download_url": "http://146.59.87.168:3000/lfg2025/archy/releases/download/v1.7.121-alpha/archipelago-frontend-1.7.121-alpha.tar.gz",
"name": "archipelago-frontend-1.7.121-alpha.tar.gz",
"new_version": "1.7.121-alpha",
"sha256": "7898a9c11fa30cadc8f0fcf814bba1e3870d20663472f4c40e8e663b2359958f",
"size_bytes": 210526689
"current_version": "1.7.120-alpha",
"download_url": "http://146.59.87.168:3000/lfg2025/archy/releases/download/v1.7.120-alpha/archipelago-frontend-1.7.120-alpha.tar.gz",
"name": "archipelago-frontend-1.7.120-alpha.tar.gz",
"new_version": "1.7.120-alpha",
"sha256": "cb9ea4dfcea3ac93dfb1ce1dca96ea30c74a4e6354471cde4d8f75c0441850a5",
"size_bytes": 210519311
}
],
"release_date": "2026-08-04",
"signature": "9d871c946e941b3c13f75fb799d8428841147267f4565920993ddd3aa0cd52d6d1a74481303cbbb26e68e6e5d44e2b711c9b7a22ad7dd73c94b4d3e39a0e2803",
"release_date": "2026-08-03",
"signature": "e76e0ca5f249111a0a57df07f790997b1a4facf97da11a2d13fcb7ec9b80aea82925244d6083544504260b776ca4317cf44774e2c37bfaa13afae248e9675601",
"signed_by": "did:key:z6MkkidEnEpo6qHMCNSZoNKWtvQvxq3whnaME9wGgEFhq7ur",
"version": "1.7.121-alpha"
"version": "1.7.120-alpha"
}
+14 -95
View File
@@ -25,7 +25,6 @@
"name": "AI Assistant",
"ports": [
{
"auth": "local",
"bind": "127.0.0.1",
"container": 80,
"host": 5180,
@@ -229,8 +228,6 @@
"name": "Mempool Web",
"ports": [
{
"auth": "gated",
"bind": "127.0.0.1",
"container": 8080,
"host": 4080,
"protocol": "tcp"
@@ -305,8 +302,6 @@
"name": "NBXplorer",
"ports": [
{
"auth": "local",
"bind": "127.0.0.1",
"container": 32838,
"host": 32838,
"protocol": "tcp"
@@ -379,8 +374,6 @@
"name": "Ark Wallet",
"ports": [
{
"auth": "local",
"bind": "127.0.0.1",
"container": 3535,
"host": 3535,
"protocol": "tcp"
@@ -469,15 +462,12 @@
"name": "Bitcoin Core",
"ports": [
{
"auth": "local",
"bind": "127.0.0.1",
"container": 8332,
"host": 8332,
"protocol": "tcp"
},
{
"auth": "none",
"auth_rationale": "Bitcoin p2p gossip. Peers are anonymous by design and speak the Bitcoin wire protocol, not HTTP.",
"container": 8333,
"host": 8333,
"protocol": "tcp"
@@ -615,15 +605,12 @@
"name": "Bitcoin Knots",
"ports": [
{
"auth": "local",
"bind": "127.0.0.1",
"container": 8332,
"host": 8332,
"protocol": "tcp"
},
{
"auth": "none",
"auth_rationale": "Bitcoin p2p gossip. Peers are anonymous by design and speak the Bitcoin wire protocol, not HTTP.",
"container": 8333,
"host": 8333,
"protocol": "tcp"
@@ -684,7 +671,7 @@
]
},
"bitcoin-ui": {
"image": "146.59.87.168:3000/lfg2025/bitcoin-ui:1.7.119-alpha",
"image": "146.59.87.168:3000/lfg2025/bitcoin-ui:1.7.84-alpha",
"manifest": {
"app": {
"container": {
@@ -732,7 +719,7 @@
]
}
},
"version": "1.7.119-alpha"
"version": "1.7.84-alpha"
},
"botfights": {
"manifest": {
@@ -944,8 +931,6 @@
"name": "BTCPay Server",
"ports": [
{
"auth": "gated",
"bind": "127.0.0.1",
"container": 49392,
"host": 23000,
"protocol": "tcp"
@@ -1016,15 +1001,11 @@
"name": "Core Lightning (CLN)",
"ports": [
{
"auth": "none",
"auth_rationale": "Lightning p2p. The BOLT-8 noise handshake authenticates and encrypts the channel itself.",
"container": 9735,
"host": 9736,
"protocol": "tcp"
},
{
"auth": "none",
"auth_rationale": "Core Lightning gRPC, authenticated by mutual TLS client certificates.",
"container": 9835,
"host": 9835,
"protocol": "tcp"
@@ -1094,8 +1075,6 @@
"name": "Web5 DID Wallet",
"ports": [
{
"auth": "gated",
"bind": "127.0.0.1",
"container": 8080,
"host": 8088,
"protocol": "tcp"
@@ -1240,8 +1219,6 @@
"name": "ElectrumX",
"ports": [
{
"auth": "none",
"auth_rationale": "Electrum wire protocol over TCP. Electrum wallets speak it directly and cannot hold a session cookie.",
"container": 50001,
"host": 50001,
"protocol": "tcp"
@@ -1365,8 +1342,6 @@
"protocol": "tcp"
},
{
"auth": "local",
"bind": "127.0.0.1",
"container": 8175,
"host": 8177,
"protocol": "tcp"
@@ -1441,8 +1416,6 @@
"name": "Fedimint Client",
"ports": [
{
"auth": "local",
"bind": "127.0.0.1",
"container": 8080,
"host": 8178,
"protocol": "tcp"
@@ -1628,8 +1601,6 @@
"name": "File Browser",
"ports": [
{
"auth": "gated",
"bind": "127.0.0.1",
"container": 80,
"host": 8083,
"protocol": "tcp"
@@ -1782,15 +1753,11 @@
},
"ports": [
{
"auth": "gated",
"bind": "127.0.0.1",
"container": 3000,
"host": 3001,
"protocol": "tcp"
},
{
"auth": "none",
"auth_rationale": "Git over SSH, authenticated by the user's own SSH keypair. Not HTTP, so the gate cannot serve a login page here.",
"container": 22,
"host": 2222,
"protocol": "tcp"
@@ -1875,8 +1842,6 @@
"name": "Grafana",
"ports": [
{
"auth": "gated",
"bind": "127.0.0.1",
"container": 3000,
"host": 3000,
"protocol": "tcp"
@@ -1960,8 +1925,6 @@
"name": "Home Assistant",
"ports": [
{
"auth": "gated",
"bind": "127.0.0.1",
"container": 8123,
"host": 8123,
"protocol": "tcp"
@@ -2071,8 +2034,6 @@
"name": "Immich",
"ports": [
{
"auth": "gated",
"bind": "127.0.0.1",
"container": 2283,
"host": 2283,
"protocol": "tcp"
@@ -2312,8 +2273,6 @@
"name": "IndeeHub",
"ports": [
{
"auth": "gated",
"bind": "127.0.0.1",
"container": 7777,
"host": 7778,
"protocol": "tcp"
@@ -2806,8 +2765,6 @@
"name": "Jellyfin",
"ports": [
{
"auth": "gated",
"bind": "127.0.0.1",
"container": 8096,
"host": 8096,
"protocol": "tcp"
@@ -2895,15 +2852,11 @@
"name": "Lightning Stack",
"ports": [
{
"auth": "none",
"auth_rationale": "Lightning p2p. The BOLT-8 noise handshake authenticates and encrypts the channel itself.",
"container": 9735,
"host": 9738,
"protocol": "tcp"
},
{
"auth": "none",
"auth_rationale": "LND gRPC, authenticated by macaroon over TLS. Remote wallets depend on reaching this directly.",
"container": 10009,
"host": 10010,
"protocol": "tcp"
@@ -2997,22 +2950,16 @@
"name": "LND",
"ports": [
{
"auth": "none",
"auth_rationale": "Lightning p2p. The BOLT-8 noise handshake authenticates and encrypts the channel itself.",
"container": 9735,
"host": 9735,
"protocol": "tcp"
},
{
"auth": "none",
"auth_rationale": "LND gRPC, authenticated by macaroon over TLS. Zeus and other remote wallets depend on reaching this directly.",
"container": 10009,
"host": 10009,
"protocol": "tcp"
},
{
"auth": "none",
"auth_rationale": "LND REST, authenticated by macaroon over TLS. A browser login page would break Zeus and every non-browser wallet client.",
"container": 8080,
"host": 18080,
"protocol": "tcp"
@@ -3051,7 +2998,7 @@
"version": "v0.18.4-beta"
},
"lnd-ui": {
"image": "146.59.87.168:3000/lfg2025/lnd-ui:1.7.119-alpha",
"image": "146.59.87.168:3000/lfg2025/lnd-ui:latest",
"manifest": {
"app": {
"container": {
@@ -3078,19 +3025,25 @@
},
"id": "lnd-ui",
"name": "LND UI",
"ports": [],
"ports": [
{
"container": 80,
"host": 18083,
"protocol": "tcp"
}
],
"resources": {
"memory_limit": "64Mi"
},
"security": {
"network_policy": "host",
"network_policy": "bridge",
"readonly_root": false
},
"version": "1.0.0",
"volumes": []
}
},
"version": "1.7.119-alpha"
"version": "latest"
},
"mempool": {
"image": "146.59.87.168:3000/lfg2025/mempool-frontend:v3.0.1",
@@ -3140,8 +3093,6 @@
"name": "Mempool Explorer",
"ports": [
{
"auth": "gated",
"bind": "127.0.0.1",
"container": 8080,
"host": 4080,
"protocol": "tcp"
@@ -3245,8 +3196,6 @@
"name": "Mempool API",
"ports": [
{
"auth": "local",
"bind": "127.0.0.1",
"container": 8999,
"host": 8999,
"protocol": "tcp"
@@ -3306,8 +3255,6 @@
"name": "MorphOS Server",
"ports": [
{
"auth": "gated",
"bind": "127.0.0.1",
"container": 8080,
"host": 8089,
"protocol": "tcp"
@@ -3622,8 +3569,6 @@
"protocol": "tcp"
},
{
"auth": "none",
"auth_rationale": "STUN over UDP for NAT traversal; it must answer unauthenticated probes to do its job at all.",
"container": 3478,
"host": 3478,
"protocol": "udp"
@@ -3708,8 +3653,6 @@
"name": "Nextcloud",
"ports": [
{
"auth": "gated",
"bind": "127.0.0.1",
"container": 80,
"host": 8085,
"protocol": "tcp"
@@ -3788,8 +3731,6 @@
},
"ports": [
{
"auth": "gated",
"bind": "127.0.0.1",
"container": 8080,
"host": 18081,
"protocol": "tcp"
@@ -3891,8 +3832,6 @@
"name": "PhotoPrism",
"ports": [
{
"auth": "gated",
"bind": "127.0.0.1",
"container": 2342,
"host": 2342,
"protocol": "tcp"
@@ -4127,8 +4066,6 @@
"name": "Pine Wake Word (openWakeWord)",
"ports": [
{
"auth": "none",
"auth_rationale": "Wyoming voice protocol, a binary local-only stream consumed by Home Assistant; not HTTP and not browser-reachable.",
"container": 10400,
"host": 10400,
"protocol": "tcp"
@@ -4207,8 +4144,6 @@
"name": "Pine Piper (TTS)",
"ports": [
{
"auth": "none",
"auth_rationale": "Wyoming voice protocol, a binary local-only stream consumed by Home Assistant; not HTTP and not browser-reachable.",
"container": 10200,
"host": 10200,
"protocol": "tcp"
@@ -4291,8 +4226,6 @@
"name": "Pine Whisper (STT)",
"ports": [
{
"auth": "none",
"auth_rationale": "Wyoming voice protocol, a binary local-only stream consumed by Home Assistant; not HTTP and not browser-reachable.",
"container": 10300,
"host": 10300,
"protocol": "tcp"
@@ -4365,8 +4298,6 @@
"name": "Portainer",
"ports": [
{
"auth": "gated",
"bind": "127.0.0.1",
"container": 9000,
"host": 9000,
"protocol": "tcp"
@@ -4463,15 +4394,11 @@
"protocol": "tcp"
},
{
"auth": "none",
"auth_rationale": "mDNS is UDP multicast service discovery; gating it would break .local name resolution for every device on the LAN.",
"container": 5353,
"host": 5353,
"protocol": "udp"
},
{
"auth": "none",
"auth_rationale": "SSDP/UPnP discovery is UDP multicast — there is no HTTP request to gate and no client that could hold a session.",
"container": 1900,
"host": 1900,
"protocol": "udp"
@@ -4551,8 +4478,6 @@
"name": "SearXNG",
"ports": [
{
"auth": "gated",
"bind": "127.0.0.1",
"container": 8080,
"host": 8888,
"protocol": "tcp"
@@ -4624,8 +4549,6 @@
},
"ports": [
{
"auth": "gated",
"bind": "127.0.0.1",
"container": 7777,
"host": 8090,
"protocol": "tcp"
@@ -4716,8 +4639,6 @@
"name": "Uptime Kuma",
"ports": [
{
"auth": "gated",
"bind": "127.0.0.1",
"container": 3001,
"host": 3002,
"protocol": "tcp"
@@ -4799,8 +4720,6 @@
"name": "Vaultwarden",
"ports": [
{
"auth": "gated",
"bind": "127.0.0.1",
"container": 80,
"host": 8082,
"protocol": "tcp"
@@ -4837,7 +4756,7 @@
}
},
"schema": 1,
"signature": "cc83d0be50ce6144e2b5693a7175d7743d4a19141f4ef9a46a3c88d2dadd848acda9c25063e7a8b5643cecb2ccde279762a00a9715a5d26c99a95b492bc82a05",
"signature": "1fe1b962317212c15b83c9ae8b0b2957f9663bb7dda3f4d117123aab496ddd4f94fa48f7d4abfd4be5b771510aed51f8ede870e55cb3fd21ce2453bea1d3510e",
"signed_by": "did:key:z6MkkidEnEpo6qHMCNSZoNKWtvQvxq3whnaME9wGgEFhq7ur",
"updated": "2026-08-04"
"updated": "2026-07-31"
}
+24 -22
View File
@@ -1,34 +1,36 @@
{
"changelog": [
"**Making another node \"Trusted\" now asks for your node password.** Trust was being handed out by machines rather than by you: any node able to reach yours could join and mark itself Trusted, because the check proved only that the caller owned the key it had just presentednever that you had approved it. Trust also spread on its own, since every peer a Trusted node advertised was added as Trusted too, so one grant quietly propagated across the whole federation. Uninvited joins are now capped at Observer, advertised peers arrive as Observers, and raising anyone to Trusted — whether by generating an invite or by changing the dropdown on a node — requires your password. Lowering trust deliberately does not, because the safe action must never be the inconvenient one. Existing peers are left exactly as they are rather than silently demoted, and each one now records how its trust was granted so you can review them.",
"**Nodes you have peered with can be messaged straight away.** Peering was not enough: you also had to be within LoRa radio range of the other node once before chat would work. The node picked how to send a message based on which radio was plugged in, and only one of those paths knew how to reach a peer over the mesh's internet transports — so on a node with a different radio, or no radio at all, messaging a peer you had just federated with simply failed until a radio contact happened to appear. Peered nodes are reachable without radio by definition, so that choice no longer depends on the hardware. Radio is still preferred when the other node is actually in range and the message fits.",
"The dashboard no longer flickers a vertical line across its cards. A rendering seam appeared at random while moving the mouse, because the two large cards used a background-blur effect that this system already disables everywhere else on the dashboard — that browser mis-draws it inside the dashboard's animated container, and these two cards had been missed when the workaround was written. Diagnosed from a single screenshot rather than by trying to reproduce it.",
"The Lightning screen will actually update from now on. Its image was set to \"latest\", and the container system will not re-fetch a label it already holds, so nodes kept the same Lightning screen forever no matter how many updates shipped. A separate copy of the same setting used only by brand-new installs also described the screen incorrectly, so fresh installs got a screen that never answered.",
"Apps that provide their own screens stop rebuilding themselves in a loop. On this system's own node one of them rebuilt every thirty-five seconds indefinitely, burning processor time and restarting the app each round. The node decided a rebuild was needed by comparing file dates against the image's creation date, but a rebuild that changes nothing reuses the existing image and leaves that date untouched — so the condition that triggered the rebuild was still true afterwards, forever. Nodes taking this update repair themselves the first time they check.",
"Groundwork you can see but that does not change access yet: the node can now tell you which of its app ports answer without a login, and every port that is deliberately open — Bitcoin's peer connections for syncing the chain, Lightning's wallet connections, the Electrum wallet protocol — now has to state in writing why it is safe, so the list of exceptions is something you can read rather than something you have to discover. The login gate that will sit in front of the rest is built and proven working end to end on a real node, but it is not yet closing any ports; that arrives with the signed app catalog that tells each app to hand its address over.",
"Releases can no longer ship an unsigned update file. Signing was skippable, and when it was skipped the release was still committed and tagged — producing an update that every node correctly refuses to install. It had been caught by hand every cycle; now the release simply stops.",
"Known gaps, disclosed rather than buried: the 5x real-node lifecycle gate was not run for this release. App ports other than the deliberate exceptions above are still reachable without a login — the gate reports them, and closing them needs the next signed catalog. Three voice-assistant ports are open without authentication and should not be; the correct fix puts them on a private network with the assistant instead, which needs testing on a node that runs both. Two nodes on the fleet still share SSH host keys (detection shipped, rotation remains a deliberate operator decision)."
"**Security, and the reason to take this update: two ports on your node handed anyone who could reach them complete control of your money, with no password.** The Lightning app's port answered a plain web request with the LND admin macaroon, the TLS certificate and the node's onion address — everything needed to drain the wallet remotely, and the onion meant an attacker kept that ability even after losing access to your network. The Bitcoin app's port reached Bitcoin Core's control interface using credentials the node itself supplied on the caller's behalf, with a wallet loaded. Anything on your home network, your Tailscale network or the mesh could use either one. Both now require you to be logged in. If your node has been reachable by anyone you do not fully trust, treat the Lightning macaroon and the Bitcoin RPC password as known to them.",
"The Bitcoin and Lightning app screens can no longer be published as public Tor addresses automatically. They were one app-id away from being handed a worldwide, permanent address as a silent side effect of being installed — which would have re-opened the hole above to the entire internet. Turning Tor on for them deliberately still works; it just never happens on its own.",
"**Fixes shipped inside the program now actually reach apps that your system keeps running.** A container the node had been told to uninstall, but that the system service manager kept alive anyway, was quietly skipped by the part of the node that applies configuration — so it never received updates that shipped with the program. This was found the hard way: the Bitcoin control-interface fix above appeared to be installed and silently was not, while the Lightning half applied correctly, which is the most misleading way for a security fix to fail. Both halves are now proven to land on a real node.",
"The Lightning and Bitcoin node screens have been rebuilt to match what umbrelOS offers. Lightning gains Overview, Channels, Activity, Insights, Connect and Settings tabs with a sats/BTC switch; Bitcoin gains Insights, Peers, Connect and Sharing. Along the way: every copy button on those screens silently did nothing (the browser blocks clipboard access inside an embedded page) and now works; the channels link led to a dead page; and Node ID showed a bare key instead of the full address someone can actually connect to.",
"Updates to the Bitcoin screen show up without a hard refresh. The page was being cached by the browser, so a freshly updated screen kept rendering the previous one.",
"The AI sidebar loads again. It was asking for its program files at an address that pointed at the main app's files, where they do not exist, so it silently loaded nothing.",
"The navigation above the bottom bar no longer follows you between screens. Back buttons and the mesh tab bar stayed pinned over every other page once you had visited the screen that owns them. Keeping tabs loaded in the background — the change that made switching between them instant — means leaving a screen hides it rather than destroying it, and this floating navigation sits outside the screen it belongs to, so it was never being hidden with it. It is now tied to whether its own screen is on display. The speed is unchanged: the screens are still kept loaded, so returning to one is still instant.",
"Wallet: Lightning actions are now offered based on whether you actually have a usable channel rather than just a running node, sending is gated the same way, and an invoice you cannot yet receive offers to install a Lightning node instead of simply failing.",
"Onboarding and viewing fixes: the \"I have written down my recovery words\" tickbox is findable on short screens, paid pictures and videos open in the app's own viewer with a visible loading state instead of a blank browser tab, picture-in-picture survives changing tabs, and the FIPS/Tor labels on peer cards stay put instead of wrapping into the card below.",
"Key-material hardening across the node: a node that is already set up refuses to have its identity replaced by an unauthenticated request; first-boot secret generation now fails loudly instead of silently continuing with shared keys; the node proves its TLS certificate and key are actually a matching pair; the Bitcoin Core wallet path that kept a second copy of your spending key outside the encrypted store has been removed; and every place the node generates a key, token or nonce now names its source of randomness explicitly, enforced at build time."
],
"components": [
{
"current_version": "1.7.121-alpha",
"download_url": "http://146.59.87.168:3000/lfg2025/archy/releases/download/v1.7.121-alpha/archipelago",
"current_version": "1.7.120-alpha",
"download_url": "http://146.59.87.168:3000/lfg2025/archy/releases/download/v1.7.120-alpha/archipelago",
"name": "archipelago",
"new_version": "1.7.121-alpha",
"sha256": "be5ef9fb284f539b06329d4108be53e55ae8cdb06cf1cf4beb90363de364706d",
"size_bytes": 54870968
"new_version": "1.7.120-alpha",
"sha256": "304255655a22bae605d728d44e857ed170a19833b6237861fdf7d852d25d9680",
"size_bytes": 54017008
},
{
"current_version": "1.7.121-alpha",
"download_url": "http://146.59.87.168:3000/lfg2025/archy/releases/download/v1.7.121-alpha/archipelago-frontend-1.7.121-alpha.tar.gz",
"name": "archipelago-frontend-1.7.121-alpha.tar.gz",
"new_version": "1.7.121-alpha",
"sha256": "7898a9c11fa30cadc8f0fcf814bba1e3870d20663472f4c40e8e663b2359958f",
"size_bytes": 210526689
"current_version": "1.7.120-alpha",
"download_url": "http://146.59.87.168:3000/lfg2025/archy/releases/download/v1.7.120-alpha/archipelago-frontend-1.7.120-alpha.tar.gz",
"name": "archipelago-frontend-1.7.120-alpha.tar.gz",
"new_version": "1.7.120-alpha",
"sha256": "cb9ea4dfcea3ac93dfb1ce1dca96ea30c74a4e6354471cde4d8f75c0441850a5",
"size_bytes": 210519311
}
],
"release_date": "2026-08-04",
"signature": "9d871c946e941b3c13f75fb799d8428841147267f4565920993ddd3aa0cd52d6d1a74481303cbbb26e68e6e5d44e2b711c9b7a22ad7dd73c94b4d3e39a0e2803",
"release_date": "2026-08-03",
"signature": "e76e0ca5f249111a0a57df07f790997b1a4facf97da11a2d13fcb7ec9b80aea82925244d6083544504260b776ca4317cf44774e2c37bfaa13afae248e9675601",
"signed_by": "did:key:z6MkkidEnEpo6qHMCNSZoNKWtvQvxq3whnaME9wGgEFhq7ur",
"version": "1.7.121-alpha"
"version": "1.7.120-alpha"
}
+2 -34
View File
@@ -212,10 +212,8 @@ if [ -n "${RELEASE_MASTER_MNEMONIC:-}" ] || [ -t 0 ]; then
"$SIGNER" ceremony verify "$PROJECT_ROOT/releases/manifest.json"
else
echo "⚠ WARNING: no TTY and RELEASE_MASTER_MNEMONIC unset — manifest left UNSIGNED."
echo " This run will ABORT before committing (step 7 refuses an unsigned"
echo " manifest), because nodes read releases/manifest.json from branch main"
echo " and would refuse to auto-apply it."
echo " Sign it, then re-run: bash scripts/sign-manifest.sh"
echo " Sign it before publishing: bash scripts/sign-manifest.sh"
echo " (publish-release-assets.sh refuses to ship an unsigned manifest)"
fi
cp "$PROJECT_ROOT/releases/manifest.json" "$PROJECT_ROOT/release-manifest.json"
@@ -227,36 +225,6 @@ install -m 0755 "$PROJECT_ROOT/core/target/release/archipelago" "$VERSION_DIR/ar
install -m 0644 "$FRONTEND_ARCHIVE" "$VERSION_DIR/archipelago-frontend-${VERSION}.tar.gz"
"$SCRIPT_DIR/check-release-manifest.sh"
# §A supply-chain gate, mirroring publish-release-assets.sh — but EARLIER,
# because publishing is not the first way an unsigned manifest reaches the
# fleet. Nodes fetch releases/manifest.json straight from branch `main`
# (see the verification URLs printed below), so the COMMIT is what exposes
# it, not the publish. publish-release-assets.sh refusing to ship is a
# backstop that arrives one step too late: by then the unsigned manifest is
# already on main and the fleet is already refusing to auto-apply.
#
# This is why every cycle needed a manual catch. The signing block above is
# conditional — no TTY and no RELEASE_MASTER_MNEMONIC means it prints a
# warning and falls through — and the commit then happened anyway. A release
# commit carrying a manifest no node will accept has no valid use, so refuse
# to create one rather than leave a tag that has to be re-cut.
EXPECTED_DID="did:key:z6MkkidEnEpo6qHMCNSZoNKWtvQvxq3whnaME9wGgEFhq7ur"
if ! grep -q '"signature":' "$PROJECT_ROOT/releases/manifest.json" \
|| ! grep -q "\"signed_by\": \"$EXPECTED_DID\"" "$PROJECT_ROOT/releases/manifest.json"; then
echo "" >&2
echo "Error: releases/manifest.json is NOT signed by the release root." >&2
echo " Refusing to commit — nodes read this file from branch main and will" >&2
echo " refuse to auto-apply it, so the release would be dead on arrival." >&2
echo "" >&2
echo " Sign it, then re-run this script:" >&2
echo " bash scripts/sign-manifest.sh" >&2
echo "" >&2
echo " (Signing needs a TTY for the mnemonic prompt, or RELEASE_MASTER_MNEMONIC set.)" >&2
exit 1
fi
"$SIGNER" ceremony verify "$PROJECT_ROOT/releases/manifest.json" \
|| { echo "Error: manifest signature failed cryptographic verification — refusing to commit" >&2; exit 1; }
echo "[7/8] Committing version bump..."
git -C "$PROJECT_ROOT" add \
core/archipelago/Cargo.toml \
+6 -13
View File
@@ -39,25 +39,18 @@ if [ -x "$PROJECT_ROOT/core/target/release/archipelago" ]; then
fi
remote_url=$(git -C "$PROJECT_ROOT" remote get-url "$REMOTE")
# https is accepted as well as http. Requiring http:// meant the only remote
# whose credential actually works for git push (the https one) was rejected,
# while the http remote it forced you to use had a dead token — so publishing
# failed on auth after the manifest had already passed every check
# (v1.7.121-alpha, 2026-08-04). The scheme is carried through to the API URL
# rather than assumed.
case "$remote_url" in
http://*@*|https://*@*) ;;
*) fail "$REMOTE must be an authenticated http(s):// Gitea remote URL for API uploads" ;;
http://*@*) ;;
*) fail "$REMOTE must be an authenticated http:// Gitea remote URL for API uploads" ;;
esac
scheme=${remote_url%%://*}
rest=${remote_url#*://}
auth=${rest%%@*}
host_path=${rest#*@}
auth=${remote_url#http://}
auth=${auth%@*}
host_path=${remote_url#http://$auth@}
host=${host_path%%/*}
repo_path=${host_path#*/}
repo_path=${repo_path%.git}
api="$scheme://$host/api/v1/repos/$repo_path"
api="http://$host/api/v1/repos/$repo_path"
release_url="$api/releases/tags/v${VERSION}"
echo "Pushing main and v${VERSION} to $REMOTE..."