Compare commits

..
Author SHA1 Message Date
ssmithxandClaude Sonnet 5 094f42312c docs(openwrt): document the confirmed working end-to-end install flow
Adds a verification checklist (service running, nodogsplash bound to
br-tollgate not br-lan via the rendered config not just UCI, LAN/SSH
untouched, mint probes succeeding) plus notes on the dev-build test-mint
injection and the default-route race between a router's LAN interface
and the node's other uplinks before the router's own WAN/WISP is live.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0176RpCxFNS9ZaSJjL72W9Z5
2026-09-07 03:06:58 +00:00
ssmithxandClaude Sonnet 5 da8c3ec193 docs(openwrt): note the Ctrl+T/LuCI workaround for setting the initial root password
Archipelago's Connect form only authenticates with an existing password;
it has no flow for setting one on a fresh, passwordless router. On the
node's kiosk display there's no visible tab bar, so Ctrl+T to open a new
tab to LuCI is the way to set it before Connect will work.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0176RpCxFNS9ZaSJjL72W9Z5
2026-09-07 02:53:21 +00:00
ssmithxandClaude Sonnet 5 4fdf8e8c58 fix(openwrt): bump pinned TollGate release v0.2.0 -> v0.5.0
The install code was hardcoded to the Oct 2025 v0.2.0 release —
nine releases behind. Its changelog covers exactly the failures hit
live against archy-x250-pa3: a mint with an empty/broken keyset
crash-looped tollgate-wrt forever (v0.5.0 adds "graceful degradation
when Cashu mints fail"), and the bundled captive-portal JS had zero
CBOR support, hard-rejecting the cashuB (NUT-00 V4) tokens modern
wallets like Minibits generate by default.

Also: v0.5.0 publishes native .apk packages for aarch64_cortex-a53
and x86_64. install_tollgate_apk_native now prefers those directly
(apk add handles deps/postinst/uci-defaults itself) instead of always
falling back to the manual ar/tar .ipk extraction dance, which only
exists because earlier releases had no native apk build at all.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0176RpCxFNS9ZaSJjL72W9Z5
2026-09-05 17:28:20 +00:00
ssmithxandClaude Sonnet 5 61b5d93b11 docs(openwrt): document the transient post-reboot apk-update failure
Observed live on archy-x250-pa3: right after WAN reconnects (fresh
boot or WAN reconfigure), the first Install attempt can fail with
"apk update failed ... router may have no internet access" purely
because the WiFi-uplink STA association hasn't finished yet — it's
not a real error, just retry a few seconds later. Also cross-referenced
the now-fixed /usr/bin/opkg hardcoding bug for anyone hitting it on an
older build.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0176RpCxFNS9ZaSJjL72W9Z5
2026-09-05 16:36:53 +00:00
ssmithxandClaude Sonnet 5 be06b3ce2b fix(ui): stop sending an empty ssh_password over the saved router connection
provisionTollgate/saveTollgateConfig/scanWifi/configureWan all fell
back to the Connect form's local refs (host/sshUser/sshPassword) when
connectedParams was null. Those refs only get populated if the form
was actually submitted this session — on a normal page load the
router reconnects via the server-persisted config instead, leaving
sshPassword at its default ''. Sending that as an explicit
(empty-but-present) ssh_password overrides the backend's saved-config
fallback, so every action auths with a blank password instead of the
real saved one.

Added authParams(): omit host/ssh_user/ssh_password entirely unless
connectedParams is actually set, same as the status poll already does.
Caught live: dropbear on archy-x250-pa3's router logged a single bad
password attempt at the exact moment "Install TollGate" was clicked,
sandwiched between periodic status-poll connections succeeding with
the real saved password.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0176RpCxFNS9ZaSJjL72W9Z5
2026-09-05 15:14:07 +00:00
ssmithxandClaude Sonnet 5 f3d96ae2ee fix(openwrt): resolve opkg/apk via $PATH, not a hardcoded /usr/bin path
opkg_check() and every opkg/apk invocation hardcoded /usr/bin/opkg and
/usr/bin/apk. Official OpenWrt images don't all symlink /bin into
/usr/bin — the glinet_gl-mt3000 24.10.2 build keeps them as separate
real directories with opkg living in /bin — so the check silently
missed a perfectly normal install and TollGate provisioning failed
with "this router's firmware may not support package management".

Switched every call to resolve through the router's own $PATH
(command -v / bare opkg / apk) instead. Reproduced and fixed live
against archy-x250-pa3, 2026-09-05.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0176RpCxFNS9ZaSJjL72W9Z5
2026-09-05 15:14:00 +00:00
ssmithxandClaude Sonnet 5 a4ae375617 docs(openwrt): fix TollGate step — install is separate from configure
Step 4 described a single "Provision TollGate" action that prompts for
price/step/mint upfront. The real UI (OpenWrtGateway.vue) doesn't work
that way: "Install TollGate" is a one-click action with no config form
that installs with defaults, and price/step/mint/enabled are only
editable afterward via a separate "Edit" panel. Caught while walking
through a live install.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0176RpCxFNS9ZaSJjL72W9Z5
2026-09-05 14:32:39 +00:00
ssmithxandClaude Sonnet 5 0646bc4e85 docs(openwrt): add GL.iNet AX3000 → stock OpenWrt flashing steps
Worked example for the Beryl AX (GL-MT3000, mediatek/filogic) verified
against the OpenWrt wiki and firmware selector: exact sysupgrade image
filename, GL.iNet UI / LuCI flash path, post-flash SSH state, and the
U-Boot recovery procedure if the flash goes sideways.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0176RpCxFNS9ZaSJjL72W9Z5
2026-09-05 14:26:21 +00:00
ssmithxandClaude Sonnet 5 0faaf4577f docs: add OpenWrt Gateway setup guide
Walks a node operator through pairing an OpenWrt router over SSH,
running the WAN/WISP wizard, and provisioning TollGate pay-as-you-go
WiFi — plus an RPC/architecture reference for developers. Distills
the openwrt crate, RPC handlers, and Vue panel into user-facing steps
that didn't exist anywhere in docs/ before.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0176RpCxFNS9ZaSJjL72W9Z5
2026-09-05 14:07:05 +00:00
archipelago d8320896c4 chore: publish release v1.8.10-alpha
Demo images / Build & push demo images (push) Successful in 3m26s
2026-09-01 19:01:54 -04:00
archipelago b87f1f0612 chore: prepare release v1.8.10-alpha 2026-09-01 18:58:33 -04:00
archipelago 1ca002661b fix(lnd): SendPaymentV2 needs an explicit fee budget — absent means ZERO
Demo images / Build & push demo images (push) Successful in 3m28s
v1.8.9's move to Router.SendPaymentV2 shipped without fee_limit_sat,
and the v2 route treats an ABSENT fee limit as zero allowed fees.
Every real route carries a routing fee (the 2-hop route here: 1.5
sats), so the pathfinder rejected them all and the wallet answered
"No route to the recipient" on EVERY send — all day, on healthy
channels with plenty of liquidity both ways.

The router debug log makes it unambiguous:
  wallet payment (v1.8.9 backend): fee_limit=0 mSAT     -> no route
  same payment by hand (lncli --fee_limit=100): fee_limit=100000 mSAT -> settles in 0.65s

My earlier "pipeline verified" claim was wrong — the manual lncli
verification set a fee limit by hand and masked this exact bug. The
400k that succeeded this morning went through the pre-update backend
on the pre-update LND.

Payments now carry lncli's own default budget — the payment amount
(100%), preferring the payer-supplied amount for zero-value invoices
and the invoice's own amount otherwise, with a nominal floor so the
limit can never be zero. Unit-pinned so it cannot regress.
2026-09-01 18:42:37 -04:00
archipelago 0d0e2e243a feat(lnd): channel-peer watchdog — a dropped peer link heals itself
Demo images / Build & push demo images (push) Successful in 3m49s
LND normally reconnects channel peers after a restart, but not reliably:
after long or repeated downtime (an app update, a node reboot,
reconciler churn) the peer link can stay down for hours while BOTH
endpoints keep the channel flagged disabled in the routing graph. The
node looks perfectly healthy, the wallet shows balance, and every
payment in either direction fails "no route to the recipient" —
observed live on framework-pt (2026-09-01): its only channel sat
disabled on both policy sides for ~17 hours after the LND 0.21.2
update, while shorty had 583k spendable and the user was told, by a
mis-mapped modal, that they had 'no payment channel'.

The channel graph is desired state — every open channel should have a
live peer connection. A daemon-side watchdog now enforces it:

- every 2 minutes, list channels + peers over LND REST
- for each channel whose remote peer is not connected, look the peer's
  advertised addresses up in the public graph and dial one
- per-peer retries throttled to 10 minutes so an unreachable peer is
  not hammered; 'already connected' counts as done; a peer with no
  advertised address is logged once per pass (cannot be dialed)
- no-ops quietly on nodes without LND (missing macaroon) and while a
  wallet is locked (503 body has no channels)

Unit tests pin the selection against the live REST shapes
(remote_pubkey in /v1/channels vs pub_key in /v1/peers).

v1.8.10 CHANGELOG + What's New entries staged so the next release run
is clean first time.
2026-09-01 17:51:15 -04:00
archipelago 9c49b502e3 docs: post-1.8.9 verification — pipeline confirmed, routing failure root-caused to framework-pt's disabled channel 2026-09-01 16:36:27 -04:00
archipelago d68a013e35 docs: tracker — v1.8.9 published, NPM live-healed on shorty via the signed catalog; funding-gate fix staged for v1.8.10 2026-09-01 11:43:33 -04:00
archipelago 1464b1b24d fix(wallet): the Lightning funding gate states the node's real channel state
Demo images / Build & push demo images (push) Successful in 3m38s
"LND thinks I do not have a channel" while the wallet showed plenty of
liquidity (framework-pt, 2026-09-01): the send gate sums outbound over
FULLY-OPEN channels only, which is correct — a just-opened channel
sits in LND's pending list until it has ~3 confirmations, and an
open channel can have all its balance on the far side — but the modal
then claimed the node had NO channel at all, in every one of those
states, and pointed the user at opening another one.

The gate already fetched the full channel list; it now records WHY
liquidity is zero and the modal says the truth per state:
- pending channels -> "your new channel is waiting for on-chain
  confirmations, it unlocks automatically, nothing is needed from you"
  (and no "Open a channel" button — that would send the user to fix
  a problem they don't have, possibly opening a second channel)
- open channels, zero on the needed side -> "balance is on the far
  side — you can receive but there's nothing to send right now"
- payment refused with a routing/liquidity error -> says so, instead
  of claiming no channels
- only a genuinely channel-less node keeps the open-one guidance

Eleven unit tests pin the state machine, including the regression
case (pending-only -> 'pending', not 'none') and fail-open on RPC
errors.
2026-09-01 11:40:25 -04:00
archipelago 82001403b4 chore: publish release v1.8.9-alpha 2026-09-01 11:05:55 -04:00
archipelago 81ede159ac chore: prepare release v1.8.9-alpha 2026-09-01 11:02:00 -04:00
archipelago 8e988be853 chore(release): v1.8.9-alpha prep — What's New block + version bumps
Demo images / Build & push demo images (push) Successful in 3m48s
The release gate requires the freshly-built bundle to embed the new
version, and the version reaches the bundle through the What's New
modal in AccountInfoSection — there was no v1.8.9-alpha block yet, so
create-release.sh correctly refused to ship a bundle that looked stale.
This adds the block (the user-facing summary of today's LND/HTTPS/
launcher/NPM/Portainer fixes) and carries the version bumps the
aborted run had already written (Cargo.toml, Cargo.lock, package.json,
package-lock), so the re-run starts from a clean tree.

Verified: npm run build now produces assets containing 1.8.9-alpha
(Settings chunk), i.e. the exact check the script runs passes.
2026-09-01 10:54:47 -04:00
archipelago 210f7f1b12 chore(catalog): re-sign the catalog — NPM letsencrypt mount + NET_BIND_SERVICE
Regenerated from the fixed apps/nginx-proxy-manager/manifest.yml (the
only semantic change vs the previous signed catalog) and signed with
the release-root key. Catalog-covered nodes pick this up on their next
hourly fetch and the NPM start/die loop ends: s6 gets its /etc/letsencrypt
mount back and the internal nginx can bind 80/443/81 again under
--cap-drop=ALL.
2026-09-01 10:37:09 -04:00
archipelago ed49cc974f docs: tracker updated — fixes landed, tests green, remaining steps are the two mnemonic ceremonies + node updates 2026-09-01 10:31:36 -04:00
archipelago 4849186ab9 docs: incident tracker for the 2026-09-01 https/launcher/LND breakage + v1.8.9 notes
Demo images / Build & push demo images (push) Successful in 3m57s
Root-cause table, fix inventory, regression-test inventory and the
deploy/live-verification checklist for today's fleet incident — written
as the working record while the fixes land, so the deploy + verify steps
can be checked off against real nodes rather than memory. CHANGELOG
carries the user-facing notes for the release these fixes ship in.
2026-09-01 10:29:10 -04:00
archipelago 3347b8b8b9 fix(ui): https app launches and the nostr bridge follow the frame's real origin
Three launcher/bridge defects combined to make HTTPS dashboards look
broken while HTTP ones worked:

1. portAuth() looked the launch port up under the name the user clicks
   ('mempool-web', 'lnd', 'bitcoin-knots'…), but the signed catalog
   declares those ports under the manifest id that owns them
   (archy-mempool-web, lnd-ui, bitcoin-ui). The lookup missed,
   portIsGateFronted answered false, and an HTTPS dashboard handed app
   frames http:// URLs — blocked as mixed content: mempool and IndeeHub
   'did not connect', bitcoin knots/core opened http:// in a new tab.
   Resolution now follows launch aliases, then a port-wide catalog scan
   that only answers when every declarer of that port agrees (a port
   any app publishes as plain HTTP is never upgraded to https).

2. The signed-catalog cache was only warmed by the Store/Discover
   views, so a user who went straight to My Apps launched apps with an
   empty cache. Warmed at dashboard mount now — fetchAppCatalog()
   already memoizes with a 1h TTL.

3. The NIP-07 bridge compared event.origin for strict equality with the
   recorded (http) app URL and replied to the recorded URL as the
   postMessage targetOrigin — both break the moment a frame is scheme-
   upgraded (cached HSTS did exactly that): every nostr request was
   silently dropped and replies to the stale origin threw. The bridge
   now matches host+port (scheme deliberately ignored) and always
   replies to event.origin — the frame's real origin.

Unit tests cover alias resolution (incl. bitcoin-knots→8334→https),
the conservative port-scan, and scheme-agnostic sender matching.
2026-09-01 10:29:05 -04:00
archipelago e382e679ae fix(apps): NPM needs /etc/letsencrypt mounted and NET_BIND_SERVICE
Converting Nginx Proxy Manager to a platform manifest (fc68c5b6) dropped
two things its image hard-requires, and the result was an endless
start/die loop — shorty-s watched it restart 3,176 times:

1. /etc/letsencrypt mount: NPM's s6 'prepare' service refuses to boot
   without it ('ERROR: /etc/letsencrypt is not mounted!'). Mounted from
   the same persistent app directory as before
   (/var/lib/archipelago/nginx-proxy-manager/letsencrypt), so existing
   certificates are preserved — no data moves, no migration.

2. NET_BIND_SERVICE: NPM's internal nginx listens on 80, 443 AND 81,
   and the orchestrator runs --cap-drop=ALL. The legacy podman-run path
   defaulted to the full capability set (and the legacy repair path in
   package/config.rs always listed it), which is why this only broke
   once the manifest became the source of truth.

The signed catalog embeds manifests with origin-wins semantics, so the
catalog carries the fix for every catalog-covered node — regenerate it
here (plus the generated store/launcher-port artifacts, which also pick
up drift from bf6ef964's retired apps). Catalog re-signing follows the
usual ceremony.
2026-09-01 10:29:05 -04:00
archipelago 77d0768a21 fix(nginx): stop pinning HSTS — actively clear it instead
The HTTPS server block sent Strict-Transport-Security:
max-age=31536000; includeSubDomains. Browsers that visited HTTPS once
cached the policy and then silently upgraded the still-open HTTP
dashboard's fetches and frames to https — a scheme change is
cross-origin, so every /rpc/v1 call died 'No Access-Control-Allow-
Origin header' while the node was perfectly healthy (framework-pt
2026-09-01: the 'Failed to fetch' storm, dashboard 'not responding',
every app frame mixed-content-blocked).

Plain HTTP is a supported access mode BY DESIGN on this platform: the
node's certificate is optional and self-signed (Settings → Node
certificate, /ca.crt flow), and setup-node-ca.sh deliberately keeps
port 80 serving for devices that haven't installed the CA. So:

- port 80 sends no HSTS at all (with the rationale inline)
- port 443 sends max-age=0, which ACTIVELY DELETES the policy already
  cached by affected browsers — leaving it absent would have kept every
  stranded browser broken for a year

tests/lifecycle/bats/nginx-hsts.bats pins all three properties at the
gate: no live policy on :80, max-age=0 (never 31536000) on :443, and
no long-lived pin anywhere in the deployed config.
2026-09-01 10:28:57 -04:00
archipelago f133d5555a feat(apps): surface Portainer's first-run setup token in the credentials interstitial
Portainer >=2.21 no longer lets whoever loads the page first claim the
admin account: on a fresh install it mints a one-time setup token and
prints it ONLY to the server logs. On an appliance that is a dead end —
'check the Portainer server logs' is exactly what a user cannot follow,
and after the 2.45.0 update it made a freshly restarted Portainer look
broken ('disappeared', then demands a token nobody can find).

package.credentials — the same RPC that powers the login-credentials
card on the app page — now extracts the setup_token line from
portainer's recent container logs and hands it over with the existing
copy-button treatment, titled and explained for a first-time user. The
token stops being printed once setup completes, and any container
recreate drops the log line, so the card disappears on its own and no
dead token lingers. Parsing is a pure, unit-tested scan against the
live-captured 2.45.0 log shape (64 hex chars after setup_token=).
2026-09-01 10:28:57 -04:00
archipelago cbd5314dd9 fix(lnd): pay through Router.SendPaymentV2 — LND 0.21 removed the old route
LND 0.21.2 removed the deprecated Lightning.SendPaymentSync REST route
(/v1/channels/transactions). The backend still called it, so every
Lightning send answered literal HTTP 404 and the wallet UI reported
'Payment failed: Not Found' fleet-wide right after the pin bump —
receive worked, which made it look intermittent.

Pay through the supported Router.SendPaymentV2 route (/v2/router/send)
instead, keeping the existing contract with the UI:
- single-record responses (no_inflight_updates) unwrapped from the
  grpc-gateway result envelope, transport errors from the nested error
- a slow multi-hop payment still resolves as pending + payment hash
  (only LND may declare failure), never a false 'Payment failed'
- LND's failure_reason codes translated to the same plain-language
  advice, invoice-expiry still says 'ask for a fresh invoice'

Guard it at the gate: tests/lifecycle/bats/lnd-api-compat.bats POSTs a
deliberately-invalid invoice to /v2/router/send on the RUNNING LND and
fails if the route answers 404 — the image/backend skew that shipped
silently last time because no test ever spoke the payment endpoint.
Also bumps the stale lnd image expectation in remote-lifecycle.sh.
2026-09-01 10:28:49 -04:00
archipelago 9fb2e1ed9e chore(catalog): sign the Cuprate logging fix 2026-09-01 08:47:29 -04:00
archipelago 7125dea05d Merge PR #152: fix Cuprate logging defaults 2026-09-01 08:39:26 -04:00
ssmithxandClaude Sonnet 5 bcdf2c75be fix(cuprate): file log level should be info, not cuprated's debug default
The previous commit on this branch copied cuprated's raw
--generate-config defaults (stdout=info, file=debug, max_log_files=7)
verbatim. Turns out that's the wrong reference: compared against
ssmithx@archy-dev-pa:/home/ssmithx/cuprate/Cuprated.toml — the actual
dev config this app was built and tested against — file logging is
meant to run at "info" with 14 rotated files, not the binary's raw
"debug"/7. Confirmed live on amishparadise: podman logs (stdout) was
already clean at info, but the on-disk file log
(.local/share/cuprate/logs/<date>) was flooding with per-peer DEBUG
gossip (~400KB in 2 minutes) because it inherited the binary default
instead of the intended one.

Left the resource-tuning knobs in the reference config (8GB
target_max_memory, tokio/rayon thread counts, P2P connection counts,
explicit reader_threads) out of this file — those were sized for
ssmithx's dev box and don't apply here; this manifest's
target_max_memory already stays deliberately under the container's
4Gi memory_limit.

Regenerated releases/app-catalog.json (still unsigned).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ga6N8Jk1YdCTMMX1LjDpAr
2026-09-01 12:27:33 +00:00
ssmithxandClaude Sonnet 5 e77f60085d fix(cuprate): make Cuprated.toml logging levels explicit
apps/cuprate/manifest.yml only ever wrote network/target_max_memory/
rpc.restricted.enable into Cuprated.toml, so the [tracing.stdout] and
[tracing.file] tables were silently absent — cuprated still applied
its built-in info/debug/7 defaults, but nothing on disk showed it.
Verified live on amishparadise 2026-09-01: the deployed 5-line file
had no [tracing] section at all, and the level was only discoverable
by running `cuprated --generate-config` and diffing.

Add both tables to the manifest's files[].content with the same
values cuprated already defaults to, so every new install ships a
Cuprated.toml an operator can actually read and tune. overwrite:false
means already-deployed nodes (amishparadise included) keep their
existing file untouched — this only changes what fresh installs get.

Regenerated releases/app-catalog.json (unsigned) to embed the updated
manifest; needs scripts/sign-catalog.sh before it's authoritative for
the fleet.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ga6N8Jk1YdCTMMX1LjDpAr
2026-09-01 12:19:20 +00:00
archipelago 6c31eb9d4a chore(catalog): sign the LND 0.21.2 sweep 2026-09-01 07:45:39 -04:00
archipelago 63e6c64c63 fix(ci): drop the remaining stray Claude-worktree gitlinks 2026-09-01 05:27:15 -04:00
archipelago 4d8bb1fd44 fix(ci): drop a stray gitlink that broke every demo build
A Claude worktree under aiui/ was committed as a submodule gitlink
(160000) with no .gitmodules entry, so actions/checkout's recursive
submodule pass exited 128 and every 'Build & push demo images' run since
v1.8.6 failed. Removing the index entry — the worktree is local state
and was never meant to be tracked.
2026-09-01 05:27:00 -04:00
archipelago 2b4b60013c feat(lnd): build LND 0.21.2-beta in-house and sweep the pin
Demo images / Build & push demo images (push) Failing after 40s
Upstream publishes no docker images; our v0.18.4 image was built in-house.
This pass: official v0.21.2-beta release binaries (sha256-verified against
the signed release manifest), static, on alpine with the same entrypoint
shape as our existing image, pushed to our registry and smoke-run.
LND 0.21 auto-migrates the channel DB on first start (keeping a backup) —
the Update button is user-initiated, never auto-applied.
2026-09-01 05:14:50 -04:00
archipelago f0ef410948 chore(catalog): sign the swept pins 2026-09-01 04:52:28 -04:00
archipelago 19467e9b7c chore(apps): sweep pin bumps — gitea 1.27.3, vaultwarden 1.37.2, filebrowser 2.63.23, home-assistant 2026.8.3, adguardhome 0.107.79, portainer 2.45.0, pine-whisper 3.6.0
Demo images / Build & push demo images (push) Failing after 39s
First upstream sweep since v1.8.5: the safe patch/minor pins, mirrored
into our registry first (source.archipelago-foundation.org/lfg2025/*).
Held for their own careful passes: the majors (grafana 11, nextcloud,
uptime-kuma 2, bitcoin-core 29, the DBs) and consensus-sensitive apps
(fedimint, electrumx 2.0). LND 0.21.2 needs an in-house image build —
upstream publishes none.
2026-09-01 04:50:49 -04:00
archipelago 628ed252b4 chore: publish release v1.8.8-alpha 2026-09-01 04:18:16 -04:00
archipelago bc94445ca0 chore: sign the v1.8.8 app catalog + release manifest 2026-09-01 03:57:23 -04:00
archipelago 04cf0f663a chore: drop the superseded v1.8.8 prep for rebuild 2026-09-01 03:49:16 -04:00
archipelago 576c642da4 fix(apps): ollama resource type + adguardhome port; gate on collisions
Demo images / Build & push demo images (push) Failing after 38s
Ollama's embedded manifest failed the typed parse (memory_limit wants a
string) so the catalog overlay was skipped for it; AdGuard Home's
conventional :3000 collided with Grafana's. The release gate now runs
the host-port collision test (repo_app_manifests_have_no_host_port_collisions)
so this class can never ship untested again.
2026-09-01 03:31:02 -04:00
archipelago 12866db84a chore: sign the v1.8.8 app catalog + release manifest 2026-09-01 03:16:10 -04:00
archipelago a184254706 style: rustfmt the ssh-mesh module 2026-09-01 02:42:39 -04:00
archipelago 192e045426 feat(ui): SSH-over-mesh card, store-listing filter, icon treatment
Demo images / Build & push demo images (push) Failing after 41s
Settings gains the SSH-over-mesh card (danger-zone confirmation for the
any-peer scope, sshd preflights, fipssh copy hint). The signed-catalog
merge filters components via the shared serviceNames module; Discover
grids get the standard icon container; install no longer yanks the user
to My Apps; v1.8.8 release notes.
2026-09-01 02:41:55 -04:00
archipelago 9ac46a69f8 feat(fips): SSH-over-mesh toggle + manifest-driven package metadata
fips/ssh_mesh.rs owns the 90-ssh.nft drop-in lifecycle: off by default,
any-peer scope behind the UI's danger confirmation or an explicit mesh
address list, reconciled on every daemon config install. The scanner now
takes installed apps' icons from their real manifest metadata (Cuprate's
Services tile) and classifies manifest-declared UI apps as launchable
even when the address probe misses (Alby Hub).
2026-09-01 02:41:55 -04:00
archipelago bf6ef9644c chore(apps): retire morphos-server, did-wallet, lightning-stack, cryptpad
Store-listing components are filtered via the shared serviceNames canon;
these four never earn a tile: MorphOS server is old, the Web5 DID wallet
and CryptPad are untested, Lightning Stack is an untracked upstream
bundle (LND covers it).
2026-09-01 02:41:55 -04:00
archipelago c32910809e chore: publish release v1.8.7-alpha 2026-09-01 01:42:12 -04:00
archipelago d2174128c5 chore: sign the v1.8.7 app catalog + release manifest 2026-09-01 01:37:24 -04:00
archipelago 2ad0171e5f fix(ui): drop the now-unused scheme helper
Demo images / Build & push demo images (push) Failing after 36s
2026-08-31 19:08:17 -04:00
archipelago 46cb0bfd37 fix(ui): gate-fronted https launches + signed-catalog App Store
Demo images / Build & push demo images (push) Failing after 36s
directAppUrl(), the legacy open() path, and resolveRuntimeLaunchUrl()
now upgrade to https only for ports the app gate fronts — decided from
the signed catalog's embedded manifest ports (auth gated/open), so
plain-HTTP publishes (legacy installs, auth:none API ports like
Cuprate's RPC) keep http instead of failing outright. fetchAppCatalog()
merges the daemon-verified signed catalog into the App Store listing
(signed entries appear immediately; community copy supplies featured
and curated metadata), and Marketplace.vue uses the same dynamic fetcher
as Discover so the grid sees signed-new apps too.
2026-08-31 18:41:00 -04:00
archipelago b8593c9090 docs(release): v1.8.7 notes — https app launches + platform round
Demo images / Build & push demo images (push) Failing after 34s
2026-08-31 18:40:51 -04:00
archipelago fc68c5b680 feat(apps): complete the manifest platform — convert the last five stragglers
Demo images / Build & push demo images (push) Failing after 36s
Nginx Proxy Manager, Tailscale, Ollama, CryptPad, and AdGuard Home now
carry full manifests: the app gate fronts their web ports (TLS on the
same port, node login where appropriate), installs run through the
orchestrator, and pins live in the signed catalog. Tailscale mirrors its
legacy shape exactly (userspace networking, web console on 8240, plain
HTTP for the gate to front). Ollama stays loopback-only — the
assistant's local model backend, not a web app.

Retires the four already-removed apps for good (FIPS, Nostr VPN,
Routstr, Penpot pins dropped from image-versions.sh, the generator map,
and image_versions.rs), fixes Cuprate's duplicated metadata block that
strict YAML parsers reject, and updates the port-inventory review gates
for the new open (3 own-login consoles) and exempt (2 DNS) ports.
2026-08-31 18:40:39 -04:00
archipelago 3ed75c328d style: rustfmt the signed-catalog serving 2026-08-31 17:09:16 -04:00
archipelago 687196ad3b chore: prepare release v1.8.7-alpha
Demo images / Build & push demo images (push) Failing after 37s
2026-08-31 17:08:37 -04:00
archipelago e2bd6330a1 test(app-catalog): pin the signed-catalog body gate 2026-08-31 17:08:37 -04:00
archipelago 7c0a492c43 fix(ui): launch apps on the page's scheme over HTTPS
New-tab apps and the companion WebView got hardcoded http:// URLs, so a
node reached over HTTPS opened Vaultwarden, BTCPay, Grafana et al in
cleartext. Every app port is gate-owned and serves TLS on the same port
(appgate/tls.rs), so directAppUrl(), the legacy open() path, and
resolveRuntimeLaunchUrl() now follow the page's scheme. HTTP pages (the
kiosk, LAN) are unchanged; netbird keeps its unconditional https.
2026-08-31 17:08:26 -04:00
archipelago 3089624969 Merge remote-tracking branch 'gitea-vps2/main' 2026-08-31 16:15:17 -04:00
archipelago 5b658cec67 feat(app-catalog): serve the signed catalog from the node first 2026-08-31 16:15:13 -04:00
archipelago 21b8d4b1ee catalog: add Cuprate (0.1.0-preview) 2026-08-31 16:10:38 -04:00
lfg2025 6f05f5583f Merge pull request 'docs: session record — companion 0.5.28 shipped + deployment playbook' (#151) from companion/session-2026-08-31 into main 2026-08-31 20:03:03 +00:00
Dorian 02ac4396d1 docs: session record — companion 0.5.28 shipped + the deployment playbook
Full state at session end (all public surfaces verified byte-identical
at 0.5.28/vc48; only node web-bundle redeploys outstanding), the feature
map, and the operational playbook next sessions need: Tor SOCKS proxy
for Gitea API/curl (the 'unreachable API' was a missing proxy flag),
token scopes, protected-main ship flow via -ship branch + PR + API merge,
stale local main lineage, the foundation server's two surfaces, demo CI
auto-redeploy, build/test commands, and the open items.
2026-08-31 21:02:59 +01:00
archipelago 5ffdcc9936 docs(release): explain the v1.8.7 correction
Demo images / Build & push demo images (push) Failing after 39s
2026-08-31 15:46:18 -04:00
archipelago 9cf07e1eac fix(release): enforce the v1.8 What's New floor
Demo images / Build & push demo images (push) Failing after 39s
2026-08-31 15:44:48 -04:00
archipelago e7854702c0 chore: publish release v1.8.6-alpha
Demo images / Build & push demo images (push) Failing after 36s
2026-08-31 15:40:23 -04:00
archipelago d4018a6e73 chore: prepare release v1.8.6-alpha 2026-08-31 15:34:51 -04:00
archipelago b57cba63d1 Merge remote-tracking branch 'gitea-vps2/main'
Demo images / Build & push demo images (push) Failing after 36s
2026-08-31 15:12:59 -04:00
archipelago 7bc9f69b1f fix(settings): start What's New history at v1.8.0 2026-08-31 15:12:18 -04:00
lfg2025 913743923c Merge pull request 'docs: deploy handoff — companion 0.5.28 to the live surfaces' (#150) from companion/0.5.28-deploy-handoff into main 2026-08-31 19:01:58 +00:00
Dorian 241e8cfca4 docs: handoff — deploy companion 0.5.28 (vc48) to the live surfaces
For the archi-dev-box agent: companion 0.5.28 is on main (PR #149) and
Gitea raw serves it (verified byte-identical, v1+v2+v3). Remaining: the
foundation server's static /packages mirror (the real-node QR download
URL — currently 0.5.27), node web-bundle redeploys (same as the
2026-07-23 flow), and confirming the demo stack flipped after CI's
webhook redeploy. Exact commands, expected shasum, and final verify
block included.
2026-08-31 20:01:44 +01:00
archipelago 017505c431 fix(release): include every curated changelog item 2026-08-31 14:52:47 -04:00
archipelago 7a39d8fbd1 fix(settings): sort What's New history newest-first
Demo images / Build & push demo images (push) Failing after 36s
2026-08-31 14:50:55 -04:00
archipelago e3275353b9 fix(release): publish assets before exposing manifest 2026-08-31 14:45:29 -04:00
lfg2025 9f1a289d1a Merge pull request 'Companion 0.5.28 — backup & restore, NIP-46 remote signer, companion-gated install pitch' (#149) from companion/0.5.28-ship into main
Demo images / Build & push demo images (push) Failing after 41s
2026-08-31 18:38:43 +00:00
Dorian dd07da53f9 chore(android): update companion apk download 2026-08-31 19:34:57 +01:00
Dorian 7d09418a09 Companion 0.5.28 — backup & restore (#128), NIP-46 remote signer (#139), companion-gated install pitch (#61 residual)
The companion-agent queue from the 2026-08-30 handoff, complete:

- Backup & Restore: hub sub-page, SAF export/import sealed in the
  node's ADR-005 envelope (Argon2id + ChaCha20-Poly1305, byte-compatible
  with core backup.rs), merge-only restore, no cloud.
- Remote Signer: the phone is the NIP-46 bunker — nsec generate/import,
  nostrconnect:// QR pairing (scanner + OS deep link), per-request
  approve/deny card, NIP-44 v2 transport with NIP-04 receive fallback,
  wire-faithful to rust-nostr's reference bunker. Crypto pinned to the
  official NIP-44 + BIP-340 vectors; e2e harness included.
- #61 residual: banner + manual intro trigger + overlay all gate on
  isCompanionApp() (web-side, vitest-covered).
- Hub modal: new sub-pages like Nodes/FIPS, 70% height cap, node ULA
  display/copy in the Nodes list, fipssh Termux helper (npub→ULA is a
  pure public-key function — verified against the fips crate).

Issues #61 (comment), #128, #139 closed on the tracker.
2026-08-31 19:34:05 +01:00
Dorian b927461f8e feat(companion): fipssh — ssh to a mesh node by npub (Termux helper)
Verified against the fips crate source: the mesh ULA is a pure function
of the PUBLIC key — fd || sha256(x-only pubkey)[0..15] — so the npub is
the durable address and needs no resolver. Android/tools/fipssh wraps
ssh for Termux: 'fipssh user@npub1…' derives the ULA (pure-python
bech32 + sha256, checksum-validated, typo protection) and execs ssh
over the companion's split tunnel; --resolve prints the ULA alone.

The derivation is pinned by a new Rust test
(npub_derives_the_same_mesh_ula_as_the_fips_identity, 3 seeds against
fips::Identity) and the helper's output was verified byte-identical
against a live fips identity pair. SSH-over-mesh handover updated with
an addendum: node docs/UI can advertise npub-based addressing, no
node-side DNS needed for this case.
2026-08-31 15:00:42 +01:00
Dorian 8cf45377a2 docs: handoff — SSH over the FIPS mesh (node-side toggle) for the node agent
Today's field test: Termux over the companion's split tunnel reaches the
node's fips0 ULA and gets RST — the mesh path works end to end, port 22
is refused by the node (fips0 default-deny, no 22 in the fips.d drop-ins;
sshd IPv6 listening unverified). The interim manual unblock (a
source-restricted 90-ssh.nft drop-in) is documented, but the real ask is
a first-class 'SSH over mesh' settings toggle in the node UI, with the
drop-in lifecycle owned by the daemon, a source-scope decision (paired
phones vs any mesh peer), sshd preflights, and an acceptance checklist.
Companion side is done (device-wide split tunnel + the node ULA now
displayed/copyable in the hub Nodes page) — the node agent is downstream.
2026-08-31 14:54:28 +01:00
Dorian 4efac99e97 feat(companion): show + copy the node's mesh ULA in the hub Nodes list
FIPS nodes carry their fips0 ULA in the saved entry, but it was never
displayed — the only way to learn it was the node itself. Each FIPS
node row in the Nodes page now shows its mesh address as a monospace
subtitle with a tap-to-copy affordance, which is exactly the address
other apps on the phone (Termux ssh over the split tunnel, for
example) need. Non-FIPS entries are unchanged.
2026-08-31 14:48:53 +01:00
Dorian 981296e8b0 fix(companion): backup + signer live inside the hub modal, not standalone screens
Field feedback on 0.5.28: the standalone Backup/Signer screens were hard
to read over the synthwave background, back left the app instead of the
menu, and they broke the hub's one-container interaction model. Both are
now hub sub-pages exactly like Nodes/FIPS:

- BackupSection / SignerSection (ui/components) render inside the NESMenu
  panel with the menu's own dark glass surface, scrim, and palette — the
  readability and theming problem disappears with the standalone surface.
- The header back arrow returns to the hub card page (same as Nodes).
- The panel height cap drops from 92% to 70% of the screen — ~15%
  breathing margin top and bottom; content scrolls inside.
- The pairing QR scanner is hosted by NESMenu OUTSIDE the panel
  (QrGlassModal is a full-screen Box, not a Dialog — inside the panel's
  scroll it would clip), and decoded nostrconnect:// URIs funnel into the
  signer section through the same latch as the deep link.
- The nostrconnect:// deep link now routes to the session and pops the
  hub open on the signer sub-page (SignerLaunch singleton) instead of a
  dedicated route; standalone screens and routes removed.
- BunkerManager.refreshState is now a proper suspend fun (was
  runBlocking on the caller's dispatcher).

Docs updated to the new locations. Rebuilt for on-device testing
(v0.5.28-debug/vc48, same signing cert).
2026-08-31 14:23:04 +01:00
Dorian 22f8129b52 feat(companion): backup & restore + NIP-46 remote signer — 0.5.28 (#128, #139)
Companion 0.5.28 (versionCode 48), the companion-agent queue items:

#128 Backup & Restore — the phone side of losing your phone or wiping it
to cross a border. Hub card → SAF export/import of an encrypted .json:
everything the app holds (servers+passwords, FIPS identity/peers, signer
key) sealed in the node's ADR-005 envelope (Argon2id + ChaCha20-Poly1305,
native backup.rs — same blob layout as the node's, node-shaped envelopes
decrypt too). Restore is merge-only: servers upsert npub-first, identity
and signer key adopt only when absent, peers union by npub. No cloud, no
telemetry — the file goes wherever the user saves it.

#139 Remote Signer — the phone IS the NIP-46 bunker. Generate/import a
nostr key, scan a nostrconnect:// QR (in-app scanner or deep link), and
approve/deny each sign_event request from a legible card (kind label,
content, tags, time) — nothing signs without a human. Wire-faithful to
rust-nostr's reference bunker (connect-carrying-secret handshake, NIP-44
v2 transport with NIP-04 receive fallback, kind-24133 responses);
get_public_key/describe/ping handled, everything else 'not authorized'.
Session state in BunkerManager, UI in SignerScreen, hub card wired.

Plus NativeCore (JNI object for the new native surface), FipsPreferences
peers-merge for restore, nostrconnect:// intent filter, and the release
docs (companion-backup-restore.md, companion-nip46-remote-signer.md).

Also Android/tools/nip46-test-client.py: a pure-Python NIP-46 client that
plays the node's login role (QR, handshake, get_public_key, sign_event)
and verifies the phone's signature with an independent BIP-340 — the
end-to-end test for the feature until node-side lands. Its crypto matches
the official NIP-44 + BIP-340 vectors byte-for-byte, the same vectors the
Rust core passes, so the two interop by construction.

Built + smoke: assembleDebug v0.5.28/vc48, same signing cert as the
served 0.5.27 (d622e07e…644d) so it updates in place.
2026-08-31 13:53:52 +01:00
Dorian 57e31eb192 feat(companion): backup envelope + NIP-46 signer crypto in the native core
Extends archy-fips-core with the two companion-release features' crypto
(#128, #139), same JNI-over-JSON contract as the mesh surface:

backup.rs — the ADR-005 encrypted-backup envelope, byte-compatible with
the node's backup code (Argon2id default params + ChaCha20-Poly1305,
blob = base64(salt||nonce||ct)); decrypt ignores extra envelope fields
so node backups read here too. Round-trip, tamper, wrong-passphrase and
cross-shape tests included.

nostr.rs — the phone-side remote-signer crypto: nsec/npub bech32 keys,
BIP340 schnorr event signing (NIP-01 id serialization), NIP-44 v2
payloads (HKDF-SHA256 + ChaCha20 + HMAC-SHA256, both padding prefixes),
NIP-04 fallback, nostrconnect:// parsing with repeated relay params.
Verified against the official NIP-44 vectors (conversation keys, message
keys, padded lengths, byte-exact encrypt vectors), the BIP-340 reference
sign vectors, and round-trip/tamper/failure tests. secp256k1 0.29 note:
Keypair::public_key() is the 33-byte compressed key — x-only pubkeys
must go through .x_only_public_key().0 (one real bug the vectors caught).

JNI glue adds com.archipelago.app.NativeCore: backupEncrypt/Decrypt,
nostrGenerateSecret/SecretFromAny/ParseConnectUri/SignEvent and the
NIP-44/NIP-04 cipher pairs. Android arm64 build verified via cargo-ndk
(7.2 MB .so, +0.4 MB for both modules). Host: cargo test 23/23, clippy clean.
2026-08-31 13:29:36 +01:00
Dorian 12c853da45 docs(companion): verify the zxing-cpp integration sketch online
The QR-decoder option doc was written on an offline machine with the
Maven coordinates and wrapper API flagged as from-memory. Verified
against Maven Central + the wrapper source: artifact is
io.github.zxing-cpp:android:3.1.1 (current release), Format.QR_CODE is
nested inside BarcodeReader (not a top-level BarcodeFormat), options are
a constructor-argument data class, and read(ImageProxy) handles the
Y-plane/cropRect/rotation itself. Sketch updated accordingly; the option
itself stays NOT-actioned pending the move-to-the-code decision trigger.
2026-08-31 13:06:45 +01:00
Dorian d259f3cbb9 fix(web): companion-gate the store banner + manual intro trigger (#61 residual)
Only the auto-popup was companion-gated — inside the companion WebView
users still saw the 'install the companion' banner in the App Store and
could pop the intro overlay through it. Gates all three paths on
isCompanionApp(): CompanionBanner self-hides, openCompanionIntro() is a
no-op, and the manual-open watcher in CompanionIntroOverlay refuses to
open (the overlay's raw window check also moves to the canonical helper
so there is exactly one detection). No APK change.
2026-08-31 12:56:32 +01:00
142 changed files with 10084 additions and 7913 deletions
+2 -2
View File
@@ -11,8 +11,8 @@ android {
applicationId = "com.archipelago.app"
minSdk = 26
targetSdk = 35
versionCode = 47
versionName = "0.5.27"
versionCode = 48
versionName = "0.5.28"
vectorDrawables {
useSupportLibrary = true
+9
View File
@@ -54,6 +54,15 @@
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="archipelago" android:host="pair" />
</intent-filter>
<!-- Remote-signer pairing deep link (NIP-46, companion 0.5.28):
nostrconnect://<client-pubkey>?relay=...&secret=... — the
node's login QR, hand-off from any QR scanner app. -->
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="nostrconnect" />
</intent-filter>
</activity>
<!-- Embedded FIPS mesh node: split-tunnel VpnService (fd00::/8 only),
@@ -0,0 +1,69 @@
package com.archipelago.app
import org.json.JSONObject
/**
* JNI binding to the companion's non-mesh native surface (same
* libarchy_fips_core.so as FipsNative — backup + nostr signer crypto, built
* from Android/rust/archy-fips-core).
*
* Same contract as FipsNative: JSON over strings, failures come back as
* {"error": "…"} rather than exceptions, and [available] is false on ABIs
* the .so isn't built for so every caller can degrade gracefully.
*/
object NativeCore {
val available: Boolean = try {
System.loadLibrary("archy_fips_core")
true
} catch (_: Throwable) {
false
}
// ── Backup (#128): the node's ADR-005 envelope ──────────────────────────
/** Encrypt a JSON payload into an ADR-005 envelope (ChaCha20-Poly1305). */
external fun backupEncrypt(payload: String, passphrase: String): String
/** Decrypt an ADR-005 envelope back to its payload JSON. */
external fun backupDecrypt(envelope: String, passphrase: String): String
// ── NIP-46 remote signer (#139) ─────────────────────────────────────────
/** Generate a fresh nostr key: {"secret","pubkey","npub","nsec"}. */
external fun nostrGenerateSecret(): String
/** Import a key from hex or nsec…: {"secret","pubkey","npub","nsec"}. */
external fun nostrSecretFromAny(secret: String): String
/** Parse nostrconnect://…: {"clientPubkey","relays":[…],"secret","perms","name","url","image"}. */
external fun nostrParseConnectUri(uri: String): String
/**
* Sign `{kind, content, tags, created_at}` with the signer key: returns
* the full signed event JSON. Approval happens BEFORE this call — the
* native side never signs unasked.
*/
external fun nostrSignEvent(secretHex: String, eventJson: String): String
/** NIP-44 v2 encrypt/decrypt; result JSON: {"result": payload} or {"error": …}. */
external fun nostrNip44Encrypt(secretHex: String, peerPub: String, plaintext: String): String
external fun nostrNip44Decrypt(secretHex: String, peerPub: String, payload: String): String
/** NIP-04 fallback (deprecated but still spoken by real clients). */
external fun nostrNip04Encrypt(secretHex: String, peerPub: String, plaintext: String): String
external fun nostrNip04Decrypt(secretHex: String, peerPub: String, payload: String): String
/** True when a native reply is an error envelope. */
fun isErr(json: String): Boolean = try {
JSONObject(json).has("error")
} catch (_: Exception) {
true
}
/** Error text from a native reply, or a generic message if malformed. */
fun errMsg(json: String): String = try {
JSONObject(json).optString("error", "native call failed")
} catch (_: Exception) {
"native call failed"
}
}
@@ -0,0 +1,229 @@
package com.archipelago.app.data
import android.content.Context
import com.archipelago.app.NativeCore
import com.archipelago.app.fips.FipsPreferences
import com.archipelago.app.nostr.NostrSignerPreferences
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.withContext
import org.json.JSONArray
import org.json.JSONObject
/**
* Companion backup & restore (#128) — the phone side of "losing your phone,
* or wiping it to cross a border".
*
* The payload (servers + FIPS identity/peers + signer key + flags) is
* serialized to JSON and sealed into the node's ADR-005 envelope (Argon2id +
* ChaCha20-Poly1305) by the native core — the SAME envelope the node uses,
* not a second format. The passphrase never leaves the encrypt call.
*
* Transport is deliberately boring: a plain .json file the user saves via
* the system file picker (SAF) — on GrapheneOS there is no cloud backup and
* there should be none here either; the file goes wherever the user puts it
* (USB drive, computer, a folder synced their way).
*/
class BackupManager(private val context: Context) {
private val servers = ServerPreferences(context)
private val fips = FipsPreferences(context)
private val signer = NostrSignerPreferences(context)
/** Everything the backup captures, for the restore preview UI. */
data class PayloadSummary(
val serverCount: Int,
val hasFipsIdentity: Boolean,
val hasSignerKey: Boolean,
val appVersion: String,
)
/** What a restore actually did, for the result UI. */
data class RestoreResult(
val serversRestored: Int,
val activeSet: Boolean,
val fipsIdentityRestored: Boolean,
val signerKeyRestored: Boolean,
)
private fun appVersion(): String = try {
context.packageManager.getPackageInfo(context.packageName, 0).versionName ?: ""
} catch (_: Exception) {
""
}
/**
* Assemble the encrypted backup envelope. Runs on IO: DataStore reads
* plus the Argon2id KDF (tens of ms) + AEAD.
*/
suspend fun createBackup(passphrase: String): String = withContext(Dispatchers.IO) {
require(passphrase.isNotEmpty()) { "passphrase required" }
val active = servers.activeServer.first()
val saved = servers.savedServers.first()
val fipsId = fips.identity()
val peers = fips.peersJson()
val partyPeers = fips.partyPeers()
val partyName = fips.partyName()
val partyListen = fips.partyListen()
val signerSecret = signer.secret()
val payload = JSONObject().apply {
put("app", "archipelago-companion")
put("payloadVersion", 1)
put("appVersion", appVersion())
put("createdAt", System.currentTimeMillis() / 1000)
put("servers", JSONArray(saved.map { it.serialize() }))
put("active", active?.serialize() ?: JSONObject.NULL)
if (fipsId != null) {
put("fips", JSONObject().apply {
put("secret", fipsId.secret)
put("npub", fipsId.npub)
put("address", fipsId.address)
put("peers", JSONArray(peers))
put("partyPeers", JSONArray().apply { partyPeers.forEach { put(JSONObject().apply {
put("npub", it.npub); put("ula", it.ula); put("name", it.name)
put("ip", it.ip); put("port", it.port)
}) } })
put("partyName", partyName)
put("partyListen", partyListen)
})
}
if (signerSecret != null) {
put("signer", JSONObject().apply { put("secret", signerSecret) })
}
put("flags", JSONObject().apply {
put("introSeen", servers.introSeen.first())
})
}
val envelope = NativeCore.backupEncrypt(payload.toString(), passphrase)
if (NativeCore.isErr(envelope)) throw BackupException(NativeCore.errMsg(envelope))
envelope
}
/**
* Peek at a decrypted backup (passphrase already checked) to preview what
* a restore would do. Does NOT touch any stored state.
*/
suspend fun readBackup(envelope: String, passphrase: String): Pair<PayloadSummary, JSONObject> =
withContext(Dispatchers.IO) {
val payload = NativeCore.backupDecrypt(envelope, passphrase)
if (NativeCore.isErr(payload)) throw BackupException(NativeCore.errMsg(payload))
val obj = JSONObject(payload)
if (obj.optString("app") != "archipelago-companion") {
throw BackupException("Not a companion backup (this may be a node backup — restore it on the node)")
}
val summary = PayloadSummary(
serverCount = obj.optJSONArray("servers")?.length() ?: 0,
hasFipsIdentity = obj.has("fips"),
hasSignerKey = obj.has("signer"),
appVersion = obj.optString("appVersion", ""),
)
summary to obj
}
/**
* Apply a decrypted backup to this install. Merge semantics — a restore
* never silently destroys what's already here:
*
* - Servers upsert (npub-first, [ServerPreferences.upsertServer]) — same
* identity merges, never duplicates.
* - The backup's active server is set active only when none is.
* - FIPS identity/peers restore only when this phone has none (a phone
* that already paired has a live identity the node peers with; swapping
* it from a backup would strand the current pairing). Peers merge by
* npub otherwise.
* - Signer key restores only when none exists locally.
*/
suspend fun restoreBackup(payload: JSONObject): RestoreResult = withContext(Dispatchers.IO) {
val serverArray = payload.optJSONArray("servers") ?: JSONArray()
var restored = 0
for (i in 0 until serverArray.length()) {
val raw = serverArray.optString(i)
val entry = ServerEntry.deserialize(raw) ?: continue
servers.upsertServer(entry)
restored++
}
var activeSet = false
val activeStr = if (payload.isNull("active")) null else payload.optString("active", "")
val activeEntry = activeStr?.takeIf { it.isNotBlank() }?.let { ServerEntry.deserialize(it) }
if (activeEntry != null && servers.activeServer.first() == null) {
servers.setActiveServer(activeEntry)
activeSet = true
}
// FIPS identity: only adopt when this phone has none.
var fipsRestored = false
val fipsObj = payload.optJSONObject("fips")
if (fipsObj != null && fips.identity() == null) {
val secret = fipsObj.optString("secret")
if (secret.isNotBlank()) {
fips.saveIdentity(
com.archipelago.app.fips.FipsNative.Identity(
secret = secret,
npub = fipsObj.optString("npub"),
address = fipsObj.optString("address"),
)
)
fipsRestored = true
}
// Peers: union by npub with whatever is already here (an empty
// store takes the backup's list wholesale).
val backupPeers = fipsObj.optJSONArray("peers")?.let { arr ->
(0 until arr.length()).joinToString(",", "[", "]") { arr.optString(it) }
} ?: "[]"
fips.mergePeersJson(backupPeers)
val partyArr = fipsObj.optJSONArray("partyPeers")
if (partyArr != null) {
for (i in 0 until partyArr.length()) {
val p = partyArr.optJSONObject(i) ?: continue
val npub = p.optString("npub")
val ula = p.optString("ula")
if (npub.isNotBlank() && ula.isNotBlank()) {
fips.upsertPartyPeer(
com.archipelago.app.fips.PartyPeer(
npub = npub, ula = ula,
name = p.optString("name").ifBlank { "Phone" },
ip = p.optString("ip"), port = p.optInt("port"),
)
)
}
}
}
if (fipsObj.optString("partyName").isNotBlank()) {
fips.setPartyName(fipsObj.optString("partyName"))
}
fips.setPartyListen(fipsObj.optBoolean("partyListen", false))
}
// Signer key: only adopt when none exists locally.
var signerRestored = false
val signerObj = payload.optJSONObject("signer")
if (signerObj != null && signer.secret() == null) {
val secret = signerObj.optString("secret")
if (secret.isNotBlank()) {
signer.saveSecret(secret)
signerRestored = true
}
}
// Flags: a user who completed the intro on the old phone shouldn't
// see it again on the new one.
val flags = payload.optJSONObject("flags")
if (flags?.optBoolean("introSeen", false) == true) {
servers.markIntroSeen()
}
RestoreResult(
serversRestored = restored,
activeSet = activeSet,
fipsIdentityRestored = fipsRestored,
signerKeyRestored = signerRestored,
)
}
class BackupException(message: String) : Exception(message)
}
@@ -89,6 +89,38 @@ class FipsPreferences(private val context: Context) {
suspend fun hasPeers(): Boolean = JSONArray(peersJson()).length() > 0
/**
* Union the stored node peers with a backup's peer list, matched by
* npub — the backup's copy wins for the same npub (its addresses are what
* the restored identity pairs against). Used by companion restore (#128)
* after [saveIdentity] adopted the backup's mesh identity.
*/
suspend fun mergePeersJson(incomingJson: String) {
context.fipsDataStore.edit { prefs ->
val current = JSONArray(prefs[peersKey] ?: "[]")
val incoming = try {
JSONArray(incomingJson)
} catch (_: Exception) {
JSONArray()
}
val incomingNpubs = mutableSetOf<String>()
val merged = JSONArray()
for (i in 0 until incoming.length()) {
val peer = incoming.optJSONObject(i) ?: continue
val npub = peer.optString("npub")
if (npub.isNotBlank()) {
incomingNpubs.add(npub)
merged.put(peer)
}
}
for (i in 0 until current.length()) {
val peer = current.optJSONObject(i) ?: continue
if (peer.optString("npub") !in incomingNpubs) merged.put(peer)
}
prefs[peersKey] = merged.toString()
}
}
// ── Mesh Party (phone↔phone) ────────────────────────────────────────────
suspend fun partyListen(): Boolean =
@@ -0,0 +1,445 @@
package com.archipelago.app.nostr
import android.content.Context
import com.archipelago.app.NativeCore
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import org.json.JSONArray
import org.json.JSONObject
import java.security.SecureRandom
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
/**
* NIP-46 remote-signer session (#139) — the phone side, wire-faithful to
* rust-nostr's reference bunker (`signer/nostr-connect/src/signer.rs`),
* which the node's login flow will interoperate with:
*
* 1. Client (the node's login page) shows a `nostrconnect://` QR.
* 2. We scan it, connect to its relay, subscribe to kind-24133 events
* p-tagged to our signer key, and send a `connect` request carrying the
* secret (the client validates it and answers "ack").
* 3. Requests arrive as NIP-44-encrypted kind-24133 events; we respond over
* the same channel. `sign_event` is the one method that never runs
* without a human tapping Approve on this phone.
*
* The session lives while the app is around (the login handshake takes
* seconds); there is no background service in v1 and no remembered-session
* auto-reconnect (research doc flow C — deferred deliberately).
*/
object BunkerManager {
sealed class SignerState {
/** Native core unavailable (e.g. x86 emulator) — signing impossible. */
object Unavailable : SignerState()
/** Key exists, no session. */
object Idle : SignerState()
/** No signer key generated/imported yet. */
object NoKey : SignerState()
data class Connecting(val relay: String) : SignerState()
/** Connect request sent; waiting for the client to ack. */
data class AwaitingClient(val relay: String, val clientName: String) : SignerState()
/** Handshake complete — this is the state where requests are answered. */
data class Ready(val relay: String, val clientName: String) : SignerState()
data class Failed(val reason: String) : SignerState()
}
/** One signature request awaiting a human decision. */
data class PendingRequest(
val id: String,
val method: String,
val clientPubkey: String,
val clientName: String,
val kind: Long?,
val content: String?,
/** Formatted tag lines for the approval card. */
val tags: List<String>,
val createdAt: Long?,
/** The full unsigned event JSON handed to the native signer on approve. */
val unsignedEventJson: String,
)
private val _state = MutableStateFlow<SignerState>(SignerState.Idle)
val state: StateFlow<SignerState> = _state.asStateFlow()
private val _pending = MutableStateFlow<PendingRequest?>(null)
val pending: StateFlow<PendingRequest?> = _pending.asStateFlow()
private val client = OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.pingInterval(25, TimeUnit.SECONDS) // relay keepalive
.build()
private data class Session(
val socket: WebSocket,
val relay: String,
/** The client's pubkey (hex) from the nostrconnect URI. */
val clientPubkey: String,
val clientName: String,
/** The pairing secret — echoed back during handshake, then kept for
* validating an incoming `connect` from the same client. */
val secret: String,
/** Our connect request id, to match the client's ack response. */
val connectRequestId: String,
/** Our signer secret (hex). */
val signerSecretHex: String,
/** Our signer pubkey (hex). */
val signerPubkeyHex: String,
/** Event ids already handled (relays may redeliver). */
val seen: MutableSet<String> = java.util.concurrent.ConcurrentHashMap.newKeySet(),
)
private val session = AtomicReference<Session?>(null)
/** Refresh Idle/NoKey state (suspend; call from a coroutine — DataStore reads hit disk). */
suspend fun refreshState(context: Context) {
if (!NativeCore.available) {
_state.value = SignerState.Unavailable
return
}
if (session.get() != null) return
val prefs = NostrSignerPreferences(context.applicationContext)
_state.value =
if (prefs.secret() == null) SignerState.NoKey else SignerState.Idle
}
/**
* Pair from a scanned or deep-linked `nostrconnect://…` URI. Returns a
* user-presentable error on failure, or null on success (state moves to
* Connecting → AwaitingClient).
*/
suspend fun pair(context: Context, uri: String): String? {
if (!NativeCore.available) return "Signing is unavailable on this device"
val appContext = context.applicationContext
return withContext(Dispatchers.IO) {
val parsed = JSONObject(NativeCore.nostrParseConnectUri(uri.trim()))
if (parsed.has("error")) return@withContext parsed.getString("error")
val prefs = NostrSignerPreferences(appContext)
val secret = prefs.secret()
?: return@withContext "No signer key yet — generate or import one first"
val info = JSONObject(NativeCore.nostrSecretFromAny(secret))
if (info.has("error")) return@withContext info.getString("error")
val clientPubkey = parsed.getString("clientPubkey")
val relays = mutableListOf<String>()
parsed.optJSONArray("relays")?.let { arr -> for (i in 0 until arr.length()) relays.add(arr.optString(i)) }
val clientName = parsed.optString("name").ifBlank { "client" }
val pairSecret = parsed.getString("secret")
if (relays.isEmpty()) return@withContext "The pairing code carries no relay to reach the client on"
teardown()
var lastError = "no relay could be reached"
for (relay in relays) {
_state.value = SignerState.Connecting(relay)
val opened = openSession(
relay, clientPubkey, clientName, pairSecret, secret, info,
)
if (opened != null) {
session.set(opened)
prefs.savePairing(
NostrSignerPreferences.Pairing(clientPubkey, relay, clientName)
)
_state.value = SignerState.AwaitingClient(relay, clientName)
return@withContext null
}
lastError = "relay $relay did not answer"
}
_state.value = SignerState.Failed(lastError)
lastError
}
}
/** Re-establish the last saved pairing without a fresh QR. */
suspend fun resume(context: Context): String? {
if (!NativeCore.available) return "Signing is unavailable on this device"
val appContext = context.applicationContext
return withContext(Dispatchers.IO) {
val prefs = NostrSignerPreferences(appContext)
val pairing = prefs.lastPairing()
?: return@withContext "Nothing to resume — no saved pairing"
val secret = prefs.secret()
?: return@withContext "No signer key"
val info = JSONObject(NativeCore.nostrSecretFromAny(secret))
if (info.has("error")) return@withContext info.getString("error")
teardown()
_state.value = SignerState.Connecting(pairing.relay)
val opened = openSession(
pairing.relay, pairing.clientPubkey, pairing.name,
secret = "", signerSecretHex = secret, info = info,
)
if (opened == null) {
_state.value = SignerState.Failed("relay ${pairing.relay} did not answer")
return@withContext "Could not reach ${pairing.relay}"
}
session.set(opened)
_state.value = SignerState.AwaitingClient(pairing.relay, pairing.name)
null
}
}
fun unpair() {
teardown()
_state.value = SignerState.Idle
}
private fun teardown() {
session.getAndSet(null)?.socket?.close(1000, "unpaired")
_pending.value = null
}
private fun randomId(): String {
val bytes = ByteArray(8)
SecureRandom().nextBytes(bytes)
return bytes.joinToString("") { "%02x".format(it) }
}
private fun openSession(
relay: String,
clientPubkey: String,
clientName: String,
secret: String,
signerSecretHex: String,
info: JSONObject,
): Session? {
val signerPubkeyHex = info.getString("pubkey")
val connectRequestId = randomId()
// The listener needs the Session, the Session needs the WebSocket:
// bind through a holder set right after newWebSocket returns (OkHttp
// invokes onOpen on its own dispatcher after the network round-trip,
// i.e. always after the bind below).
val holder = AtomicReference<Session?>()
val request = Request.Builder().url(relay).build()
val socket = client.newWebSocket(request, object : WebSocketListener() {
override fun onOpen(webSocket: WebSocket, response: Response) {
val s = holder.get() ?: return
// Subscribe to requests addressed to us (p-tag filter), from
// now — no history replay of stale login attempts.
webSocket.send(
"""["REQ","${s.connectRequestId}sub",{"kinds":[24133],"#p":["${s.signerPubkeyHex}"],"since":${epochSecs() - 120}}]"""
)
// Handshake: the signer sends `connect` carrying the secret
// (rust-nostr's NostrConnectRemoteSigner.send_connect_ack —
// the exact frame the node's client waits for).
val content = JSONObject().apply {
put("id", s.connectRequestId)
put("method", "connect")
put("params", JSONArray().put(s.signerPubkeyHex).put(s.secret))
}.toString()
if (!sendEncrypted(s, content)) {
_state.value = SignerState.Failed("Could not encrypt the connect message")
}
}
override fun onMessage(webSocket: WebSocket, text: String) {
val s = session.get() ?: return
handleRelayMessage(s, text)
}
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
if (session.get()?.socket === webSocket) {
_state.value = SignerState.Failed(t.message ?: "relay connection failed")
session.getAndSet(null)
}
}
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
if (session.get()?.socket === webSocket) {
_state.value = SignerState.Idle
session.getAndSet(null)
}
}
})
val s = Session(
socket = socket,
relay = relay,
clientPubkey = clientPubkey,
clientName = clientName,
secret = secret,
connectRequestId = connectRequestId,
signerSecretHex = signerSecretHex,
signerPubkeyHex = signerPubkeyHex,
)
holder.set(s)
return s
}
private fun epochSecs(): Long = System.currentTimeMillis() / 1000
/** Encrypt a JSON-RPC frame to the peer and publish it as kind 24133. */
private fun sendEncrypted(s: Session, json: String): Boolean {
val enc = NativeCore.nostrNip44Encrypt(s.signerSecretHex, s.clientPubkey, json)
if (NativeCore.isErr(enc)) return false
val payload = JSONObject(enc).getString("result")
val event = JSONObject().apply {
put("kind", 24133)
put("content", payload)
put("tags", JSONArray().put(JSONArray().put("p").put(s.clientPubkey)))
put("created_at", epochSecs())
}.toString()
val signed = NativeCore.nostrSignEvent(s.signerSecretHex, event)
if (NativeCore.isErr(signed)) return false
return s.socket.send("""["EVENT",$signed]""")
}
private fun handleRelayMessage(s: Session, text: String) {
val arr = try {
JSONArray(text)
} catch (_: Exception) {
return
}
if (arr.length() == 0) return
when (arr.optString(0)) {
"EVENT" -> {
val event = arr.optJSONObject(2) ?: return
if (event.optLong("kind") != 24133L) return
val id = event.optString("id")
if (id.isNotEmpty() && !s.seen.add(id)) return
val author = event.optString("pubkey")
if (author != s.clientPubkey) return // not our client
handleClientEvent(s, author, event.optString("content"))
}
// OK / CLOSED / NOTICE: nothing actionable for the bunker in v1.
}
}
private fun handleClientEvent(s: Session, author: String, content: String) {
// NIP-44 is the mandated transport; NIP-04 stays as receive fallback
// for clients that still speak the deprecated scheme.
val plain = run {
val nip44 = NativeCore.nostrNip44Decrypt(s.signerSecretHex, author, content)
if (!NativeCore.isErr(nip44)) JSONObject(nip44).getString("result") else {
val nip04 = NativeCore.nostrNip04Decrypt(s.signerSecretHex, author, content)
if (!NativeCore.isErr(nip04)) JSONObject(nip04).getString("result") else return
}
}
val msg = try {
JSONObject(plain)
} catch (_: Exception) {
return
}
val id = msg.optString("id")
val method = msg.optString("method", "")
if (method.isNotEmpty()) {
when (method) {
"connect" -> {
val params = msg.optJSONArray("params") ?: return
// Param 0 must be OUR pubkey (client is connecting to us,
// not some other bunker through this session).
val target = params.optString(0)
val givenSecret = params.optString(1)
val authorized = target == s.signerPubkeyHex &&
(s.secret.isBlank() || givenSecret == s.secret || givenSecret.isBlank())
if (authorized) {
respond(s, id, result = "ack")
_state.value = SignerState.Ready(s.relay, s.clientName)
} else {
respond(s, id, error = "unauthorized")
}
}
"get_public_key" -> respond(s, id, result = s.signerPubkeyHex)
"describe" -> respond(s, id, result = "connect get_public_key sign_event ping")
"ping" -> respond(s, id, result = "pong")
"sign_event" -> {
val params = msg.optJSONArray("params") ?: return
val eventJson = params.optString(0)
val ev = try {
JSONObject(eventJson)
} catch (_: Exception) {
respond(s, id, error = "malformed event")
return
}
// Never overwrite a pending request silently — a second
// tap on the node would otherwise cancel the visible one.
if (_pending.value == null) {
_pending.value = PendingRequest(
id = id,
method = method,
clientPubkey = author,
clientName = s.clientName,
kind = if (ev.has("kind") && !ev.isNull("kind")) ev.optLong("kind") else null,
content = if (ev.has("content") && !ev.isNull("content")) ev.optString("content") else null,
tags = formatTags(ev.optJSONArray("tags")),
createdAt = if (ev.has("created_at") && !ev.isNull("created_at")) ev.optLong("created_at") else null,
unsignedEventJson = eventJson,
)
} else {
respond(s, id, error = "busy")
}
}
else -> respond(s, id, error = "not authorized")
}
} else if (msg.has("result") || msg.has("error")) {
// A response to OUR connect request (the client's ack).
if (id == s.connectRequestId) {
if (msg.has("error")) {
_state.value = SignerState.Failed("Client rejected the connection: ${msg.optString("error")}")
} else if (msg.optString("result") == "ack") {
_state.value = SignerState.Ready(s.relay, s.clientName)
}
}
}
}
/** Approve the pending request: sign and send the result. */
suspend fun approve(): Boolean {
val s = session.get() ?: return false
val req = _pending.value ?: return false
val ok = withContext(Dispatchers.IO) {
val signed = NativeCore.nostrSignEvent(s.signerSecretHex, req.unsignedEventJson)
if (NativeCore.isErr(signed)) {
respond(s, req.id, error = "signing failed")
false
} else {
// Result is the signed event, JSON-stringified per the spec.
respond(s, req.id, result = signed)
}
}
_pending.value = null
return ok
}
/** Deny the pending request with an explicit error. */
fun deny() {
val s = session.get() ?: return
val req = _pending.value ?: return
respond(s, req.id, error = "denied")
_pending.value = null
}
/** Send a JSON-RPC response frame to the client. True when the WS send worked. */
private fun respond(s: Session, id: String, result: String? = null, error: String? = null): Boolean {
val frame = JSONObject().apply {
put("id", id)
if (error != null) put("error", error)
if (result != null) put("result", result)
}.toString()
return sendEncrypted(s, frame)
}
private fun formatTags(tags: JSONArray?): List<String> {
tags ?: return emptyList()
val out = mutableListOf<String>()
for (i in 0 until tags.length()) {
val tag = tags.optJSONArray(i) ?: continue
val parts = mutableListOf<String>()
for (j in 0 until tag.length()) parts.add(tag.optString(j))
out.add(parts.joinToString(" "))
}
return out
}
}
@@ -0,0 +1,95 @@
package com.archipelago.app.nostr
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.archipelago.app.NativeCore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.json.JSONObject
private val Context.signerDataStore: DataStore<Preferences> by preferencesDataStore(name = "nostr_signer")
/**
* Storage for the phone-side NIP-46 remote signer (#139): the signer secret
* key (hex) and the last pairing, so a re-opened app can resume a session
* without re-scanning the node's QR.
*
* Same plaintext-DataStore model as the FIPS secret (app-private storage,
* no extra OS keystore ceremony — the node login password lives the same way
* in ServerPreferences); the nsec grants the ability to sign as this identity,
* never node login.
*/
class NostrSignerPreferences(private val context: Context) {
private val secretKey = stringPreferencesKey("signer_secret")
private val clientPubkeyKey = stringPreferencesKey("pair_client_pubkey")
private val clientRelayKey = stringPreferencesKey("pair_client_relay")
private val clientNameKey = stringPreferencesKey("pair_client_name")
/** The signer secret (hex) or null when no key exists yet. */
suspend fun secret(): String? = context.signerDataStore.data.first()[secretKey]
val secretFlow: Flow<String?> = context.signerDataStore.data
.map { it[secretKey] }
.distinctUntilChanged()
suspend fun saveSecret(hex: String) {
context.signerDataStore.edit { it[secretKey] = hex.trim() }
}
/** Generate a fresh signer key (fails if the native core is missing). */
suspend fun generateSecret(): JSONObject = withContext(Dispatchers.IO) {
val json = NativeCore.nostrGenerateSecret()
val obj = JSONObject(json)
if (obj.has("error")) throw IllegalStateException(obj.getString("error"))
saveSecret(obj.getString("secret"))
obj
}
/** Import a secret from hex or nsec…; returns the parsed key info. */
suspend fun importSecret(raw: String): JSONObject = withContext(Dispatchers.IO) {
val json = NativeCore.nostrSecretFromAny(raw.trim())
val obj = JSONObject(json)
if (obj.has("error")) throw IllegalArgumentException(obj.getString("error"))
saveSecret(obj.getString("secret"))
obj
}
data class Pairing(val clientPubkey: String, val relay: String, val name: String)
suspend fun lastPairing(): Pairing? {
val prefs = context.signerDataStore.data.first()
val pubkey = prefs[clientPubkeyKey] ?: return null
val relay = prefs[clientRelayKey] ?: return null
if (pubkey.isBlank() || relay.isBlank()) return null
return Pairing(pubkey, relay, prefs[clientNameKey] ?: "")
}
suspend fun savePairing(pairing: Pairing) {
context.signerDataStore.edit {
it[clientPubkeyKey] = pairing.clientPubkey
it[clientRelayKey] = pairing.relay
it[clientNameKey] = pairing.name
}
}
suspend fun clearPairing() {
context.signerDataStore.edit {
it.remove(clientPubkeyKey)
it.remove(clientRelayKey)
it.remove(clientNameKey)
}
}
suspend fun wipeKey() {
context.signerDataStore.edit { it.remove(secretKey) }
}
}
@@ -0,0 +1,294 @@
package com.archipelago.app.ui.components
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Restore
import androidx.compose.material.icons.filled.Save
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.archipelago.app.data.BackupManager
import com.archipelago.app.ui.theme.BitcoinOrange
import com.archipelago.app.ui.theme.SuccessGreen
import com.archipelago.app.ui.theme.TextMuted
import com.archipelago.app.ui.theme.TextPrimary
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
/**
* Backup & Restore (#128) — the hub's BACKUP sub-page (same container as
* Nodes/FIPS), the phone side of losing your phone or wiping it to cross a
* border. See docs/companion-backup-restore.md for the envelope and merge
* semantics; this composable is the flow only.
*/
@Composable
internal fun BackupSection() {
val context = LocalContext.current
val scope = rememberCoroutineScope()
val manager = remember { BackupManager(context) }
var passphrase by remember { mutableStateOf("") }
var confirm by remember { mutableStateOf("") }
var status by remember { mutableStateOf<String?>(null) }
var statusError by remember { mutableStateOf(false) }
var busy by remember { mutableStateOf(false) }
// Decrypted backup awaiting the user's go-ahead (restore flow).
var restorePreview by remember { mutableStateOf<Pair<BackupManager.PayloadSummary, org.json.JSONObject>?>(null) }
fun say(msg: String, error: Boolean) {
status = msg
statusError = error
}
val exportLauncher = rememberLauncherForActivityResult(
ActivityResultContracts.CreateDocument("application/json")
) { uri ->
if (uri == null) return@rememberLauncherForActivityResult
scope.launch {
busy = true
try {
val envelope = manager.createBackup(passphrase)
withContext(Dispatchers.IO) {
context.contentResolver.openOutputStream(uri)?.use { out ->
out.write(envelope.toByteArray())
} ?: throw BackupManager.BackupException("could not open the destination file")
}
say("Saved — keep the file and the passphrase somewhere safe.", false)
} catch (e: Exception) {
say(e.message ?: "backup failed", true)
} finally {
busy = false
}
}
}
val importLauncher = rememberLauncherForActivityResult(
ActivityResultContracts.OpenDocument()
) { uri ->
if (uri == null) return@rememberLauncherForActivityResult
scope.launch {
busy = true
try {
val envelope = withContext(Dispatchers.IO) {
context.contentResolver.openInputStream(uri)?.use { it.readBytes().decodeToString() }
?: throw BackupManager.BackupException("could not read the selected file")
}
val (summary, payload) = manager.readBackup(envelope, passphrase)
restorePreview = summary to payload
} catch (e: Exception) {
say(e.message ?: "restore failed", true)
} finally {
busy = false
}
}
}
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
SectionCopy(
"An encrypted copy of everything this phone holds — nodes and their passwords, " +
"your mesh identity, the remote-signer key. Same envelope your node uses (ADR-005), " +
"one passphrase, no cloud."
)
// ── Create a backup ──────────────────────────────────────────────
SectionHeader(Icons.Default.Save, "Create a backup")
GlassField(
value = passphrase,
onValueChange = { passphrase = it },
placeholder = "Passphrase",
visualTransformation = androidx.compose.ui.text.input.PasswordVisualTransformation(),
)
GlassField(
value = confirm,
onValueChange = { confirm = it },
placeholder = "Repeat passphrase",
visualTransformation = androidx.compose.ui.text.input.PasswordVisualTransformation(),
)
SectionHint("The passphrase cannot be recovered — a backup nobody can open is a paperweight.")
WideAction(
text = if (busy) "Working…" else "Save backup file",
onClick = {
if (busy) return@WideAction
if (passphrase.length < 8) {
say("Use at least 8 characters — this passphrase guards every secret in the app.", true)
return@WideAction
}
if (passphrase != confirm) {
say("The two passphrases don't match.", true)
return@WideAction
}
val stamp = SimpleDateFormat("yyyyMMdd-HHmm", Locale.US).format(Date())
exportLauncher.launch("archy-companion-backup-$stamp.json")
},
)
Spacer(Modifier.height(2.dp))
// ── Restore a backup ─────────────────────────────────────────────
SectionHeader(Icons.Default.Restore, "Restore a backup")
SectionHint(
"Nothing is overwritten: nodes merge by identity, and the mesh identity and " +
"signer key only restore when this phone has none."
)
WideAction(
text = if (busy) "Working…" else "Choose backup file",
onClick = {
if (busy) return@WideAction
if (passphrase.isEmpty()) {
say("Enter the backup's passphrase first.", true)
return@WideAction
}
importLauncher.launch(arrayOf("application/json"))
},
)
restorePreview?.let { (summary, payload) ->
Spacer(Modifier.height(2.dp))
Column(
Modifier
.fillMaxWidth()
.clip(RoundedCornerShape(14.dp))
.background(Color.White.copy(alpha = 0.04f))
.border(1.dp, Color.White.copy(alpha = 0.08f), RoundedCornerShape(14.dp))
.padding(12.dp),
verticalArrangement = Arrangement.spacedBy(6.dp),
) {
Text(
"Backup verified${if (summary.appVersion.isNotBlank()) " (made by v${summary.appVersion})" else ""}",
color = SuccessGreen, fontSize = 13.sp, fontWeight = FontWeight.SemiBold,
)
SummaryRow("Nodes", summary.serverCount.toString())
if (summary.hasFipsIdentity) SummaryRow("Mesh identity", "included")
if (summary.hasSignerKey) SummaryRow("Remote-signer key", "included")
WideAction(
text = if (busy) "Restoring…" else "Restore onto this phone",
onClick = {
if (busy) return@WideAction
scope.launch {
busy = true
try {
val result = manager.restoreBackup(payload)
restorePreview = null
passphrase = ""
confirm = ""
say(
"Restored ${result.serversRestored} node(s)" +
(if (result.activeSet) ", set active" else "") +
(if (result.fipsIdentityRestored) ", mesh identity" else "") +
(if (result.signerKeyRestored) ", signer key" else "") +
". Restart the app to reconnect.",
false,
)
} catch (e: Exception) {
say(e.message ?: "restore failed", true)
} finally {
busy = false
}
}
},
)
}
}
status?.takeIf { it.isNotBlank() }?.let { msg ->
Text(
msg,
color = if (statusError) Color(0xFFFF6B6B) else SuccessGreen,
fontSize = 12.sp,
textAlign = TextAlign.Center,
modifier = Modifier.fillMaxWidth(),
)
}
}
}
@Composable
internal fun SectionHeader(icon: androidx.compose.ui.graphics.vector.ImageVector, title: String) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp),
) {
Icon(icon, contentDescription = null, tint = BitcoinOrange, modifier = Modifier.size(18.dp))
Text(title, color = TextPrimary, fontSize = 15.sp, fontWeight = FontWeight.SemiBold)
}
}
@Composable
internal fun SectionCopy(text: String) {
Text(text, color = TextMuted, fontSize = 12.sp, lineHeight = 16.sp)
}
@Composable
internal fun SectionHint(text: String) {
Text(text, color = TextMuted.copy(alpha = 0.8f), fontSize = 10.sp, lineHeight = 13.sp)
}
/** Wide orange-outline action button in the menu's visual language. */
@Composable
internal fun WideAction(
text: String,
onClick: () -> Unit,
icon: androidx.compose.ui.graphics.vector.ImageVector? = null,
) {
Row(
Modifier
.fillMaxWidth()
.height(44.dp)
.clip(RoundedCornerShape(12.dp))
.background(BitcoinOrange.copy(alpha = 0.15f))
.border(1.dp, BitcoinOrange.copy(alpha = 0.4f), RoundedCornerShape(12.dp))
.clickable { onClick() },
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center,
) {
if (icon != null) {
Icon(icon, contentDescription = null, tint = BitcoinOrange, modifier = Modifier.size(16.dp))
Spacer(Modifier.size(8.dp))
}
Text(text, color = BitcoinOrange, fontSize = 13.sp, fontWeight = FontWeight.Bold)
}
}
@Composable
internal fun SummaryRow(label: String, value: String) {
Row(
Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
) {
Text(label, color = TextMuted, fontSize = 12.sp)
Text(value, color = TextPrimary, fontSize = 12.sp, fontWeight = FontWeight.Medium)
}
}
@@ -31,6 +31,8 @@ import androidx.compose.material.icons.filled.Dns
import androidx.compose.material.icons.filled.Groups
import androidx.compose.material.icons.filled.Keyboard
import androidx.compose.material.icons.filled.RestartAlt
import androidx.compose.material.icons.filled.SettingsBackupRestore
import androidx.compose.material.icons.filled.Key
import androidx.compose.material.icons.filled.SportsEsports
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.shape.RoundedCornerShape
@@ -106,22 +108,62 @@ fun NESMenu(
onKeyboard: () -> Unit,
onBackToWebView: (() -> Unit)? = null,
onMeshParty: (() -> Unit)? = null,
// Remote-signer pairing request (nostrconnect://… deep link, or a scan):
// non-null opens the hub on the signer sub-page and pairs. Consumed once
// the signer section hands it back via [onSignerPairHandled].
signerPairRequest: String? = null,
onSignerPairHandled: () -> Unit = {},
) {
// Pairing state is latched here (not passed straight through) so the
// source can clear itself while the request stays alive until consumed.
var pendingSignerPair by remember { mutableStateOf<String?>(null) }
var signerScan by remember { mutableStateOf(false) }
LaunchedEffect(signerPairRequest) {
if (signerPairRequest != null) pendingSignerPair = signerPairRequest
}
AnimatedVisibility(visible = visible, enter = fadeIn(), exit = fadeOut()) {
// Contained hub overlay: a centred glass panel (not full-screen) that
// holds the card page and its sub-pages (Nodes, FIPS) and scrolls
// inside its own bounds when content is tall. Tapping the dimmed
// backdrop dismisses.
// holds the card page and its sub-pages (Nodes, FIPS, Backup, Signer)
// and scrolls inside its own bounds when content is tall. Tapping the
// dimmed backdrop dismisses.
Box(
Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.7f))
.clickable(indication = null, interactionSource = remember { MutableInteractionSource() }) { onDismiss() },
contentAlignment = Alignment.Center,
) {
AnimatedVisibility(visible = visible, enter = fadeIn() + scaleIn(initialScale = 0.95f), exit = fadeOut() + scaleOut(targetScale = 0.95f)) {
MenuPanel(servers, activeServer, onDismiss, onSelectServer, onAddServer, onScanQr, onEditServer, onRemoveServer, onRemote, onKeyboard, onBackToWebView, onMeshParty)
MenuPanel(
servers, activeServer, onDismiss, onSelectServer, onAddServer, onScanQr,
onEditServer, onRemoveServer, onRemote, onKeyboard, onBackToWebView, onMeshParty,
signerPairUri = pendingSignerPair,
onSignerScan = { signerScan = true },
onSignerPairHandled = {
pendingSignerPair = null
onSignerPairHandled()
},
)
}
}
}
// Pairing-QR scanner for the signer sub-page — a full-screen glass
// modal hosted OUTSIDE the hub panel so it isn't clipped to the panel's
// bounds (same layering the pairing scanner gets from WebViewScreen).
QrGlassModal(
visible = signerScan && visible,
title = "Scan pairing QR",
status = null,
idleHint = "Point at the nostrconnect QR the node or client shows",
permissionRationale = "Camera access is needed to scan the pairing code",
onDismiss = { signerScan = false },
onDecoded = { text ->
if (text.startsWith("nostrconnect://")) {
signerScan = false
pendingSignerPair = text
}
},
)
}
@Composable
@@ -138,6 +180,9 @@ private fun MenuPanel(
onKeyboard: () -> Unit,
onBackToWebView: (() -> Unit)?,
onMeshParty: (() -> Unit)?,
signerPairUri: String?,
onSignerScan: () -> Unit,
onSignerPairHandled: () -> Unit,
) {
var showAdd by remember { mutableStateOf(false) }
// The saved server being edited, or null when adding a new one.
@@ -176,9 +221,10 @@ private fun MenuPanel(
.widthIn(max = 420.dp)
.fillMaxWidth()
.padding(horizontal = 20.dp)
// Cap height just short of the full screen; the panel wraps short
// content and only scrolls in the rare case it outgrows this.
.heightIn(max = (LocalConfiguration.current.screenHeightDp * 0.92f).dp)
// Cap height at 70% of the screen — a ~15% breathing margin top
// and bottom — the panel wraps short content and scrolls inside
// its own bounds when a sub-page outgrows this.
.heightIn(max = (LocalConfiguration.current.screenHeightDp * 0.70f).dp)
.clip(RoundedCornerShape(PANEL_R))
.background(PanelBg.copy(alpha = 0.86f))
.border(1.dp, PanelBorder, RoundedCornerShape(PANEL_R))
@@ -201,7 +247,13 @@ private fun MenuPanel(
IconRound(Icons.AutoMirrored.Filled.ArrowBack, "Back") { resetForm(); page = HubPage.HUB }
Spacer(Modifier.width(12.dp))
Text(
if (page == HubPage.NODES) "Nodes" else "FIPS Mesh",
when (page) {
HubPage.NODES -> "Nodes"
HubPage.FIPS -> "FIPS Mesh"
HubPage.BACKUP -> "Backup & Restore"
HubPage.SIGNER -> "Remote Signer"
HubPage.HUB -> "Menu"
},
color = TextPrimary, fontSize = 20.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.sp,
)
}
@@ -233,6 +285,12 @@ private fun MenuPanel(
if (onMeshParty != null) {
HubCard(Icons.Default.Groups, "Mesh Party", "Phone-to-phone chat & beam") { onMeshParty() }
}
// Backup & Restore (#128): the phone side of losing your phone
// or wiping it to cross a border — encrypted export file, no cloud.
HubCard(Icons.Default.SettingsBackupRestore, "Backup & Restore", "Encrypted export for a wiped phone") { page = HubPage.BACKUP }
// Remote Signer (#139): hold a nostr key on the phone and
// approve/deny remote signature requests (NIP-46).
HubCard(Icons.Default.Key, "Remote Signer", "Approve signatures for your node") { page = HubPage.SIGNER }
// Dark/Classic style lives on the remote/keyboard screen next to
// the settings button — not here.
@@ -272,6 +330,11 @@ private fun MenuPanel(
val active = server.serialize() == activeServer?.serialize()
MenuItem(
label = server.displayName(),
// FIPS nodes carry their mesh ULA — the address Termux
// (or any other app) can reach over the split-tunnel,
// from anywhere. Tap to copy; the node's npub stays
// visible in the FIPS Mesh page.
subtitle = server.meshIp.takeIf { it.isNotBlank() },
selected = active,
onClick = { onSelectServer(server) },
onEdit = { startEdit(server) },
@@ -391,11 +454,23 @@ private fun MenuPanel(
HubPage.FIPS -> {
FipsSection(embedded = true)
}
HubPage.BACKUP -> {
BackupSection()
}
HubPage.SIGNER -> {
SignerSection(
pairUri = signerPairUri,
onScan = onSignerScan,
onPairHandled = onSignerPairHandled,
)
}
}
}
}
private enum class HubPage { HUB, NODES, FIPS }
private enum class HubPage { HUB, NODES, FIPS, BACKUP, SIGNER }
/** Big tappable destination card for the hub page: icon + title + subtitle. */
@Composable
@@ -582,26 +657,52 @@ private fun MenuItem(
onClick: () -> Unit,
onEdit: (() -> Unit)? = null,
onRemove: (() -> Unit)? = null,
/** Optional second line (the node's mesh ULA); tapping it copies. */
subtitle: String? = null,
) {
val clipboard = LocalClipboardManager.current
Row(
Modifier
.fillMaxWidth()
.height(ROW_H)
// Rows with a second line grow to fit it.
.then(if (subtitle == null) Modifier.height(ROW_H) else Modifier.heightIn(min = ROW_H))
.clip(RoundedCornerShape(ROW_R))
.background(if (selected) BitcoinOrange.copy(alpha = 0.12f) else RowBg)
.border(1.dp, if (selected) BitcoinOrange.copy(alpha = 0.4f) else RowBorder, RoundedCornerShape(ROW_R))
.clickable { onClick() }
.padding(horizontal = 16.dp),
.padding(horizontal = 16.dp)
.then(if (subtitle == null) Modifier else Modifier.padding(vertical = 8.dp)),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
) {
Text(
label,
color = if (selected) BitcoinOrange else labelColor,
fontSize = 16.sp,
fontWeight = FontWeight.Medium,
modifier = Modifier.weight(1f),
)
Column(Modifier.weight(1f)) {
Text(
label,
color = if (selected) BitcoinOrange else labelColor,
fontSize = 16.sp,
fontWeight = FontWeight.Medium,
)
if (subtitle != null) {
Row(
Modifier
.padding(top = 2.dp)
.clip(RoundedCornerShape(6.dp))
.clickable { clipboard.setText(AnnotatedString(subtitle)) }
.padding(horizontal = 4.dp, vertical = 2.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
subtitle,
color = TextMuted,
fontSize = 10.sp,
fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
maxLines = 1,
overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,
)
Text("⧉", color = TextMuted.copy(alpha = 0.7f), fontSize = 11.sp, modifier = Modifier.padding(start = 6.dp))
}
}
}
if (onEdit != null) {
Text(
"✎",
@@ -623,7 +724,7 @@ private fun MenuItem(
/** Glass text field with centered input text. */
@Composable
private fun GlassField(
internal fun GlassField(
value: String,
onValueChange: (String) -> Unit,
placeholder: String,
@@ -0,0 +1,14 @@
package com.archipelago.app.ui.components
import kotlinx.coroutines.flow.MutableStateFlow
/**
* Cross-layer handoff for remote-signer pairing (#139): NavGraph's
* `nostrconnect://` deep link drops the URI here and routes to the session;
* WebViewScreen collects it, opens the hub menu, and NESMenu opens the
* signer sub-page with the request. Cleared once the signer section has
* consumed it (via NESMenu's onSignerPairHandled).
*/
object SignerLaunch {
val pendingUri = MutableStateFlow<String?>(null)
}
@@ -0,0 +1,381 @@
package com.archipelago.app.ui.components
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Key
import androidx.compose.material.icons.filled.QrCodeScanner
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.archipelago.app.NativeCore
import com.archipelago.app.nostr.BunkerManager
import com.archipelago.app.nostr.NostrSignerPreferences
import com.archipelago.app.ui.theme.BitcoinOrange
import com.archipelago.app.ui.theme.SuccessGreen
import com.archipelago.app.ui.theme.TextMuted
import com.archipelago.app.ui.theme.TextPrimary
import kotlinx.coroutines.launch
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
/**
* Remote Signer (#139) — the hub's SIGNER sub-page (same container as
* Nodes/FIPS). The phone holds a nostr key; a NIP-46 client (the node's
* login QR, any nostrconnect:// app) pairs via [pairUri] or the scanner
* (hosted by NESMenu outside this panel), and every `sign_event` request
* lands as a legible approve/deny card. See
* docs/companion-nip46-remote-signer.md.
*/
@Composable
internal fun SignerSection(
pairUri: String?,
onScan: () -> Unit,
onPairHandled: () -> Unit,
) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
val clipboard = LocalClipboardManager.current
val prefs = remember { NostrSignerPreferences(context) }
var keyInfo by remember { mutableStateOf<JSONObject?>(null) }
var keyError by remember { mutableStateOf<String?>(null) }
var importText by remember { mutableStateOf("") }
var showNsec by remember { mutableStateOf(false) }
var notice by remember { mutableStateOf<String?>(null) }
var noticeError by remember { mutableStateOf(false) }
val bunkerState by BunkerManager.state.collectAsState()
val pending by BunkerManager.pending.collectAsState()
fun say(msg: String, error: Boolean) {
notice = msg
noticeError = error
}
suspend fun loadKey() {
val secret = prefs.secret()
keyInfo = secret?.let {
val json = NativeCore.nostrSecretFromAny(it)
if (NativeCore.isErr(json)) null else JSONObject(json)
}
}
LaunchedEffect(Unit) {
BunkerManager.refreshState(context)
loadKey()
}
// Consume a pairing request (deep link or scanner) exactly once.
LaunchedEffect(pairUri) {
val uri = pairUri?.takeIf { it.isNotBlank() } ?: return@LaunchedEffect
if (keyInfo == null) loadKey()
val err = BunkerManager.pair(context, uri)
if (err != null) say(err, true) else say("Pairing started…", false)
onPairHandled()
}
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
SectionCopy(
"Hold a nostr key on this phone and sign for it remotely — pair with your " +
"node's login QR (or any NIP-46 client), then approve each signature " +
"request as it arrives. Nothing signs without you."
)
if (bunkerState is BunkerManager.SignerState.Unavailable) {
Text(
"Signing is unavailable on this device (native core missing).",
color = Color(0xFFFF6B6B), fontSize = 12.sp,
)
}
val info = keyInfo
if (info == null) {
// ── No key yet: generate or import ──────────────────────────
keyError?.let { Text(it, color = Color(0xFFFF6B6B), fontSize = 11.sp) }
WideAction(text = "Generate signer key", onClick = {
scope.launch {
try {
keyInfo = prefs.generateSecret()
keyError = null
BunkerManager.refreshState(context)
} catch (e: Exception) {
keyError = e.message ?: "could not generate a key"
}
}
})
GlassField(
value = importText,
onValueChange = { importText = it },
placeholder = "or import nsec…",
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
keyboardActions = KeyboardActions(onGo = {
if (importText.isNotBlank()) {
scope.launch {
try {
keyInfo = prefs.importSecret(importText)
importText = ""
keyError = null
BunkerManager.refreshState(context)
} catch (e: Exception) {
keyError = e.message ?: "not a valid nsec"
}
}
}
}),
)
WideAction(text = "Import", onClick = {
if (importText.isBlank()) return@WideAction
scope.launch {
try {
keyInfo = prefs.importSecret(importText)
importText = ""
keyError = null
BunkerManager.refreshState(context)
} catch (e: Exception) {
keyError = e.message ?: "not a valid nsec"
}
}
})
} else {
// ── Identity ─────────────────────────────────────────────────
SectionHeader(Icons.Default.Key, "Signer identity")
MonoValue("npub", info.optString("npub")) {
clipboard.setText(AnnotatedString(info.optString("npub")))
}
if (showNsec) {
MonoValue("nsec", info.optString("nsec"), secret = true) {
clipboard.setText(AnnotatedString(info.optString("nsec")))
}
SectionHint("Anyone with the nsec can sign as you — clear the clipboard after copying.")
} else {
Text(
"Show nsec",
color = TextMuted, fontSize = 11.sp,
modifier = Modifier
.clip(RoundedCornerShape(8.dp))
.clickable { showNsec = true }
.padding(vertical = 2.dp, horizontal = 6.dp),
)
}
// ── Session ──────────────────────────────────────────────────
Spacer(Modifier.height(2.dp))
val label = when (val s = bunkerState) {
BunkerManager.SignerState.Unavailable -> "Unavailable on this device"
BunkerManager.SignerState.NoKey -> "No signer key yet"
BunkerManager.SignerState.Idle -> "Idle — pair to start"
is BunkerManager.SignerState.Connecting -> "Connecting to ${s.relay}…"
is BunkerManager.SignerState.AwaitingClient -> "Paired with \"${s.clientName}\" — waiting for the handshake to finish"
is BunkerManager.SignerState.Ready -> "Ready for \"${s.clientName}\""
is BunkerManager.SignerState.Failed -> s.reason
}
Text("Session", color = TextMuted, fontSize = 11.sp)
Text(
label,
color = if (bunkerState is BunkerManager.SignerState.Failed) Color(0xFFFF6B6B)
else if (bunkerState is BunkerManager.SignerState.Ready) SuccessGreen
else TextPrimary,
fontSize = 13.sp,
lineHeight = 17.sp,
)
WideAction(
text = "Scan pairing QR",
onClick = {
if (bunkerState is BunkerManager.SignerState.NoKey) {
say("Generate or import a signer key first.", true)
return@WideAction
}
onScan()
},
icon = Icons.Default.QrCodeScanner,
)
if (bunkerState is BunkerManager.SignerState.Ready ||
bunkerState is BunkerManager.SignerState.AwaitingClient ||
bunkerState is BunkerManager.SignerState.Connecting
) {
Text(
"End session",
color = TextMuted, fontSize = 11.sp,
modifier = Modifier
.clip(RoundedCornerShape(8.dp))
.clickable { BunkerManager.unpair() }
.padding(vertical = 2.dp, horizontal = 6.dp),
)
}
// ── Pending signature request — the whole point ──────────────
pending?.let { req ->
Spacer(Modifier.height(2.dp))
Column(
Modifier
.fillMaxWidth()
.clip(RoundedCornerShape(14.dp))
.background(Color.White.copy(alpha = 0.04f))
.border(1.dp, BitcoinOrange.copy(alpha = 0.35f), RoundedCornerShape(14.dp))
.padding(12.dp),
verticalArrangement = Arrangement.spacedBy(6.dp),
) {
Text("Signature request", color = BitcoinOrange, fontSize = 13.sp, fontWeight = FontWeight.Bold)
SummaryRow("Client", req.clientName.ifBlank { req.clientPubkey.take(12) + "…" })
SummaryRow("Kind", kindLabel(req.kind))
req.createdAt?.let {
SummaryRow("Time", SimpleDateFormat("HH:mm:ss", Locale.US).format(Date(it * 1000)))
}
req.content?.takeIf { it.isNotBlank() }?.let { content ->
Text(
content,
color = TextPrimary, fontSize = 10.sp, lineHeight = 14.sp,
fontFamily = FontFamily.Monospace,
modifier = Modifier
.fillMaxWidth()
.clip(RoundedCornerShape(10.dp))
.background(Color.Black.copy(alpha = 0.45f))
.padding(8.dp)
.heightIn(max = 160.dp),
)
}
if (req.tags.isNotEmpty()) {
Column(
Modifier
.fillMaxWidth()
.clip(RoundedCornerShape(10.dp))
.background(Color.Black.copy(alpha = 0.45f))
.padding(8.dp),
verticalArrangement = Arrangement.spacedBy(2.dp),
) {
req.tags.take(6).forEach {
Text(
it,
color = TextMuted, fontSize = 9.sp,
fontFamily = FontFamily.Monospace,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
if (req.tags.size > 6) {
Text("+${req.tags.size - 6} more", color = TextMuted, fontSize = 9.sp)
}
}
}
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
Box(
Modifier
.weight(1f)
.height(40.dp)
.clip(RoundedCornerShape(12.dp))
.background(Color(0xFFE5484D).copy(alpha = 0.16f))
.border(1.dp, Color(0xFFE5484D).copy(alpha = 0.5f), RoundedCornerShape(12.dp))
.clickable { BunkerManager.deny() },
contentAlignment = Alignment.Center,
) { Text("Deny", color = Color(0xFFFF8A8D), fontSize = 13.sp, fontWeight = FontWeight.Bold) }
Box(
Modifier
.weight(1f)
.height(40.dp)
.clip(RoundedCornerShape(12.dp))
.background(BitcoinOrange.copy(alpha = 0.2f))
.border(1.dp, BitcoinOrange.copy(alpha = 0.6f), RoundedCornerShape(12.dp))
.clickable {
scope.launch {
val ok = BunkerManager.approve()
say(if (ok) "Signed and sent." else "Could not send the signature.", !ok)
}
},
contentAlignment = Alignment.Center,
) { Text("Approve", color = BitcoinOrange, fontSize = 13.sp, fontWeight = FontWeight.Bold) }
}
}
}
}
notice?.takeIf { it.isNotBlank() }?.let { msg ->
Text(
msg,
color = if (noticeError) Color(0xFFFF6B6B) else SuccessGreen,
fontSize = 12.sp,
textAlign = TextAlign.Center,
modifier = Modifier.fillMaxWidth(),
)
}
}
}
/** Kind number → legible label, so the approve/deny card reads like a sentence. */
private fun kindLabel(kind: Long?): String = when (kind) {
0L -> "Metadata (kind 0)"
1L -> "Text note (kind 1)"
3L -> "Contact list (kind 3)"
4L -> "Direct message (kind 4)"
7L -> "Reaction (kind 7)"
14L -> "Chat message (kind 14)"
22242L -> "Client authentication (kind 22242)"
30078L -> "App-stored data (kind 30078)"
null -> "Unknown kind"
else -> "Kind $kind"
}
/** Monospace value chip with a copy affordance (tap the row). */
@Composable
private fun MonoValue(label: String, value: String, secret: Boolean = false, onCopy: () -> Unit) {
Column(Modifier.fillMaxWidth()) {
Text(label, color = TextMuted, fontSize = 10.sp)
Row(
Modifier
.fillMaxWidth()
.clip(RoundedCornerShape(10.dp))
.background(Color.Black.copy(alpha = 0.45f))
.clickable { onCopy() }
.padding(horizontal = 10.dp, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
value,
color = if (secret) Color(0xFFFFB86B) else TextPrimary,
fontSize = 10.sp,
fontFamily = FontFamily.Monospace,
modifier = Modifier.weight(1f),
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Text("⧉", color = TextMuted, fontSize = 13.sp, modifier = Modifier.padding(start = 8.dp))
}
}
}
@@ -22,6 +22,7 @@ import com.archipelago.app.data.ServerEntry
import com.archipelago.app.data.ServerPreferences
import com.archipelago.app.data.ServerQrParser
import com.archipelago.app.fips.FipsManager
import com.archipelago.app.ui.components.SignerLaunch
import com.archipelago.app.ui.screens.FlareScreen
import com.archipelago.app.ui.screens.IntroScreen
import com.archipelago.app.ui.screens.NodePickerScreen
@@ -133,27 +134,41 @@ fun AppNavHost(
LaunchedEffect(pairUri) {
val raw = pairUri ?: return@LaunchedEffect
onPairUriConsumed()
when (val result = ServerQrParser.parse(raw)) {
is PairResult.Success -> {
// Pairing implies the app is installed and in use — skip the intro.
when {
// Remote-signer pairing deep link (NIP-46): nostrconnect://…
// from the node's login QR — any QR scanner app can hand it over.
// The signer UI lives inside the hub menu: drop the URI where
// WebViewScreen picks it up and route to the session, which opens
// the hub on its signer sub-page.
raw.startsWith("nostrconnect://") -> {
prefs.markIntroSeen()
val merged = prefs.upsertServer(result.server)
FipsManager.registerNode(context, result.fips, merged.displayName())
if (merged.password.isNotBlank()) {
// Demo flow: password came with the link — connect in one step.
prefs.setActiveServer(merged)
navController.navigate(Routes.WEB_VIEW) {
popUpTo(0) { inclusive = true }
}
} else {
pairPrefill = merged
navController.navigate(Routes.SERVER_CONNECT) {
popUpTo(0) { inclusive = true }
}
SignerLaunch.pendingUri.value = raw
navController.navigate(Routes.WEB_VIEW) {
popUpTo(0) { inclusive = true }
}
}
else -> {
// Invalid or too-new pairing link — ignore; normal startup continues.
else -> when (val result = ServerQrParser.parse(raw)) {
is PairResult.Success -> {
// Pairing implies the app is installed and in use — skip the intro.
prefs.markIntroSeen()
val merged = prefs.upsertServer(result.server)
FipsManager.registerNode(context, result.fips, merged.displayName())
if (merged.password.isNotBlank()) {
// Demo flow: password came with the link — connect in one step.
prefs.setActiveServer(merged)
navController.navigate(Routes.WEB_VIEW) {
popUpTo(0) { inclusive = true }
}
} else {
pairPrefill = merged
navController.navigate(Routes.SERVER_CONNECT) {
popUpTo(0) { inclusive = true }
}
}
}
else -> {
// Invalid or too-new pairing link — ignore; normal startup continues.
}
}
}
}
@@ -101,6 +101,7 @@ import com.archipelago.app.fips.FipsManager
import com.archipelago.app.ui.components.GestureHintOverlay
import com.archipelago.app.ui.components.MeshLoadingScreen
import com.archipelago.app.ui.components.NESMenu
import com.archipelago.app.ui.components.SignerLaunch
import com.archipelago.app.ui.components.QrScannerOverlay
import com.archipelago.app.ui.components.SlidingLoader
import com.archipelago.app.ui.components.WalletQrScannerModal
@@ -1373,6 +1374,16 @@ fun WebViewScreen(
// Hub menu overlay — opened by the three-finger hold, drawn above
// everything (also reachable from the error screen, where switching
// servers is exactly what's needed).
// Remote-signer deep link: route to the session and pop the hub open
// on its signer sub-page (the request itself is consumed by NESMenu).
var signerPairRequest by remember { mutableStateOf<String?>(null) }
val signerLaunch by SignerLaunch.pendingUri.collectAsState()
LaunchedEffect(signerLaunch) {
val uri = signerLaunch ?: return@LaunchedEffect
signerPairRequest = uri
SignerLaunch.pendingUri.value = null
showHubMenu = true
}
NESMenu(
visible = showHubMenu,
servers = savedServers,
@@ -1427,6 +1438,8 @@ fun WebViewScreen(
onKeyboard = { showHubMenu = false; onRemoteKeyboard() },
onBackToWebView = { showHubMenu = false },
onMeshParty = onMeshParty?.let { open -> { showHubMenu = false; open() } },
signerPairRequest = signerPairRequest,
onSignerPairHandled = { signerPairRequest = null },
)
// Pairing-QR scan launched from the menu's Nodes page; the menu stays
+369 -1
View File
@@ -12,6 +12,17 @@ dependencies = [
"generic-array",
]
[[package]]
name = "aes"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"
dependencies = [
"cfg-if",
"cipher",
"cpufeatures 0.2.17",
]
[[package]]
name = "aho-corasick"
version = "1.1.4"
@@ -81,17 +92,41 @@ checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
name = "archy-fips-core"
version = "0.1.0"
dependencies = [
"aes",
"anyhow",
"argon2",
"base64",
"bech32",
"cbc",
"chacha20 0.9.1",
"chacha20poly1305",
"fips",
"getrandom 0.2.17",
"hex",
"hkdf",
"hmac",
"jni",
"libc",
"paranoid-android",
"secp256k1 0.29.1",
"serde_json",
"sha2",
"tokio",
"tracing",
"tracing-subscriber",
"url",
]
[[package]]
name = "argon2"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072"
dependencies = [
"base64ct",
"blake2",
"cpufeatures 0.2.17",
"password-hash",
]
[[package]]
@@ -124,6 +159,18 @@ version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
[[package]]
name = "base64"
version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "base64ct"
version = "1.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
[[package]]
name = "bech32"
version = "0.11.1"
@@ -172,6 +219,15 @@ version = "2.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da"
[[package]]
name = "blake2"
version = "0.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"
dependencies = [
"digest",
]
[[package]]
name = "block-buffer"
version = "0.10.4"
@@ -181,6 +237,15 @@ dependencies = [
"generic-array",
]
[[package]]
name = "block-padding"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93"
dependencies = [
"generic-array",
]
[[package]]
name = "blocking"
version = "1.6.2"
@@ -200,6 +265,15 @@ version = "1.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
[[package]]
name = "cbc"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6"
dependencies = [
"cipher",
]
[[package]]
name = "cc"
version = "1.3.0"
@@ -406,6 +480,17 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "displaydoc"
version = "0.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.3",
]
[[package]]
name = "either"
version = "1.16.0"
@@ -476,7 +561,7 @@ dependencies = [
"libc",
"rand 0.10.2",
"rtnetlink",
"secp256k1",
"secp256k1 0.30.0",
"serde",
"serde_json",
"serde_yaml",
@@ -491,6 +576,15 @@ dependencies = [
"tun",
]
[[package]]
name = "form_urlencoded"
version = "1.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
dependencies = [
"percent-encoding",
]
[[package]]
name = "futures"
version = "0.3.33"
@@ -676,6 +770,110 @@ dependencies = [
"digest",
]
[[package]]
name = "icu_collections"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513"
dependencies = [
"displaydoc",
"potential_utf",
"utf8_iter",
"yoke",
"zerofrom",
"zerovec",
]
[[package]]
name = "icu_locale_core"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb"
dependencies = [
"displaydoc",
"litemap",
"tinystr",
"writeable",
"zerovec",
]
[[package]]
name = "icu_normalizer"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f"
dependencies = [
"icu_collections",
"icu_normalizer_data",
"icu_properties",
"icu_provider",
"smallvec",
"zerovec",
]
[[package]]
name = "icu_normalizer_data"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0"
[[package]]
name = "icu_properties"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148"
dependencies = [
"displaydoc",
"icu_collections",
"icu_locale_core",
"icu_properties_data",
"icu_provider",
"zerotrie",
"zerovec",
]
[[package]]
name = "icu_properties_data"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa"
[[package]]
name = "icu_provider"
version = "2.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73"
dependencies = [
"displaydoc",
"icu_locale_core",
"writeable",
"yoke",
"zerofrom",
"zerotrie",
"zerovec",
]
[[package]]
name = "idna"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"
dependencies = [
"idna_adapter",
"smallvec",
"utf8_iter",
]
[[package]]
name = "idna_adapter"
version = "1.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714"
dependencies = [
"icu_normalizer",
"icu_properties",
]
[[package]]
name = "indexmap"
version = "2.14.0"
@@ -692,6 +890,7 @@ version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
dependencies = [
"block-padding",
"generic-array",
]
@@ -788,6 +987,12 @@ dependencies = [
"libc",
]
[[package]]
name = "litemap"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae"
[[package]]
name = "log"
version = "0.4.33"
@@ -954,12 +1159,29 @@ version = "2.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba"
[[package]]
name = "password-hash"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166"
dependencies = [
"base64ct",
"rand_core 0.6.4",
"subtle",
]
[[package]]
name = "paste"
version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
[[package]]
name = "percent-encoding"
version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
[[package]]
name = "pin-project-lite"
version = "0.2.17"
@@ -988,6 +1210,15 @@ dependencies = [
"universal-hash",
]
[[package]]
name = "potential_utf"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661"
dependencies = [
"zerovec",
]
[[package]]
name = "ppv-lite86"
version = "0.2.21"
@@ -1129,6 +1360,15 @@ dependencies = [
"winapi-util",
]
[[package]]
name = "secp256k1"
version = "0.29.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9465315bc9d4566e1724f0fffcbcc446268cb522e60f9a27bcded6b19c108113"
dependencies = [
"secp256k1-sys",
]
[[package]]
name = "secp256k1"
version = "0.30.0"
@@ -1272,6 +1512,12 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "stable_deref_trait"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
[[package]]
name = "strsim"
version = "0.11.1"
@@ -1306,6 +1552,17 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "synstructure"
version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "thiserror"
version = "1.0.69"
@@ -1355,6 +1612,16 @@ dependencies = [
"cfg-if",
]
[[package]]
name = "tinystr"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643"
dependencies = [
"displaydoc",
"zerovec",
]
[[package]]
name = "tokio"
version = "1.53.1"
@@ -1519,6 +1786,24 @@ version = "0.2.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861"
[[package]]
name = "url"
version = "2.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
dependencies = [
"form_urlencoded",
"idna",
"percent-encoding",
"serde",
]
[[package]]
name = "utf8_iter"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
[[package]]
name = "utf8parse"
version = "0.2.2"
@@ -1657,6 +1942,35 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "writeable"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"
[[package]]
name = "yoke"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5"
dependencies = [
"stable_deref_trait",
"yoke-derive",
"zerofrom",
]
[[package]]
name = "yoke-derive"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
"synstructure",
]
[[package]]
name = "zerocopy"
version = "0.8.55"
@@ -1677,12 +1991,66 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "zerofrom"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"
dependencies = [
"zerofrom-derive",
]
[[package]]
name = "zerofrom-derive"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
"synstructure",
]
[[package]]
name = "zeroize"
version = "1.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"
[[package]]
name = "zerotrie"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f"
dependencies = [
"displaydoc",
"yoke",
"zerofrom",
]
[[package]]
name = "zerovec"
version = "0.11.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8"
dependencies = [
"yoke",
"zerofrom",
"zerovec-derive",
]
[[package]]
name = "zerovec-derive"
version = "0.11.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.3",
]
[[package]]
name = "zmij"
version = "1.0.23"
+29
View File
@@ -37,6 +37,35 @@ tracing = "0.1"
# fcntl: force the VpnService TUN fd into blocking mode (see mesh::start).
libc = "0.2"
# ── Companion backup (#128) ───────────────────────────────────────────────
# ADR-005 envelope: the SAME crates and blob layout as the node's backup code
# (core/archipelago/src/backup/identity.rs) — Argon2id KDF + ChaCha20-Poly1305
# AEAD — applied to the companion's own JSON payload. Do not diverge from
# those parameters: a companion backup and a node backup must decrypt with
# the same code path on either side.
argon2 = "0.5"
chacha20poly1305 = "0.10"
base64 = "0.22"
# ── NIP-46 remote signer (#139) ───────────────────────────────────────────
# BIP340 schnorr signing + secp256k1 ECDH (NIP-44/NIP-04 conversation keys).
# Audited libsecp256k1 via cc; cargo-ndk provides the NDK clang on Android.
secp256k1 = "0.29"
# NIP-44 v2: HKDF-SHA256 (conversation/message keys) + HMAC-SHA256 (MAC).
sha2 = "0.10"
hmac = "0.12"
hkdf = "0.12"
# NIP-44 v2 stream cipher (raw ChaCha20, RFC 8439 — NOT the AEAD).
chacha20 = "0.9"
# NIP-04 fallback (deprecated in the spec but still sent by real clients):
# AES-256-CBC, key = raw ECDH x-coordinate.
aes = "0.8"
cbc = { version = "0.1", features = ["alloc"] }
# npub/nsec (bech32, BIP173 variant — NOT Bech32m).
bech32 = "0.11"
# nostrconnect:// URI parsing (repeated relay params + percent-decoding).
url = "2.5"
# The JNI surface only exists on Android; host builds skip it and drive the
# mesh module directly (tests).
[target.'cfg(target_os = "android")'.dependencies]
+246
View File
@@ -0,0 +1,246 @@
//! Companion app backup — the ADR-005 encrypted-backup envelope.
//!
//! Reuses the node's backup format exactly (ADR-005:
//! `core/archipelago/src/backup/identity.rs`): Argon2id key derivation with
//! default params, ChaCha20-Poly1305 AEAD, and the same blob layout
//! `base64(salt[16] || nonce[12] || ciphertext)`. A companion backup and a
//! node backup share one crypto story — the payload differs (the companion
//! serializes its servers, FIPS identity and signer key instead of a node
//! key), the envelope does not.
//!
//! The envelope is JSON with `version`, `kind`, `encrypted`, `blob` and
//! `timestamp`; [`decrypt`] ignores any extra fields, so node envelopes
//! (which carry `did`/`pubkey`/`kid`) decrypt here too.
use anyhow::{bail, Context, Result};
use argon2::Argon2;
use base64::engine::general_purpose::STANDARD as BASE64;
use base64::Engine;
use chacha20poly1305::aead::{Aead, KeyInit};
use chacha20poly1305::{ChaCha20Poly1305, Key, Nonce};
use serde_json::json;
/// Envelope version. Bump only when the blob layout itself changes — and
/// then only with a reader for the old layout (same policy as the node).
const BACKUP_VERSION: u32 = 1;
const SALT_LEN: usize = 16;
const NONCE_LEN: usize = 12;
const KEY_LEN: usize = 32;
/// Encrypt a JSON payload into an ADR-005 envelope.
///
/// The passphrase never leaves this call; the envelope carries only the
/// salt (Argon2id parameter), the AEAD nonce, and the ciphertext.
pub fn encrypt(payload: &str, passphrase: &str) -> Result<String> {
if payload.is_empty() {
bail!("backup payload is empty");
}
if passphrase.is_empty() {
bail!("backup passphrase must not be empty");
}
let mut salt = [0u8; SALT_LEN];
let mut nonce = [0u8; NONCE_LEN];
// Same CSPRNG discipline as identity generation (getrandom, see mesh.rs):
// OS RNG, never thread-local or derived-from-content randomness for key
// material or nonces.
getrandom::getrandom(&mut salt).context("OS RNG")?;
getrandom::getrandom(&mut nonce).context("OS RNG")?;
let key = derive_key(passphrase, &salt)?;
let cipher = ChaCha20Poly1305::new(Key::from_slice(&key));
let ciphertext = cipher
.encrypt(Nonce::from_slice(&nonce), payload.as_bytes())
.map_err(|_| anyhow::anyhow!("encryption failed"))?;
let mut blob = Vec::with_capacity(SALT_LEN + NONCE_LEN + ciphertext.len());
blob.extend_from_slice(&salt);
blob.extend_from_slice(&nonce);
blob.extend_from_slice(&ciphertext);
Ok(json!({
"version": BACKUP_VERSION,
"kind": "companion",
"encrypted": true,
"blob": BASE64.encode(&blob),
"timestamp": chrono_like_now(),
})
.to_string())
}
/// Decrypt an ADR-005 envelope back into its JSON payload.
///
/// Accepts `version: 1` envelopes regardless of `kind` or extra fields —
/// the node's identity backups use the same blob, and being able to decrypt
/// one here is free interop (the caller decides what to do with it).
pub fn decrypt(envelope: &str, passphrase: &str) -> Result<String> {
let obj: serde_json::Value =
serde_json::from_str(envelope).context("not a JSON backup envelope")?;
if obj.get("version").and_then(|v| v.as_u64()) != Some(BACKUP_VERSION as u64) {
bail!("unsupported backup version (expected {BACKUP_VERSION})");
}
let blob_b64 = obj
.get("blob")
.and_then(|v| v.as_str())
.context("missing 'blob' in backup envelope")?;
let blob = BASE64
.decode(blob_b64)
.context("invalid base64 in backup blob")?;
if blob.len() < SALT_LEN + NONCE_LEN {
bail!("backup blob too short");
}
let salt = &blob[..SALT_LEN];
let nonce = &blob[SALT_LEN..SALT_LEN + NONCE_LEN];
let ciphertext = &blob[SALT_LEN + NONCE_LEN..];
let key = derive_key(passphrase, salt)?;
let cipher = ChaCha20Poly1305::new(Key::from_slice(&key));
let plaintext = cipher
.decrypt(Nonce::from_slice(nonce), ciphertext)
.map_err(|_| anyhow::anyhow!("decryption failed — wrong passphrase or corrupted backup"))?;
String::from_utf8(plaintext).context("decrypted payload is not valid UTF-8")
}
fn derive_key(passphrase: &str, salt: &[u8]) -> Result<[u8; KEY_LEN]> {
let mut key = [0u8; KEY_LEN];
Argon2::default()
.hash_password_into(passphrase.as_bytes(), salt, &mut key)
.map_err(|e| anyhow::anyhow!("Argon2 key derivation failed: {e}"))?;
Ok(key)
}
/// RFC 3339 UTC timestamp without pulling chrono into the .so — the node's
/// envelope field is informational (display), not part of the authenticated
/// or derived material.
fn chrono_like_now() -> String {
let secs = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let days = secs / 86_400;
let rem = secs % 86_400;
let (h, m, s) = (rem / 3600, (rem % 3600) / 60, rem % 60);
// Civil-from-days (Howard Hinnant's algorithm), valid for 1970-2100+.
let z = days as i64 + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let mo = if mp < 10 { mp + 3 } else { mp - 9 };
let y = if mo <= 2 { y + 1 } else { y };
format!("{y:04}-{mo:02}-{d:02}T{h:02}:{m:02}:{s:02}Z")
}
#[cfg(test)]
mod tests {
use super::*;
const PAYLOAD: &str = r#"{"app":"archipelago-companion","servers":["192.168.1.10|false|1301||Lab Node|fd00::1|npub1abc"]}"#;
#[test]
fn round_trip() {
let envelope = encrypt(PAYLOAD, "correct horse battery staple").unwrap();
let decrypted = decrypt(&envelope, "correct horse battery staple").unwrap();
assert_eq!(decrypted, PAYLOAD);
}
#[test]
fn wrong_passphrase_fails() {
let envelope = encrypt(PAYLOAD, "right").unwrap();
let err = decrypt(&envelope, "wrong").unwrap_err();
assert!(
err.to_string().contains("wrong passphrase"),
"error should name the likely cause: {err}"
);
}
#[test]
fn envelope_shape_matches_node_format() {
let envelope = encrypt(PAYLOAD, "pw").unwrap();
let obj: serde_json::Value = serde_json::from_str(&envelope).unwrap();
assert_eq!(obj["version"], 1);
assert_eq!(obj["encrypted"], true);
assert!(obj["kind"].as_str().is_some());
assert!(obj["timestamp"].as_str().is_some());
// Blob layout is exactly the node's: base64(salt||nonce||ct) with the
// AEAD tag inside the ciphertext — at least 16+12+16+1 bytes.
let blob = BASE64
.decode(obj["blob"].as_str().unwrap())
.expect("blob is base64");
assert!(blob.len() >= SALT_LEN + NONCE_LEN + 16 + PAYLOAD.len());
}
#[test]
fn fresh_salt_and_nonce_every_time() {
let a = encrypt(PAYLOAD, "pw").unwrap();
let b = encrypt(PAYLOAD, "pw").unwrap();
let (oa, ob): (serde_json::Value, serde_json::Value) = (
serde_json::from_str(&a).unwrap(),
serde_json::from_str(&b).unwrap(),
);
assert_ne!(oa["blob"], ob["blob"], "salt/nonce must never repeat");
}
#[test]
fn tampered_blob_fails_to_decrypt() {
let envelope = encrypt(PAYLOAD, "pw").unwrap();
let mut obj: serde_json::Value = serde_json::from_str(&envelope).unwrap();
let blob = BASE64.decode(obj["blob"].as_str().unwrap()).unwrap();
let mut tampered = blob.clone();
// Flip a bit inside the ciphertext (past salt+nonce).
tampered[SALT_LEN + NONCE_LEN] ^= 0x01;
obj["blob"] = serde_json::Value::String(BASE64.encode(&tampered));
assert!(decrypt(&obj.to_string(), "pw").is_err());
}
/// Node identity backups use the same blob layout but carry their own
/// envelope fields (did/pubkey/kid). Decrypt must ignore those extras —
/// one envelope reader, two producers.
#[test]
fn node_style_envelope_with_extra_fields_decrypts() {
let envelope = encrypt(PAYLOAD, "pw").unwrap();
let mut obj: serde_json::Value = serde_json::from_str(&envelope).unwrap();
obj["kind"] = serde_json::Value::String("node-identity".into());
obj["did"] = serde_json::Value::String("did:key:z6Mktest".into());
obj["pubkey"] = serde_json::Value::String("aabbcc".into());
obj["kid"] = serde_json::Value::String("did:key:z6Mktest#key-1".into());
let decrypted = decrypt(&obj.to_string(), "pw").unwrap();
assert_eq!(decrypted, PAYLOAD);
}
#[test]
fn rejects_unknown_version_and_garbage() {
let err = decrypt("{\"version\":99,\"blob\":\"AAAA\"}", "pw").unwrap_err();
assert!(err.to_string().contains("version"));
assert!(decrypt("not json", "pw").is_err());
assert!(decrypt("{\"version\":1}", "pw").is_err());
}
#[test]
fn rejects_empty_passphrase_and_payload() {
assert!(encrypt(PAYLOAD, "").is_err());
assert!(encrypt("", "pw").is_err());
}
#[test]
fn timestamp_is_rfc3339_utc() {
let envelope = encrypt(PAYLOAD, "pw").unwrap();
let obj: serde_json::Value = serde_json::from_str(&envelope).unwrap();
let ts = obj["timestamp"].as_str().unwrap();
// 2026-08-31T12:34:56Z — 20 chars, RFC 3339 UTC.
assert_eq!(ts.len(), 20);
assert!(ts.ends_with('Z'));
assert_eq!(&ts[4..5], "-");
assert_eq!(&ts[10..11], "T");
assert!(ts.starts_with("20"));
}
}
+177 -2
View File
@@ -1,5 +1,6 @@
//! JNI surface for `com.archipelago.app.fips.FipsNative` — JSON over strings,
//! no codegen (the myco / nostr-vpn embedding pattern). Errors come back as
//! JNI surface for `com.archipelago.app.fips.FipsNative` and
//! `com.archipelago.app.NativeCore` — JSON over strings, no codegen (the
//! myco / nostr-vpn embedding pattern). Errors come back as
//! `{"error": "…"}` so Kotlin never sees a raw exception from native code.
use std::sync::Once;
@@ -127,3 +128,177 @@ pub extern "system" fn Java_com_archipelago_app_fips_FipsNative_statusJson(
) -> jstring {
out(&env, mesh::status_json())
}
// ─────────────────────────────────────────────────────────────────────────────
// com.archipelago.app.NativeCore — companion backup (#128) and NIP-46 remote
// signer crypto (#139). Same library, JSON-over-strings contract.
// ─────────────────────────────────────────────────────────────────────────────
/// Kotlin: `external fun backupEncrypt(payload: String, passphrase: String): String`
/// Returns the ADR-005 envelope JSON or `{"error": …}`.
#[no_mangle]
pub extern "system" fn Java_com_archipelago_app_NativeCore_backupEncrypt(
mut env: JNIEnv,
_class: JClass,
payload: JString,
passphrase: JString,
) -> jstring {
init_logging();
let payload = jstr(&mut env, &payload);
let passphrase = jstr(&mut env, &passphrase);
let json = match crate::backup::encrypt(&payload, &passphrase) {
Ok(envelope) => envelope,
Err(e) => err_json(e),
};
out(&env, json)
}
/// Kotlin: `external fun backupDecrypt(envelope: String, passphrase: String): String`
/// Returns the decrypted payload JSON or `{"error": …}`.
#[no_mangle]
pub extern "system" fn Java_com_archipelago_app_NativeCore_backupDecrypt(
mut env: JNIEnv,
_class: JClass,
envelope: JString,
passphrase: JString,
) -> jstring {
init_logging();
let envelope = jstr(&mut env, &envelope);
let passphrase = jstr(&mut env, &passphrase);
let json = match crate::backup::decrypt(&envelope, &passphrase) {
Ok(payload) => payload,
Err(e) => err_json(e),
};
out(&env, json)
}
/// Kotlin: `external fun nostrGenerateSecret(): String`
/// Returns `{"secret": hex, "pubkey": hex, "npub": …, "nsec": …}` or `{"error": …}`.
#[no_mangle]
pub extern "system" fn Java_com_archipelago_app_NativeCore_nostrGenerateSecret(
env: JNIEnv,
_class: JClass,
) -> jstring {
init_logging();
let json = match crate::nostr::generate_secret() {
Ok(secret) => nostr_key_info_json(&secret),
Err(e) => err_json(e),
};
out(&env, json)
}
/// Kotlin: `external fun nostrSecretFromAny(secret: String): String`
/// Accepts hex or `nsec…`; returns key-info JSON or `{"error": …}`.
#[no_mangle]
pub extern "system" fn Java_com_archipelago_app_NativeCore_nostrSecretFromAny(
mut env: JNIEnv,
_class: JClass,
secret: JString,
) -> jstring {
init_logging();
let secret = jstr(&mut env, &secret);
let json = match crate::nostr::secret_from_any(&secret) {
Ok(hex) => nostr_key_info_json(&hex),
Err(e) => err_json(e),
};
out(&env, json)
}
fn nostr_key_info_json(secret_hex: &str) -> String {
match (
crate::nostr::pubkey_hex(secret_hex),
crate::nostr::npub_from_pubkey(&crate::nostr::pubkey_hex(secret_hex).unwrap_or_default()),
crate::nostr::nsec_from_secret(secret_hex),
) {
(Ok(pubkey), Ok(npub), Ok(nsec)) => serde_json::json!({
"secret": secret_hex,
"pubkey": pubkey,
"npub": npub,
"nsec": nsec,
})
.to_string(),
(e, _, _) => err_json(e.unwrap_err()),
}
}
/// Kotlin: `external fun nostrParseConnectUri(uri: String): String`
/// Returns the parsed URI fields or `{"error": …}`.
#[no_mangle]
pub extern "system" fn Java_com_archipelago_app_NativeCore_nostrParseConnectUri(
mut env: JNIEnv,
_class: JClass,
uri: JString,
) -> jstring {
init_logging();
let uri = jstr(&mut env, &uri);
let json = match crate::nostr::parse_connect_uri(&uri) {
Ok(info) => info.to_json().to_string(),
Err(e) => err_json(e),
};
out(&env, json)
}
/// Kotlin: `external fun nostrSignEvent(secretHex: String, eventJson: String): String`
/// Returns the signed event JSON or `{"error": …}`. The approve/deny decision
/// is made in Kotlin BEFORE this is called — native code never signs unasked.
#[no_mangle]
pub extern "system" fn Java_com_archipelago_app_NativeCore_nostrSignEvent(
mut env: JNIEnv,
_class: JClass,
secret_hex: JString,
event_json: JString,
) -> jstring {
init_logging();
let secret = jstr(&mut env, &secret_hex);
let event = jstr(&mut env, &event_json);
let json = match crate::nostr::sign_event(&secret, &event) {
Ok(signed) => signed,
Err(e) => err_json(e),
};
out(&env, json)
}
macro_rules! nostr_cipher {
($name:ident, $doc:literal, $fn:path) => {
#[doc = $doc]
#[no_mangle]
pub extern "system" fn $name(
mut env: JNIEnv,
_class: JClass,
secret_hex: JString,
peer_pub: JString,
text: JString,
) -> jstring {
init_logging();
let secret = jstr(&mut env, &secret_hex);
let peer = jstr(&mut env, &peer_pub);
let text = jstr(&mut env, &text);
let json = match $fn(&secret, &peer, &text) {
Ok(out) => serde_json::json!({ "result": out }).to_string(),
Err(e) => err_json(e),
};
out(&env, json)
}
};
}
nostr_cipher!(
Java_com_archipelago_app_NativeCore_nostrNip44Encrypt,
"Kotlin: `external fun nostrNip44Encrypt(secretHex: String, peerPub: String, plaintext: String): String` — returns `{\"result\": payload}` or `{\"error\": …}`.",
crate::nostr::nip44_encrypt
);
nostr_cipher!(
Java_com_archipelago_app_NativeCore_nostrNip44Decrypt,
"Kotlin: `external fun nostrNip44Decrypt(secretHex: String, peerPub: String, payload: String): String`",
crate::nostr::nip44_decrypt
);
nostr_cipher!(
Java_com_archipelago_app_NativeCore_nostrNip04Encrypt,
"Kotlin: `external fun nostrNip04Encrypt(secretHex: String, peerPub: String, plaintext: String): String`",
crate::nostr::nip04_encrypt
);
nostr_cipher!(
Java_com_archipelago_app_NativeCore_nostrNip04Decrypt,
"Kotlin: `external fun nostrNip04Decrypt(secretHex: String, peerPub: String, payload: String): String`",
crate::nostr::nip04_decrypt
);
+2
View File
@@ -11,7 +11,9 @@
//! JSON-over-strings, mirroring the myco / nostr-vpn embedding pattern:
//! `generateIdentity`, `deriveIdentity`, `start`, `stop`, `isRunning`.
pub mod backup;
pub mod mesh;
pub mod nostr;
#[cfg(target_os = "android")]
mod jni_glue;
+824
View File
@@ -0,0 +1,824 @@
//! NIP-46 phone-side remote signer ("bunker") crypto core.
//!
//! Everything that must be constant-time correct for the companion to act as
//! a nostr remote signer: key handling (nsec/npub bech32), BIP340 schnorr
//! event signing, NIP-44 v2 payload encryption (the mandated NIP-46
//! transport), NIP-04 fallback decryption (deprecated, but real clients
//! still speak it), and `nostrconnect://` URI parsing. The protocol session
//! — relay WebSocket, JSON-RPC dispatch, approve/deny UX — lives in Kotlin;
//! this module is the crypto and nothing but.
//!
//! Verified against the official NIP-44 vectors and BIP-340 reference
//! vectors (see tests below).
use anyhow::{bail, Context, Result};
use base64::engine::general_purpose::{STANDARD as BASE64, URL_SAFE as BASE64_URL};
use base64::Engine;
use bech32::{Bech32, Hrp};
use chacha20::cipher::{KeyIvInit, StreamCipher};
use chacha20::ChaCha20;
use hmac::{Hmac, Mac};
use hkdf::Hkdf;
use secp256k1::ecdh;
use secp256k1::schnorr::Signature;
use secp256k1::{
Keypair, Message, PublicKey, Secp256k1, SecretKey, XOnlyPublicKey,
};
use sha2::{Digest, Sha256};
type HmacSha256 = Hmac<Sha256>;
const NIP44_VERSION: u8 = 2;
const NIP44_SALT: &[u8] = b"nip44-v2";
const NIP44_MIN_PAYLOAD_LEN: usize = 99; // 1 ver + 32 nonce + 32 ct + 32 mac
const NIP44_MIN_B64_LEN: usize = 132;
// ── keys ──────────────────────────────────────────────────────────────────
/// Generate a fresh nostr secret key (hex) from the OS CSPRNG.
pub fn generate_secret() -> Result<String> {
loop {
let mut bytes = [0u8; 32];
getrandom::getrandom(&mut bytes).context("OS RNG")?;
// Reject zero and >= curve order — the valid scalar range (mirrors
// the mesh identity loop; rejection is astronomically unlikely).
if bytes.iter().all(|&b| b == 0) {
continue;
}
if SecretKey::from_slice(&bytes).is_ok() {
return Ok(hex::encode(bytes));
}
}
}
/// Parse a secret key from hex or bech32 `nsec…` form into hex.
pub fn secret_from_any(s: &str) -> Result<String> {
let s = s.trim();
if s.starts_with("nsec") {
return secret_from_nsec(s);
}
let bytes = hex::decode(s.trim()).context("secret key must be hex or nsec")?;
let sk = SecretKey::from_slice(&bytes).context("invalid nostr secret key")?;
Ok(hex::encode(sk.secret_bytes()))
}
pub fn secret_from_nsec(nsec: &str) -> Result<String> {
let (hrp, data) = bech32::decode(nsec).context("bad nsec encoding")?;
if hrp.as_str() != "nsec" {
bail!("not an nsec");
}
let sk = SecretKey::from_slice(&data).context("invalid nostr secret key")?;
Ok(hex::encode(sk.secret_bytes()))
}
pub fn nsec_from_secret(secret_hex: &str) -> Result<String> {
let bytes = hex::decode(secret_hex.trim()).context("bad secret hex")?;
let hrp = Hrp::parse("nsec").context("nsec hrp")?;
bech32::encode::<Bech32>(hrp, &bytes).context("nsec encoding")
}
/// x-only public key (hex) for a secret key.
/// NOTE: `Keypair::public_key()` in secp256k1 0.29 is the full compressed
/// (33-byte) key — nostr uses x-only pubkeys, so serialize `.x_only_public_key().0`.
pub fn pubkey_hex(secret_hex: &str) -> Result<String> {
let kp = keypair(secret_hex)?;
Ok(hex::encode(kp.public_key().x_only_public_key().0.serialize()))
}
pub fn npub_from_pubkey(pub_hex: &str) -> Result<String> {
let bytes = hex::decode(pub_hex.trim()).context("bad pubkey hex")?;
let hrp = Hrp::parse("npub").context("npub hrp")?;
bech32::encode::<Bech32>(hrp, &bytes).context("npub encoding")
}
/// Parse an x-only pubkey from hex or bech32 `npub…` form into hex.
pub fn pubkey_from_any(s: &str) -> Result<String> {
let s = s.trim();
let bytes = if s.starts_with("npub") {
let (hrp, data) = bech32::decode(s).context("bad npub encoding")?;
if hrp.as_str() != "npub" {
bail!("not an npub");
}
data
} else {
hex::decode(s).context("pubkey must be hex or npub")?
};
XOnlyPublicKey::from_slice(&bytes).context("invalid x-only pubkey")?;
Ok(hex::encode(bytes))
}
fn keypair(secret_hex: &str) -> Result<Keypair> {
let bytes = hex::decode(secret_hex.trim()).context("bad secret hex")?;
let sk = SecretKey::from_slice(&bytes).context("invalid nostr secret key")?;
Ok(Keypair::from_secret_key(&Secp256k1::new(), &sk))
}
// ── nostrconnect:// URI ───────────────────────────────────────────────────
#[derive(Debug, Clone)]
pub struct ConnectUri {
/// The client's pubkey, hex.
pub client_pubkey: String,
/// Relays the client is listening on (≥1 by spec; kept in URI order).
pub relays: Vec<String>,
/// One-time pairing secret the client expects to see echoed back.
pub secret: String,
/// Comma-separated permission grants the client requests (display hint
/// only — approval always stays with the human).
pub perms: Vec<String>,
pub name: String,
pub url: String,
pub image: String,
}
impl ConnectUri {
/// JSON shape for the JNI boundary (flat strings/arrays — easy to parse
/// with org.json on the Kotlin side).
pub fn to_json(&self) -> serde_json::Value {
serde_json::json!({
"clientPubkey": self.client_pubkey,
"relays": self.relays,
"secret": self.secret,
"perms": self.perms,
"name": self.name,
"url": self.url,
"image": self.image,
})
}
}
/// Parse `nostrconnect://<client-pubkey>?relay=…&secret=…&perms=…&name=…`.
///
/// Query values are percent-decoded; `relay` may repeat. The pubkey in the
/// host position may be hex or (non-spec but harmless) `npub…`.
pub fn parse_connect_uri(uri: &str) -> Result<ConnectUri> {
let uri = uri.trim();
let rest = uri
.strip_prefix("nostrconnect://")
.ok_or_else(|| anyhow::anyhow!("not a nostrconnect:// URI"))?;
let (host, query) = match rest.split_once('?') {
Some((h, q)) => (h, q),
None => bail!("nostrconnect URI has no query parameters"),
};
let client_pubkey = pubkey_from_any(host).context("nostrconnect URI: bad client pubkey")?;
let mut relays = Vec::new();
let mut secret = String::new();
let mut perms: Vec<String> = Vec::new();
let mut name = String::new();
let mut url = String::new();
let mut image = String::new();
for (k, v) in url::form_urlencoded::parse(query.as_bytes()) {
let v = v.into_owned();
match k.as_ref() {
"relay" => {
if v.starts_with("ws://") || v.starts_with("wss://") {
relays.push(v);
}
}
"secret" => secret = v,
"perms" => perms = v.split(',').filter(|s| !s.is_empty()).map(String::from).collect(),
"name" => name = v,
"url" => url = v,
"image" => image = v,
_ => {} // forward-compat: ignore unknown params
}
}
if relays.is_empty() {
bail!("nostrconnect URI carries no relay");
}
if secret.is_empty() {
bail!("nostrconnect URI carries no secret");
}
Ok(ConnectUri {
client_pubkey,
relays,
secret,
perms,
name,
url,
image,
})
}
// ── events (NIP-01 id + BIP340 signature) ─────────────────────────────────
/// Compute the NIP-01 event id: sha256 over the compact serialization
/// `[0, pubkey, created_at, kind, tags, content]`.
fn event_id(pubkey: &str, created_at: u64, kind: u64, tags: &serde_json::Value, content: &str) -> [u8; 32] {
let serialized = serde_json::json!([
0,
pubkey,
created_at,
kind,
tags,
content,
]);
let mut hasher = Sha256::new();
hasher.update(serialized.to_string().as_bytes());
hasher.finalize().into()
}
/// Sign an unsigned event `{kind, content, tags, created_at}` (pubkey filled
/// from the secret key; `pubkey` in the input ignored) and return the signed
/// event JSON. This is the `sign_event` NIP-46 method's core — the approve
/// happens before this call, never inside it.
pub fn sign_event(secret_hex: &str, event_json: &str) -> Result<String> {
let ev: serde_json::Value = serde_json::from_str(event_json).context("event is not JSON")?;
let kind = ev
.get("kind")
.and_then(|v| v.as_u64())
.context("event has no kind")?;
let created_at = ev
.get("created_at")
.and_then(|v| v.as_u64())
.context("event has no created_at")?;
let tags = ev
.get("tags")
.cloned()
.unwrap_or_else(|| serde_json::json!([]));
let content = ev
.get("content")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let kp = keypair(secret_hex)?;
let pubkey = hex::encode(kp.public_key().x_only_public_key().0.serialize());
let id = event_id(&pubkey, created_at, kind, &tags, &content);
let mut aux = [0u8; 32];
getrandom::getrandom(&mut aux).context("OS RNG")?;
let sig = Secp256k1::new().sign_schnorr_with_aux_rand(
&Message::from_digest(id),
&kp,
&aux,
);
Ok(serde_json::json!({
"id": hex::encode(id),
"pubkey": pubkey,
"created_at": created_at,
"kind": kind,
"tags": tags,
"content": content,
"sig": hex::encode(sig.serialize()),
})
.to_string())
}
/// Verify a signed event's id and schnorr signature (tests + defensive use).
pub fn verify_event(event_json: &str) -> Result<()> {
let ev: serde_json::Value = serde_json::from_str(event_json).context("event is not JSON")?;
let pubkey = ev.get("pubkey").and_then(|v| v.as_str()).context("no pubkey")?;
let id_hex = ev.get("id").and_then(|v| v.as_str()).context("no id")?;
let sig_hex = ev.get("sig").and_then(|v| v.as_str()).context("no sig")?;
let kind = ev.get("kind").and_then(|v| v.as_u64()).context("no kind")?;
let created_at = ev.get("created_at").and_then(|v| v.as_u64()).context("no created_at")?;
let tags = ev.get("tags").cloned().unwrap_or_else(|| serde_json::json!([]));
let content = ev.get("content").and_then(|v| v.as_str()).unwrap_or("");
let expected = event_id(pubkey, created_at, kind, &tags, content);
if hex::encode(expected) != id_hex {
bail!("event id mismatch");
}
let pk = XOnlyPublicKey::from_slice(&hex::decode(pubkey)?)
.context("bad pubkey")?;
let sig = Signature::from_slice(&hex::decode(sig_hex)?)
.context("bad signature")?;
Secp256k1::new()
.verify_schnorr(&sig, &Message::from_digest(expected), &pk)
.context("signature verification failed")?;
Ok(())
}
// ── NIP-44 v2 ──────────────────────────────────────────────────────────────
/// ECDH shared x-coordinate (unhashed, 32 bytes) between our secret key and
/// the peer's x-only public key. Lifting the x-only key with even-y parity
/// is safe here: negating a point flips only y, so the shared x — the only
/// thing NIP-44/NIP-04 consume — is unchanged.
fn shared_x(secret_hex: &str, peer_pubkey_hex: &str) -> Result<[u8; 32]> {
let sk_bytes = hex::decode(secret_hex.trim()).context("bad secret hex")?;
let sk = SecretKey::from_slice(&sk_bytes).context("invalid secret key")?;
let peer_hex = pubkey_from_any(peer_pubkey_hex)?;
let peer = XOnlyPublicKey::from_slice(&hex::decode(&peer_hex)?)
.context("invalid peer pubkey")?;
// Lift x-only key to a full public key (even-y representative).
let full = PublicKey::from_x_only_public_key(peer, secp256k1::Parity::Even);
let point = ecdh::shared_secret_point(&full, &sk); // 64 bytes: x || y
let mut x = [0u8; 32];
x.copy_from_slice(&point[..32]);
Ok(x)
}
/// NIP-44 v2 conversation key: HKDF-extract(IKM = ECDH x, salt = 'nip44-v2').
fn conversation_key(secret_hex: &str, peer_pubkey_hex: &str) -> Result<[u8; 32]> {
let x = shared_x(secret_hex, peer_pubkey_hex)?;
let mut hk = HkdfExtractSha256::new(Some(NIP44_SALT));
hk.input_ikm(&x);
let (prk, _) = hk.finalize();
let mut ck = [0u8; 32];
ck.copy_from_slice(prk.as_slice());
Ok(ck)
}
/// HKDF-SHA256 extract step, exposing the raw PRK (Hkdf::expand hashes with
/// an info suffix even when info is empty, which is NOT the extract output;
/// finalize returns (PRK, ready-to-expand Hkdf)).
type HkdfExtractSha256 = hkdf::HkdfExtract<Sha256>;
/// Per-message keys: HKDF-expand(PRK = conversation key, info = nonce, L = 76)
/// sliced into chacha_key[32] chacha_nonce[12] hmac_key[32].
fn message_keys(ck: &[u8; 32], nonce: &[u8; 32]) -> ([u8; 32], [u8; 12], [u8; 32]) {
let hk = Hkdf::<Sha256>::from_prk(ck).expect("conversation key is 32 bytes");
let mut okm = [0u8; 76];
hk.expand(nonce, &mut okm).expect("76 <= 255 * hash len");
let mut chacha_key = [0u8; 32];
let mut chacha_nonce = [0u8; 12];
let mut hmac_key = [0u8; 32];
chacha_key.copy_from_slice(&okm[..32]);
chacha_nonce.copy_from_slice(&okm[32..44]);
hmac_key.copy_from_slice(&okm[44..76]);
(chacha_key, chacha_nonce, hmac_key)
}
/// NIP-44 padding: 2-byte big-endian plaintext length (6 bytes, `0x0000` +
/// u32, when ≥ 65536), zero-padded to the next power-of-two-ish chunk.
fn calc_padded_len(unpadded: usize) -> usize {
let unpadded: u64 = unpadded as u64;
if unpadded <= 32 {
return 32;
}
let next_power = 1u64 << ((63 - (unpadded - 1).leading_zeros()) + 1);
let chunk = if next_power <= 256 { 32 } else { next_power / 8 };
(chunk * ((unpadded - 1) / chunk + 1)) as usize
}
fn pad(plaintext: &[u8]) -> Result<Vec<u8>> {
if plaintext.is_empty() || plaintext.len() > u32::MAX as usize {
bail!("invalid plaintext length");
}
let prefix: Vec<u8> = if plaintext.len() >= 65536 {
let mut p = vec![0u8, 0u8];
p.extend_from_slice(&(plaintext.len() as u32).to_be_bytes());
p
} else {
(plaintext.len() as u16).to_be_bytes().to_vec()
};
let padded_len = calc_padded_len(plaintext.len());
let mut out = Vec::with_capacity(prefix.len() + padded_len);
out.extend_from_slice(&prefix);
out.extend_from_slice(plaintext);
out.resize(prefix.len() + padded_len, 0);
Ok(out)
}
fn unpad(padded: &[u8]) -> Result<Vec<u8>> {
if padded.len() < 2 {
bail!("invalid padding");
}
let first_two = u16::from_be_bytes([padded[0], padded[1]]);
let (unpadded_len, prefix_len) = if first_two == 0 {
if padded.len() < 6 {
bail!("invalid padding");
}
(u32::from_be_bytes([padded[2], padded[3], padded[4], padded[5]]) as usize, 6)
} else {
(first_two as usize, 2)
};
if unpadded_len == 0
|| padded.len() < prefix_len + unpadded_len
|| padded.len() != prefix_len + calc_padded_len(unpadded_len)
{
bail!("invalid padding");
}
Ok(padded[prefix_len..prefix_len + unpadded_len].to_vec())
}
/// Constant-time equality (length differs → false; content comparison never
/// short-circuits on a byte).
fn ct_eq(a: &[u8], b: &[u8]) -> bool {
if a.len() != b.len() {
return false;
}
let mut diff = 0u8;
for (x, y) in a.iter().zip(b.iter()) {
diff |= x ^ y;
}
diff == 0
}
/// NIP-44 v2 encrypt: returns `base64(0x02 || nonce || ciphertext || mac)`.
pub fn nip44_encrypt(secret_hex: &str, peer_pubkey_hex: &str, plaintext: &str) -> Result<String> {
let ck = conversation_key(secret_hex, peer_pubkey_hex)?;
let mut nonce = [0u8; 32];
getrandom::getrandom(&mut nonce).context("OS RNG")?;
let (chacha_key, chacha_nonce, hmac_key) = message_keys(&ck, &nonce);
let mut padded = pad(plaintext.as_bytes())?;
ChaCha20::new(&chacha_key.into(), &chacha_nonce.into()).apply_keystream(&mut padded);
let mut mac = <HmacSha256 as Mac>::new_from_slice(&hmac_key).expect("hmac accepts any key len");
mac.update(&nonce);
mac.update(&padded);
let tag = mac.finalize().into_bytes();
let mut out = Vec::with_capacity(1 + 32 + padded.len() + 32);
out.push(NIP44_VERSION);
out.extend_from_slice(&nonce);
out.extend_from_slice(&padded);
out.extend_from_slice(&tag);
Ok(BASE64.encode(&out))
}
/// NIP-44 v2 decrypt of a `base64(0x02 || …)` payload.
pub fn nip44_decrypt(secret_hex: &str, peer_pubkey_hex: &str, payload: &str) -> Result<String> {
if payload.starts_with('#') {
bail!("unknown NIP-44 version (non-base64 payload)");
}
let data = BASE64
.decode(payload.trim())
.context("payload is not base64")?;
if payload.len() < NIP44_MIN_B64_LEN || data.len() < NIP44_MIN_PAYLOAD_LEN {
bail!("invalid NIP-44 payload size");
}
if data[0] != NIP44_VERSION {
bail!("unknown NIP-44 version {}", data[0]);
}
let nonce: [u8; 32] = data[1..33].try_into().expect("slice is 32");
let ciphertext = &data[33..data.len() - 32];
let mac_bytes = &data[data.len() - 32..];
let ck = conversation_key(secret_hex, peer_pubkey_hex)?;
let (chacha_key, chacha_nonce, hmac_key) = message_keys(&ck, &nonce);
let mut mac = <HmacSha256 as Mac>::new_from_slice(&hmac_key).expect("hmac accepts any key len");
mac.update(&nonce);
mac.update(ciphertext);
let expected = mac.finalize().into_bytes();
if !ct_eq(&expected, mac_bytes) {
bail!("invalid NIP-44 MAC");
}
let mut buf = ciphertext.to_vec();
ChaCha20::new(&chacha_key.into(), &chacha_nonce.into()).apply_keystream(&mut buf);
let plaintext = unpad(&buf)?;
String::from_utf8(plaintext).context("decrypted payload is not UTF-8")
}
// ── NIP-04 (deprecated transport, still spoken by real clients) ────────────
/// NIP-04 encrypt: AES-256-CBC, key = raw ECDH x-coordinate (unhashed — the
/// spec's quirk), output `<base64 ct>?iv=<base64 iv>`.
pub fn nip04_encrypt(secret_hex: &str, peer_pubkey_hex: &str, plaintext: &str) -> Result<String> {
use aes::cipher::{BlockEncryptMut, KeyIvInit};
type Enc = cbc::Encryptor<aes::Aes256>;
let key = shared_x(secret_hex, peer_pubkey_hex)?;
let mut iv = [0u8; 16];
getrandom::getrandom(&mut iv).context("OS RNG")?;
let ct = Enc::new(&key.into(), &iv.into()).encrypt_padded_vec_mut::<aes::cipher::block_padding::Pkcs7>(plaintext.as_bytes());
Ok(format!("{}?iv={}", BASE64.encode(&ct), BASE64.encode(iv)))
}
/// NIP-04 decrypt of `<base64 ct>?iv=<base64 iv>`.
pub fn nip04_decrypt(secret_hex: &str, peer_pubkey_hex: &str, payload: &str) -> Result<String> {
use aes::cipher::{BlockDecryptMut, KeyIvInit};
type Dec = cbc::Decryptor<aes::Aes256>;
let (ct_b64, iv_b64) = payload
.trim()
.split_once("?iv=")
.ok_or_else(|| anyhow::anyhow!("not a NIP-04 payload (no iv)"))?;
let ct = BASE64.decode(ct_b64).context("bad NIP-04 ciphertext base64")?;
let iv: [u8; 16] = BASE64
.decode(iv_b64)
.context("bad NIP-04 iv base64")?
.try_into()
.map_err(|_| anyhow::anyhow!("NIP-04 iv must be 16 bytes"))?;
let key = shared_x(secret_hex, peer_pubkey_hex)?;
let pt = Dec::new(&key.into(), &iv.into())
.decrypt_padded_vec_mut::<aes::cipher::block_padding::Pkcs7>(&ct)
.map_err(|_| anyhow::anyhow!("NIP-04 decryption failed"))?;
String::from_utf8(pt).context("decrypted payload is not UTF-8")
}
/// URL-safe base64 for keys that cross the JNI boundary — unused by the
/// protocol but handy for the Kotlin side; keep the engine in one place.
pub fn b64_url(data: &[u8]) -> String {
BASE64_URL.encode(data)
}
#[cfg(test)]
mod tests {
use super::*;
// ── official NIP-44 vectors (paulmillr/nip44 nip44.vectors.json) ──────
#[test]
fn nip44_official_conversation_keys() {
let vectors: &[(&str, &str, &str)] = &[
("315e59ff51cb9209768cf7da80791ddcaae56ac9775eb25b6dee1234bc5d2268", "c2f9d9948dc8c7c38321e4b85c8558872eafa0641cd269db76848a6073e69133", "3dfef0ce2a4d80a25e7a328accf73448ef67096f65f79588e358d9a0eb9013f1"),
("98a5902fd67518a0c900f0fb62158f278f94a21d6f9d33d30cd3091195500311", "aae65c15f98e5e677b5050de82e3aba47a6fe49b3dab7863cf35d9478ba9f7d1", "9c00b769d5f54d02bf175b7284a1cbd28b6911b06cda6666b2243561ac96bad7"),
("86ae5ac8034eb2542ce23ec2f84375655dab7f836836bbd3c54cefe9fdc9c19f", "59f90272378089d73f1339710c02e2be6db584e9cdbe86eed3578f0c67c23585", "19f934aafd3324e8415299b64df42049afaa051c71c98d0aa10e1081f2e3e2ba"),
// sec1 == pub2 (ECDH with self)
("0000000000000000000000000000000000000000000000000000000000000001", "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", "3b4610cb7189beb9cc29eb3716ecc6102f1247e8f3101a03a1787d8908aeb54e"),
];
for (sec1, pub2, expected) in vectors {
let ck = conversation_key(sec1, pub2).unwrap();
assert_eq!(hex::encode(ck), *expected);
}
}
#[test]
fn nip44_official_message_keys() {
let ck_bytes: [u8; 32] = hex::decode("a1a3d60f3470a8612633924e91febf96dc5366ce130f658b1f0fc652c20b3b54")
.unwrap()
.try_into()
.unwrap();
let vectors: &[(&str, &str, &str, &str)] = &[
("e1e6f880560d6d149ed83dcc7e5861ee62a5ee051f7fde9975fe5d25d2a02d72", "f145f3bed47cb70dbeaac07f3a3fe683e822b3715edb7c4fe310829014ce7d76", "c4ad129bb01180c0933a160c", "027c1db445f05e2eee864a0975b0ddef5b7110583c8c192de3732571ca5838c4"),
("ea6eb84cac23c5c1607c334e8bdf66f7977a7e374052327ec28c6906cbe25967", "ff68db24b34fa62c78ac5ffeeaf19533afaedf651fb6a08384e46787f6ce94be", "50bb859aa2dde938cc49ec7a", "06ff32e1f7b29753a727d7927b25c2dd175aca47751462d37a2039023ec6b5a6"),
];
for (nonce_h, ck_exp, cn_exp, hk_exp) in vectors {
let nonce: [u8; 32] = hex::decode(nonce_h).unwrap().try_into().unwrap();
let (chacha_key, chacha_nonce, hmac_key) = message_keys(&ck_bytes, &nonce);
assert_eq!(hex::encode(chacha_key), *ck_exp);
assert_eq!(hex::encode(chacha_nonce), *cn_exp);
assert_eq!(hex::encode(hmac_key), *hk_exp);
}
}
#[test]
fn nip44_offical_padded_len() {
let vectors: &[(usize, usize)] = &[
(16, 32), (32, 32), (33, 64), (37, 64), (45, 64), (49, 64), (64, 64),
(65, 96), (100, 128), (111, 128), (200, 224), (250, 256), (320, 320),
(383, 384), (384, 384), (400, 448), (500, 512), (512, 512), (515, 640),
(700, 768), (800, 896), (900, 1024), (1020, 1024), (65536, 65536),
];
for (unpadded, padded) in vectors {
assert_eq!(calc_padded_len(*unpadded), *padded, "unpadded {unpadded}");
}
}
#[test]
fn nip44_official_encrypt_vectors() {
// (sec1, sec2, nonce, plaintext, payload) — decrypt with the peer's
// view (sec2, pub(sec1)) so this also proves key symmetry.
let vectors: &[(&str, &str, &str, &str, &str)] = &[
("0000000000000000000000000000000000000000000000000000000000000001",
"0000000000000000000000000000000000000000000000000000000000000002",
"0000000000000000000000000000000000000000000000000000000000000001",
"a",
"AgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABee0G5VSK0/9YypIObAtDKfYEAjD35uVkHyB0F4DwrcNaCXlCWZKaArsGrY6M9wnuTMxWfp1RTN9Xga8no+kF5Vsb"),
("0000000000000000000000000000000000000000000000000000000000000002",
"0000000000000000000000000000000000000000000000000000000000000001",
"f00000000000000000000000000000f00000000000000000000000000000000f",
"🍕🫃",
"AvAAAAAAAAAAAAAAAAAAAPAAAAAAAAAAAAAAAAAAAAAPSKSK6is9ngkX2+cSq85Th16oRTISAOfhStnixqZziKMDvB0QQzgFZdjLTPicCJaV8nDITO+QfaQ61+KbWQIOO2Yj"),
("5c0c523f52a5b6fad39ed2403092df8cebc36318b39383bca6c00808626fab3a",
"4b22aa260e4acb7021e32f38a6cdf4b673c6a277755bfce287e370c924dc936d",
"b635236c42db20f021bb8d1cdff5ca75dd1a0cc72ea742ad750f33010b24f73b",
"表ポあA鷗ŒéB逍Üߪąñ丂㐀𠀀",
"ArY1I2xC2yDwIbuNHN/1ynXdGgzHLqdCrXUPMwELJPc7s7JqlCMJBAIIjfkpHReBPXeoMCyuClwgbT419jUWU1PwaNl4FEQYKCDKVJz+97Mp3K+Q2YGa77B6gpxB/lr1QgoqpDf7wDVrDmOqGoiPjWDqy8KzLueKDcm9BVP8xeTJIxs="),
("eba1687cab6a3101bfc68fd70f214aa4cc059e9ec1b79fdb9ad0a0a4e259829f",
"dff20d262bef9dfd94666548f556393085e6ea421c8af86e9d333fa8747e94b3",
"2180b52ae645fcf9f5080d81b1f0b5d6f2cd77ff3c986882bb549158462f3407",
"( ͡° ͜ʖ ͡°)",
"AiGAtSrmRfz59QgNgbHwtdbyzXf/PJhogrtUkVhGLzQHv4qhKQwnFQ54OjVMgqCea/Vj0YqBSdhqNR777TJ4zIUk7R0fnizp6l1zwgzWv7+ee6u+0/89KIjY5q1wu6inyuiv"),
("d5633530f5bcfebceb5584cfbbf718a30df0751b729dd9a789b9f30c0587d74e",
"b74e6a341fb134127272b795a08b59250e5fa45a82a2eb4095e4ce9ed5f5e214",
"a3e219242d85465e70adcd640b564b3feff57d2ef8745d5e7a0663b2dccceb54",
"🙈 🙉 🙊 0️⃣ 1️⃣ 2️⃣ 3️⃣ 4️⃣ 5️⃣ 6️⃣ 7️⃣ 8️⃣ 9️⃣ 🔟 Powerلُلُصّبُلُلصّبُررً ॣ ॣh ॣ ॣ冗",
"AqPiGSQthUZecK3NZAtWSz/v9X0u+HRdXnoGY7LczOtUf05aMF89q1FLwJvaFJYICZoMYgRJHFLwPiOHce7fuAc40kX0wXJvipyBJ9HzCOj7CgtnC1/cmPCHR3s5AIORmroBWglm1LiFMohv1FSPEbaBD51VXxJa4JyWpYhreSOEjn1wd0lMKC9b+osV2N2tpbs+rbpQem2tRen3sWflmCqjkG5VOVwRErCuXuPb5+hYwd8BoZbfCrsiAVLd7YT44dRtKNBx6rkabWfddKSLtreHLDysOhQUVOp/XkE7OzSkWl6sky0Hva6qJJ/V726hMlomvcLHjE41iKmW2CpcZfOedg=="),
];
for (sec1, sec2, nonce_hex, plaintext, payload) in vectors {
// Encrypt from A to B with the fixed nonce must reproduce the
// official payload byte-for-byte.
let pub1 = pubkey_hex(sec1).unwrap();
let made = {
let ck = conversation_key(sec1, &pubkey_hex(sec2).unwrap()).unwrap();
let nonce: [u8; 32] = hex::decode(nonce_hex).unwrap().try_into().unwrap();
let (chacha_key, chacha_nonce, hmac_key) = message_keys(&ck, &nonce);
let mut padded = pad(plaintext.as_bytes()).unwrap();
ChaCha20::new(&chacha_key.into(), &chacha_nonce.into()).apply_keystream(&mut padded);
let mut mac = <HmacSha256 as Mac>::new_from_slice(&hmac_key).unwrap();
mac.update(&nonce);
mac.update(&padded);
let tag = mac.finalize().into_bytes();
let mut out = vec![NIP44_VERSION];
out.extend_from_slice(&nonce);
out.extend_from_slice(&padded);
out.extend_from_slice(&tag);
BASE64.encode(&out)
};
assert_eq!(&made, payload, "encrypt vector for {plaintext:?}");
// Decrypt from B's view of A (key-role symmetry).
let got = nip44_decrypt(sec2, &pub1, payload).unwrap();
assert_eq!(got, *plaintext);
}
}
#[test]
fn nip44_round_trip_and_failures() {
let sk_a = generate_secret().unwrap();
let sk_b = generate_secret().unwrap();
let pub_b = pubkey_hex(&sk_b).unwrap();
let pub_a = pubkey_hex(&sk_a).unwrap();
let msg = "hello, remote signer";
let payload = nip44_encrypt(&sk_a, &pub_b, msg).unwrap();
assert_eq!(nip44_decrypt(&sk_b, &pub_a, &payload).unwrap(), msg);
// Round-trip long content across the 65536 prefix boundary.
let long = "x".repeat(70_000);
let payload = nip44_encrypt(&sk_a, &pub_b, &long).unwrap();
assert_eq!(nip44_decrypt(&sk_b, &pub_a, &payload).unwrap(), long);
// Wrong peer key must fail the MAC, not return garbage.
let stranger = generate_secret().unwrap();
assert!(nip44_decrypt(&sk_b, &pub_b, &payload).is_err());
let _ = stranger;
// Tampered payload fails.
let payload = nip44_encrypt(&sk_a, &pub_b, msg).unwrap();
let mut tampered = BASE64.decode(&payload).unwrap();
let n = tampered.len();
tampered[n - 1] ^= 0x01;
assert!(nip44_decrypt(&sk_b, &pub_a, &BASE64.encode(&tampered)).is_err());
// Truncated payload fails.
assert!(nip44_decrypt(&sk_b, &pub_a, "AAAA").is_err());
}
// ── BIP-340 official vectors (github.com/bitcoin/bips test vectors) ────
#[test]
fn bip340_reference_sign_vectors() {
// (seckey, pubkey, aux, msg, expected sig) — indices 0/1/2 of the
// official BIP-340 `bip-0340/test-vectors.csv` "should sign" set,
// transcribed from the file itself (x(3G) additionally verified
// by independent scalar-math in the review notes for this commit).
let vectors: &[(&str, &str, &str, &str, &str)] = &[
("0000000000000000000000000000000000000000000000000000000000000003",
"F9308A019258C31049344F85F89D5229B531C845836F99B08601F113BCE036F9",
"0000000000000000000000000000000000000000000000000000000000000000",
"0000000000000000000000000000000000000000000000000000000000000000",
"E907831F80848D1069A5371B402410364BDF1C5F8307B0084C55F1CE2DCA821525F66A4A85EA8B71E482A74F382D2CE5EBEEE8FDB2172F477DF4900D310536C0"),
("B7E151628AED2A6ABF7158809CF4F3C762E7160F38B4DA56A784D9045190CFEF",
"DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659",
"0000000000000000000000000000000000000000000000000000000000000001",
"243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89",
"6896BD60EEAE296DB48A229FF71DFE071BDE413E6D43F917DC8DCF8C78DE33418906D11AC976ABCCB20B091292BFF4EA897EFCB639EA871CFA95F6DE339E4B0A"),
("C90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B14E5C9",
"DD308AFEC5777E13121FA72B9CC1B7CC0139715309B086C960E18FD969774EB8",
"C87AA53824B4D7AE2EB035A2B5BBBCCC080E76CDC6D1692C4B0B62D798E6D906",
"7E2D58D8B3BCDF1ABADEC7829054F90DDA9805AAB56C77333024B9D0A508B75C",
"5831AAEED7B44BB74E5EAB94BA9D4294C49BCF2A60728D8B4C200F50DD313C1BAB745879A5AD954A72C45A91C3A51D3C7ADEA98D82F8481E0E1E03674A6F3FB7"),
];
for (sk_hex, pk_hex, aux_hex, msg_hex, sig_hex) in vectors {
let sk_bytes = hex::decode(sk_hex).unwrap();
let sk = SecretKey::from_slice(&sk_bytes).unwrap();
let kp = Keypair::from_secret_key(&Secp256k1::new(), &sk);
assert_eq!(hex::encode(kp.public_key().x_only_public_key().0.serialize()).to_uppercase(), *pk_hex);
let msg: [u8; 32] = hex::decode(msg_hex).unwrap().try_into().unwrap();
let aux: [u8; 32] = hex::decode(aux_hex).unwrap().try_into().unwrap();
let sig = Secp256k1::new().sign_schnorr_with_aux_rand(
&Message::from_digest(msg),
&kp,
&aux,
);
assert_eq!(hex::encode(sig.serialize()).to_uppercase(), *sig_hex);
}
}
#[test]
fn event_signing_round_trip() {
let sk = generate_secret().unwrap();
let unsigned = r#"{"kind":22242,"content":"{\"challenge\":\"abc123\"}","tags":[["relay","ws://127.0.0.1:7777"]],"created_at":1725100000}"#;
let signed = sign_event(&sk, unsigned).unwrap();
verify_event(&signed).unwrap();
let ev: serde_json::Value = serde_json::from_str(&signed).unwrap();
assert_eq!(ev["kind"], 22242);
assert_eq!(ev["pubkey"], pubkey_hex(&sk).unwrap());
// Tampering with content breaks the id, which breaks verification.
let mut tampered = ev.clone();
tampered["content"] = serde_json::Value::String("nope".into());
assert!(verify_event(&tampered.to_string()).is_err());
}
#[test]
fn connect_uri_parsing() {
let uri = "nostrconnect://83f3b2ae6aa368e8275397b9c26cf550101d63ebaab900d19dd4a4429f5ad8f5?relay=wss%3A%2F%2Frelay1.example.com&perms=nip44_encrypt%2Csign_event%3A22242&name=My+Client&secret=0s8j2djs&relay=ws%3A%2F%2F192.168.1.20%3A7777";
let info = parse_connect_uri(uri).unwrap();
assert_eq!(info.client_pubkey, "83f3b2ae6aa368e8275397b9c26cf550101d63ebaab900d19dd4a4429f5ad8f5");
assert_eq!(
info.relays,
vec!["wss://relay1.example.com", "ws://192.168.1.20:7777"]
);
assert_eq!(info.secret, "0s8j2djs");
assert_eq!(info.perms, vec!["nip44_encrypt", "sign_event:22242"]);
assert_eq!(info.name, "My Client");
// npub client keys and unknown params tolerated — the npub is
// generated through our own encoder so the test carries no
// hand-transcribed bech32 string.
let sk1 = "0000000000000000000000000000000000000000000000000000000000000001";
let npub = npub_from_pubkey(&pubkey_hex(sk1).unwrap()).unwrap();
let pubkey = pubkey_from_any(&npub).unwrap();
let uri = format!("nostrconnect://{npub}?relay=wss://r&secret=s&future=1");
let info = parse_connect_uri(&uri).unwrap();
assert_eq!(info.client_pubkey, pubkey);
assert_eq!(info.relays, vec!["wss://r"]);
assert!(parse_connect_uri("bunker://abc?relay=wss://r&secret=s").is_err());
assert!(parse_connect_uri("nostrconnect://zz?relay=wss://r&secret=s").is_err());
assert!(parse_connect_uri("nostrconnect://83f3b2ae6aa368e8275397b9c26cf550101d63ebaab900d19dd4a4429f5ad8f5?name=x").is_err());
}
#[test]
fn nip04_round_trip_and_cross_check() {
let sk_a = generate_secret().unwrap();
let sk_b = generate_secret().unwrap();
let pub_b = pubkey_hex(&sk_b).unwrap();
let pub_a = pubkey_hex(&sk_a).unwrap();
let payload = nip04_encrypt(&sk_a, &pub_b, "old client hello").unwrap();
assert!(payload.contains("?iv="));
assert_eq!(nip04_decrypt(&sk_b, &pub_a, &payload).unwrap(), "old client hello");
// Wrong key must fail (PKCS#7 padding check) rather than return garbage.
assert!(nip04_decrypt(&sk_a, &pub_a, &payload).is_err());
assert!(nip04_decrypt(&sk_b, &pub_b, &payload).is_err());
assert!(nip04_decrypt(&sk_b, &pub_a, "not-a-payload").is_err());
}
#[test]
fn key_encoding_round_trip() {
let sk = generate_secret().unwrap();
let nsec = nsec_from_secret(&sk).unwrap();
assert!(nsec.starts_with("nsec1"));
assert_eq!(secret_from_nsec(&nsec).unwrap(), sk);
assert_eq!(secret_from_any(&nsec).unwrap(), sk);
assert_eq!(secret_from_any(&sk).unwrap(), sk);
let pk = pubkey_hex(&sk).unwrap();
let npub = npub_from_pubkey(&pk).unwrap();
assert!(npub.starts_with("npub1"));
assert_eq!(pubkey_from_any(&npub).unwrap(), pk);
assert_eq!(pubkey_from_any(&pk).unwrap(), pk);
// The famous even-y lift edge case: pubkey of sk=1 is x(G) (y is odd);
// shared_x with oneself is exactly x(G) — pins the unhashed-x ECDH and
// the even-parity lift in one assertion (x is invariant under y-negation,
// so the lift is safe for NIP-44/NIP-04 keys).
let g_x = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798";
assert_eq!(
pubkey_hex("0000000000000000000000000000000000000000000000000000000000000001").unwrap(),
g_x
);
assert_eq!(
hex::encode(
shared_x("0000000000000000000000000000000000000000000000000000000000000001", g_x).unwrap()
),
g_x
);
assert!(secret_from_nsec("npub1").is_err());
}
/// The mesh ULA is a PURE function of the node's public key:
/// `fd ‖ sha256(x-only pubkey)[0..15]` (fips identity/node_addr.rs →
/// identity/address.rs). That is what makes "address by npub" work —
/// Termux's fipssh helper, and any future DNS-style resolver, just
/// computes what the fips daemon's DNS answers.
#[test]
fn npub_derives_the_same_mesh_ula_as_the_fips_identity() {
for seed in [0x42u8, 0x07, 0x31] {
// 0xff… would exceed the curve order — secret keys must be valid scalars.
let secret = [seed; 32];
let id = fips::Identity::from_secret_bytes(&secret).unwrap();
let npub = id.npub();
let expected = id.address().to_ipv6().to_string();
let pubkey_hex = pubkey_from_any(&npub).unwrap();
let pk = hex::decode(&pubkey_hex).unwrap();
let mut hasher = Sha256::new();
hasher.update(&pk);
let hash = hasher.finalize();
let mut ula = [0u8; 16];
ula[0] = 0xfd;
ula[1..].copy_from_slice(&hash[..15]);
assert_eq!(std::net::Ipv6Addr::from(ula).to_string(), expected, "npub {npub}");
}
}
}
+145
View File
@@ -0,0 +1,145 @@
#!/data/data/com.termux/files/usr/bin/sh
# fipssh — SSH to an Archipelago FIPS mesh node BY NPUB.
#
# The mesh ULA is a pure function of the node's public key (verified against
# the fips crate itself — archy-fips-core's npub_derives_the_same_mesh_ula
# test, and the Android tools commit that shipped this script):
#
# ula = fd || sha256(x-only pubkey)[0..15]
#
# so the npub IS the address: no DNS server, no mesh query, works offline.
# The node's fips daemon answers the same question through its DNS resolver
# (core/archipelago/src/fips/dial.rs) — this is the phone-side equivalent.
#
# Setup (Termux): pkg install python openssh
# Usage:
# fipssh <user>@npub1… [ssh args…] connect
# fipssh npub1… connect as $FIPSSH_USER
# fipssh --resolve npub1… print the ULA and exit
#
# The companion's split tunnel carries the connection (fd00::/8 routes the
# whole device while the mesh is up) — at home on LAN, away via the anchors.
# The node still has to allow port 22 through its fips0 firewall: see
# docs/HANDOFF-2026-08-31-ssh-over-mesh.md (the interim 90-ssh.nft drop-in,
# restricted to your phone's ULA, until the node-side toggle ships).
set -eu
usage() {
sed -n '2,20p' "$0" | sed 's/^# \{0,1\}//'
exit 1
}
RESOLVE_ONLY=0
if [ "${1:-}" = "--resolve" ]; then
RESOLVE_ONLY=1
shift
fi
[ $# -ge 1 ] || usage
TARGET="$1"
shift 2>/dev/null || true
case "$TARGET" in
*npub1*)
case "$TARGET" in
*@npub1*) USER_PART="${TARGET%%@*}"; N_PUB="${TARGET#*@}" ;;
npub1*)
USER_PART="${FIPSSH_USER:-}"
N_PUB="$TARGET"
if [ -z "$USER_PART" ] && [ "$RESOLVE_ONLY" = 0 ]; then
echo "fipssh: no user given (use user@npub… or set FIPSSH_USER)" >&2
exit 1
fi
;;
*) echo "fipssh: expected [user@]npub1…, got '$TARGET'" >&2; exit 1 ;;
esac
;;
*) echo "fipssh: '$TARGET' is not an npub (expected [user@]npub1…)" >&2; exit 1 ;;
esac
command -v python3 >/dev/null 2>&1 || {
echo "fipssh: python3 not found — run: pkg install python" >&2
exit 1
}
ULA=$(python3 - "$N_PUB" <<'PYEOF'
import hashlib, ipaddress, sys
CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"
def bech32_polymod(values):
gen = [0x3B6A57B2, 0x26508E6D, 0x1EA119FA, 0x3D4233DD, 0x2A1462B3]
chk = 1
for value in values:
top = chk >> 25
chk = (chk & 0x1FFFFFF) << 5 ^ value
for i in range(5):
chk ^= gen[i] if ((top >> i) & 1) else 0
return chk
def bech32_hrp_expand(hrp):
return [ord(c) >> 5 for c in hrp] + [0] + [ord(c) & 31 for c in hrp]
def bech32_verify_checksum(hrp, data):
return bech32_polymod(bech32_hrp_expand(hrp) + data) == 1
def bech32_decode(s):
if any(ord(c) < 33 or ord(c) > 126 for c in s):
raise ValueError("bad character")
if s.lower() != s and s.upper() != s:
raise ValueError("mixed case")
s = s.lower()
pos = s.rfind("1")
if pos < 1 or pos + 7 > len(s) or len(s) > 90:
raise ValueError("bad separator")
hrp = s[:pos]
data = [CHARSET.find(c) for c in s[pos + 1:]]
if -1 in data:
raise ValueError("bad data character")
if not bech32_verify_checksum(hrp, data):
raise ValueError("bad checksum — typo in the npub?")
return hrp, data[:-6]
def convertbits(data, frombits, tobits):
acc = 0
bits = 0
ret = bytearray()
maxv = (1 << tobits) - 1
for value in data:
if value < 0 or (value >> frombits):
raise ValueError("bad value")
acc = (acc << frombits) | value
bits += frombits
while bits >= tobits:
bits -= tobits
ret.append((acc >> bits) & maxv)
if bits >= frombits or ((acc << (tobits - bits)) & maxv):
raise ValueError("bad padding")
return bytes(ret)
npub = sys.argv[1]
hrp, data = bech32_decode(npub)
if hrp != "npub":
raise ValueError(f"expected hrp 'npub', got '{hrp}'")
pubkey = convertbits(data, 5, 8)
if len(pubkey) != 32:
raise ValueError(f"npub data must be 32 bytes, got {len(pubkey)}")
# ula = fd || sha256(pubkey)[0..15] — mirrors fips identity/node_addr.rs +
# identity/address.rs (FIPS_ADDRESS_PREFIX = 0xfd).
ula = bytes([0xFD]) + hashlib.sha256(pubkey).digest()[:15]
print(ipaddress.IPv6Address(ula).compressed)
PYEOF
) || exit 1
if [ "$RESOLVE_ONLY" = 1 ]; then
echo "$ULA"
exit 0
fi
exec ssh "${USER_PART}@${ULA}" "$@"
+384
View File
@@ -0,0 +1,384 @@
#!/usr/bin/env python3
"""
NIP-46 test client for the Archipelago companion's Remote Signer (#139).
Plays the role the node's login flow will play (rust-nostr nostr-connect
client): generates a nostrconnect:// pairing QR, connects to a relay, waits
for the phone's bunker `connect` (secret echo), acks it, then exercises
get_public_key + sign_event and VERIFIES the returned schnorr signature with
independent pure-Python BIP-340 code (no shared code with the phone's Rust).
Run it on your computer next to the phone:
python3 -m venv /tmp/nip46env
/tmp/nip46env/bin/pip install websockets qrcode
/tmp/nip46env/bin/python Android/tools/nip46-test-client.py [--relay wss://relay.damus.io]
…then on the phone: hub menu (three-finger hold) → Remote Signer →
Generate key (once) → Scan pairing QR → point at the terminal QR → Approve.
Pure Python (no deps for the crypto; websockets + qrcode for transport/QR).
"""
import argparse
import asyncio
import base64
import hashlib
import hmac
import json
import os
import secrets
import struct
import sys
import time
import urllib.parse
import websockets # pip install websockets
# ── secp256k1 / BIP-340 (independent of the phone's Rust code) ──────────────
P = 2**256 - 2**32 - 977
N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798
GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8
G = (GX, GY)
def _add(pt1, pt2):
if pt1 is None:
return pt2
if pt2 is None:
return pt1
x1, y1 = pt1
x2, y2 = pt2
if x1 == x2 and (y1 + y2) % P == 0:
return None
if pt1 == pt2:
lam = (3 * x1 * x1) * pow(2 * y1, -1, P) % P
else:
lam = (y2 - y1) * pow(x2 - x1, -1, P) % P
x3 = (lam * lam - x1 - x2) % P
return (x3, (lam * (x1 - x3) - y1) % P)
def _mul(k, pt):
r = None
while k:
if k & 1:
r = _add(r, pt)
pt = _add(pt, pt)
k >>= 1
return r
def lift_x(x):
if x >= P:
return None
y_sq = (pow(x, 3, P) + 7) % P
y = pow(y_sq, (P + 1) // 4, P)
if y * y % P != y_sq:
return None
return (x, y if y % 2 == 0 else P - y)
def tagged(tag: bytes, data: bytes) -> bytes:
"""BIP-340 tagged hash: sha256(hash(tag) || hash(tag) || data)."""
th = hashlib.sha256(tag).digest()
return hashlib.sha256(th + th + data).digest()
def bip340_sign(msg: bytes, seckey: int, aux: bytes) -> bytes:
d = seckey if seckey <= N - 1 else seckey - N
pub = _mul(d, G)
if pub[1] % 2 != 0:
d = N - d
t = bytes(a ^ b for a, b in zip(d.to_bytes(32, "big"), tagged(b"BIP0340/aux", aux)))
rand = tagged(b"BIP0340/nonce", t + pub[0].to_bytes(32, "big") + msg)
k = int.from_bytes(rand, "big") % N
assert k > 0
R = _mul(k, G)
if R[1] % 2 != 0:
k = N - k
e = int.from_bytes(tagged(b"BIP0340/challenge", R[0].to_bytes(32, "big") + pub[0].to_bytes(32, "big") + msg), "big") % N
return R[0].to_bytes(32, "big") + ((k + e * d) % N).to_bytes(32, "big")
def bip340_verify(msg: bytes, pubkey_x: bytes, sig: bytes) -> bool:
"""Check s·G − e·P == R with even-y R and x(R) == r (BIP-340)."""
if len(sig) != 64 or len(pubkey_x) != 32:
return False
pub = lift_x(int.from_bytes(pubkey_x, "big"))
if pub is None:
return False
r = int.from_bytes(sig[:32], "big")
s = int.from_bytes(sig[32:], "big")
if r >= P or s >= N:
return False
e = int.from_bytes(tagged(b"BIP0340/challenge", sig[:32] + pubkey_x + msg), "big") % N
sg = _mul(s, G)
ep = _mul(e, pub)
neg_ep = (ep[0], (P - ep[1]) % P)
rp = _add(sg, neg_ep)
return rp is not None and rp[0] == r and rp[1] % 2 == 0
def ecdh_x(secret_hex: str, peer_x_hex: str) -> bytes:
"""Raw ECDH x-coordinate against an x-only peer key (even-y lift)."""
peer = lift_x(int(peer_x_hex, 16))
assert peer is not None, "peer pubkey not on curve"
pt = _mul(int(secret_hex, 16) % N, peer)
return pt[0].to_bytes(32, "big")
# ── NIP-44 v2 (pure python, spec-literal) ────────────────────────────────────
def hkdf_extract(salt: bytes, ikm: bytes) -> bytes:
return hmac.new(salt, ikm, hashlib.sha256).digest()
def hkdf_expand(prk: bytes, info: bytes, length: int) -> bytes:
t = b""
out = b""
i = 1
while len(out) < length:
t = hmac.new(prk, t + info + bytes([i]), hashlib.sha256).digest()
out += t
i += 1
return out[:length]
def _rotl(x: int, n: int) -> int:
return ((x << n) | (x >> (32 - n))) & 0xFFFFFFFF
def _qr(s, a, b, c, d):
s[a] = (s[a] + s[b]) & 0xFFFFFFFF; s[d] ^= s[a]; s[d] = _rotl(s[d], 16)
s[c] = (s[c] + s[d]) & 0xFFFFFFFF; s[b] ^= s[c]; s[b] = _rotl(s[b], 12)
s[a] = (s[a] + s[b]) & 0xFFFFFFFF; s[d] ^= s[a]; s[d] = _rotl(s[d], 8)
s[c] = (s[c] + s[d]) & 0xFFFFFFFF; s[b] ^= s[c]; s[b] = _rotl(s[b], 7)
def chacha20_block(key: bytes, counter: int, nonce: bytes) -> bytes:
consts = [0x61707865, 0x3320646E, 0x79622D32, 0x6B206574]
state = consts + list(struct.unpack("<8I", key)) + [counter] + list(struct.unpack("<3I", nonce))
working = list(state)
for _ in range(10):
_qr(working, 0, 4, 8, 12); _qr(working, 1, 5, 9, 13)
_qr(working, 2, 6, 10, 14); _qr(working, 3, 7, 11, 15)
_qr(working, 0, 5, 10, 15); _qr(working, 1, 6, 11, 12)
_qr(working, 2, 7, 8, 13); _qr(working, 3, 4, 9, 14)
return struct.pack("<16I", *[(x + y) & 0xFFFFFFFF for x, y in zip(working, state)])
def chacha20(key: bytes, nonce: bytes, data: bytes) -> bytes:
counter = 0 # NIP-44: "ChaCha20 (RFC 8439) with starting counter set to 0"
out = bytearray()
for i in range(0, len(data), 64):
ks = chacha20_block(key, counter, nonce)
chunk = data[i:i + 64]
out += bytes(a ^ b for a, b in zip(chunk, ks))
counter += 1
return bytes(out)
def calc_padded_len(n: int) -> int:
if n <= 32:
return 32
power = 1 << ((n - 1).bit_length())
chunk = 32 if power <= 256 else power // 8
return chunk * ((n - 1) // chunk + 1)
def nip44_encrypt(secret_hex: str, peer_hex: str, plaintext: str) -> str:
ck = hkdf_extract(b"nip44-v2", ecdh_x(secret_hex, peer_hex))
nonce = secrets.token_bytes(32)
okm = hkdf_expand(ck, nonce, 76)
key, iv, mac_key = okm[:32], okm[32:44], okm[44:76]
pt = plaintext.encode()
padded = (len(pt).to_bytes(2, "big") if len(pt) < 65536 else b"\x00\x00" + len(pt).to_bytes(4, "big")) + pt
padded += b"\x00" * (calc_padded_len(len(pt)) - len(pt))
ct = chacha20(key, iv, padded)
mac = hmac.new(mac_key, nonce + ct, hashlib.sha256).digest()
return base64.b64encode(bytes([2]) + nonce + ct + mac).decode()
def nip44_decrypt(secret_hex: str, peer_hex: str, payload: str) -> str:
data = base64.b64decode(payload)
assert data[0] == 2, "only NIP-44 v2 supported"
nonce, ct, mac = data[1:33], data[33:-32], data[-32:]
ck = hkdf_extract(b"nip44-v2", ecdh_x(secret_hex, peer_hex))
okm = hkdf_expand(ck, nonce, 76)
key, iv, mac_key = okm[:32], okm[32:44], okm[44:76]
assert hmac.compare_digest(hmac.new(mac_key, nonce + ct, hashlib.sha256).digest(), mac), "bad MAC"
padded = chacha20(key, iv, ct)
ln = int.from_bytes(padded[:2], "big")
body = padded[2:2 + ln] if ln else padded[6:6 + int.from_bytes(padded[2:6], "big")]
return body.decode()
# ── nostr events ─────────────────────────────────────────────────────────────
def event_id(pubkey_hex: str, created_at: int, kind: int, tags, content: str) -> str:
serialized = json.dumps([0, pubkey_hex, created_at, kind, tags, content], separators=(",", ":"))
return hashlib.sha256(serialized.encode()).hexdigest()
def sign_event(secret_hex: str, event: dict) -> dict:
eid = event_id(event["pubkey"], event["created_at"], event["kind"], event["tags"], event["content"])
ev = dict(event)
ev["id"] = eid
ev["sig"] = bip340_sign(bytes.fromhex(eid), int(secret_hex, 16), os.urandom(32)).hex()
return ev
# ── the client session ────────────────────────────────────────────────────────
def compact(d) -> str:
return json.dumps(d, separators=(",", ":"))
async def run(relay: str):
client_secret = os.urandom(32).hex()
client_secret_int = int(client_secret, 16) % N
client_pub_hex = _mul(client_secret_int, G)[0].to_bytes(32, "big").hex()
pair_secret = secrets.token_hex(16)
nonce = secrets.token_hex(8)
uri = (
f"nostrconnect://{client_pub_hex}"
f"?relay={urllib.parse.quote(relay, safe='')}"
f"&secret={pair_secret}"
f"&name=Archipelago+Test+Client"
)
print(f"· client key : {client_pub_hex}")
print(f"· relay : {relay}")
print()
print("Scan this QR with: Companion → hub (3-finger) → Remote Signer → Scan pairing QR")
print()
try:
import qrcode
qr = qrcode.QRCode(border=1)
qr.add_data(uri)
qr.make(fit=True)
qr.print_ascii(invert=True)
except ImportError:
print(uri)
print()
print("Waiting for the phone to pair (connect, ack, get_public_key, sign_event)…")
async with websockets.connect(relay, max_size=2**22) as ws:
await ws.send(compact(["REQ", "test", {"kinds": [24133], "#p": [client_pub_hex], "since": int(time.time()) - 60}]))
signer_pub = None
acked = False
requests = []
def send_frame(content: dict):
assert signer_pub is not None
ev = {
"pubkey": client_pub_hex,
"created_at": int(time.time()),
"kind": 24133,
"tags": [["p", signer_pub]],
"content": nip44_encrypt(client_secret, signer_pub, compact(content)),
}
return asyncio.ensure_future(ws.send(compact(["EVENT", sign_event(client_secret, ev)])))
async def request(method, params, rid):
send_frame({"id": rid, "method": method, "params": params})
timeout = time.time() + 120
got_pubkey = None
signed_event = None
while time.time() < timeout:
try:
raw = await asyncio.wait_for(ws.recv(), timeout=timeout - time.time())
except (asyncio.TimeoutError, TimeoutError):
break
arr = json.loads(raw)
if not isinstance(arr, list) or len(arr) < 3 or arr[0] != "EVENT":
continue
ev = arr[2]
if ev.get("kind") != 24133 or ev.get("pubkey") == client_pub_hex:
continue
author = ev["pubkey"]
try:
msg = json.loads(nip44_decrypt(client_secret, author, ev["content"]))
except Exception:
continue
if "method" in msg and msg["method"] == "connect":
params = msg.get("params", [])
if params and params[0] == author and (len(params) < 2 or params[1] == pair_secret):
signer_pub = author
print(f"✓ phone paired — signer pubkey {author[:16]}…")
send_frame({"id": msg["id"], "result": "ack"})
acked = True
await asyncio.sleep(0.5)
await request("get_public_key", [], nonce + "-gpk")
else:
print("✗ phone sent connect but the secret didn't match")
return 1
continue
if "result" in msg or "error" in msg:
rid = msg.get("id", "")
if "error" in msg:
print(f"✗ error for {rid}: {msg['error']}")
if rid.endswith("-sign"):
return 1
continue
result = msg.get("result", "")
if rid.endswith("-gpk"):
got_pubkey = result
print(f"✓ get_public_key → {result}")
await request(
"sign_event",
[compact({
"kind": 1,
"content": "Hello from the Archipelago NIP-46 test client — approved by hand.",
"tags": [],
"created_at": int(time.time()),
})],
nonce + "-sign",
)
elif rid.endswith("-sign"):
signed_event = json.loads(result)
print(f"✓ sign_event → signed event {signed_event.get('id', '')[:16]}…")
break
if not acked:
print("✗ the phone never connected (2-minute timeout)")
return 1
if got_pubkey is None or got_pubkey != signer_pub:
print("✗ get_public_key missing or mismatched")
return 1
if signed_event is None:
return 1
ev = signed_event
expected_id = event_id(ev["pubkey"], ev["created_at"], ev["kind"], ev["tags"], ev["content"])
ok_id = expected_id == ev["id"]
ok_sig = bip340_verify(bytes.fromhex(expected_id), bytes.fromhex(ev["pubkey"]), bytes.fromhex(ev["sig"]))
print(f"· event id correct : {ok_id}")
print(f"· schnorr signature: {'VERIFIED ✓' if ok_sig else 'INVALID ✗'}")
if ok_id and ok_sig:
print()
print("END-TO-END PASS — the companion signed as the identity the phone holds,")
print("and the signature verifies under an independent BIP-340 implementation.")
return 0
return 1
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--relay", default="wss://relay.damus.io", help="any nostr relay both devices can reach")
args = ap.parse_args()
sys.exit(asyncio.run(run(args.relay)))
if __name__ == "__main__":
main()
+56
View File
@@ -1,5 +1,61 @@
# Changelog
## v1.8.10-alpha (2026-09-02)
- **Lightning sends work again — v1.8.9's payment switch lost the fee budget.** Moving payments to LND 0.21's supported route (Router.SendPaymentV2) shipped without a fee limit, and the v2 API treats an absent limit as **zero allowed fees**: every real route carries a routing fee, so the pathfinder rejected them all and the wallet answered "No route to the recipient" on every send — all day, on healthy channels with plenty of liquidity. The router debug log made it unambiguous (`fee_limit=0 mSAT` on every failing wallet payment; the same payment succeeded by hand the moment a fee limit was set). Payments now carry lncli's default budget (the payment amount), the wallet's amount handling for zero-value invoices is preserved, and a unit test pins the limit can never be zero again.
- **A channel that drops its peer link now heals itself — on every node.** Restarting LND (an app update, a reboot, container churn) can leave a channel's peer connection down for hours while both endpoints keep the channel flagged disabled in the routing graph: the node looks perfectly healthy, the wallet shows balance, and every payment in either direction fails "no route to the recipient". Observed live: a node's only channel sat unroutable for ~17 hours after the LND 0.21.2 update, with no sign of it in any dashboard. The daemon now watches the channel graph as desired state — every open channel should have a live peer — and reconnects any that don't, using the peer's advertised addresses. Nodes without LND are untouched; an unreachable peer is retried gently, not hammered.
- **The Lightning wallet states the node's real funding state instead of "you have no channel."** Trying to send while a freshly opened channel was still waiting for on-chain confirmations — or when all its balance sits on the far side — raised a modal that claimed the node had NO channel at all (the outbound sum is legitimately zero in both states), pointed the user at opening a second channel, and — for payment routing failures — even showed the *receiving* copy. The funding gate now reads the channel list it already fetched: a confirming channel gets "it unlocks automatically once confirmed, nothing is needed from you", a far-side balance gets "you can receive, but there's nothing to send right now", a routing/liquidity payment failure says so instead of claiming channel problems, and only a genuinely channel-less node keeps the open-one guidance.
## v1.8.9-alpha (2026-09-01)
- **Lightning sends work again after the LND 0.21.2 update.** LND 0.21 removed the old synchronous payment route the node's backend paid through (`/v1/channels/transactions`) — every Lightning send answered the literal "Not Found" and the wallet showed "Payment failed: Not Found". The backend now pays through the supported Router.SendPaymentV2 route, keeps the same settle-then-report behaviour (a slow multi-hop payment is still tracked to completion, never falsely declared failed), and translates LND's failure reasons into plain advice. A new gate test speaks the payment route directly against the running LND, so an image/backend skew like this can never ship silently again.
- **The node no longer pins HSTS — HTTP access is a supported mode, and it stays working.** The HTTPS listener used to send `Strict-Transport-Security: max-age=31536000; includeSubDomains`; browsers that visited HTTPS once cached that and then silently upgraded the still-open HTTP dashboard's calls to HTTPS, which is a scheme change — cross-origin — so every request died as "CORS blocked / Failed to fetch" while the node was perfectly healthy. The HTTPS listener now actively clears the cached policy (`max-age=0`) and port 80 sends no HSTS at all, which is deliberate: the node's certificate is optional and self-signed, and devices that haven't installed the CA must keep plain-HTTP access (that's what Settings → Node certificate is for). If your browser already cached the old policy, visiting the dashboard over HTTPS once after this update clears it; a gate test now refuses any config that reintroduces the pin.
- **App frames open over HTTPS again — including the ones that "did not connect."** The launcher asked the signed catalog for each app's port policy under the name you click ("Mempool Web", "Bitcoin Knots"), but the catalog declares those ports under the manifest that owns them (the Mempool web container, Bitcoin UI). The lookup missed, the launcher handed the iframe an `http://` address, and the browser blocked it as mixed content — the app tile went blank or spun forever. Port resolution now follows launch aliases (mempool-web, bitcoin-knots/bitcoin-core, lnd, electrs and friends), falls back to a port-wide catalog scan when the id is unknown, and the catalog is warmed as soon as the dashboard loads rather than only in the App Store, so the very first app you open already knows which ports serve TLS.
- **Signing in to IndeeHub with Nostr works over HTTPS.** The NIP-07 bridge compared the app frame's origin for exact equality with the recorded `http://` app URL — a frame the browser upgraded to HTTPS (or any scheme change) was silently ignored, and replies addressed to the stale origin were refused outright, so Nostr sign-in quietly did nothing. The bridge now matches host and port (scheme intentionally ignored) and always replies to the frame's real origin.
- **Nginx Proxy Manager starts again.** Converting it to a platform manifest dropped two things its image needs: the `/etc/letsencrypt` mount its boot script hard-requires, and the `NET_BIND_SERVICE` capability its internal nginx needs to bind ports 80/443/81 under the orchestrator's `--cap-drop=ALL`. The result was an endless start/die loop (a node watched it restart 3,176 times). Both are declared in its manifest now, its certs live on unchanged under the same persistent app directory, and the signed catalog carries the fix so installed nodes heal on the next update.
- **Portainer's first-run token is in the app page, not buried in "server logs."** New Portainer versions mint a one-time setup token on a fresh install and print it only to the container logs — on an appliance that meant telling the user to go read a server log to get into their own app. The token now appears in the same launch interstitial as app login credentials (with a copy button), only while first-run setup is actually pending; once the admin account exists the card disappears on its own.
- **The Lightning wallet states the node's real funding state instead of "you have no channel."** Trying to send while a freshly opened channel was still waiting for on-chain confirmations — or when all its balance sits on the far side — raised a modal that claimed the node had no channel at all (the outbound sum is legitimately zero in both states). The funding gate now reads the channel list it already fetched: a confirming channel gets "it unlocks automatically once confirmed, nothing is needed from you", a far-side balance gets "you can receive, but there's nothing to send right now", a routing/liquidity payment failure says so instead of pointing at channel setup, and only a genuinely channel-less node is sent to open one.
## v1.8.8-alpha (2026-09-01)
- **SSH over the mesh is now a first-class setting.** Settings gains an "SSH over mesh" card: off by default, and when you allow it the node's mesh firewall opens port 22 — either to every mesh peer (behind an explicit "I understand" confirmation, because that's a real exposure) or only to the mesh addresses you list. The rule is owned by the node (the `90-ssh.nft` drop-in), so it survives upgrades and daemon reinstalls, and the card tells you up front whether sshd is running, whether it listens on IPv6 (the mesh is IPv6-only — this is what a broken attempt looks like before it happens), and whether password login is on (keys-only is the recommended pairing). From Termux on your phone, `fipssh <user>@<node-npub>` connects once the toggle is on — the npub is the durable address, and the command is shown with a copy button on the card.
- **The App Store now lists apps — not parts of apps.** The signed catalog carries every manifest because the node's update layer needs their pins, and the store briefly listed them all: Mempool API, LND UI, Bitcoin UI, the Pine voice engines, the IndeeHub and Immich backends, the mesh router and friends. Components are hidden from the store listing (they still appear where they belong — the Services tab of My Apps, once installed), and four entries that never earned a tile are gone outright: MorphOS server (old), the Web5 DID wallet, Lightning Stack (an untracked upstream bundle — LND covers the need), and CryptPad (never tested).
- **App icons now persist everywhere, in the proper container style.** Two fixes: installed apps render the icon from their own manifest — Cuprate no longer falls back to the generic A-mark on its Services tile — and the store grids (the Discover page) apply the same icon container treatment (backdrop, border, shadow) as My Apps, the detail pages, and Home. Manifest-declared UI apps also classify correctly again: Alby Hub installs into My Apps with a working tile, not into Services, because a probe miss no longer buries an app the manifest itself says has a frontend.
- **Installing from the store keeps you on the store page.** The install progress lives on the tile itself and the app appears in My Apps when it lands — no more being yanked to My Apps mid-browse.
## v1.8.7-alpha (2026-08-31)
- **What's New really does stop at v1.8.0 now.** The first correction removed old generated release blocks but missed six much older hand-written v1.2 sections at the bottom of the modal. Those sections are gone, and the release check now recognizes and rejects that legacy format too, so the history floor cannot falsely pass again.
- **The installer carries the same corrected release and Companion 0.5.28.** Its artifact gate now checks the companion APK version and the v1.8.0 What's New floor inside the finished ISO, so a stale frontend or phone app cannot be published under the current release label.
- **Crash dumps work on fresh installs as well as upgraded nodes.** The installer gate checks every kdump package inside the finished ISO, and `makedumpfile` is installed explicitly rather than accidentally relying on a recommended dependency that the minimal image deliberately omits.
- **Apps open over HTTPS when your node does.** Connect to your node over HTTPS and the apps you open — Vaultwarden in its own tab, BTCPay, Grafana, and the rest, on a remote browser or in the phone's in-app browser — now open on the same secure connection instead of silently dropping to plain HTTP. The node's app gate already served TLS on every app port; the dashboard was handing out `http://` addresses regardless of how you reached it. Ports the gate does not front (plain-HTTP publishes, and the API ports like Cuprate's RPC) deliberately stay on `http` — `https` there would simply fail to connect. Plain-HTTP access (the kiosk, LAN browsing) is unchanged.
- **Every app in the store is now a first-class platform app.** The last stragglers — Nginx Proxy Manager, Tailscale, Ollama, CryptPad, and AdGuard Home — now carry full manifests: the node's app gate fronts their web ports (TLS on the same port, the node login where appropriate, embedding fixes, Tor), installs go through the orchestrator like every other app, and their pins live in the signed catalog. Ollama stays loopback-only — it is the assistant's local model backend, not a web app. The four apps retired earlier (FIPS, Nostr VPN, Routstr, Penpot) are finally dropped from the catalog, and Cuprate's manifest — which carried a duplicated metadata block that strict parsers reject — is fixed.
- **Newly signed apps appear in the App Store immediately.** The App Store now serves the release-signed catalog the node has already fetched and verified — so publishing a signed app (like Cuprate) makes it appear for every updated node without waiting for a dashboard release. The unsigned community catalog remains only as a fallback for nodes that can't reach the registry. The same signed catalog now also decides which ports serve TLS, so nothing is upgraded to `https` that can't answer it.
## v1.8.6-alpha (2026-08-31)
- **Companion 0.5.28 is included in the node download this time, with the work that missed v1.8.5.** The companion hub can back up and restore its node list, act as a NIP-46 remote signer, and shows each paired node's FIPS mesh address with tap-to-copy. For Termux users, the included `fipssh` helper turns a durable node npub into its mesh address, so `fipssh user@npub1…` can reach SSH once that node has explicitly allowed port 22. The node-side “SSH over mesh” firewall toggle is not claimed here—it still needs implementation and remains off by default.
- **What's New now starts cleanly at v1.8.0 and is guaranteed to be newest-first.** Older alpha history no longer overwhelms the useful recent changes, the three stray v1.7 entries that appeared above current releases are gone, and the release check now fails if either the ordering or the v1.8.0 history floor drifts again.
- **A release can no longer advertise itself before its files exist.** New releases are prepared behind a pending manifest; the publisher uploads the backend and frontend, downloads both back and verifies their size and hash, and only then promotes the signed manifest to the path nodes read. The manifest generator also includes every curated What's New item instead of silently stopping after the first ten physical changelog lines.
## v1.8.5-alpha (2026-08-30)
- **Cuprate — an independent Monero node — is now an app.** Monero consensus validated by a second, unrelated codebase (Rust), the same layer of security-in-depth Bitcoin gets from Knots. Review caught two problems before anything shipped: the unrestricted RPC that can move funds stayed bound to the container's loopback (never published to the node, let alone the LAN — anything on the node could previously have reached it), and its restricted RPC moved off port 18089 to avoid colliding with Penpot. Honest caveat: upstream has cut no stable release yet, so the pin tracks an exact preview build (0.1.0-preview-18-g618ff14) and moves to their first tagged release when there is one.
Submodule aiui/.claude/worktrees/agitated-hofstadter deleted from 10e12a329f
Submodule aiui/.claude/worktrees/funny-hofstadter deleted from 1c5185a15c
Submodule aiui/.claude/worktrees/happy-colden deleted from 666e1232f4
Submodule aiui/.claude/worktrees/hardcore-beaver deleted from a817fa199f
Submodule aiui/.claude/worktrees/heuristic-raman deleted from e8e002debc
Submodule aiui/.claude/worktrees/priceless-colden deleted from aaaef7d710
+409 -373
View File
@@ -11,16 +11,47 @@
},
"apps": [
{
"id": "bitcoin-knots",
"title": "Bitcoin Knots",
"version": "28.1.0",
"description": "Full Bitcoin Knots node with dynamic prune/full-mode startup based on host disk.",
"icon": "/assets/img/app-icons/bitcoin-knots.webp",
"author": "Bitcoin Knots",
"id": "adguardhome",
"title": "AdGuard Home",
"version": "v0.107.79",
"description": "Network-wide ad and tracker blocking: a DNS server that filters every device on your LAN, with a web console for rules and client management.",
"icon": "",
"author": "AdGuard",
"category": "networking",
"tier": "optional",
"dockerImage": "source.archipelago-foundation.org/lfg2025/adguardhome:v0.107.79",
"repoUrl": "https://github.com/AdguardTeam/AdGuardHome"
},
{
"id": "alby-hub",
"title": "Alby Hub",
"version": "1.23.0",
"description": "Self-custodial Lightning wallet hub. Runs its own Lightning node on your Archipelago and connects your apps to it over Nostr Wallet Connect — one hub, every app pays through it.",
"icon": "/assets/img/app-icons/alby-hub.svg",
"author": "Alby",
"category": "money",
"tier": "core",
"dockerImage": "source.archipelago-foundation.org/lfg2025/bitcoin-knots:29.3.knots20260210",
"repoUrl": "https://github.com/bitcoinknots/bitcoin"
"tier": "optional",
"dockerImage": "source.archipelago-foundation.org/lfg2025/alby-hub:v1.24.0",
"repoUrl": "https://github.com/getAlby/hub"
},
{
"id": "barkd",
"title": "Ark Wallet",
"version": "0.3.0",
"description": "Ark protocol wallet daemon (barkd). Lets the node hold self-custodial off-chain bitcoin via an Ark server; the wallet talks to it over a local REST API. Signet by default while Ark matures.",
"icon": "/assets/img/app-icons/bark.png",
"author": "Second",
"category": "money",
"dockerImage": "source.archipelago-foundation.org/lfg2025/barkd:0.3.0",
"repoUrl": "https://gitlab.com/ark-bitcoin/bark",
"containerConfig": {
"ports": [
"3535:3535"
],
"volumes": [
"/var/lib/archipelago/barkd:/data"
]
}
},
{
"id": "bitcoin-core",
@@ -35,76 +66,16 @@
"repoUrl": "https://github.com/bitcoin/bitcoin"
},
{
"id": "lnd",
"title": "LND",
"version": "0.18.4",
"description": "Lightning Network implementation by Lightning Labs. Enables instant, low-cost Bitcoin payments.",
"icon": "/assets/img/app-icons/lnd.png",
"author": "Lightning Labs",
"id": "bitcoin-knots",
"title": "Bitcoin Knots",
"version": "28.1.0",
"description": "Full Bitcoin Knots node with dynamic prune/full-mode startup based on host disk.",
"icon": "/assets/img/app-icons/bitcoin-knots.webp",
"author": "Bitcoin Knots",
"category": "money",
"tier": "core",
"dockerImage": "source.archipelago-foundation.org/lfg2025/lnd:v0.18.4-beta",
"repoUrl": "https://github.com/lightningnetwork/lnd",
"requires": [
"bitcoin-knots"
]
},
{
"id": "btcpay-server",
"title": "BTCPay Server",
"version": "2.4.3",
"description": "Self-hosted Bitcoin payment processor. Accept Bitcoin payments without intermediaries.",
"icon": "/assets/img/app-icons/btcpay-server.png",
"author": "BTCPay Server Foundation",
"category": "commerce",
"tier": "core",
"dockerImage": "docker.io/btcpayserver/btcpayserver:2.4.3",
"repoUrl": "https://github.com/btcpayserver/btcpayserver",
"requires": [
"bitcoin-knots"
]
},
{
"id": "mempool",
"title": "Mempool Explorer",
"version": "3.0.0",
"description": "Bitcoin mempool and blockchain explorer. Real-time transaction and block visualization.",
"icon": "/assets/img/app-icons/mempool.webp",
"author": "Mempool",
"category": "money",
"tier": "core",
"dockerImage": "source.archipelago-foundation.org/lfg2025/mempool-frontend:v3.3.1",
"repoUrl": "https://github.com/mempool/mempool",
"requires": [
"bitcoin-knots",
"electrumx"
]
},
{
"id": "electrumx",
"title": "ElectrumX",
"version": "1.18.0",
"description": "Electrum server indexing Bitcoin chain data for lightweight wallet queries.",
"icon": "/assets/img/app-icons/electrumx.png",
"author": "Luke Childs",
"category": "money",
"tier": "core",
"dockerImage": "source.archipelago-foundation.org/lfg2025/electrumx:v1.18.0",
"repoUrl": "https://github.com/spesmilo/electrumx",
"requires": [
"bitcoin-knots"
]
},
{
"id": "indeedhub",
"title": "IndeeHub",
"version": "1.0.0",
"description": "Bitcoin documentary streaming platform featuring God Bless Bitcoin and other educational content about Bitcoin, sovereignty, and decentralized technology. Sign in with your Nostr identity.",
"icon": "/assets/img/app-icons/indeedhub.png",
"author": "IndeeHub",
"category": "community",
"dockerImage": "source.archipelago-foundation.org/lfg2025/indeedhub:1.0.0",
"repoUrl": "https://github.com/indeedhub/indeedhub"
"dockerImage": "source.archipelago-foundation.org/lfg2025/bitcoin-knots:29.3.knots20260210",
"repoUrl": "https://github.com/bitcoinknots/bitcoin"
},
{
"id": "botfights",
@@ -132,127 +103,46 @@
}
},
{
"id": "gitea",
"title": "Gitea",
"version": "1.23",
"description": "Self-hosted Git service with built-in container registry, CI/CD, and package hosting.",
"icon": "/assets/img/app-icons/gitea.svg",
"author": "Gitea",
"category": "development",
"dockerImage": "docker.io/gitea/gitea:1.23",
"repoUrl": "https://gitea.com",
"containerConfig": {
"ports": [
"3001:3000",
"2222:22"
],
"volumes": [
"/var/lib/archipelago/gitea/data:/data",
"/var/lib/archipelago/gitea/config:/etc/gitea"
],
"env": [
"GITEA__database__DB_TYPE=sqlite3",
"GITEA__server__SSH_PORT=2222",
"GITEA__server__SSH_LISTEN_PORT=22",
"GITEA__server__LFS_START_SERVER=true",
"GITEA__packages__ENABLED=true",
"GITEA__repository__ENABLE_PUSH_CREATE_USER=true",
"GITEA__repository__ENABLE_PUSH_CREATE_ORG=true",
"GITEA__security__X_FRAME_OPTIONS="
]
},
"tier": "optional"
},
{
"id": "filebrowser",
"title": "File Browser",
"version": "2.27.0",
"description": "Baseline Archipelago file manager service.",
"icon": "/assets/img/app-icons/file-browser.webp",
"author": "File Browser",
"category": "data",
"id": "btcpay-server",
"title": "BTCPay Server",
"version": "2.4.3",
"description": "Self-hosted Bitcoin payment processor. Accept Bitcoin payments without intermediaries.",
"icon": "/assets/img/app-icons/btcpay-server.png",
"author": "BTCPay Server Foundation",
"category": "commerce",
"tier": "core",
"dockerImage": "source.archipelago-foundation.org/lfg2025/filebrowser:v2.27.0",
"repoUrl": "https://github.com/filebrowser/filebrowser",
"containerConfig": {
"ports": [
"8083:80"
],
"volumes": [
"/var/lib/archipelago/filebrowser:/srv",
"/var/lib/archipelago/filebrowser-data:/data"
],
"args": [
"--database=/data/database.db",
"--root=/srv",
"--address=0.0.0.0",
"--port=80"
]
}
"dockerImage": "docker.io/btcpayserver/btcpayserver:2.4.3",
"repoUrl": "https://github.com/btcpayserver/btcpayserver",
"requires": [
"bitcoin-knots"
]
},
{
"id": "nostr-rs-relay",
"title": "Nostr Relay (Rust)",
"version": "0.10.0",
"description": "High-performance Nostr relay written in Rust. Host your own decentralized social media relay and earn networking profits.",
"icon": "/assets/img/app-icons/nostrudel.svg",
"author": "Nostr RS Relay",
"category": "community",
"tier": "recommended",
"dockerImage": "scsibug/nostr-rs-relay:0.10.0",
"repoUrl": "https://github.com/scsibug/nostr-rs-relay",
"containerConfig": {
"ports": [
"8081:8080"
],
"volumes": [
"/var/lib/archipelago/nostr-relay:/usr/src/app/db"
],
"env": [
"RELAY_NAME=Archipelago Nostr Relay",
"RELAY_DESCRIPTION=Self-hosted Nostr relay on Archipelago"
]
}
"id": "cuprate",
"title": "Cuprate",
"version": "0.1.0-preview",
"description": "Alternative Monero node implementation in Rust. Independently validates Monero consensus rules, providing a layer of security and redundancy for the network.",
"icon": "/assets/img/app-icons/cuprate.svg",
"author": "Cuprate contributors",
"category": "money",
"tier": "optional",
"dockerImage": "source.archipelago-foundation.org/lfg2025/cuprate:0.1.0-preview-18-g618ff14",
"repoUrl": "https://github.com/Cuprate/cuprate"
},
{
"id": "vaultwarden",
"title": "Vaultwarden",
"version": "1.30.0",
"description": "Self-hosted password vault with zero-knowledge encryption.",
"icon": "/assets/img/app-icons/vaultwarden.webp",
"author": "Vaultwarden",
"category": "data",
"tier": "recommended",
"dockerImage": "source.archipelago-foundation.org/lfg2025/vaultwarden:1.37.1-alpine",
"repoUrl": "https://github.com/dani-garcia/vaultwarden",
"containerConfig": {
"ports": [
"8082:80"
],
"volumes": [
"/var/lib/archipelago/vaultwarden:/data"
]
}
},
{
"id": "searxng",
"title": "SearXNG",
"version": "1.0.0",
"description": "Privacy-respecting metasearch engine. Search the web without tracking.",
"icon": "/assets/img/app-icons/searxng.png",
"author": "SearXNG",
"category": "data",
"tier": "recommended",
"dockerImage": "source.archipelago-foundation.org/lfg2025/searxng:latest",
"repoUrl": "https://github.com/searxng/searxng",
"containerConfig": {
"ports": [
"8888:8080"
],
"volumes": [
"/var/lib/archipelago/searxng:/etc/searxng"
]
}
"id": "electrumx",
"title": "ElectrumX",
"version": "1.18.0",
"description": "Electrum server indexing Bitcoin chain data for lightweight wallet queries.",
"icon": "/assets/img/app-icons/electrumx.png",
"author": "Luke Childs",
"category": "money",
"tier": "core",
"dockerImage": "source.archipelago-foundation.org/lfg2025/electrumx:v1.18.0",
"repoUrl": "https://github.com/spesmilo/electrumx",
"requires": [
"bitcoin-knots"
]
},
{
"id": "fedimint",
@@ -299,87 +189,63 @@
}
},
{
"id": "barkd",
"title": "Ark Wallet",
"version": "0.3.0",
"description": "Ark protocol wallet daemon (barkd). Lets the node hold self-custodial off-chain bitcoin via an Ark server; the wallet talks to it over a local REST API. Signet by default while Ark matures.",
"icon": "/assets/img/app-icons/bark.png",
"author": "Second",
"category": "money",
"dockerImage": "source.archipelago-foundation.org/lfg2025/barkd:0.3.0",
"repoUrl": "https://gitlab.com/ark-bitcoin/bark",
"id": "filebrowser",
"title": "File Browser",
"version": "2.63.23",
"description": "Baseline Archipelago file manager service.",
"icon": "/assets/img/app-icons/file-browser.webp",
"author": "File Browser",
"category": "data",
"tier": "core",
"dockerImage": "source.archipelago-foundation.org/lfg2025/filebrowser:v2.63.23",
"repoUrl": "https://github.com/filebrowser/filebrowser",
"containerConfig": {
"ports": [
"3535:3535"
"8083:80"
],
"volumes": [
"/var/lib/archipelago/barkd:/data"
"/var/lib/archipelago/filebrowser:/srv",
"/var/lib/archipelago/filebrowser-data:/data"
],
"args": [
"--database=/data/database.db",
"--root=/srv",
"--address=0.0.0.0",
"--port=80"
]
}
},
{
"id": "jellyfin",
"title": "Jellyfin",
"version": "10.8.13",
"description": "Free media server. Stream movies, music, and photos.",
"icon": "/assets/img/app-icons/jellyfin.webp",
"author": "Jellyfin",
"category": "data",
"dockerImage": "source.archipelago-foundation.org/lfg2025/jellyfin:10.11.11",
"repoUrl": "https://github.com/jellyfin/jellyfin",
"id": "gitea",
"title": "Gitea",
"version": "1.27.3",
"description": "Self-hosted Git service with built-in container registry, CI/CD, and package hosting.",
"icon": "/assets/img/app-icons/gitea.svg",
"author": "Gitea",
"category": "development",
"dockerImage": "source.archipelago-foundation.org/lfg2025/gitea:1.27.3",
"repoUrl": "https://gitea.com",
"containerConfig": {
"ports": [
"8096:8096"
"3001:3000",
"2222:22"
],
"volumes": [
"/var/lib/archipelago/jellyfin/config:/config",
"/var/lib/archipelago/jellyfin/cache:/cache"
]
}
},
{
"id": "immich",
"title": "Immich",
"version": "2.7.4",
"description": "Self-hosted photo and video backup with mobile apps and search.",
"icon": "/assets/img/app-icons/immich.png",
"author": "Immich",
"category": "data",
"dockerImage": "source.archipelago-foundation.org/lfg2025/immich-server:release",
"repoUrl": "https://github.com/immich-app/immich"
},
{
"id": "homeassistant",
"title": "Home Assistant",
"version": "2026.7.3",
"description": "Open source home automation platform. Control and monitor your smart home devices.",
"icon": "/assets/img/app-icons/homeassistant.png",
"author": "Home Assistant",
"category": "home",
"dockerImage": "source.archipelago-foundation.org/lfg2025/home-assistant:2026.8.2",
"repoUrl": "https://github.com/home-assistant/core",
"containerConfig": {
"ports": [
"8123:8123"
],
"volumes": [
"/var/lib/archipelago/home-assistant:/config"
"/var/lib/archipelago/gitea/data:/data",
"/var/lib/archipelago/gitea/config:/etc/gitea"
],
"env": [
"TZ=UTC"
"GITEA__database__DB_TYPE=sqlite3",
"GITEA__server__SSH_PORT=2222",
"GITEA__server__SSH_LISTEN_PORT=22",
"GITEA__server__LFS_START_SERVER=true",
"GITEA__packages__ENABLED=true",
"GITEA__repository__ENABLE_PUSH_CREATE_USER=true",
"GITEA__repository__ENABLE_PUSH_CREATE_ORG=true",
"GITEA__security__X_FRAME_OPTIONS="
]
}
},
{
"id": "pine",
"title": "Pine",
"version": "1.3.0",
"description": "A private voice assistant for your home. Pine runs speech-to-text (Whisper), text-to-speech (Piper) and wake-word detection (openWakeWord) on your own node and pairs with a PineVoice satellite speaker, so Home Assistant Assist works locally with nothing sent to the cloud. Ask it about your node — block height, sync, peers, Lightning balance — and, when a Claude API key is set, anything else.",
"icon": "/assets/img/app-icons/pine.svg",
"author": "Archipelago",
"category": "home",
"dockerImage": "docker.io/library/nginx:1.31.4-alpine",
"repoUrl": "https://github.com/rhasspy/wyoming"
},
"tier": "optional"
},
{
"id": "grafana",
@@ -405,6 +271,279 @@
]
}
},
{
"id": "homeassistant",
"title": "Home Assistant",
"version": "2026.8.3",
"description": "Open source home automation platform. Control and monitor your smart home devices.",
"icon": "/assets/img/app-icons/homeassistant.png",
"author": "Home Assistant",
"category": "home",
"dockerImage": "source.archipelago-foundation.org/lfg2025/home-assistant:2026.8.3",
"repoUrl": "https://github.com/home-assistant/core",
"containerConfig": {
"ports": [
"8123:8123"
],
"volumes": [
"/var/lib/archipelago/home-assistant:/config"
],
"env": [
"TZ=UTC"
]
}
},
{
"id": "immich",
"title": "Immich",
"version": "2.7.4",
"description": "Self-hosted photo and video backup with mobile apps and search.",
"icon": "/assets/img/app-icons/immich.png",
"author": "Immich",
"category": "data",
"dockerImage": "source.archipelago-foundation.org/lfg2025/immich-server:release",
"repoUrl": "https://github.com/immich-app/immich"
},
{
"id": "indeedhub",
"title": "IndeeHub",
"version": "1.0.0",
"description": "Bitcoin documentary streaming platform featuring God Bless Bitcoin and other educational content about Bitcoin, sovereignty, and decentralized technology. Sign in with your Nostr identity.",
"icon": "/assets/img/app-icons/indeedhub.png",
"author": "IndeeHub",
"category": "community",
"dockerImage": "source.archipelago-foundation.org/lfg2025/indeedhub:1.0.0",
"repoUrl": "https://github.com/indeedhub/indeedhub"
},
{
"id": "jellyfin",
"title": "Jellyfin",
"version": "10.8.13",
"description": "Free media server. Stream movies, music, and photos.",
"icon": "/assets/img/app-icons/jellyfin.webp",
"author": "Jellyfin",
"category": "data",
"dockerImage": "source.archipelago-foundation.org/lfg2025/jellyfin:10.11.11",
"repoUrl": "https://github.com/jellyfin/jellyfin",
"containerConfig": {
"ports": [
"8096:8096"
],
"volumes": [
"/var/lib/archipelago/jellyfin/config:/config",
"/var/lib/archipelago/jellyfin/cache:/cache"
]
}
},
{
"id": "lnd",
"title": "LND",
"version": "0.21.2",
"description": "Lightning Network implementation by Lightning Labs. Enables instant, low-cost Bitcoin payments.",
"icon": "/assets/img/app-icons/lnd.png",
"author": "Lightning Labs",
"category": "money",
"tier": "core",
"dockerImage": "source.archipelago-foundation.org/lfg2025/lnd:v0.21.2-beta",
"repoUrl": "https://github.com/lightningnetwork/lnd",
"requires": [
"bitcoin-knots"
]
},
{
"id": "mempool",
"title": "Mempool Explorer",
"version": "3.0.0",
"description": "Bitcoin mempool and blockchain explorer. Real-time transaction and block visualization.",
"icon": "/assets/img/app-icons/mempool.webp",
"author": "Mempool",
"category": "money",
"tier": "core",
"dockerImage": "source.archipelago-foundation.org/lfg2025/mempool-frontend:v3.3.1",
"repoUrl": "https://github.com/mempool/mempool",
"requires": [
"bitcoin-knots",
"electrumx"
]
},
{
"id": "netbird",
"title": "NetBird",
"version": "2.38.0",
"description": "Self-hosted WireGuard mesh VPN control plane with dashboard, embedded identity provider, management API, signal, relay, and STUN. The user-facing entry point — a TLS proxy in front of the dashboard + server.",
"icon": "/assets/img/app-icons/netbird.svg",
"author": "NetBird",
"category": "networking",
"tier": "recommended",
"dockerImage": "docker.io/library/nginx:1.31.4-alpine",
"repoUrl": "https://github.com/netbirdio/netbird",
"containerConfig": {
"ports": [
"8087:80",
"8086:80",
"3478:3478/udp"
],
"volumes": [
"/var/lib/archipelago/netbird:/var/lib/netbird"
],
"notes": "Installed as a two-container stack: netbird dashboard on 8087 and netbird-server control plane on 8086 plus UDP 3478. For production clients, publish a DNS name over HTTPS with gRPC/WebSocket routing."
}
},
{
"id": "nextcloud",
"title": "Nextcloud",
"version": "29",
"description": "Your own private cloud. File sync, calendars, contacts.",
"icon": "/assets/img/app-icons/nextcloud.webp",
"author": "Nextcloud",
"category": "data",
"dockerImage": "source.archipelago-foundation.org/lfg2025/nextcloud:29",
"repoUrl": "https://github.com/nextcloud/server",
"containerConfig": {
"ports": [
"8085:80"
],
"volumes": [
"/var/lib/archipelago/nextcloud:/var/www/html"
]
}
},
{
"id": "nginx-proxy-manager",
"title": "Nginx Proxy Manager",
"version": "2.12.1",
"description": "Reverse proxy with SSL. Beautiful web interface for managing proxies. On a node, this manages its admin UI and upstream configuration — the proxy's own :80/:443 listeners are not published (the node's web server owns those ports).",
"icon": "/assets/img/app-icons/nginx.svg",
"author": "Nginx Proxy Manager",
"category": "networking",
"tier": "optional",
"dockerImage": "source.archipelago-foundation.org/lfg2025/nginx-proxy-manager:latest",
"repoUrl": "https://github.com/NginxProxyManager/nginx-proxy-manager"
},
{
"id": "nostr-rs-relay",
"title": "Nostr Relay (Rust)",
"version": "0.10.0",
"description": "High-performance Nostr relay written in Rust. Host your own decentralized social media relay and earn networking profits.",
"icon": "/assets/img/app-icons/nostrudel.svg",
"author": "Nostr RS Relay",
"category": "community",
"tier": "recommended",
"dockerImage": "scsibug/nostr-rs-relay:0.10.0",
"repoUrl": "https://github.com/scsibug/nostr-rs-relay",
"containerConfig": {
"ports": [
"8081:8080"
],
"volumes": [
"/var/lib/archipelago/nostr-relay:/usr/src/app/db"
],
"env": [
"RELAY_NAME=Archipelago Nostr Relay",
"RELAY_DESCRIPTION=Self-hosted Nostr relay on Archipelago"
]
}
},
{
"id": "ollama",
"title": "Ollama",
"version": "0.5.4",
"description": "Run large language models locally. Download and run AI models like Llama, Mistral on your own hardware — served on the node's loopback for the AI assistant (Settings → Claude Auth → model backend), never exposed to the network.",
"icon": "/assets/img/app-icons/ollama.png",
"author": "Ollama",
"category": "community",
"tier": "optional",
"dockerImage": "source.archipelago-foundation.org/lfg2025/ollama:latest",
"repoUrl": "https://github.com/ollama/ollama"
},
{
"id": "phoenixd",
"title": "phoenixd",
"version": "0.9.0",
"description": "Headless Lightning daemon by ACINQ (the Phoenix wallet team). No screen of its own — it exposes a small local API that other apps and tools use to send and receive Lightning payments. Channel liquidity is managed automatically for a fee.",
"icon": "/assets/img/app-icons/phoenixd.svg",
"author": "ACINQ",
"category": "money",
"tier": "optional",
"dockerImage": "source.archipelago-foundation.org/lfg2025/phoenixd:0.9.0",
"repoUrl": "https://github.com/ACINQ/phoenixd"
},
{
"id": "photoprism",
"title": "PhotoPrism",
"version": "240915",
"description": "AI-powered photo management with facial recognition.",
"icon": "/assets/img/app-icons/photoprism.svg",
"author": "PhotoPrism",
"category": "data",
"dockerImage": "source.archipelago-foundation.org/lfg2025/photoprism:240915",
"repoUrl": "https://github.com/photoprism/photoprism",
"containerConfig": {
"ports": [
"2342:2342"
],
"volumes": [
"/var/lib/archipelago/photoprism:/photoprism/storage"
],
"env": [
"PHOTOPRISM_ADMIN_PASSWORD=archipelago",
"PHOTOPRISM_DEFAULT_LOCALE=en"
]
}
},
{
"id": "pine",
"title": "Pine",
"version": "1.3.0",
"description": "A private voice assistant for your home. Pine runs speech-to-text (Whisper), text-to-speech (Piper) and wake-word detection (openWakeWord) on your own node and pairs with a PineVoice satellite speaker, so Home Assistant Assist works locally with nothing sent to the cloud. Ask it about your node — block height, sync, peers, Lightning balance — and, when a Claude API key is set, anything else.",
"icon": "/assets/img/app-icons/pine.svg",
"author": "Archipelago",
"category": "home",
"dockerImage": "docker.io/library/nginx:1.31.4-alpine",
"repoUrl": "https://github.com/rhasspy/wyoming"
},
{
"id": "portainer",
"title": "Portainer",
"version": "2.45.0",
"description": "Container management web UI for the local Podman socket.",
"icon": "/assets/img/app-icons/portainer.webp",
"author": "Portainer",
"category": "development",
"tier": "optional",
"dockerImage": "source.archipelago-foundation.org/lfg2025/portainer:2.45.0",
"repoUrl": "https://github.com/portainer/portainer",
"containerConfig": {
"ports": [
"9000:9000"
],
"volumes": [
"/var/lib/archipelago/portainer:/data",
"/run/user/1000/podman/podman.sock:/var/run/docker.sock"
],
"notes": "Uses the manifest-owned Podman socket bind mount preparation path."
}
},
{
"id": "searxng",
"title": "SearXNG",
"version": "1.0.0",
"description": "Privacy-respecting metasearch engine. Search the web without tracking.",
"icon": "/assets/img/app-icons/searxng.png",
"author": "SearXNG",
"category": "data",
"tier": "recommended",
"dockerImage": "source.archipelago-foundation.org/lfg2025/searxng:latest",
"repoUrl": "https://github.com/searxng/searxng",
"containerConfig": {
"ports": [
"8888:8080"
],
"volumes": [
"/var/lib/archipelago/searxng:/etc/searxng"
]
}
},
{
"id": "tailscale",
"title": "Tailscale",
@@ -433,51 +572,6 @@
]
}
},
{
"id": "portainer",
"title": "Portainer",
"version": "2.19.4",
"description": "Container management web UI for the local Podman socket.",
"icon": "/assets/img/app-icons/portainer.webp",
"author": "Portainer",
"category": "development",
"tier": "optional",
"dockerImage": "source.archipelago-foundation.org/lfg2025/portainer:2.39.6",
"repoUrl": "https://github.com/portainer/portainer",
"containerConfig": {
"ports": [
"9000:9000"
],
"volumes": [
"/var/lib/archipelago/portainer:/data",
"/run/user/1000/podman/podman.sock:/var/run/docker.sock"
],
"notes": "Uses the manifest-owned Podman socket bind mount preparation path."
}
},
{
"id": "netbird",
"title": "NetBird",
"version": "2.38.0",
"description": "Self-hosted WireGuard mesh VPN control plane with dashboard, embedded identity provider, management API, signal, relay, and STUN. The user-facing entry point — a TLS proxy in front of the dashboard + server.",
"icon": "/assets/img/app-icons/netbird.svg",
"author": "NetBird",
"category": "networking",
"tier": "recommended",
"dockerImage": "docker.io/library/nginx:1.31.4-alpine",
"repoUrl": "https://github.com/netbirdio/netbird",
"containerConfig": {
"ports": [
"8087:80",
"8086:80",
"3478:3478/udp"
],
"volumes": [
"/var/lib/archipelago/netbird:/var/lib/netbird"
],
"notes": "Installed as a two-container stack: netbird dashboard on 8087 and netbird-server control plane on 8086 plus UDP 3478. For production clients, publish a DNS name over HTTPS with gRPC/WebSocket routing."
}
},
{
"id": "uptime-kuma",
"title": "Uptime Kuma",
@@ -507,82 +601,24 @@
}
},
{
"id": "photoprism",
"title": "PhotoPrism",
"version": "240915",
"description": "AI-powered photo management with facial recognition.",
"icon": "/assets/img/app-icons/photoprism.svg",
"author": "PhotoPrism",
"id": "vaultwarden",
"title": "Vaultwarden",
"version": "1.37.2",
"description": "Self-hosted password vault with zero-knowledge encryption.",
"icon": "/assets/img/app-icons/vaultwarden.webp",
"author": "Vaultwarden",
"category": "data",
"dockerImage": "source.archipelago-foundation.org/lfg2025/photoprism:240915",
"repoUrl": "https://github.com/photoprism/photoprism",
"tier": "recommended",
"dockerImage": "source.archipelago-foundation.org/lfg2025/vaultwarden:1.37.2-alpine",
"repoUrl": "https://github.com/dani-garcia/vaultwarden",
"containerConfig": {
"ports": [
"2342:2342"
"8082:80"
],
"volumes": [
"/var/lib/archipelago/photoprism:/photoprism/storage"
],
"env": [
"PHOTOPRISM_ADMIN_PASSWORD=archipelago",
"PHOTOPRISM_DEFAULT_LOCALE=en"
"/var/lib/archipelago/vaultwarden:/data"
]
}
},
{
"id": "nextcloud",
"title": "Nextcloud",
"version": "29",
"description": "Your own private cloud. File sync, calendars, contacts.",
"icon": "/assets/img/app-icons/nextcloud.webp",
"author": "Nextcloud",
"category": "data",
"dockerImage": "source.archipelago-foundation.org/lfg2025/nextcloud:29",
"repoUrl": "https://github.com/nextcloud/server",
"containerConfig": {
"ports": [
"8085:80"
],
"volumes": [
"/var/lib/archipelago/nextcloud:/var/www/html"
]
}
},
{
"id": "alby-hub",
"title": "Alby Hub",
"version": "1.23.0",
"description": "Self-custodial Lightning wallet hub. Runs its own Lightning node on your Archipelago and connects your apps to it over Nostr Wallet Connect — one hub, every app pays through it.",
"icon": "/assets/img/app-icons/alby-hub.svg",
"author": "Alby",
"category": "money",
"tier": "optional",
"dockerImage": "source.archipelago-foundation.org/lfg2025/alby-hub:v1.24.0",
"repoUrl": "https://github.com/getAlby/hub"
},
{
"id": "phoenixd",
"title": "phoenixd",
"version": "0.9.0",
"description": "Headless Lightning daemon by ACINQ (the Phoenix wallet team). No screen of its own — it exposes a small local API that other apps and tools use to send and receive Lightning payments. Channel liquidity is managed automatically for a fee.",
"icon": "/assets/img/app-icons/phoenixd.svg",
"author": "ACINQ",
"category": "money",
"tier": "optional",
"dockerImage": "source.archipelago-foundation.org/lfg2025/phoenixd:0.9.0",
"repoUrl": "https://github.com/ACINQ/phoenixd"
},
{
"id": "cuprate",
"title": "Cuprate",
"version": "0.1.0-preview",
"description": "Alternative Monero node implementation in Rust. Independently validates Monero consensus rules, providing a layer of security and redundancy for the network.",
"icon": "/assets/img/app-icons/cuprate.svg",
"author": "Cuprate contributors",
"category": "money",
"tier": "optional",
"dockerImage": "source.archipelago-foundation.org/lfg2025/cuprate:0.1.0-preview-18-g618ff14",
"repoUrl": "https://github.com/Cuprate/cuprate"
}
]
}
+91
View File
@@ -0,0 +1,91 @@
app:
id: adguardhome
name: AdGuard Home
version: v0.107.79
upstream:
kind: github
repo: AdguardTeam/AdGuardHome
description: >-
Network-wide ad and tracker blocking: a DNS server that filters every
device on your LAN, with a web console for rules and client management.
container:
image: source.archipelago-foundation.org/lfg2025/adguardhome:v0.107.79
pull_policy: if-not-present
network: pasta
dependencies:
- storage: 1Gi
resources:
memory_limit: 512Mi
disk_limit: 1Gi
security:
capabilities: [NET_BIND_SERVICE]
readonly_root: false
no_new_privileges: true
network_policy: isolated
ports:
- host: 3030
container: 3000
protocol: tcp
bind: 127.0.0.1
# 3030, not AdGuard Home's conventional 3000: Grafana owns :3000 on a
# node, and both being installable means the host ports must not
# collide (the orchestrator refuses/loads warn on overlap).
# open: the setup wizard and admin console carry AdGuard Home's own
# login; the gate fronts the port (TLS, header fixes) without a
# second cookie challenge.
auth: open
auth_rationale: >-
AdGuard Home enforces its own admin login on the console, and the
first-run wizard must answer before any account exists.
- host: 53
container: 53
protocol: udp
# none: plain DNS must answer every unauthenticated query from LAN
# devices — a login page in front of :53 breaks every client on the
# network by design.
auth: none
auth_rationale: >-
Plain DNS answers unauthenticated by protocol: resolvers and clients
send queries directly; a login challenge would make DNS unreachable.
- host: 53
container: 53
protocol: tcp
auth: none
auth_rationale: >-
DNS-over-TCP fallback (truncated responses, zone transfers); same
protocol-level requirement as the UDP port.
volumes:
- type: bind
source: /var/lib/archipelago/adguardhome
target: /opt/adguardhome
options: [rw]
environment: []
health_check:
type: tcp
endpoint: localhost:3030
interval: 30s
timeout: 5s
retries: 3
interfaces:
main:
name: Admin console
description: AdGuard Home web console
type: ui
port: 3030
protocol: http
path: /
metadata:
author: AdGuard
category: networking
repo: https://github.com/AdguardTeam/AdGuardHome
tier: optional
+20 -5
View File
@@ -15,11 +15,6 @@ app:
description: Alternative Monero node implementation in Rust. Independently validates Monero consensus rules, providing a layer of security and redundancy for the network.
category: money
metadata:
icon: /assets/img/app-icons/cuprate.svg
repo: https://github.com/Cuprate/cuprate
tier: optional
container:
# Built from the upstream Dockerfile at the tip of main, 18 commits past
# the cuprated-0.1.0-preview tag (commit 618ff14, 2026-08-19) — there is
@@ -130,6 +125,19 @@ app:
# uses for its own RPC port (-rpcbind=0.0.0.0:8332 internally, gate
# restricts it externally) — not a new risk, the same one already
# reviewed and accepted for Bitcoin's RPC.
# - tracing.stdout.level / tracing.file.{level,max_log_files}: an
# operator reading Cuprated.toml on disk should be able to see and
# tune the log level directly instead of the file silently omitting
# the whole [tracing] table (verified live on amishparadise
# 2026-09-01: the deployed file had no [tracing] section at all, and
# the level was only discoverable by running `cuprated
# --generate-config` and diffing). file.level is set to "info", NOT
# cuprated's own raw default of "debug" — matches the reference dev
# config this app was built and tested against
# (ssmithx@archy-dev-pa:/home/ssmithx/cuprate/Cuprated.toml,
# verified 2026-09-01), which deliberately runs file logging quieter
# than the binary default. max_log_files similarly follows that
# reference (14, not the binary default of 7).
files:
- path: /var/lib/archipelago/cuprate/Cuprated.toml
content: |
@@ -138,6 +146,13 @@ app:
[rpc.restricted]
enable = true
[tracing.stdout]
level = "info"
[tracing.file]
level = "info"
max_log_files = 14
overwrite: false
health_check:
-6
View File
@@ -1,6 +0,0 @@
node_modules
dist
*.log
.git
.gitignore
README.md
-39
View File
@@ -1,39 +0,0 @@
FROM node:20-alpine AS builder
WORKDIR /app
# Copy package files
COPY package*.json ./
RUN npm ci
# Copy source code
COPY . .
# Build the application
RUN npm run build
# Production stage
FROM node:20-alpine
WORKDIR /app
# Copy built application
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json ./
COPY --from=builder /app/public ./public
# Create non-root user
RUN addgroup -g 1000 appuser && \
adduser -D -u 1000 -G appuser appuser && \
mkdir -p /app/wallet && \
chown -R appuser:appuser /app
USER appuser
EXPOSE 8080
ENV WALLET_STORAGE=/app/wallet
ENV DWN_ENDPOINT=http://web5-dwn:3000
CMD ["node", "dist/index.js"]
-35
View File
@@ -1,35 +0,0 @@
# DID Wallet
Web5 wallet with Decentralized Identifier (DID) support.
## Building
```bash
# From the apps directory
./build.sh did-wallet
# Or manually
cd did-wallet
docker build -t archipelago/did-wallet:latest .
```
## Development
```bash
cd did-wallet
npm install
npm run dev
```
## Ports
- **8083**: Web UI (dev: 18083)
## Running Locally
```bash
docker run -p 8083:8080 \
-v /tmp/archipelago-dev/did-wallet:/app/wallet \
-e DWN_ENDPOINT=http://localhost:13000 \
archipelago/did-wallet:latest
```
-59
View File
@@ -1,59 +0,0 @@
app:
id: did-wallet
name: Web5 DID Wallet
version: 1.0.0
# Built by this project — there is no upstream release feed to watch.
upstream:
kind: internal
description: Web5 wallet with Decentralized Identifier (DID) support. Manage your digital identity and Web5 assets.
container:
image: archipelago/did-wallet:1.0.0
image_signature: cosign://...
pull_policy: if-not-present
dependencies:
- storage: 2Gi
resources:
cpu_limit: 1
memory_limit: 512Mi
disk_limit: 2Gi
security:
capabilities: []
readonly_root: true
no_new_privileges: true
user: 1000
seccomp_profile: default
network_policy: isolated
apparmor_profile: did-wallet
ports:
- host: 8088
container: 8080
protocol: tcp # Web UI
bind: 127.0.0.1
auth: gated
volumes:
- type: bind
source: /var/lib/archipelago/did-wallet
target: /app/wallet
options: [rw]
environment:
- WALLET_STORAGE=/app/wallet
health_check:
type: http
endpoint: http://127.0.0.1:8080
path: /health
interval: 30s
timeout: 5s
retries: 3
web5_integration:
did_support: true
wallet_functionality: true
bitcoin_integration: true
-2747
View File
File diff suppressed because it is too large Load Diff
-21
View File
@@ -1,21 +0,0 @@
{
"name": "did-wallet",
"version": "1.0.0",
"description": "Web5 DID Wallet for Archipelago",
"main": "dist/index.js",
"scripts": {
"build": "tsc",
"start": "node dist/index.js",
"dev": "ts-node src/index.ts"
},
"dependencies": {
"express": "^4.18.2",
"@web5/api": "^0.9.0"
},
"devDependencies": {
"@types/express": "^4.17.21",
"@types/node": "^20.10.0",
"typescript": "^5.3.3",
"ts-node": "^10.9.2"
}
}
-23
View File
@@ -1,23 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DID Wallet</title>
<style>
body {
font-family: system-ui, -apple-system, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
</style>
</head>
<body>
<h1>Web5 DID Wallet</h1>
<p>Decentralized Identity Wallet for Archipelago</p>
<div id="app">
<p>Wallet interface coming soon...</p>
</div>
</body>
</html>
-37
View File
@@ -1,37 +0,0 @@
import express from 'express';
const app = express();
const port = 8080;
// Middleware
app.use(express.json());
app.use(express.static('public'));
// Health check endpoint
app.get('/health', (req, res) => {
res.json({ status: 'ok', service: 'did-wallet' });
});
// Wallet API endpoints
app.get('/api/wallet/info', (req, res) => {
res.json({
status: 'ok',
wallet: {
dids: [],
balance: 0
}
});
});
app.post('/api/wallet/did/create', async (req, res) => {
// Placeholder for DID creation
res.json({
status: 'ok',
did: 'did:key:placeholder'
});
});
// Start server
app.listen(port, '0.0.0.0', () => {
console.log(`DID Wallet listening on port ${port}`);
});
-16
View File
@@ -1,16 +0,0 @@
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"lib": ["ES2020"],
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
+2 -2
View File
@@ -1,7 +1,7 @@
app:
id: filebrowser
name: File Browser
version: 2.27.0
version: 2.63.23
# Where this app comes from, so scripts/check-upstream-releases.py can
# tell us when the pin below has fallen behind. Without it nothing can:
# container.image names our mirror, not the project it was mirrored from.
@@ -11,7 +11,7 @@ app:
description: Baseline Archipelago file manager service.
container:
image: source.archipelago-foundation.org/lfg2025/filebrowser:v2.27.0
image: source.archipelago-foundation.org/lfg2025/filebrowser:v2.63.23
pull_policy: if-not-present
network: archy-net
custom_args: ["--config", "/data/.filebrowser.json"]
+2 -2
View File
@@ -1,7 +1,7 @@
app:
id: gitea
name: Gitea
version: "1.23"
version: "1.27.3"
# Where this app comes from, so scripts/check-upstream-releases.py can
# tell us when the pin below has fallen behind. Without it nothing can:
# container.image names our mirror, not the project it was mirrored from.
@@ -12,7 +12,7 @@ app:
category: development
container:
image: docker.io/gitea/gitea:1.23
image: source.archipelago-foundation.org/lfg2025/gitea:1.27.3
pull_policy: if-not-present
dependencies:
+2 -2
View File
@@ -1,7 +1,7 @@
app:
id: homeassistant
name: Home Assistant
version: 2026.7.3
version: 2026.8.3
# Where this app comes from, so scripts/check-upstream-releases.py can
# tell us when the pin below has fallen behind. Without it nothing can:
# container.image names our mirror, not the project it was mirrored from.
@@ -11,7 +11,7 @@ app:
description: Open source home automation platform. Control and monitor your smart home devices.
container:
image: source.archipelago-foundation.org/lfg2025/home-assistant:2026.8.2
image: source.archipelago-foundation.org/lfg2025/home-assistant:2026.8.3
pull_policy: if-not-present
network: pasta
-5
View File
@@ -1,5 +0,0 @@
# Lightning Stack - uses official image
FROM lightninglabs/lightning-stack:v0.12.0
# Default configuration is in the image
# No additional setup needed
-85
View File
@@ -1,85 +0,0 @@
app:
id: lightning-stack
name: Lightning Stack
version: 0.12.0
# No public listing exists for lightninglabs/lightning-stack (checked
# docker.io, ghcr.io and github.com) — nothing can be queried automatically,
# so this one is tracked by hand.
upstream:
kind: manual
url: no public listing for lightninglabs/lightning-stack — verify by hand
description: Complete Lightning Network implementation. Includes LND, CLN, and management tools.
container:
image: lightninglabs/lightning-stack:v0.12.0
image_signature: cosign://...
pull_policy: if-not-present
dependencies:
- app_id: bitcoin-core
version: ">=24.0"
- storage: 50Gi
resources:
cpu_limit: 4
memory_limit: 4Gi
disk_limit: 50Gi
security:
capabilities: [NET_BIND_SERVICE]
readonly_root: true
no_new_privileges: true
user: 1000
seccomp_profile: default
network_policy: isolated
apparmor_profile: lightning-stack
ports:
- 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.
# Mirrors lnd's 18080 exemption — same LND REST API, same macaroon auth.
- host: 8091
container: 8080
protocol: tcp # REST/Web UI
auth: none
auth_rationale: >-
LND REST, authenticated by macaroon over TLS. A browser login page would break
Zeus and every non-browser wallet client, exactly as for lnd's 18080.
volumes:
- type: bind
source: /var/lib/archipelago/lightning-stack
target: /root/.lightning
options: [rw]
environment:
- BITCOIND_HOST=bitcoin-core
- BITCOIND_RPCUSER=${BITCOIN_RPC_USER}
- BITCOIND_RPCPASS=${BITCOIN_RPC_PASSWORD}
- NETWORK=mainnet
health_check:
type: http
endpoint: http://127.0.0.1:8080
path: /v1/getinfo
interval: 30s
timeout: 5s
retries: 3
bitcoin_integration:
rpc_access: admin
sync_required: true
lightning_integration:
channel_management: true
payment_routing: true
+2 -2
View File
@@ -1,7 +1,7 @@
app:
id: lnd
name: LND
version: 0.18.4
version: 0.21.2
# Where this app comes from, so scripts/check-upstream-releases.py can
# tell us when the pin below has fallen behind. Without it nothing can:
# container.image names our mirror, not the project it was mirrored from.
@@ -11,7 +11,7 @@ app:
description: Lightning Network implementation by Lightning Labs. Enables instant, low-cost Bitcoin payments.
container:
image: source.archipelago-foundation.org/lfg2025/lnd:v0.18.4-beta
image: source.archipelago-foundation.org/lfg2025/lnd:v0.21.2-beta
pull_policy: if-not-present
network: archy-net
# BITCOIND_HOST must follow the node's actual Bitcoin container — Knots or
-6
View File
@@ -1,6 +0,0 @@
node_modules
dist
*.log
.git
.gitignore
README.md
-37
View File
@@ -1,37 +0,0 @@
FROM node:20-alpine AS builder
WORKDIR /app
# Copy package files
COPY package*.json ./
RUN npm ci --only=production
# Copy source code
COPY . .
# Build the application
RUN npm run build
# Production stage
FROM node:20-alpine
WORKDIR /app
# Copy built application
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json ./
# Create non-root user
RUN addgroup -g 1000 appuser && \
adduser -D -u 1000 -G appuser appuser && \
mkdir -p /app/data && \
chown -R appuser:appuser /app
USER appuser
EXPOSE 8080
ENV MORPHOS_DATA_DIR=/app/data
CMD ["node", "dist/index.js"]
-55
View File
@@ -1,55 +0,0 @@
app:
id: morphos-server
name: MorphOS Server
version: 1.0.0
# Built by this project — there is no upstream release feed to watch.
upstream:
kind: internal
description: MorphOS server platform. Decentralized application server.
container:
image: archipelago/morphos-server:1.0.0
image_signature: cosign://...
pull_policy: if-not-present
dependencies:
- storage: 5Gi
resources:
cpu_limit: 2
memory_limit: 2Gi
disk_limit: 5Gi
security:
capabilities: []
readonly_root: true
no_new_privileges: true
user: 1000
seccomp_profile: default
network_policy: isolated
apparmor_profile: morphos-server
ports:
- host: 8089
container: 8080
protocol: tcp # Web UI
bind: 127.0.0.1
auth: gated
volumes:
- type: bind
source: /var/lib/archipelago/morphos-server
target: /app/data
options: [rw]
environment:
- MORPHOS_ENV=production
- MORPHOS_DATA_DIR=/app/data
health_check:
type: http
endpoint: http://127.0.0.1:8080
path: /health
interval: 30s
timeout: 5s
retries: 3
File diff suppressed because it is too large Load Diff
-20
View File
@@ -1,20 +0,0 @@
{
"name": "morphos-server",
"version": "1.0.0",
"description": "MorphOS server platform",
"main": "dist/index.js",
"scripts": {
"build": "tsc",
"start": "node dist/index.js",
"dev": "ts-node src/index.ts"
},
"dependencies": {
"express": "^4.18.2"
},
"devDependencies": {
"@types/express": "^4.17.21",
"@types/node": "^20.10.0",
"typescript": "^5.3.3",
"ts-node": "^10.9.2"
}
}
-27
View File
@@ -1,27 +0,0 @@
import express from 'express';
const app = express();
const port = 8080;
// Middleware
app.use(express.json());
// Health check endpoint
app.get('/health', (req, res) => {
res.json({ status: 'ok', service: 'morphos-server', version: '1.0.0' });
});
// API endpoints
app.get('/api/info', (req, res) => {
res.json({
name: 'MorphOS Server',
version: '1.0.0',
status: 'running'
});
});
// Start server
app.listen(port, '0.0.0.0', () => {
console.log(`MorphOS Server listening on port ${port}`);
console.log(`Data directory: ${process.env.MORPHOS_DATA_DIR || '/app/data'}`);
});
-16
View File
@@ -1,16 +0,0 @@
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"lib": ["ES2020"],
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
+88
View File
@@ -0,0 +1,88 @@
app:
id: nginx-proxy-manager
name: Nginx Proxy Manager
version: 2.12.1
upstream:
kind: github
repo: NginxProxyManager/nginx-proxy-manager
description: >-
Reverse proxy with SSL. Beautiful web interface for managing proxies.
On a node, this manages its admin UI and upstream configuration — the
proxy's own :80/:443 listeners are not published (the node's web server
owns those ports).
container:
image: source.archipelago-foundation.org/lfg2025/nginx-proxy-manager:latest
pull_policy: if-not-present
network: pasta
dependencies:
- storage: 1Gi
resources:
memory_limit: 512Mi
disk_limit: 1Gi
security:
# NET_BIND_SERVICE is load-bearing, not decoration: NPM's internal nginx
# listens on 80, 443 AND 81, and the orchestrator runs --cap-drop=ALL —
# without this cap every start dies with "bind() to 0.0.0.0:80 failed
# (13: Permission denied)" and s6 restart-loops forever (shorty-s,
# 2026-09-01, restart counter 3176 within hours of the manifest
# conversion). The legacy podman-run path defaulted to the full cap set,
# which is why it never showed there.
capabilities: [CHOWN, SETUID, SETGID, DAC_OVERRIDE, NET_BIND_SERVICE]
readonly_root: false
no_new_privileges: true
network_policy: isolated
ports:
- host: 8081
container: 81
protocol: tcp
bind: 127.0.0.1
# open, not gated: NPM carries a complete admin login of its own. The
# gate still fronts the port (TLS on the same port, header fixes, retry
# page, Tor) without putting a cookie challenge in front of it.
auth: open
auth_rationale: >-
Nginx Proxy Manager enforces its own admin account on every page;
the initial setup wizard also has to answer before any account exists.
volumes:
- type: bind
source: /var/lib/archipelago/nginx-proxy-manager
target: /data
options: [rw]
# Current NPM images refuse to start unless /etc/letsencrypt is a mount in
# its own right. Keeping the files below the same persistent app directory
# preserves existing certificates while satisfying that startup contract.
- type: bind
source: /var/lib/archipelago/nginx-proxy-manager/letsencrypt
target: /etc/letsencrypt
options: [rw]
environment: []
health_check:
type: tcp
endpoint: localhost:81
interval: 30s
timeout: 5s
retries: 3
interfaces:
main:
name: Admin UI
description: Nginx Proxy Manager admin interface
type: ui
port: 8081
protocol: http
path: /
metadata:
author: Nginx Proxy Manager
category: networking
icon: /assets/img/app-icons/nginx.svg
repo: https://github.com/NginxProxyManager/nginx-proxy-manager
tier: optional
+63
View File
@@ -0,0 +1,63 @@
app:
id: ollama
name: Ollama
version: 0.5.4
upstream:
kind: github
repo: ollama/ollama
description: >-
Run large language models locally. Download and run AI models like
Llama, Mistral on your own hardware — served on the node's loopback for
the AI assistant (Settings → Claude Auth → model backend), never exposed
to the network.
container:
image: source.archipelago-foundation.org/lfg2025/ollama:latest
pull_policy: if-not-present
network: pasta
dependencies:
- storage: 50Gi
resources:
# No memory limit: models are sized by the disk allowance below, and a
# RAM ceiling would just OOM-kill long inferences.
disk_limit: 50Gi
security:
capabilities: []
readonly_root: false
no_new_privileges: true
network_policy: isolated
ports:
- host: 11434
container: 11434
protocol: tcp
# local: Ollama's REST API is consumed by the node's own assistant over
# loopback — never externally reachable, so no gate, no TLS, and no
# login surface exist at all.
bind: 127.0.0.1
auth: local
volumes:
- type: bind
source: /var/lib/archipelago/ollama
target: /root/.ollama
options: [rw]
environment: []
health_check:
type: tcp
endpoint: localhost:11434
interval: 30s
timeout: 5s
retries: 3
metadata:
author: Ollama
category: community
icon: /assets/img/app-icons/ollama.png
repo: https://github.com/ollama/ollama
tier: optional
+2 -2
View File
@@ -5,7 +5,7 @@ app:
# (--beam-size 1). Bumped past the image version so catalog-driven nodes
# pick up the args change; the pre-release form "3.4.1-1" would compare
# LOWER than 3.4.1 under semver and never roll out.
version: "3.4.2"
version: "3.6.0"
# Tracks the rhasspy/wyoming-whisper image we pin (Docker Hub — the
# project's GitHub tags are not the image tags). NOTE: this manifest
# deliberately ships an args-tuned revision AHEAD of the image tag (see
@@ -24,7 +24,7 @@ app:
container_name: pine-whisper
container:
image: docker.io/rhasspy/wyoming-whisper:3.4.1
image: docker.io/rhasspy/wyoming-whisper:3.6.0
pull_policy: if-not-present
network: archy-net
network_aliases: [pine-whisper]
+2 -2
View File
@@ -1,7 +1,7 @@
app:
id: portainer
name: Portainer
version: 2.19.4
version: 2.45.0
# Where this app comes from, so scripts/check-upstream-releases.py can
# tell us when the pin below has fallen behind. Without it nothing can:
# container.image names our mirror, not the project it was mirrored from.
@@ -12,7 +12,7 @@ app:
category: development
container:
image: source.archipelago-foundation.org/lfg2025/portainer:2.39.6
image: source.archipelago-foundation.org/lfg2025/portainer:2.45.0
pull_policy: if-not-present
data_uid: "1000:1000"
+78
View File
@@ -0,0 +1,78 @@
app:
id: tailscale
name: Tailscale
version: 1.78.0
upstream:
kind: github
repo: tailscale/tailscale
description: Zero-config VPN with WireGuard mesh networking.
container:
image: source.archipelago-foundation.org/lfg2025/tailscale:stable
pull_policy: if-not-present
network: pasta
# Mirrors the legacy curated install exactly: tailscaled in userspace
# networking (no host TUN device needed — the rootless container cannot
# have one anyway), then `tailscale web` serving the console on :8240 as
# plain HTTP the app gate can front (TLS on the same port via the node
# certificate, framing-header fixes, retry page, Tor).
entrypoint: ["sh", "-c", "tailscaled --tun=userspace-networking & for i in $(seq 1 30); do [ -S /var/run/tailscale/tailscaled.sock ] && break; sleep 1; done; tailscale web --listen 0.0.0.0:8240 & wait"]
dependencies:
- storage: 1Gi
resources:
memory_limit: 512Mi
disk_limit: 1Gi
security:
capabilities: []
readonly_root: false
no_new_privileges: true
network_policy: isolated
ports:
- host: 8240
container: 8240
protocol: tcp
bind: 127.0.0.1
# open, not gated: the web console requires the tailnet's own login for
# every administrative action — the gate fronts the port without adding
# a second login in front of it.
auth: open
auth_rationale: >-
Tailscale's web console authenticates against the tailnet account for
all administrative actions; the node's cookie challenge would be a
second, redundant login.
volumes:
- type: bind
source: /var/lib/archipelago/tailscale
target: /var/lib/tailscale
options: [rw]
environment:
- TS_STATE_DIR=/var/lib/tailscale
health_check:
type: tcp
endpoint: localhost:8240
interval: 30s
timeout: 5s
retries: 3
interfaces:
main:
name: Web console
description: Tailscale web console
type: ui
port: 8240
protocol: http
path: /
metadata:
author: Tailscale
category: networking
icon: /assets/img/app-icons/tailscale.webp
repo: https://github.com/tailscale/tailscale
tier: recommended
+2 -2
View File
@@ -1,7 +1,7 @@
app:
id: vaultwarden
name: Vaultwarden
version: 1.30.0
version: 1.37.2
# Where this app comes from, so scripts/check-upstream-releases.py can
# tell us when the pin below has fallen behind. Without it nothing can:
# container.image names our mirror, not the project it was mirrored from.
@@ -11,7 +11,7 @@ app:
description: Self-hosted password vault with zero-knowledge encryption.
container:
image: source.archipelago-foundation.org/lfg2025/vaultwarden:1.37.1-alpine
image: source.archipelago-foundation.org/lfg2025/vaultwarden:1.37.2-alpine
pull_policy: if-not-present
network: pasta
+588
View File
@@ -0,0 +1,588 @@
{
"version": 2,
"updated": "2026-04-22T00:00:00Z",
"registry": "source.archipelago-foundation.org/lfg2025",
"featured": {
"id": "indeedhub",
"banner": "/assets/img/featured/indeedhub-banner.jpg",
"headline": "Stream Sovereignty",
"description": "Bitcoin documentaries with Nostr identity.",
"tag": "NOSTR IDENTITY // YOUR NODE"
},
"apps": [
{
"id": "bitcoin-knots",
"title": "Bitcoin Knots",
"version": "28.1.0",
"description": "Full Bitcoin Knots node with dynamic prune/full-mode startup based on host disk.",
"icon": "/assets/img/app-icons/bitcoin-knots.webp",
"author": "Bitcoin Knots",
"category": "money",
"tier": "core",
"dockerImage": "source.archipelago-foundation.org/lfg2025/bitcoin-knots:29.3.knots20260210",
"repoUrl": "https://github.com/bitcoinknots/bitcoin"
},
{
"id": "bitcoin-core",
"title": "Bitcoin Core",
"version": "28.4.0",
"description": "Reference Bitcoin Core node with dynamic prune/full-mode startup based on host disk.",
"icon": "/assets/img/app-icons/bitcoin-core.svg",
"author": "Bitcoin Core contributors",
"category": "money",
"tier": "optional",
"dockerImage": "source.archipelago-foundation.org/lfg2025/bitcoin:28.4",
"repoUrl": "https://github.com/bitcoin/bitcoin"
},
{
"id": "lnd",
"title": "LND",
"version": "0.18.4",
"description": "Lightning Network implementation by Lightning Labs. Enables instant, low-cost Bitcoin payments.",
"icon": "/assets/img/app-icons/lnd.png",
"author": "Lightning Labs",
"category": "money",
"tier": "core",
"dockerImage": "source.archipelago-foundation.org/lfg2025/lnd:v0.18.4-beta",
"repoUrl": "https://github.com/lightningnetwork/lnd",
"requires": [
"bitcoin-knots"
]
},
{
"id": "btcpay-server",
"title": "BTCPay Server",
"version": "2.4.3",
"description": "Self-hosted Bitcoin payment processor. Accept Bitcoin payments without intermediaries.",
"icon": "/assets/img/app-icons/btcpay-server.png",
"author": "BTCPay Server Foundation",
"category": "commerce",
"tier": "core",
"dockerImage": "docker.io/btcpayserver/btcpayserver:2.4.3",
"repoUrl": "https://github.com/btcpayserver/btcpayserver",
"requires": [
"bitcoin-knots"
]
},
{
"id": "mempool",
"title": "Mempool Explorer",
"version": "3.0.0",
"description": "Bitcoin mempool and blockchain explorer. Real-time transaction and block visualization.",
"icon": "/assets/img/app-icons/mempool.webp",
"author": "Mempool",
"category": "money",
"tier": "core",
"dockerImage": "source.archipelago-foundation.org/lfg2025/mempool-frontend:v3.3.1",
"repoUrl": "https://github.com/mempool/mempool",
"requires": [
"bitcoin-knots",
"electrumx"
]
},
{
"id": "electrumx",
"title": "ElectrumX",
"version": "1.18.0",
"description": "Electrum server indexing Bitcoin chain data for lightweight wallet queries.",
"icon": "/assets/img/app-icons/electrumx.png",
"author": "Luke Childs",
"category": "money",
"tier": "core",
"dockerImage": "source.archipelago-foundation.org/lfg2025/electrumx:v1.18.0",
"repoUrl": "https://github.com/spesmilo/electrumx",
"requires": [
"bitcoin-knots"
]
},
{
"id": "indeedhub",
"title": "IndeeHub",
"version": "1.0.0",
"description": "Bitcoin documentary streaming platform featuring God Bless Bitcoin and other educational content about Bitcoin, sovereignty, and decentralized technology. Sign in with your Nostr identity.",
"icon": "/assets/img/app-icons/indeedhub.png",
"author": "IndeeHub",
"category": "community",
"dockerImage": "source.archipelago-foundation.org/lfg2025/indeedhub:1.0.0",
"repoUrl": "https://github.com/indeedhub/indeedhub"
},
{
"id": "botfights",
"title": "BotFights",
"version": "1.2.11",
"description": "Bot competition arena with 2-player arcade fighting mode. AI bots battle in trivia challenges while humans duke it out with controllers. Built for Bitcoiners.",
"icon": "/assets/img/app-icons/botfights.svg",
"author": "BotFights",
"category": "community",
"dockerImage": "source.archipelago-foundation.org/lfg2025/botfights:1.2.11",
"repoUrl": "https://botfights.net",
"containerConfig": {
"ports": [
"9100:9100"
],
"volumes": [
"/var/lib/archipelago/botfights:/app/server/data"
],
"env": [
"NODE_ENV=production",
"PORT=9100",
"FIGHT_LOOP_ENABLED=true",
"ARCHY_EMBEDDED=1"
]
}
},
{
"id": "gitea",
"title": "Gitea",
"version": "1.23",
"description": "Self-hosted Git service with built-in container registry, CI/CD, and package hosting.",
"icon": "/assets/img/app-icons/gitea.svg",
"author": "Gitea",
"category": "development",
"dockerImage": "docker.io/gitea/gitea:1.23",
"repoUrl": "https://gitea.com",
"containerConfig": {
"ports": [
"3001:3000",
"2222:22"
],
"volumes": [
"/var/lib/archipelago/gitea/data:/data",
"/var/lib/archipelago/gitea/config:/etc/gitea"
],
"env": [
"GITEA__database__DB_TYPE=sqlite3",
"GITEA__server__SSH_PORT=2222",
"GITEA__server__SSH_LISTEN_PORT=22",
"GITEA__server__LFS_START_SERVER=true",
"GITEA__packages__ENABLED=true",
"GITEA__repository__ENABLE_PUSH_CREATE_USER=true",
"GITEA__repository__ENABLE_PUSH_CREATE_ORG=true",
"GITEA__security__X_FRAME_OPTIONS="
]
},
"tier": "optional"
},
{
"id": "filebrowser",
"title": "File Browser",
"version": "2.27.0",
"description": "Baseline Archipelago file manager service.",
"icon": "/assets/img/app-icons/file-browser.webp",
"author": "File Browser",
"category": "data",
"tier": "core",
"dockerImage": "source.archipelago-foundation.org/lfg2025/filebrowser:v2.27.0",
"repoUrl": "https://github.com/filebrowser/filebrowser",
"containerConfig": {
"ports": [
"8083:80"
],
"volumes": [
"/var/lib/archipelago/filebrowser:/srv",
"/var/lib/archipelago/filebrowser-data:/data"
],
"args": [
"--database=/data/database.db",
"--root=/srv",
"--address=0.0.0.0",
"--port=80"
]
}
},
{
"id": "nostr-rs-relay",
"title": "Nostr Relay (Rust)",
"version": "0.10.0",
"description": "High-performance Nostr relay written in Rust. Host your own decentralized social media relay and earn networking profits.",
"icon": "/assets/img/app-icons/nostrudel.svg",
"author": "Nostr RS Relay",
"category": "community",
"tier": "recommended",
"dockerImage": "scsibug/nostr-rs-relay:0.10.0",
"repoUrl": "https://github.com/scsibug/nostr-rs-relay",
"containerConfig": {
"ports": [
"8081:8080"
],
"volumes": [
"/var/lib/archipelago/nostr-relay:/usr/src/app/db"
],
"env": [
"RELAY_NAME=Archipelago Nostr Relay",
"RELAY_DESCRIPTION=Self-hosted Nostr relay on Archipelago"
]
}
},
{
"id": "vaultwarden",
"title": "Vaultwarden",
"version": "1.30.0",
"description": "Self-hosted password vault with zero-knowledge encryption.",
"icon": "/assets/img/app-icons/vaultwarden.webp",
"author": "Vaultwarden",
"category": "data",
"tier": "recommended",
"dockerImage": "source.archipelago-foundation.org/lfg2025/vaultwarden:1.37.1-alpine",
"repoUrl": "https://github.com/dani-garcia/vaultwarden",
"containerConfig": {
"ports": [
"8082:80"
],
"volumes": [
"/var/lib/archipelago/vaultwarden:/data"
]
}
},
{
"id": "searxng",
"title": "SearXNG",
"version": "1.0.0",
"description": "Privacy-respecting metasearch engine. Search the web without tracking.",
"icon": "/assets/img/app-icons/searxng.png",
"author": "SearXNG",
"category": "data",
"tier": "recommended",
"dockerImage": "source.archipelago-foundation.org/lfg2025/searxng:latest",
"repoUrl": "https://github.com/searxng/searxng",
"containerConfig": {
"ports": [
"8888:8080"
],
"volumes": [
"/var/lib/archipelago/searxng:/etc/searxng"
]
}
},
{
"id": "fedimint",
"title": "Fedimint Guardian",
"version": "0.10.0",
"description": "Federated Bitcoin minting service with built-in Guardian UI. Privacy-preserving Bitcoin custody.",
"icon": "/assets/img/app-icons/fedimint.png",
"author": "Fedimint",
"category": "money",
"dockerImage": "source.archipelago-foundation.org/lfg2025/fedimintd:v0.10.1",
"repoUrl": "https://github.com/fedimint/fedimint"
},
{
"id": "fedimint-clientd",
"title": "Fedimint Client",
"version": "0.8.0",
"description": "Fedimint ecash client daemon (fmcd). Lets the node hold Fedimint ecash and join federations; the wallet talks to it over a local REST API.",
"icon": "/assets/img/app-icons/fedimint.png",
"author": "Fedimint",
"category": "money",
"tier": "core",
"dockerImage": "source.archipelago-foundation.org/lfg2025/fmcd:0.8.1",
"repoUrl": "https://github.com/minmoto/fmcd"
},
{
"id": "fedimint-gateway",
"title": "Fedimint Gateway",
"version": "0.10.0",
"description": "Fedimint gateway service with automatic LND-or-LDK backend selection.",
"icon": "/assets/img/app-icons/fedimint.png",
"author": "Fedimint",
"category": "money",
"dockerImage": "source.archipelago-foundation.org/lfg2025/gatewayd:v0.10.1",
"repoUrl": "https://github.com/fedimint/fedimint",
"containerConfig": {
"ports": [
"8176:8176",
"9737:9737"
],
"volumes": [
"/var/lib/archipelago/fedimint-gateway:/data",
"/var/lib/archipelago/lnd:/lnd:ro"
]
}
},
{
"id": "barkd",
"title": "Ark Wallet",
"version": "0.3.0",
"description": "Ark protocol wallet daemon (barkd). Lets the node hold self-custodial off-chain bitcoin via an Ark server; the wallet talks to it over a local REST API. Signet by default while Ark matures.",
"icon": "/assets/img/app-icons/bark.png",
"author": "Second",
"category": "money",
"dockerImage": "source.archipelago-foundation.org/lfg2025/barkd:0.3.0",
"repoUrl": "https://gitlab.com/ark-bitcoin/bark",
"containerConfig": {
"ports": [
"3535:3535"
],
"volumes": [
"/var/lib/archipelago/barkd:/data"
]
}
},
{
"id": "jellyfin",
"title": "Jellyfin",
"version": "10.8.13",
"description": "Free media server. Stream movies, music, and photos.",
"icon": "/assets/img/app-icons/jellyfin.webp",
"author": "Jellyfin",
"category": "data",
"dockerImage": "source.archipelago-foundation.org/lfg2025/jellyfin:10.11.11",
"repoUrl": "https://github.com/jellyfin/jellyfin",
"containerConfig": {
"ports": [
"8096:8096"
],
"volumes": [
"/var/lib/archipelago/jellyfin/config:/config",
"/var/lib/archipelago/jellyfin/cache:/cache"
]
}
},
{
"id": "immich",
"title": "Immich",
"version": "2.7.4",
"description": "Self-hosted photo and video backup with mobile apps and search.",
"icon": "/assets/img/app-icons/immich.png",
"author": "Immich",
"category": "data",
"dockerImage": "source.archipelago-foundation.org/lfg2025/immich-server:release",
"repoUrl": "https://github.com/immich-app/immich"
},
{
"id": "homeassistant",
"title": "Home Assistant",
"version": "2026.7.3",
"description": "Open source home automation platform. Control and monitor your smart home devices.",
"icon": "/assets/img/app-icons/homeassistant.png",
"author": "Home Assistant",
"category": "home",
"dockerImage": "source.archipelago-foundation.org/lfg2025/home-assistant:2026.8.2",
"repoUrl": "https://github.com/home-assistant/core",
"containerConfig": {
"ports": [
"8123:8123"
],
"volumes": [
"/var/lib/archipelago/home-assistant:/config"
],
"env": [
"TZ=UTC"
]
}
},
{
"id": "pine",
"title": "Pine",
"version": "1.3.0",
"description": "A private voice assistant for your home. Pine runs speech-to-text (Whisper), text-to-speech (Piper) and wake-word detection (openWakeWord) on your own node and pairs with a PineVoice satellite speaker, so Home Assistant Assist works locally with nothing sent to the cloud. Ask it about your node — block height, sync, peers, Lightning balance — and, when a Claude API key is set, anything else.",
"icon": "/assets/img/app-icons/pine.svg",
"author": "Archipelago",
"category": "home",
"dockerImage": "docker.io/library/nginx:1.31.4-alpine",
"repoUrl": "https://github.com/rhasspy/wyoming"
},
{
"id": "grafana",
"title": "Grafana",
"version": "10.2.0",
"description": "Analytics and monitoring platform. Visualize metrics and create dashboards.",
"icon": "/assets/img/app-icons/grafana.png",
"author": "Grafana Labs",
"category": "data",
"tier": "recommended",
"dockerImage": "source.archipelago-foundation.org/lfg2025/grafana:10.2.0",
"repoUrl": "https://github.com/grafana/grafana",
"containerConfig": {
"ports": [
"3000:3000"
],
"volumes": [
"/var/lib/archipelago/grafana:/var/lib/grafana"
],
"env": [
"GF_PATHS_DATA=/var/lib/grafana",
"GF_USERS_ALLOW_SIGN_UP=false"
]
}
},
{
"id": "tailscale",
"title": "Tailscale",
"version": "1.78.0",
"description": "Zero-config VPN with WireGuard mesh networking.",
"icon": "/assets/img/app-icons/tailscale.webp",
"author": "Tailscale",
"category": "networking",
"tier": "recommended",
"dockerImage": "source.archipelago-foundation.org/lfg2025/tailscale:stable",
"repoUrl": "https://github.com/tailscale/tailscale",
"containerConfig": {
"ports": [
"8240:8240"
],
"volumes": [
"/var/lib/archipelago/tailscale:/var/lib/tailscale"
],
"env": [
"TS_STATE_DIR=/var/lib/tailscale"
],
"args": [
"sh",
"-c",
"tailscaled --tun=userspace-networking & for i in $(seq 1 30); do [ -S /var/run/tailscale/tailscaled.sock ] && break; sleep 1; done; tailscale web --listen 0.0.0.0:8240 & wait"
]
}
},
{
"id": "portainer",
"title": "Portainer",
"version": "2.19.4",
"description": "Container management web UI for the local Podman socket.",
"icon": "/assets/img/app-icons/portainer.webp",
"author": "Portainer",
"category": "development",
"tier": "optional",
"dockerImage": "source.archipelago-foundation.org/lfg2025/portainer:2.39.6",
"repoUrl": "https://github.com/portainer/portainer",
"containerConfig": {
"ports": [
"9000:9000"
],
"volumes": [
"/var/lib/archipelago/portainer:/data",
"/run/user/1000/podman/podman.sock:/var/run/docker.sock"
],
"notes": "Uses the manifest-owned Podman socket bind mount preparation path."
}
},
{
"id": "netbird",
"title": "NetBird",
"version": "2.38.0",
"description": "Self-hosted WireGuard mesh VPN control plane with dashboard, embedded identity provider, management API, signal, relay, and STUN. The user-facing entry point — a TLS proxy in front of the dashboard + server.",
"icon": "/assets/img/app-icons/netbird.svg",
"author": "NetBird",
"category": "networking",
"tier": "recommended",
"dockerImage": "docker.io/library/nginx:1.31.4-alpine",
"repoUrl": "https://github.com/netbirdio/netbird",
"containerConfig": {
"ports": [
"8087:80",
"8086:80",
"3478:3478/udp"
],
"volumes": [
"/var/lib/archipelago/netbird:/var/lib/netbird"
],
"notes": "Installed as a two-container stack: netbird dashboard on 8087 and netbird-server control plane on 8086 plus UDP 3478. For production clients, publish a DNS name over HTTPS with gRPC/WebSocket routing."
}
},
{
"id": "uptime-kuma",
"title": "Uptime Kuma",
"version": "1.23.0",
"description": "Self-hosted uptime monitoring.",
"icon": "/assets/img/app-icons/uptime-kuma.webp",
"author": "Uptime Kuma",
"category": "data",
"tier": "recommended",
"dockerImage": "source.archipelago-foundation.org/lfg2025/uptime-kuma:1",
"repoUrl": "https://github.com/louislam/uptime-kuma",
"containerConfig": {
"ports": [
"3002:3001"
],
"volumes": [
"/var/lib/archipelago/uptime-kuma:/app/data"
],
"env": [
"TZ=UTC"
],
"args": [
"--",
"node",
"server/server.js"
]
}
},
{
"id": "photoprism",
"title": "PhotoPrism",
"version": "240915",
"description": "AI-powered photo management with facial recognition.",
"icon": "/assets/img/app-icons/photoprism.svg",
"author": "PhotoPrism",
"category": "data",
"dockerImage": "source.archipelago-foundation.org/lfg2025/photoprism:240915",
"repoUrl": "https://github.com/photoprism/photoprism",
"containerConfig": {
"ports": [
"2342:2342"
],
"volumes": [
"/var/lib/archipelago/photoprism:/photoprism/storage"
],
"env": [
"PHOTOPRISM_ADMIN_PASSWORD=archipelago",
"PHOTOPRISM_DEFAULT_LOCALE=en"
]
}
},
{
"id": "nextcloud",
"title": "Nextcloud",
"version": "29",
"description": "Your own private cloud. File sync, calendars, contacts.",
"icon": "/assets/img/app-icons/nextcloud.webp",
"author": "Nextcloud",
"category": "data",
"dockerImage": "source.archipelago-foundation.org/lfg2025/nextcloud:29",
"repoUrl": "https://github.com/nextcloud/server",
"containerConfig": {
"ports": [
"8085:80"
],
"volumes": [
"/var/lib/archipelago/nextcloud:/var/www/html"
]
}
},
{
"id": "alby-hub",
"title": "Alby Hub",
"version": "1.23.0",
"description": "Self-custodial Lightning wallet hub. Runs its own Lightning node on your Archipelago and connects your apps to it over Nostr Wallet Connect — one hub, every app pays through it.",
"icon": "/assets/img/app-icons/alby-hub.svg",
"author": "Alby",
"category": "money",
"tier": "optional",
"dockerImage": "source.archipelago-foundation.org/lfg2025/alby-hub:v1.24.0",
"repoUrl": "https://github.com/getAlby/hub"
},
{
"id": "phoenixd",
"title": "phoenixd",
"version": "0.9.0",
"description": "Headless Lightning daemon by ACINQ (the Phoenix wallet team). No screen of its own — it exposes a small local API that other apps and tools use to send and receive Lightning payments. Channel liquidity is managed automatically for a fee.",
"icon": "/assets/img/app-icons/phoenixd.svg",
"author": "ACINQ",
"category": "money",
"tier": "optional",
"dockerImage": "source.archipelago-foundation.org/lfg2025/phoenixd:0.9.0",
"repoUrl": "https://github.com/ACINQ/phoenixd"
},
{
"id": "cuprate",
"title": "Cuprate",
"version": "0.1.0-preview",
"description": "Alternative Monero node implementation in Rust. Independently validates Monero consensus rules, providing a layer of security and redundancy for the network.",
"icon": "/assets/img/app-icons/cuprate.svg",
"author": "Cuprate contributors",
"category": "money",
"tier": "optional",
"dockerImage": "source.archipelago-foundation.org/lfg2025/cuprate:0.1.0-preview-18-g618ff14",
"repoUrl": "https://github.com/Cuprate/cuprate"
}
]
}
+1 -1
View File
@@ -104,7 +104,7 @@ dependencies = [
[[package]]
name = "archipelago"
version = "1.8.5-alpha"
version = "1.8.10-alpha"
dependencies = [
"anyhow",
"archipelago-container",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "archipelago"
version = "1.8.5-alpha"
version = "1.8.10-alpha"
edition = "2021"
license.workspace = true
description = "Archipelago Bitcoin Node OS - Native backend"
+15
View File
@@ -145,6 +145,21 @@ impl ApiHandler {
/// URL so the App Store still renders on nodes that haven't persisted
/// a registry config yet. 15s total timeout.
async fn handle_app_catalog_proxy(&self) -> Result<Response<hyper::Body>> {
// The daemon already refreshes and verifies releases/app-catalog.json.
// Serve that release-root-anchored cache first so a newly published app
// appears immediately, without a frontend release. The old external UI
// catalog below is emergency compatibility only; it must never override
// a healthy signed catalog (Cuprate was invisible for exactly that reason).
if let Ok(body) =
crate::container::app_catalog::verified_catalog_body(&self.config.data_dir).await
{
return Ok(Response::builder()
.status(hyper::StatusCode::OK)
.header("Content-Type", "application/json")
.header("Cache-Control", "no-cache")
.body(hyper::Body::from(body))?);
}
let mut upstreams: Vec<String> = Vec::new();
if let Ok(config) = crate::container::registry::load_registries(&self.config.data_dir).await
{
@@ -558,6 +558,11 @@ impl RpcHandler {
self.handle_fips_remove_seed_anchor(&p).await
}
"fips.apply-seed-anchors" => self.handle_fips_apply_seed_anchors().await,
"fips.ssh-over-mesh.get" => self.handle_fips_ssh_over_mesh_get().await,
"fips.ssh-over-mesh.set" => {
let p = params.unwrap_or(serde_json::json!({}));
self.handle_fips_ssh_over_mesh_set(&p).await
}
// System updates
"update.check" => self.handle_update_check().await,
+47
View File
@@ -261,4 +261,51 @@ impl RpcHandler {
}).collect::<Vec<_>>(),
}))
}
/// The SSH-over-mesh toggle state plus sshd preflights (the card explains
/// the rule instead of gating on it — see ssh_mesh.rs).
pub(super) async fn handle_fips_ssh_over_mesh_get(&self) -> Result<serde_json::Value> {
let state = fips::ssh_mesh::load(&self.config.data_dir).await;
let preflights = fips::ssh_mesh::preflights().await;
Ok(serde_json::json!({
"enabled": state.enabled,
"sources": state.sources,
"scope": if state.sources.is_empty() { "any" } else { "list" },
"preflights": preflights,
}))
}
/// Set the toggle. Params: `{ enabled: bool, sources?: string[] }` —
/// an empty/absent source list opens port 22 to every mesh peer (the UI
/// confirms that explicitly before calling with it).
pub(super) async fn handle_fips_ssh_over_mesh_set(
&self,
params: &serde_json::Value,
) -> Result<serde_json::Value> {
let enabled = params
.get("enabled")
.and_then(|v| v.as_bool())
.ok_or_else(|| anyhow::anyhow!("missing boolean 'enabled'"))?;
let sources: Vec<String> = params
.get("sources")
.and_then(|v| v.as_array())
.map(|a| {
a.iter()
.filter_map(|s| s.as_str().map(str::to_string))
.collect()
})
.unwrap_or_default();
let (state, outcome) =
fips::ssh_mesh::set(&self.config.data_dir, enabled, &sources).await?;
let preflights = fips::ssh_mesh::preflights().await;
Ok(serde_json::json!({
"enabled": state.enabled,
"sources": state.sources,
"scope": if state.sources.is_empty() { "any" } else { "list" },
"applied": outcome.applied,
"removed": outcome.removed,
"reloaded": outcome.reloaded,
"preflights": preflights,
}))
}
}
+152 -49
View File
@@ -4,6 +4,59 @@ use tracing::info;
use super::LND_REST_BASE_URL;
fn router_error_message(body: &serde_json::Value) -> Option<&str> {
body.get("error")
.and_then(|e| e.get("message"))
.and_then(|v| v.as_str())
.or_else(|| body.get("message").and_then(|v| v.as_str()))
}
fn payment_error(message: &str) -> anyhow::Error {
if message.to_ascii_lowercase().contains("invoice expired") {
anyhow::anyhow!(
"Payment failed: this invoice has expired ({}). Ask the recipient for a fresh invoice and try again.",
message.trim_start_matches("invoice expired. ")
)
} else {
anyhow::anyhow!("Payment failed: {message}")
}
}
fn payment_failure_reason(reason: &str) -> &'static str {
match reason {
"FAILURE_REASON_NO_ROUTE" => "No route to the recipient",
"FAILURE_REASON_INSUFFICIENT_BALANCE" => "Insufficient channel balance",
"FAILURE_REASON_TIMEOUT" => "Payment timed out in the network",
"FAILURE_REASON_INCORRECT_PAYMENT_DETAILS" => {
"Recipient rejected the payment (wrong details or expired invoice)"
}
_ => "Payment failed",
}
}
fn json_i64(value: &serde_json::Value, key: &str) -> Option<i64> {
value.get(key).and_then(|v| {
v.as_str()
.and_then(|s| s.parse().ok())
.or_else(|| v.as_i64())
})
}
/// Fee budget for a send, matching lncli's own default: the payment amount
/// (100%). Zero-amount invoices take the payer-supplied amount; fixed invoices
/// take the invoice's own amount. Falls back to a nominal 1,000 sats only when
/// both are somehow absent — the limit must never be left at LND's zero
/// default, which rejects every fee-carrying route as "no route".
fn fee_limit_sats(amount_sats: Option<u64>, decoded_amt: i64) -> i64 {
if let Some(amt) = amount_sats {
return amt as i64;
}
if decoded_amt > 0 {
return decoded_amt;
}
1_000
}
impl RpcHandler {
/// Pay a Lightning invoice.
pub(in crate::api::rpc) async fn handle_lnd_payinvoice(
@@ -65,23 +118,30 @@ impl RpcHandler {
let mut pay_body = serde_json::json!({
"payment_request": payment_request,
// Suppress intermediate stream records: one terminal Payment is
// enough, and it makes grpc-gateway's response a single JSON value.
"no_inflight_updates": true,
"timeout_seconds": 120,
// Router.SendPaymentV2 treats an ABSENT fee limit as ZERO — every
// real route carries a routing fee, so the pathfinder rejects
// them all and the wallet gets "No route to the recipient" on
// every send (fleet-wide, 2026-09-01: the v1.8.9 switch to the v2
// route shipped without this, and a manual lncli test that set
// --fee_limit masked it). lncli's own default is the payment
// amount (100%), which is what we send here.
"fee_limit_sat": fee_limit_sats(amount_sats, decoded_amt),
});
if let Some(amt) = amount_sats {
pay_body["amt"] = serde_json::json!(amt.to_string());
}
// `/v1/channels/transactions` is SYNCHRONOUS: it blocks until the
// payment settles or definitively fails, and multi-hop routing with
// retries routinely takes longer than the shared client's 15s budget.
// That 15s abort used to surface as "Payment failed" while LND kept
// paying in the background — only LND may declare a payment failed,
// so a post-connect timeout is IN FLIGHT (status: pending), never
// failure. The window is deliberately SHORT: most payments settle in
// a couple of seconds and still get their answer in one round trip,
// while a slow multi-hop route flips the UI into its "settling…"
// polling state (lnd.paymentstatus every 3s) after ~8s instead of
// freezing the modal for two minutes with no feedback (a test node
// user report, 2026-07-29).
// LND 0.21 removed the deprecated Lightning.SendPaymentSync REST route
// (`/v1/channels/transactions`). Router.SendPaymentV2 is its supported
// replacement. The old route now returns literal 404 "Not Found" on
// every payment — the fleet failure seen immediately after the 0.21.2
// update. Keep the short browser-facing wait: after LND accepts a slow
// payment we return pending and the UI follows it through
// lnd.paymentstatus instead of declaring a transport timeout a failure.
let pay_client = reqwest::Client::builder()
.no_proxy()
.connect_timeout(std::time::Duration::from_secs(10))
@@ -91,7 +151,7 @@ impl RpcHandler {
.context("Failed to create HTTP client")?;
let resp = match pay_client
.post(format!("{LND_REST_BASE_URL}/v1/channels/transactions"))
.post(format!("{LND_REST_BASE_URL}/v2/router/send"))
.header("Grpc-Metadata-macaroon", &macaroon_hex)
.json(&pay_body)
.send()
@@ -119,49 +179,42 @@ impl RpcHandler {
let body: serde_json::Value = resp
.json()
.await
.context("Failed to parse payment response")?;
.context("Failed to parse Router.SendPaymentV2 response")?;
// grpc-gateway wraps server-streaming records as {"result": ...} and
// transport/RPC failures as {"error": {"message": ...}}. Do not look
// only for the old endpoint's top-level `message`: that turns useful
// LND errors into "Unknown error".
if !status.is_success() {
let msg = body
.get("message")
.and_then(|v| v.as_str())
.unwrap_or("Unknown error");
// Invoices are short-lived; retrying the same one can never
// succeed, so tell the user the way out instead of just the fact.
if msg.contains("invoice expired") {
return Err(anyhow::anyhow!(
"Payment failed: this invoice has expired ({}). Ask the recipient for a fresh invoice and try again.",
msg.trim_start_matches("invoice expired. ")
));
let msg = router_error_message(&body).unwrap_or("Unknown error");
return Err(payment_error(msg));
}
let payment = body.get("result").unwrap_or(&body);
match payment.get("status").and_then(|v| v.as_str()).unwrap_or("") {
"SUCCEEDED" => {}
"FAILED" => {
let reason = payment
.get("failure_reason")
.and_then(|v| v.as_str())
.map(payment_failure_reason)
.unwrap_or("Payment failed");
return Err(anyhow::anyhow!("Payment failed: {reason}"));
}
_ => {
return Ok(serde_json::json!({
"status": "pending",
"payment_hash": decoded_hash,
"amount_sats": decoded_amt,
}));
}
return Err(anyhow::anyhow!("Payment failed: {}", msg));
}
let payment_error = body
.get("payment_error")
.and_then(|v| v.as_str())
.unwrap_or("");
if !payment_error.is_empty() {
return Err(anyhow::anyhow!("Payment failed: {}", payment_error));
}
let amount_sat = body
.get("payment_route")
.and_then(|r| r.get("total_amt"))
.and_then(|v| v.as_str())
.and_then(|s| s.parse::<i64>().ok())
.unwrap_or(decoded_amt);
let payment_hash = body
.get("payment_hash")
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty())
.map(|s| s.to_string())
.unwrap_or(decoded_hash);
let amount_sat = json_i64(payment, "value_sat").unwrap_or(decoded_amt);
Ok(serde_json::json!({
"status": "succeeded",
"payment_hash": payment_hash,
// The decode endpoint returns the canonical hex hash used by our
// polling/list APIs. Router's bytes field is base64 in REST JSON.
"payment_hash": decoded_hash,
"amount_sats": amount_sat,
}))
}
@@ -482,3 +535,53 @@ impl RpcHandler {
Ok(serde_json::json!({ "transactions": transactions }))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn unwraps_grpc_gateway_router_success() {
let body = serde_json::json!({
"result": { "status": "SUCCEEDED", "value_sat": "1000" }
});
let payment = body.get("result").unwrap_or(&body);
assert_eq!(
payment.get("status").and_then(|v| v.as_str()),
Some("SUCCEEDED")
);
assert_eq!(json_i64(payment, "value_sat"), Some(1000));
}
#[test]
fn reads_nested_router_error() {
let body = serde_json::json!({
"error": { "code": 2, "message": "invoice expired. valid until yesterday" }
});
let msg = router_error_message(&body).unwrap();
assert!(payment_error(msg).to_string().contains("fresh invoice"));
}
#[test]
fn router_failure_reasons_are_actionable() {
assert_eq!(
payment_failure_reason("FAILURE_REASON_NO_ROUTE"),
"No route to the recipient"
);
assert_eq!(
payment_failure_reason("FAILURE_REASON_INSUFFICIENT_BALANCE"),
"Insufficient channel balance"
);
}
#[test]
fn fee_limit_never_falls_back_to_zero() {
// SendPaymentV2 defaults an ABSENT fee limit to zero — which rejects
// every fee-carrying route as "no route". The budget must always be
// positive: the payer-supplied amount for zero-amount invoices, the
// invoice's own amount otherwise.
assert_eq!(fee_limit_sats(Some(20_000), 0), 20_000);
assert_eq!(fee_limit_sats(None, 20_000), 20_000);
assert_eq!(fee_limit_sats(None, 0), 1_000);
}
}
+1 -1
View File
@@ -135,7 +135,7 @@ impl RpcHandler {
// not /usr/bin/tollgate-module-basic-go — that's only the opkg/apk
// *package* name, never an on-disk filename.
let tollgate_installed = router
.run("/usr/bin/opkg list-installed 2>/dev/null | grep -q '^tollgate-module-basic-go ' || \
.run("opkg list-installed 2>/dev/null | grep -q '^tollgate-module-basic-go ' || \
test -f /usr/bin/tollgate-wrt 2>/dev/null")
.map(|(_, code)| code == 0)
.unwrap_or(false);
@@ -2040,10 +2040,59 @@ autopilot.active=false\n",
}));
}
// Portainer ≥2.21 no longer lets whoever loads the page first claim the
// admin account: on a fresh install it mints a one-time setup token and
// prints it to the SERVER LOGS, expecting the operator to go digging.
// On an appliance that is hostile UX — "check the Portainer server
// logs" is exactly the dead end users cannot follow. The token is the
// only thing standing between the user and their own app, so surface
// it in the same launch interstitial as the login credentials: extract
// it from the container logs and hand it over with a copy button.
// Once setup completes Portainer invalidates the token, and a container
// recreate (any update) drops the log line entirely — so absence of the
// line naturally makes the card disappear and no stale token lingers.
if app_id == "portainer" {
if let Some(token) = portainer_setup_token(self).await {
return Ok(serde_json::json!({
"title": "Portainer first-run token",
"description": "New Portainer versions protect the first launch with a one-time setup token instead of letting anyone on the network claim the admin account. Paste this token into Portainer's setup screen to create your administrator login. It is only valid until setup finishes — if you already created your admin account, ignore this.",
"credentials": [
{ "label": "Setup token", "value": token, "sensitive": true }
]
}));
}
}
Ok(serde_json::json!({ "credentials": [] }))
}
}
/// Extract Portainer's first-run `setup_token=…` from the live container's
/// recent logs. `None` when the line is absent (setup already done, or an
/// older Portainer without the token flow).
async fn portainer_setup_token(rpc: &RpcHandler) -> Option<String> {
let logs = rpc.get_container_logs_value("portainer", 300).await.ok()?;
let lines = logs.as_array()?;
let lines: Vec<&str> = lines.iter().filter_map(|l| l.as_str()).collect();
parse_setup_token(&lines)
}
/// Pure log-line scan: the token is 64 hex chars after `setup_token=`.
/// Sear newest-first so the most recent mint wins.
fn parse_setup_token(lines: &[&str]) -> Option<String> {
for line in lines.iter().rev() {
let Some(idx) = line.find("setup_token=") else {
continue;
};
let tail = &line[idx + "setup_token=".len()..];
let token: String = tail.chars().take_while(|c| c.is_ascii_hexdigit()).collect();
if token.len() == 64 {
return Some(token);
}
}
None
}
async fn cleanup_stale_package_ports(package_id: &str) {
match package_id {
"grafana" => cleanup_stale_pasta_port("3000").await,
@@ -2751,7 +2800,7 @@ fn is_unknown_app_id_error(err: &anyhow::Error) -> bool {
#[cfg(test)]
mod tests {
use super::{
orchestrator_install_app_id, should_try_orchestrator_install,
orchestrator_install_app_id, parse_setup_token, should_try_orchestrator_install,
uses_orchestrator_install_flow,
};
use crate::api::rpc::package::runtime::orchestrator_uninstall_app_ids;
@@ -2861,4 +2910,41 @@ mod tests {
"Error: no container with name or ID \"bitcoin-knots\" found"
));
}
#[test]
fn portainer_setup_token_is_extracted_from_log_lines() {
// Shape captured live from portainer:2.45.0 on 2026-09-01 — the
// token line is plain text inside the bordered s6 log block.
let logs = [
"2026/09/01 12:38PM INF github.com/portainer/portainer/api/database/boltdb/db.go:163 > loading PortainerDB | filename=portainer.db",
"==========================",
"setup_token=27637c02b6323972dff76bcad4caa456f957b521d3cfe3bc7fb95d2488dfd23a",
"Paste it into the setup screen, or send it in the X-Setup-Token header.",
"==========================",
];
assert_eq!(
parse_setup_token(&logs).as_deref(),
Some("27637c02b6323972dff76bcad4caa456f957b521d3cfe3bc7fb95d2488dfd23a")
);
}
#[test]
fn portainer_setup_token_absent_when_setup_already_done() {
// An instance with an existing admin account never prints the line —
// the credentials card must not render a stale or empty token.
let logs = [
"2026/09/01 11:37AM INF api/datastore/migrator/migrate_ce.go:76 > db migrated to 2.45.0 |",
"2026/09/01 11:37:38 server: Listening on http://0.0.0.0:8000",
];
assert_eq!(parse_setup_token(&logs), None);
}
#[test]
fn portainer_setup_token_rejects_short_or_non_hex_values() {
assert_eq!(parse_setup_token(&["setup_token=abc123"]), None);
assert_eq!(
parse_setup_token(&["setup_token=".to_string().as_str()]),
None
);
}
}
@@ -24,6 +24,7 @@
//! Unknown fields are ignored (no `deny_unknown_fields`), so adding fields on the
//! publisher side never breaks older nodes.
use anyhow::Context;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
@@ -194,6 +195,27 @@ fn entry_for(app_id: &str) -> Option<AppCatalogEntry> {
load_catalog().apps.get(app_id).cloned()
}
/// Return the cached catalog bytes only when they carry a signature anchored
/// to the release root. This is the browser App Store's source: newly signed
/// apps must appear without waiting for a frontend OTA, while unsigned or
/// self-signed registry data must never become an install button.
pub async fn verified_catalog_body(data_dir: &Path) -> anyhow::Result<String> {
let path = data_dir.join(APP_CATALOG_FILE);
let body = tokio::fs::read_to_string(&path)
.await
.with_context(|| format!("read signed app catalog {}", path.display()))?;
let raw: serde_json::Value = serde_json::from_str(&body)?;
match crate::trust::verify_detached(&raw)? {
crate::trust::SignatureStatus::Verified { anchored: true, .. } => Ok(body),
crate::trust::SignatureStatus::Verified {
anchored: false, ..
} => {
anyhow::bail!("app catalog signer is not anchored to the release root")
}
crate::trust::SignatureStatus::Unsigned => anyhow::bail!("app catalog is unsigned"),
}
}
/// Primary image for an app per the remote catalog, if covered.
pub fn catalog_primary_image(app_id: &str) -> Option<String> {
entry_for(app_id).and_then(|e| e.image)
@@ -641,4 +663,27 @@ mod tests {
]
);
}
// The signed-catalog body served to the browser must be the anchored,
// release-root-verified bytes — and nothing else. Unsigned caches (the
// migration-window form) and self-consistent-but-unanchored signatures
// must both be refused so a tampered mirror can never become an install
// button (same posture as the OTA manifest supply-chain gate).
#[tokio::test]
async fn verified_catalog_body_rejects_unsigned_cache() {
let dir = tempfile::tempdir().unwrap();
write_cache(
dir.path(),
r#"{"schema":1,"apps":{"demo":{"version":"1"}}}"#,
)
.unwrap();
let err = verified_catalog_body(dir.path()).await.unwrap_err();
assert!(err.to_string().contains("unsigned"));
}
#[tokio::test]
async fn verified_catalog_body_rejects_missing_cache() {
let dir = tempfile::tempdir().unwrap();
assert!(verified_catalog_body(dir.path()).await.is_err());
}
}
@@ -141,6 +141,12 @@ impl DockerPackageScanner {
// Get metadata for this app
let metadata = get_app_metadata(&app_id);
// Manifest-owned metadata (icon) wins over the static table: the
// manifest is what the catalog signed and what the App Store shows,
// so it is also what an installed tile must render.
let manifest_icon = real_manifest_metadata(&app_id)
.and_then(|m| m.get("icon").and_then(|v| v.as_str()).map(str::to_string))
.filter(|s| !s.trim().is_empty());
// Resolve UI address: separate UI containers > static map > dynamic ports
let lan_address = if app_id == "netbird" {
@@ -191,7 +197,7 @@ impl DockerPackageScanner {
static_files: StaticFiles {
license: "MIT".to_string(),
instructions: metadata.description.clone(),
icon: metadata.icon.clone(),
icon: manifest_icon.unwrap_or_else(|| metadata.icon.clone()),
},
manifest: Manifest {
id: app_id.clone(),
@@ -211,28 +217,34 @@ impl DockerPackageScanner {
author: Some("Archipelago".to_string()),
website: lan_address.clone(),
tier: Some(metadata.tier.to_string()),
interfaces: if lan_address.is_some() || tor_address.is_some() {
interfaces: {
// `ui` is no longer implied by a published port: a
// headless backend with an exposed port is a service,
// not a launchable app. ui_detection consults the
// manifest declaration first, then HTTP-probes the
// port. Addresses stay present either way so the
// Services tab can still show where a backend lives.
// port. A DECLARED UI classifies the app as launchable
// even when no reachable address was confirmed this
// scan — the launch button falls back to the static
// port map, and burying a manifest-declared UI app
// (Alby Hub) in Services because a probe missed was
// exactly the classification bug this fixes.
let has_ui = super::ui_detection::has_web_ui(
&app_id,
lan_address.as_deref(),
package_state == PackageState::Running,
)
.await;
Some(Interfaces {
main: Some(MainInterface {
ui: has_ui.then(|| "true".to_string()),
tor_config: tor_address.clone(),
lan_config: None,
}),
})
} else {
None
if lan_address.is_some() || tor_address.is_some() || has_ui {
Some(Interfaces {
main: Some(MainInterface {
ui: has_ui.then(|| "true".to_string()),
tor_config: tor_address.clone(),
lan_config: None,
}),
})
} else {
None
}
},
},
available_update,
@@ -322,6 +334,47 @@ fn is_transient_podman_helper(app_id: &str, ports: &[String]) -> bool {
&& right.chars().all(|c| c.is_ascii_lowercase())
}
/// Raw `metadata` block of an installed app's real manifest — catalog overlay
/// first (origin-wins), disk manifest as fallback. Kept as raw JSON because
/// the typed `AppManifest` deliberately does not model `metadata`, yet its
/// `icon` is what makes an installed app's tile render the right icon on
/// every surface (My Apps, Services, launcher, companion) instead of the
/// generic A-mark — the exact regression Cuprate exposed on install.
fn real_manifest_metadata(app_id: &str) -> Option<serde_json::Value> {
for (id, value) in crate::container::app_catalog::catalog_manifest_values() {
if id == app_id {
return value.get("app").and_then(|a| a.get("metadata")).cloned();
}
}
let mut candidates = Vec::new();
if let Ok(dir) = std::env::var("ARCHIPELAGO_DATA_DIR") {
candidates.push(
std::path::PathBuf::from(dir)
.join("../apps")
.join(app_id)
.join("manifest.yml"),
);
}
candidates.push(
std::path::PathBuf::from("/opt/archipelago/apps")
.join(app_id)
.join("manifest.yml"),
);
for path in candidates {
let Ok(content) = std::fs::read_to_string(&path) else {
continue;
};
let Ok(value) = serde_yaml::from_str::<serde_json::Value>(&content) else {
continue;
};
let meta = value.get("app").and_then(|a| a.get("metadata")).cloned();
if meta.is_some() {
return meta;
}
}
None
}
fn get_app_metadata(app_id: &str) -> AppMetadata {
let mut meta = match app_id {
"bitcoin-core" => AppMetadata {
@@ -163,7 +163,6 @@ fn image_var_for_app(app_id: &str) -> Option<&'static str> {
"vaultwarden" => Some("VAULTWARDEN_IMAGE"),
"nextcloud" => Some("NEXTCLOUD_IMAGE"),
"searxng" => Some("SEARXNG_IMAGE"),
"cryptpad" => Some("CRYPTPAD_IMAGE"),
"filebrowser" => Some("FILEBROWSER_IMAGE"),
"nginx-proxy-manager" => Some("NPM_IMAGE"),
"portainer" => Some("PORTAINER_IMAGE"),
@@ -178,18 +177,10 @@ fn image_var_for_app(app_id: &str) -> Option<&'static str> {
// Nostr / VPN
"nostr-rs-relay" => Some("NOSTR_RS_RELAY_IMAGE"),
"nostr-vpn" => Some("NOSTR_VPN_IMAGE"),
"fips" => Some("FIPS_IMAGE"),
// Immich (primary = server)
"immich" | "immich_server" => Some("IMMICH_SERVER_IMAGE"),
// Penpot (primary = frontend)
"penpot" | "penpot-frontend" => Some("PENPOT_FRONTEND_IMAGE"),
// AI
"routstr" => Some("ROUTSTR_IMAGE"),
// Networking
"adguardhome" => Some("ADGUARDHOME_IMAGE"),
"tor" | "archy-tor" => Some("ALPINE_TOR_IMAGE"),
@@ -341,13 +332,6 @@ pub fn containers_for_stack(app_id: &str) -> Vec<(&'static str, &'static str)> {
("immich_redis", "REDIS_IMAGE"),
("immich_server", "IMMICH_SERVER_IMAGE"),
],
"penpot" | "penpot-frontend" => vec![
("penpot-postgres", "PENPOT_POSTGRES_IMAGE"),
("penpot-valkey", "PENPOT_VALKEY_IMAGE"),
("penpot-backend", "PENPOT_BACKEND_IMAGE"),
("penpot-exporter", "PENPOT_EXPORTER_IMAGE"),
("penpot-frontend", "PENPOT_FRONTEND_IMAGE"),
],
"netbird" => vec![
("netbird", "NETBIRD_PROXY_IMAGE"),
("netbird-dashboard", "NETBIRD_DASHBOARD_IMAGE"),
+217
View File
@@ -131,6 +131,10 @@ const LND_STATE_DIRS: &[&str] = &[
/// container, not a Quadlet unit, so it is restarted via `podman`, not systemctl.
const LND_CONTAINER: &str = "lnd";
/// Canonical on-host admin macaroon — same path the RPC layer reads.
const LND_ADMIN_MACAROON: &str =
"/var/lib/archipelago/lnd/data/chain/bitcoin/mainnet/admin.macaroon";
/// Archipelago data dir (default; not overridden in prod). Holds the
/// `user-stopped.json` that gates health-monitor auto-restart.
const ARCHY_DATA_DIR: &str = "/var/lib/archipelago";
@@ -872,6 +876,188 @@ fn cert_sha256_thumbprint(pem: &str) -> Result<String> {
Ok(hex::encode_upper(Sha256::digest(&der)))
}
// ── Channel-peer watchdog ──────────────────────────────────────────────────
/// Every open channel's remote peer that is NOT currently connected.
/// Pure over LND's REST JSON so the selection can be unit-tested.
///
/// `/v1/peers` uses `pub_key`; `/v1/channels` uses `remote_pubkey` — the
/// asymmetry is LND's, not ours.
fn select_reconnect_targets(
channels: &serde_json::Value,
peers: &serde_json::Value,
) -> Vec<String> {
let connected: std::collections::HashSet<&str> = peers
.get("peers")
.and_then(|p| p.as_array())
.map(|arr| {
arr.iter()
.filter_map(|p| p.get("pub_key").and_then(|v| v.as_str()))
.collect()
})
.unwrap_or_default();
let mut targets: Vec<String> = channels
.get("channels")
.and_then(|c| c.as_array())
.map(|arr| {
arr.iter()
.filter_map(|c| c.get("remote_pubkey").and_then(|v| v.as_str()))
.filter(|pk| !connected.contains(pk))
.map(str::to_string)
.collect()
})
.unwrap_or_default();
targets.sort();
targets.dedup();
targets
}
/// Reconnect peers of open channels that LND has not re-established on its
/// own. Returns the number of peers reconnected this pass.
///
/// LND normally reconnects channel peers after a restart — but not reliably:
/// when the restart outages are long or repeated (an app update, a node
/// reboot, reconciler churn), the peer link can stay down for hours while
/// BOTH endpoints keep flagging the channel `disabled` in the routing
/// graph. The node itself looks perfectly healthy and every payment in
/// either direction fails "no route to the recipient" — observed live on
/// framework-pt (2026-09-01): its only channel sat disabled on both policy
/// sides for ~17h after the LND 0.21.2 update, while the wallet showed
/// plenty of outbound. The channel graph is desired state; this keeps it.
///
/// Quietly returns Ok(0) when LND is not installed or its wallet is locked —
/// that is every node without LND, on every pass.
///
/// `last_attempt` throttles retries per peer (`min_retry`) so an unreachable
/// peer is not hammered every pass; the caller owns the map so the pass
/// itself stays stateless and testable.
pub(crate) async fn reconnect_disconnected_channel_peers(
last_attempt: &mut std::collections::HashMap<String, std::time::Instant>,
min_retry: std::time::Duration,
) -> Result<usize> {
let Ok(macaroon) = read_file_as_root(LND_ADMIN_MACAROON).await else {
return Ok(0); // LND not installed (or not initialized yet)
};
let macaroon_hex = hex::encode(macaroon);
let client = reqwest::Client::builder()
.no_proxy()
.timeout(std::time::Duration::from_secs(8))
.danger_accept_invalid_certs(true)
.build()
.context("building LND REST client for the channel-peer watchdog")?;
let channels: serde_json::Value = client
.get(format!("{LND_REST_BASE_URL}/v1/channels"))
.header("Grpc-Metadata-macaroon", &macaroon_hex)
.send()
.await
.context("LND REST: listing channels for the peer watchdog")?
.json()
.await
.context("parsing LND channel list")?;
// A locked wallet answers 503 with an error body — it parses as JSON
// with no "channels" key, which selects nothing. That is a quiet pass.
let peers: serde_json::Value = client
.get(format!("{LND_REST_BASE_URL}/v1/peers"))
.header("Grpc-Metadata-macaroon", &macaroon_hex)
.send()
.await
.context("LND REST: listing peers for the peer watchdog")?
.json()
.await
.context("parsing LND peer list")?;
let mut reconnected = 0usize;
for pubkey in select_reconnect_targets(&channels, &peers) {
if last_attempt
.get(&pubkey)
.is_some_and(|t| t.elapsed() < min_retry)
{
continue;
}
last_attempt.insert(pubkey.clone(), std::time::Instant::now());
// Where does the peer live? Its advertised addresses in the public
// graph. A peer with none (fully private) cannot be dialed from here
// — LND itself may still find it; we only log the gap once per pass.
// Unknown to the public graph (or the graph query failed) — nothing
// to dial on.
let Ok(node) = client
.get(format!("{LND_REST_BASE_URL}/v1/graph/node/{pubkey}"))
.header("Grpc-Metadata-macaroon", &macaroon_hex)
.send()
.await
.and_then(|r| r.error_for_status())
else {
continue;
};
let Ok(node) = node.json::<serde_json::Value>().await else {
continue;
};
let addresses: Vec<String> = node
.get("node")
.and_then(|n| n.get("addresses"))
.and_then(|a| a.as_array())
.map(|arr| {
arr.iter()
.filter_map(|a| a.get("addr").and_then(|v| v.as_str()))
.map(str::to_string)
.collect()
})
.unwrap_or_default();
if addresses.is_empty() {
tracing::warn!(
peer = %pubkey,
"LND channel peer is disconnected and advertises no address — cannot dial it; payments through this channel stay unroutable"
);
continue;
}
for addr in addresses {
let Some((host, port)) = addr.rsplit_once(':') else {
continue;
};
let Ok(port) = port.parse::<u32>() else {
continue;
};
let body = serde_json::json!({
"perm": false,
"timeout": "15s",
"addr": { "pubkey": pubkey, "host": host, "port": port },
});
match client
.post(format!("{LND_REST_BASE_URL}/v1/peers"))
.header("Grpc-Metadata-macaroon", &macaroon_hex)
.json(&body)
.send()
.await
{
Ok(resp) if resp.status().is_success() => {
reconnected += 1;
tracing::info!(
peer = %pubkey,
addr = %addr,
"reconnected a disconnected channel peer (channel was unroutable)"
);
break;
}
Ok(resp) => {
let msg = resp.text().await.unwrap_or_default();
// Already connected between our list call and now — success.
if msg.contains("already connected") {
break;
}
tracing::debug!(peer = %pubkey, addr = %addr, %msg, "channel-peer connect attempt failed");
}
Err(e) => {
tracing::debug!(peer = %pubkey, addr = %addr, error = %e, "channel-peer connect attempt failed");
}
}
}
}
Ok(reconnected)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -985,4 +1171,35 @@ mod tests {
let cands = unlock_password_candidates().await;
assert!(cands.iter().any(|p| p == LEGACY_WALLET_PASSWORD));
}
#[test]
fn reconnect_targets_pick_disconnected_channel_peers_only() {
// Shape captured from a live node: /v1/channels uses remote_pubkey,
// /v1/peers uses pub_key, and an offline channel's peer is simply
// absent from the peer list — that absence is the whole signal.
let channels = serde_json::json!({
"channels": [
{ "remote_pubkey": "AAA", "active": true },
{ "remote_pubkey": "BBB", "active": false },
{ "remote_pubkey": "AAA" }
]
});
let peers = serde_json::json!({ "peers": [ { "pub_key": "AAA" } ] });
let targets = select_reconnect_targets(&channels, &peers);
assert_eq!(targets, vec!["BBB".to_string()]);
}
#[test]
fn reconnect_targets_empty_without_channels_or_peers() {
// No LND wallet (503 error body), locked wallet, or an empty node:
// selects nothing, quietly.
let error_body = serde_json::json!({ "message": "locked" });
assert!(select_reconnect_targets(&error_body, &serde_json::json!({})).is_empty());
assert!(select_reconnect_targets(
&serde_json::json!({ "channels": [] }),
&serde_json::json!({ "peers": [] })
)
.is_empty());
}
}
+3 -3
View File
@@ -6,7 +6,7 @@
//! no listener, so allowing them is inert.
pub const APP_LAUNCH_PORTS: &[u16] = &[
2283, 2342, 3000, 3001, 3002, 4080, 5180, 7778, 8080, 8081, 8082, 8083, 8084, 8085, 8087, 8088,
8089, 8090, 8096, 8123, 8175, 8176, 8187, 8240, 8334, 8336, 8888, 8999, 9000, 9100, 10380,
11434, 18081, 18083, 23000, 32838, 50002,
2283, 2342, 3000, 3001, 3002, 3030, 4080, 5180, 7778, 8080, 8081, 8082, 8083, 8084, 8085, 8087,
8090, 8096, 8123, 8175, 8176, 8187, 8240, 8334, 8336, 8888, 8999, 9000, 9100, 10380, 11434,
18081, 18083, 23000, 32838, 50002,
];
+8
View File
@@ -305,6 +305,14 @@ pub async fn install(identity_dir: &Path) -> Result<()> {
}
}
// SSH-over-mesh rides every config install so the on-state survives
// upgrades, reconnects, and the startup self-heal (see ssh_mesh.rs —
// this module owns the 90-ssh.nft slot exclusively).
let ssh_data_dir = identity_dir.parent().unwrap_or(identity_dir);
if let Err(e) = super::ssh_mesh::reconcile(ssh_data_dir).await {
tracing::warn!("ssh-over-mesh reconcile after config install failed (non-fatal): {e:#}");
}
sudo_install_file(&src_key, DAEMON_KEY_PATH, "0600").await?;
// Heal a legacy fips_key.pub that was written as bech32 npub text
// (pre-fix identity::write_fips_key_from_seed did this). Upstream
+1
View File
@@ -32,6 +32,7 @@ pub mod dial;
pub mod endpoints;
pub mod iface;
pub mod service;
pub mod ssh_mesh;
pub mod telemetry;
pub mod update;
+492
View File
@@ -0,0 +1,492 @@
//! SSH over the FIPS mesh — a first-class settings toggle.
//!
//! `fips0` is default-deny inbound: the hardening baseline (`/etc/fips/
//! fips.nft`) rejects un-allowlisted ports, and the daemon's own drop-ins
//! (`80-web-ui.nft`, `85-app-ports.nft`) do not include 22. That is correct
//! by default — but the user asked to be able to SSH their node from Termux
//! over the phone's FIPS mesh instead of keeping a second VPN around for it,
//! and the mesh path already works end-to-end (verified live: the connect
//! reaches fips0 and gets a RST from the node).
//!
//! This module owns the whole lifecycle of the `90-ssh.nft` drop-in, exactly
//! the way `config.rs` owns `80-web-ui.nft` — a hand-added rule and this
//! feature can never fight over the same slot:
//!
//! * toggle OFF → drop-in removed, port 22 refused again
//! * toggle ON → drop-in written on every toggle change AND on every
//! daemon config install (upgrade, reconnect, self-heal),
//! so the on-state survives reinstalls idempotently
//! * scope → "any" (every mesh peer — a real exposure, gated in the
//! UI behind an explicit confirmation) or an explicit list
//! of mesh addresses
//!
//! Nothing else is touched: `80-web-ui.nft` / `85-app-ports.nft` belong to
//! `config.rs`, and the sshd process itself is entirely the operator's.
use std::net::Ipv6Addr;
use std::path::Path;
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use tokio::process::Command;
/// On-disk state under the archipelago data dir. Absent file = disabled,
/// which is the safe default for every node that never touched the toggle.
const STATE_FILE: &str = "fips-ssh-over-mesh.json";
/// The drop-in slot this module owns. 90 sorts after the daemon's own
/// drop-ins (80/85) so a human reading the directory sees the deliberate
/// order; the include order does not change semantics for plain accepts.
pub const DROPIN_PATH: &str = "/etc/fips/fips.d/90-ssh.nft";
/// The hardening baseline this drop-in hangs off. Same file `config.rs`
/// reloads after its own drop-ins.
const FIPS_NFT: &str = "/etc/fips/fips.nft";
/// Persisted toggle state.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct SshMeshState {
/// Whether port 22 is allowed through the fips0 baseline at all.
#[serde(default)]
pub enabled: bool,
/// Mesh addresses (ULAs) the rule is restricted to. Empty = any mesh
/// peer. Kept as strings as-entered but validated as IPv6 on save.
#[serde(default)]
pub sources: Vec<String>,
}
fn state_path(data_dir: &Path) -> std::path::PathBuf {
data_dir.join(STATE_FILE)
}
/// Load the persisted state. Missing file = disabled, no sources — never an
/// error, so a fresh node and a deleted file both mean "off".
pub async fn load(data_dir: &Path) -> SshMeshState {
match tokio::fs::read_to_string(state_path(data_dir)).await {
Ok(content) => serde_json::from_str(&content).unwrap_or_default(),
Err(_) => SshMeshState::default(),
}
}
/// Validate and normalise an operator-supplied source list. Every entry must
/// be a parseable IPv6 address (mesh addresses are full ULAs, not CIDRs) —
/// anything else is refused with the offending entry named, so a typo can
/// never silently narrow or widen the rule.
pub fn validate_sources(raw: &[String]) -> Result<Vec<String>> {
let mut out = Vec::with_capacity(raw.len());
for entry in raw {
let trimmed = entry.trim();
if trimmed.is_empty() {
continue;
}
let addr: Ipv6Addr = trimmed
.parse()
.with_context(|| format!("not a valid mesh (IPv6) address: {trimmed:?}"))?;
out.push(addr.to_string());
}
out.dedup();
Ok(out)
}
/// Render the nft drop-in for a state. The rule shape mirrors the interim
/// manual unblock from the field notes (`ip6 saddr <ula> tcp dport 22
/// accept`) — an unrestricted rule is the same statement without the saddr.
pub fn render_dropin(state: &SshMeshState) -> String {
let mut out = String::from(
"# Written by archipelago — SSH over mesh (Settings → SSH over mesh).\n\
# Allows sshd (port 22) through the fips0 default-deny inbound\n\
# baseline. Remove = refused again; never edit 80/85-* by hand.\n",
);
if state.sources.is_empty() {
out.push_str("tcp dport 22 accept\n");
} else {
out.push_str(&format!(
"ip6 saddr {{ {} }} tcp dport 22 accept\n",
state.sources.join(", ")
));
}
out
}
/// Write or remove the drop-in to match the persisted state, then reload the
/// baseline so the change is live immediately. Returns whether a reload was
/// attempted and succeeded — a node without the hardening baseline has
/// nothing to reload (port 22 is governed by sshd and the host firewall
/// there), which is reported rather than treated as failure.
pub async fn reconcile(data_dir: &Path) -> Result<ReconcileOutcome> {
let state = load(data_dir).await;
if !state.enabled {
let removed = remove_dropin().await?;
let reloaded = reload_nft().await;
return Ok(ReconcileOutcome {
applied: false,
removed,
reloaded,
});
}
// Ensure /etc/fips/fips.d exists, exactly like config::install.
let out = Command::new("sudo")
.args(["install", "-d", "-m", "0755", "/etc/fips/fips.d"])
.output()
.await
.context("sudo install -d /etc/fips/fips.d")?;
if !out.status.success() {
anyhow::bail!(
"sudo install -d /etc/fips/fips.d failed: {}",
String::from_utf8_lossy(&out.stderr).trim()
);
}
let dropin = render_dropin(&state);
let stage = std::env::temp_dir().join(format!("fips-ssh-{}.nft", std::process::id()));
tokio::fs::write(&stage, &dropin)
.await
.context("stage ssh nft drop-in")?;
let install = Command::new("sudo")
.args(["install", "-m", "0644"])
.arg(&stage)
.arg(DROPIN_PATH)
.output()
.await;
let _ = tokio::fs::remove_file(&stage).await;
let install = install?;
if !install.status.success() {
anyhow::bail!(
"install {} failed: {}",
DROPIN_PATH,
String::from_utf8_lossy(&install.stderr).trim()
);
}
let reloaded = reload_nft().await;
Ok(ReconcileOutcome {
applied: true,
removed: false,
reloaded,
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ReconcileOutcome {
/// The allow rule is in place.
pub applied: bool,
/// A previously-written drop-in was removed this call.
pub removed: bool,
/// The hardening baseline existed and `nft -f` succeeded.
pub reloaded: bool,
}
async fn remove_dropin() -> Result<bool> {
match tokio::fs::try_exists(DROPIN_PATH).await {
Ok(true) => {}
_ => return Ok(false),
}
let out = Command::new("sudo")
.args(["rm", "-f", DROPIN_PATH])
.output()
.await
.context("sudo rm 90-ssh.nft")?;
if !out.status.success() {
anyhow::bail!(
"removing {} failed: {}",
DROPIN_PATH,
String::from_utf8_lossy(&out.stderr).trim()
);
}
tracing::info!("ssh-over-mesh: drop-in removed — port 22 refused over fips0 again");
Ok(true)
}
/// Reload the hardening baseline. Best-effort in the same spirit as
/// `config.rs`: absent baseline (nothing to reload) → Ok(false); a failed
/// reload is Ok(false) with a warn, never an error — the drop-in is on disk
/// either way and the next daemon install reloads it.
async fn reload_nft() -> bool {
match tokio::fs::try_exists(FIPS_NFT).await {
Ok(true) => {}
_ => return false,
}
match Command::new("sudo")
.args(["nft", "-f", FIPS_NFT])
.output()
.await
{
Ok(out) if out.status.success() => true,
Ok(out) => {
tracing::warn!(
"ssh-over-mesh: nft reload failed: {}",
String::from_utf8_lossy(&out.stderr).trim()
);
false
}
Err(e) => {
tracing::warn!("ssh-over-mesh: nft reload failed: {e}");
false
}
}
}
/// Persist new state and reconcile immediately. Validation happens here so
/// an invalid source list can never reach disk, and reconcile reads back
/// exactly what was saved.
pub async fn set(
data_dir: &Path,
enabled: bool,
sources: &[String],
) -> Result<(SshMeshState, ReconcileOutcome)> {
let state = SshMeshState {
enabled,
sources: validate_sources(sources)?,
};
tokio::fs::create_dir_all(data_dir)
.await
.with_context(|| format!("mkdir -p {}", data_dir.display()))?;
tokio::fs::write(state_path(data_dir), serde_json::to_string_pretty(&state)?)
.await
.with_context(|| format!("write {}", state_path(data_dir).display()))?;
let outcome = reconcile(data_dir).await?;
Ok((state, outcome))
}
/// Preflights surfaced in the settings card. None of these gate the toggle —
/// they explain it: writing the rule on a node whose sshd doesn't listen on
/// IPv6 simply has no effect until sshd does, and the card says so instead of
/// the user discovering it as a silent connection failure.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct SshPreflights {
/// ssh.service (or sshd.service) is active.
pub sshd_active: bool,
/// Something listens on :22 for IPv6 (`[::]:22` or a dual-stack `*:22`).
/// fips0 is IPv6-only, so a 0.0.0.0-bound sshd is unreachable over it.
pub sshd_ipv6_listen: bool,
/// sshd_config's PasswordAuthentication (last directive wins, includes
/// after the main file). None = not found / unreadable.
pub password_auth: Option<bool>,
}
pub async fn preflights() -> SshPreflights {
SshPreflights {
sshd_active: sshd_active().await,
sshd_ipv6_listen: sshd_ipv6_listen().await,
password_auth: password_auth_enabled().await,
}
}
async fn sshd_active() -> bool {
for unit in ["ssh", "sshd"] {
if let Ok(out) = Command::new("systemctl")
.args(["is-active", "--quiet", unit])
.output()
.await
{
if out.status.success() {
return true;
}
}
}
false
}
async fn sshd_ipv6_listen() -> bool {
let Ok(out) = Command::new("ss").args(["-H", "-tln"]).output().await else {
return false;
};
let text = String::from_utf8_lossy(&out.stdout);
text.lines().any(|line| {
let mut cols = line.split_whitespace();
// -t -l: State Recv-Q Send-Q Local:Port Peer:Port → local is col 4.
let _state = cols.next();
let _recv = cols.next();
let _send = cols.next();
match cols.next() {
Some(local) => {
let port_ok = local.rsplit(':').next() == Some("22");
let v6 = local.starts_with("[::]") || local.starts_with('*');
port_ok && v6
}
None => false,
}
})
}
async fn password_auth_enabled() -> Option<bool> {
let mut directives: Vec<bool> = Vec::new();
if let Ok(main) = tokio::fs::read_to_string("/etc/ssh/sshd_config").await {
collect_password_auth(&main, &mut directives);
}
if let Ok(includes) = glob_sorted("/etc/ssh/sshd_config.d/*.conf").await {
for path in includes {
if let Ok(content) = tokio::fs::read_to_string(&path).await {
collect_password_auth(&content, &mut directives);
}
}
}
directives.pop()
}
fn collect_password_auth(content: &str, out: &mut Vec<bool>) {
for line in content.lines() {
let trimmed = line.trim();
if let Some(rest) = trimmed.strip_prefix("PasswordAuthentication") {
let rest = rest.trim_start();
let value = rest.split_whitespace().next().unwrap_or("");
if value.eq_ignore_ascii_case("yes") {
out.push(true);
} else if value.eq_ignore_ascii_case("no") {
out.push(false);
}
}
}
}
async fn glob_sorted(pattern: &str) -> Result<Vec<std::path::PathBuf>> {
let dir = std::path::Path::new(pattern)
.parent()
.unwrap_or_else(|| Path::new("/"));
let prefix = std::path::Path::new(pattern)
.file_name()
.and_then(|n| n.to_str())
.and_then(|n| n.split('.').next())
.unwrap_or("")
.to_string();
let mut files: Vec<std::path::PathBuf> = Vec::new();
let mut entries = tokio::fs::read_dir(dir)
.await
.context("read sshd_config.d")?;
while let Ok(Some(entry)) = entries.next_entry().await {
let name = entry.file_name();
let name = name.to_string_lossy();
if name.starts_with(&prefix) && name.ends_with(".conf") {
files.push(entry.path());
}
}
files.sort();
Ok(files)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn disabled_is_the_default_and_missing_file_is_not_an_error() {
let dir = tempfile::tempdir().unwrap();
let state = tokio::runtime::Runtime::new()
.unwrap()
.block_on(load(dir.path()));
assert!(!state.enabled);
assert!(state.sources.is_empty());
}
#[test]
fn any_peer_dropin_is_an_unrestricted_accept() {
let state = SshMeshState {
enabled: true,
sources: vec![],
};
let out = render_dropin(&state);
assert!(out.contains("tcp dport 22 accept"));
assert!(!out.contains("ip6 saddr"), "no saddr restriction expected");
}
#[test]
fn source_list_dropin_restricts_to_those_addresses() {
let state = SshMeshState {
enabled: true,
sources: vec![
"fd68:496d:fe34:a06d:cf1:6e4:b6a4:3586".to_string(),
"fd79:1aa:b9e9:4c9f:1f80:5376:9385:1824".to_string(),
],
};
let out = render_dropin(&state);
assert!(out.contains("ip6 saddr { fd68:496d:fe34:a06d:cf1:6e4:b6a4:3586, fd79:1aa:b9e9:4c9f:1f80:5376:9385:1824 } tcp dport 22 accept"));
}
#[test]
fn sources_must_be_ipv6_and_are_normalised() {
let bad = validate_sources(&["192.168.1.5".to_string()]).unwrap_err();
assert!(bad.to_string().contains("192.168.1.5"));
let bad = validate_sources(&["not-an-address".to_string()]).unwrap_err();
assert!(bad.to_string().contains("not-an-address"));
// Uppercase/whitespace entries normalise to canonical lowercase.
let ok = validate_sources(&[
" FD68:496D:FE34:A06D:0CF1:06E4:B6A4:3586 ".to_string(),
"fd68:496d:fe34:a06d:cf1:6e4:b6a4:3586".to_string(),
String::new(),
])
.unwrap();
assert_eq!(
ok,
vec!["fd68:496d:fe34:a06d:cf1:6e4:b6a4:3586".to_string()]
);
}
#[test]
fn state_round_trips_through_disk() {
let dir = tempfile::tempdir().unwrap();
let state = SshMeshState {
enabled: true,
sources: vec!["fd00::1".to_string()],
};
std::fs::write(
dir.path().join(STATE_FILE),
serde_json::to_string(&state).unwrap(),
)
.unwrap();
let loaded = tokio::runtime::Runtime::new()
.unwrap()
.block_on(load(dir.path()));
assert_eq!(loaded, state);
}
#[test]
fn set_validates_before_persisting() {
let dir = tempfile::tempdir().unwrap();
let rt = tokio::runtime::Runtime::new().unwrap();
let err = rt
.block_on(set(dir.path(), true, &["bogus".to_string()]))
.unwrap_err();
assert!(err.to_string().contains("bogus"));
// Nothing was persisted.
let state = rt.block_on(load(dir.path()));
assert!(!state.enabled);
}
#[test]
fn preflight_parse_helpers_cover_the_directives() {
let mut directives = Vec::new();
collect_password_auth(
"# comment\nPasswordAuthentication yes\nMatch all\n PasswordAuthentication no\n",
&mut directives,
);
assert_eq!(directives, vec![true, false]);
}
#[test]
fn sshd_ipv6_listen_recognises_dual_stack_and_v6_only() {
assert!(line_listens("[::]:22"));
assert!(line_listens("*:22"));
assert!(!line_listens("0.0.0.0:22"));
assert!(!line_listens("[::]:80"));
}
fn line_listens(local: &str) -> bool {
let line = format!("LISTEN 0 128 {local} 0.0.0.0:*");
let mut cols = line.split_whitespace();
cols.next();
cols.next();
cols.next();
match cols.next() {
Some(l) => {
let port_ok = l.rsplit(':').next() == Some("22");
let v6 = l.starts_with("[::]") || l.starts_with('*');
port_ok && v6
}
None => false,
}
}
}
+31
View File
@@ -841,6 +841,37 @@ impl Server {
});
}
// LND channel-peer watchdog — every 2 minutes, reconnect the peers
// of open channels that LND has not re-established on its own. LND's
// reconnect logic gives up with a long backoff after repeated or
// extended downtime (an app update, a reboot, reconciler churn), and
// while the peer link is down BOTH endpoints keep the channel flagged
// `disabled` in the routing graph — payments fail "no route" in both
// directions while the node itself looks perfectly healthy. The
// channel graph is desired state; this keeps it (framework-pt,
// 2026-09-01: only channel unroutable ~17h after the 0.21.2 update).
// No-ops quietly on nodes without LND. Per-peer retries are throttled
// to 10 minutes so an unreachable peer is not hammered every pass.
{
tokio::spawn(async move {
let mut interval = tokio::time::interval(Duration::from_secs(120));
let mut last_attempt: HashMap<String, Instant> = HashMap::new();
loop {
interval.tick().await;
match crate::container::lnd::reconnect_disconnected_channel_peers(
&mut last_attempt,
Duration::from_secs(600),
)
.await
{
Ok(0) => {}
Ok(n) => info!(n, "LND channel-peer watchdog reconnected channel peers"),
Err(e) => debug!("LND channel-peer watchdog (non-fatal): {}", e),
}
}
});
}
// FIPS seed-anchor apply loop — every 5 minutes we re-push the
// configured seed anchors into the running fips daemon via
// `fipsctl connect`. This keeps the mesh bootstrap resilient:
+17 -5
View File
@@ -1746,6 +1746,11 @@ app:
}
}
exempt.sort();
// 30 as of 2026-08-31: the 28 below plus adguardhome's two DNS ports
// (53 udp + tcp) — plain DNS answers unauthenticated by protocol, the
// same reason router's mDNS/SSDP and every p2p port is exempt; each
// carries its auth_rationale in the manifest.
//
// 28 as of 2026-08-23: the 26 below plus cuprate's two exemptions —
// 18183 (Monero p2p gossip, same reasoning as bitcoin's 8333) and
// 18090 (host mapping for Monero's canonical 18089 restricted RPC,
@@ -1771,7 +1776,7 @@ app:
// stage timed out that cycle, so the count here lagged at 17.
assert_eq!(
exempt.len(),
28,
30,
"unauthenticated port set changed — review before updating this count: {exempt:?}"
);
}
@@ -1801,15 +1806,22 @@ app:
}
}
open.sort();
// Gitea 3001 (git clients speak basic-auth, not browser cookies) and
// Gitea 3001 (git clients speak basic-auth, not browser cookies),
// BTCPay 23000 (checkout/invoice/webhook endpoints must be reachable
// by anonymous payers). Both enforce their own account login, and an
// operator can re-gate either from Settings → Access control.
// by anonymous payers), and — since the v1.8.7 platform round — the
// three own-login consoles brought onto the manifest platform:
// nginx-proxy-manager 8081 (NPM admin accounts), tailscale 8240
// (tailnet login on the web console), adguardhome 3000 (AGH admin
// accounts + first-run wizard). All enforce their own login, and an
// operator can re-gate any of them from Settings → Access control.
assert_eq!(
open,
vec![
("adguardhome".to_string(), 3000u16),
("btcpay-server".to_string(), 23000u16),
("gitea".to_string(), 3001u16)
("gitea".to_string(), 3001u16),
("nginx-proxy-manager".to_string(), 8081u16),
("tailscale".to_string(), 8240u16),
],
"gate-open port set changed — every entry must be an app with its own login"
);
+19 -15
View File
@@ -15,25 +15,32 @@ pub enum PkgManager {
impl Router {
/// Detect which package manager is available.
///
/// - If `/usr/bin/opkg` exists → `PkgManager::Opkg` (nothing to do).
/// - If `/usr/bin/apk` exists → run `apk update` (switching repos to HTTP
/// Looks up `opkg`/`apk` via the router's `$PATH` (`command -v`) rather
/// than a hardcoded `/usr/bin/<tool>` — official OpenWrt images don't all
/// symlink `/bin` into `/usr/bin` (e.g. the `glinet_gl-mt3000` 24.10.2
/// build keeps them as separate real directories with `opkg` living in
/// `/bin`), so a fixed absolute path silently misses a perfectly normal
/// install and reports "no package management" (archy-x250-pa3, 2026-09-05).
///
/// - If `opkg` is on PATH → `PkgManager::Opkg` (nothing to do).
/// - If `apk` is on PATH → run `apk update` (switching repos to HTTP
/// first to work around missing CA bundle on fresh images), then try
/// `apk add opkg`. If opkg is in the repos → `Opkg`. If not (OpenWrt
/// 25.x) → `ApkNative`.
/// - Neither found → error.
pub fn opkg_check(&self) -> Result<PkgManager> {
let (_, code) = self.run("test -x /usr/bin/opkg")?;
let (_, code) = self.run("command -v opkg >/dev/null 2>&1")?;
if code == 0 {
return Ok(PkgManager::Opkg);
}
let (_, apk_code) = self.run("test -x /usr/bin/apk")?;
let (_, apk_code) = self.run("command -v apk >/dev/null 2>&1")?;
if apk_code == 0 {
info!("[{}] opkg not found — using apk (OpenWrt 25.x+)", self.host);
// Fresh images ship without a CA bundle; switch repos to HTTP so
// apk's wget can reach the package index without TLS verification.
self.run_ok("sed -i 's|https://|http://|g' /etc/apk/repositories 2>/dev/null || true")?;
let (update_out, update_code) = self.run("/usr/bin/apk update 2>&1")?;
let (update_out, update_code) = self.run("apk update 2>&1")?;
if update_code != 0 {
anyhow::bail!(
"apk update failed (exit {}) — router may have no internet access. \
@@ -43,7 +50,7 @@ impl Router {
);
}
// Try to install opkg (only available on some 25.x builds).
let (add_out, add_code) = self.run("/usr/bin/apk add opkg 2>&1")?;
let (add_out, add_code) = self.run("apk add opkg 2>&1")?;
if add_code == 0 {
return Ok(PkgManager::Opkg);
}
@@ -62,7 +69,7 @@ impl Router {
}
anyhow::bail!(
"opkg not found at /usr/bin/opkg — this router's firmware may not \
"Neither opkg nor apk found on this router's $PATH — its firmware may not \
support package management (TollGate requires a standard OpenWrt build)"
);
}
@@ -70,31 +77,28 @@ impl Router {
/// `opkg update` — refresh package lists.
pub fn opkg_update(&self) -> Result<()> {
info!("[{}] opkg update", self.host);
self.run_ok("/usr/bin/opkg update")?;
self.run_ok("opkg update")?;
Ok(())
}
/// Install a package, skipping if already installed.
pub fn opkg_install(&self, package: &str) -> Result<()> {
// Check if already installed to avoid unnecessary network traffic.
let (_, code) = self.run(&format!(
"/usr/bin/opkg list-installed | grep -q '^{} '",
package
))?;
let (_, code) = self.run(&format!("opkg list-installed | grep -q '^{} '", package))?;
if code == 0 {
info!("[{}] {} already installed", self.host, package);
return Ok(());
}
info!("[{}] opkg install {}", self.host, package);
self.run_ok(&format!("/usr/bin/opkg install {}", package))?;
self.run_ok(&format!("opkg install {}", package))?;
Ok(())
}
/// Remove a package.
pub fn opkg_remove(&self, package: &str) -> Result<()> {
info!("[{}] opkg remove {}", self.host, package);
self.run_ok(&format!("/usr/bin/opkg remove {}", package))?;
self.run_ok(&format!("opkg remove {}", package))?;
Ok(())
}
@@ -121,7 +125,7 @@ impl Router {
}
info!("[{}] apk add {}", self.host, package);
self.run_ok(&format!("/usr/bin/apk add {}", package))?;
self.run_ok(&format!("apk add {}", package))?;
Ok(())
}
}
+81 -13
View File
@@ -6,18 +6,53 @@ use crate::Router;
/// The OpenWrt package name for the TollGate reference implementation.
const TOLLGATE_PACKAGE: &str = "tollgate-module-basic-go";
/// Direct-download fallback URLs by opkg architecture string.
/// Pinned upstream release. Was stuck on v0.2.0 (Oct 2025) until 2026-09-05 —
/// nine releases behind. v0.5.0's changelog covers exactly the failure modes
/// hit live against archy-x250-pa3: a mint with an empty/broken keyset used
/// to crash-loop the daemon forever ("graceful degradation when Cashu mints
/// fail" in v0.5.0), and the bundled captive-portal build had no CBOR support
/// at all, so it could only decode legacy `cashuA` tokens — rejecting the
/// `cashuB` (NUT-00 V4) tokens modern wallets like Minibits generate by
/// default ("portal improvements" in v0.5.0 include a JS bundle update that
/// should carry a current cashu-ts with V4 support). Bump this string to move
/// both this crate's URLs and the version baked into the source comments.
const TOLLGATE_VERSION: &str = "v0.5.0";
/// Direct-download fallback URLs by opkg architecture string, for the
/// `.ipk` (ar-archive) package format.
/// Used when the package is not in any configured feed.
/// Source: https://github.com/OpenTollGate/tollgate-module-basic-go/releases/tag/v0.2.0
fn ipk_url(arch: &str) -> Option<&'static str> {
match arch {
"mips_24kc" => Some("https://github.com/OpenTollGate/tollgate-module-basic-go/releases/download/v0.2.0/mips_24kc.ipk"),
"mipsel_24kc" => Some("https://github.com/OpenTollGate/tollgate-module-basic-go/releases/download/v0.2.0/mipsel_24kc.ipk"),
"aarch64_cortex-a53" => Some("https://github.com/OpenTollGate/tollgate-module-basic-go/releases/download/v0.2.0/aarch64_cortex-a53.ipk"),
"aarch64_cortex-a72" => Some("https://github.com/OpenTollGate/tollgate-module-basic-go/releases/download/v0.2.0/aarch64_cortex-a72.ipk"),
"arm_cortex-a7" => Some("https://github.com/OpenTollGate/tollgate-module-basic-go/releases/download/v0.2.0/arm_cortex-a7.ipk"),
_ => None,
}
/// Source: https://github.com/OpenTollGate/tollgate-module-basic-go/releases/tag/v0.5.0
fn ipk_url(arch: &str) -> Option<String> {
let name = match arch {
"mips_24kc" => "mips_24kc",
"mipsel_24kc" => "mipsel_24kc",
"aarch64_cortex-a53" => "aarch64_cortex-a53",
"aarch64_cortex-a72" => "aarch64_cortex-a72",
"arm_cortex-a7" => "arm_cortex-a7",
"x86_64" => "x86_64",
_ => return None,
};
Some(format!(
"https://github.com/OpenTollGate/tollgate-module-basic-go/releases/download/{TOLLGATE_VERSION}/tollgate-wrt_{TOLLGATE_VERSION}_{name}.ipk"
))
}
/// Direct-download URLs for the native Alpine-style `.apk` package format —
/// only published for a subset of architectures as of v0.5.0. Where
/// available this is strictly better than [`ipk_url`] on an apk-native
/// (OpenWrt 25.x+) router: `apk add` installs it directly (dependency
/// resolution, postinst, uci-defaults all handled by apk itself), instead of
/// the manual `ar`/`tar` extraction dance `install_ipk` has to do to unpack
/// an `.ipk` on a router with no `opkg`.
fn apk_url(arch: &str) -> Option<String> {
let name = match arch {
"aarch64_cortex-a53" => "aarch64_cortex-a53",
"x86_64" => "x86_64",
_ => return None,
};
Some(format!(
"https://github.com/OpenTollGate/tollgate-module-basic-go/releases/download/{TOLLGATE_VERSION}/tollgate-wrt_{TOLLGATE_VERSION}_{name}.apk"
))
}
/// Install tollgate-module-basic-go via opkg (OpenWrt ≤24.x).
@@ -35,7 +70,7 @@ pub fn install_tollgate(router: &Router) -> Result<()> {
// Package not in any feed — download the .ipk directly.
let arch = router
.run_ok("/usr/bin/opkg print-architecture | grep -v all | grep -v noarch | tail -1 | awk '{print $2}'")?;
.run_ok("opkg print-architecture | grep -v all | grep -v noarch | tail -1 | awk '{print $2}'")?;
let arch = arch.trim();
let url = ipk_url(arch).ok_or_else(|| {
@@ -88,7 +123,7 @@ pub fn install_tollgate_apk_native(router: &Router) -> Result<()> {
". /etc/openwrt_release 2>/dev/null \
&& a=\"${DISTRIB_ARCH:-${OPENWRT_ARCH:-}}\" \
&& [ -n \"$a\" ] && echo \"$a\" \
|| /usr/bin/apk --print-arch 2>/dev/null \
|| apk --print-arch 2>/dev/null \
|| uname -m",
)?;
// Normalise: uname -m returns bare "mipsel"/"mips"; map to 24kc variant
@@ -103,6 +138,39 @@ pub fn install_tollgate_apk_native(router: &Router) -> Result<()> {
anyhow::bail!("Could not determine router architecture");
}
// Prefer a native .apk when the release publishes one for this arch —
// `apk add` handles the install itself (deps, postinst, uci-defaults),
// skipping the manual ar/tar extraction the .ipk fallback below needs.
if let Some(url) = apk_url(arch) {
info!(
"[{}] Downloading native TollGate .apk for {} from GitHub releases",
router.host, arch
);
let (dl_out, dl_code) = router.run(&format!(
"wget --no-check-certificate -O /tmp/tollgate.apk '{}' 2>&1",
url
))?;
if dl_code != 0 {
anyhow::bail!("TollGate .apk download failed: {}", dl_out.trim());
}
let (size_out, _) = router.run("wc -c < /tmp/tollgate.apk 2>/dev/null")?;
let size: u64 = size_out.trim().parse().unwrap_or(0);
if size < 50_000 {
anyhow::bail!(
"Downloaded TollGate .apk is only {}B — wget likely captured an error page. \
Check router internet access and that the release URL is reachable.",
size
);
}
let (add_out, add_code) =
router.run("apk add --allow-untrusted /tmp/tollgate.apk 2>&1")?;
router.run_ok("rm -f /tmp/tollgate.apk")?;
if add_code != 0 {
anyhow::bail!("TollGate .apk install failed: {}", add_out.trim());
}
return Ok(());
}
let url = ipk_url(arch).ok_or_else(|| {
anyhow::anyhow!(
"No pre-built TollGate package for architecture '{}'. \
@@ -0,0 +1,74 @@
# HANDOFF — deploy companion 0.5.28 (vc48) to the live surfaces
**For: the agent on archi-dev-box.** Companion 0.5.28 shipped to `main`
today (PR #149, merge `9f1a289d` — backup & restore #128, NIP-46 remote
signer #139, companion-gated install pitch #61 residual, hub sub-pages).
The dev box verified everything it can reach; three live surfaces remain,
same shape as the 2026-07-23 deploy handoff
([`HANDOFF-2026-07-23-companion-apk-deploy.md`](HANDOFF-2026-07-23-companion-apk-deploy.md)).
## Already done and verified (do not redo)
- `neode-ui/public/packages/archipelago-companion.apk` on `main` is
**0.5.28 / versionCode 48**, clean build via `Android/ship-companion.sh`,
**v1+v2+v3 signatures verified**, meta json refreshed beside it.
- Gitea raw-on-main serves it byte-identical:
`shasum -a 256` = `fc786b46c704c5752f04fe603371365524c749734f17bd8858cf02fa2dbc34ca`
(2 bytes: 28,206,999… file size ≈ 28.2 MB).
- The foundation server's **raw-proxy** path already serves 0.5.28 (verified
via `https://source.archipelago-foundation.org/lfg2025/archy/raw/branch/main/neode-ui/public/packages/archipelago-companion.json`).
- Demo CI (`demo-images.yml`) fired on the push and redeploys the stack via
the Portainer webhook — should flip on its own; confirm only.
- Signing key unchanged (cert SHA-256 `d622e07e…ec2664d`), so phones update
**in place** over any 0.5.27 install.
## 1. Foundation server static `/packages/` mirror — the real-node QR URL
`https://source.archipelago-foundation.org/packages/archipelago-companion.apk`
is a **static dir** on the release server (openresty; still 0.5.27,
last-modified 2026-08-17). This is the exact URL real nodes' companion QR
downloads (`DEFAULT_DOWNLOAD_URL` in `CompanionIntroOverlay.vue`) — it must
flip before the release is done.
```bash
# Find the webroot once:
grep -rl "packages" /etc/openresty /etc/nginx 2>/dev/null
find / -name archipelago-companion.apk -not -path '/proc/*' 2>/dev/null
# Mirror the exact bytes from Gitea raw-on-main (no rebuild, no re-sign):
cd <that webroot>
curl -fsS -o archipelago-companion.apk http://146.59.87.168:3000/lfg2025/archy/raw/branch/main/neode-ui/public/packages/archipelago-companion.apk
curl -fsS -o archipelago-companion.json http://146.59.87.168:3000/lfg2025/archy/raw/branch/main/neode-ui/public/packages/archipelago-companion.json
shasum -a 256 archipelago-companion.apk
# MUST print: fc786b46c704c5752f04fe603371365524c749734f17bd8858cf02fa2dbc34ca
```
## 2. Node web-bundle redeploys
Same as 2026-07-23: redeploy the web-ui bundle from current `main` to the
active nodes — web root `/opt/archipelago/web-ui/` (NOT a `neode-ui/`
subfolder), at minimum every node the user pairs against. The APK rides in
the bundle's `packages/` dir, so this is also what makes each node's own
served QR download 0.5.28.
## 3. Confirm the demo flipped
`curl -s http://146.59.87.168:2100/packages/archipelago-companion.json`
should read 0.5.28/48 once CI's Portainer webhook redeploy lands; trigger a
stack redeploy if it lags.
## Final verify (all three must show 0.5.28 / 48)
```bash
aapt2 dump badging <downloaded apk> | head -1 # versionCode='48' versionName='0.5.28-debug'
apksigner verify -v --min-sdk-version 21 <downloaded apk> | grep scheme # v1/v2/v3 true
curl -s https://source.archipelago-foundation.org/packages/archipelago-companion.json
curl -s http://146.59.87.168:2100/packages/archipelago-companion.json
```
Then the user's on-device end-to-end: scan the node's companion QR →
installs vc48 in place → hub → Backup & Restore / Remote Signer.
Testing notes for the new features live in the closed tracker issues
(#61/#128/#139) and `docs/companion-backup-restore.md` /
`docs/companion-nip46-remote-signer.md` (the signer's e2e harness:
`Android/tools/nip46-test-client.py`).
+116
View File
@@ -0,0 +1,116 @@
# HANDOFF — SSH over the FIPS mesh (node-side toggle), 2026-08-31
**For: the node OS agent.** From the companion agent, mid-0.5.28 testing. The
user wants to SSH their node from Termux over the phone's FIPS mesh instead
of keeping Tailscale around for it — the phone side is done and verified; the
remaining work is all node-side, and it wants to be a **first-class settings
toggle**, not a hand-edited firewall rule.
## What already works (do not rebuild this)
- The companion's embedded mesh is a **device-wide split tunnel**
(`ArchyVpnService` routes `fd00::/8` for the whole phone, no per-app
filter, `allowBypass`). Termux — or any app — reaches mesh addresses with
zero setup while the tunnel is up, on-LAN and away (anchor path).
- The hub's Nodes page now **displays and copies each FIPS node's `fips0`
ULA** (committed on `companion/0.5.28`).
- Verified live today: `ssh user@<node-ULA>` from Termux answers **RST** —
the path works end-to-end; something on the node is doing the refusing.
## The diagnosis (from today's field test + code read)
1. **`fips0` is default-deny inbound.** The hardening baseline
(`/etc/fips/fips.nft`, provisioned out-of-band) rejects un-allowlisted
ports with RST — the exact symptom the web-UI drop-in's comment documents
on :80 (`core/archipelago/src/fips/config.rs` ~L237). The daemon's own
drop-ins (`/etc/fips/fips.d/80-web-ui.nft`: 80/8443/5679,
`85-app-ports.nft`: app launch ports) **do not include 22**.
2. **sshd IPv6 listening is unverified.** `fips0` is IPv6-only; a sshd pinned
to `ListenAddress 0.0.0.0` RSTs on the ULA identically. The image installs
and enables openssh-server (`image-recipe/archipelago-scripts/install-to-disk.sh`
L177/L210) with default config (binds `::`), but a preflight in the toggle
should confirm rather than assume.
**Interim manual unblock (what the user can do today, keep valid):**
`/etc/fips/fips.d/90-ssh.nft` containing `ip6 saddr <phone-ULA> tcp dport 22
accept`, then `sudo nft -f /etc/fips/fips.nft`. A daemon-owned toggle must
**own that file name/lifecycle** so a hand-added rule and the feature don't
fight over the same slot.
## The ask: a "SSH over mesh" toggle
The user's instinct (seconded here): **a setting in the FIPS/network area of
the node UI**, default **off**. Sketch:
- **UI**: a small settings card in the pattern of
`neode-ui/src/views/settings/` (see `TransportPrefsCard.vue` for a
segmented-pref card + vitest). Toggle + a source-scope selector +
preflight status rows.
- **RPC**: `fips.ssh-over-mesh.get` / `fips.ssh-over-mesh.set` (dispatch arm
in `core/archipelago/src/api/rpc/dispatcher.rs` alongside the existing
`fips.*` arms at ~L544; handler in `api/rpc/fips.rs`). Persisted with the
other fips daemon-config state.
- **Enforcement**: mirror the existing drop-in lifecycle in
`core/archipelago/src/fips/config.rs` (~L243–320): when the toggle is on,
write `/etc/fips/fips.d/90-ssh.nft` on every daemon config install and on
toggle change; when off, remove it. Reload stays
`sudo nft -f /etc/fips/fips.nft`. Never touch `80-web-ui.nft` /
`85-app-ports.nft`.
- **Source scope** (the design decision worth an issue thread):
- *Paired phones only* — restricts to the phone ULAs/npubs the node has
actually paired with. Open question: does the node durably know which
inbound peers are "its" phones? FIPS accepts inbound peers without prior
registration, so this may need a small persisted "trusted peers" list
(seeded when `fips.pair-info` is issued, or on first successful dial).
Recommended default if the data can be made reliable.
- *Custom source list* — raw ULA list, per-rule `ip6 saddr <ula> …`
entries. Escape hatch; fine to ship alongside.
- *Any mesh peer* — what the user literally asked for, but flag it
honestly in the UI: with no registration requirement, this faces port 22
at every peer that can route to the node over the mesh. If offered at
all, gate it behind the same "I understand" confirmation pattern as
other danger-zone settings.
- **Preflights, surfaced in the card**: sshd enabled + listening on IPv6
(`[::]:22` or `*:22` via `ss -tln`), and whether
`PasswordAuthentication` is on — if it is, show a keys-only recommendation
(the firewall restriction is the belt; this is the suspenders).
## Acceptance (on-device)
- [ ] Toggle on, phone on LAN: `ssh user@<node-ULA>` from Termux connects.
- [ ] Phone away from LAN (anchor path): same result.
- [ ] Toggle off: connection refused again; `90-ssh.nft` gone.
- [ ] Daemon config install (upgrade/restart) preserves the on-state and
the rule; nothing duplicated.
- [ ] Non-default source scope actually restricts (try from a second mesh
peer, or a wrong ULA).
- [ ] Settings UI survives a page reload; RPC has a vitest like
`TransportPrefsCard.test.ts`.
## Addendum (2026-08-31, same day): the npub IS the address
While wiring this up we confirmed the mesh ULA is a **pure function of the
public key** — `fd ‖ sha256(x-only pubkey)[0..15]` (`fips/src/identity/node_addr.rs`
`from_pubkey` → `identity/address.rs` `from_node_addr`,
`FIPS_ADDRESS_PREFIX = 0xfd`). The daemon's DNS resolver (`fips/dial.rs`) just
answers what anyone can compute. Consequences for the node side:
- Docs/UI can advertise `ssh <user>@npub1…`-style addressing: Termux's
`Android/tools/fipssh` (shipped with the companion work) derives the ULA
from the npub with zero infrastructure, verified byte-identical against
the fips crate (`archy-fips-core` test
`npub_derives_the_same_mesh_ula_as_the_fips_identity`).
- If the settings toggle from this handover ever grows a "copy command"
affordance, `fipssh <user>@<npub>` is the natural shape (npub, not ULA —
it is the durable identity; the ULA follows from it).
- No node-side DNS surface is required for the SSH case; the resolver stays
what it is today (the node's own peer dials).
## Working rules
Same as the queue handoffs: small commits, tracker issue for this feature
(`ssh-over-mesh`), and the companion agent is downstream-only here — no
companion changes are required (the phone already routes and displays the
ULA). Optional nicety later, NOT part of this issue: the companion's FIPS
hub page could one day surface the toggle state — only worth it if the
`fips.ssh-over-mesh.get` RPC is trivial to add to the existing status call.
+1
View File
@@ -10,6 +10,7 @@ disagree, the code wins and the doc is a bug.
- [Talking to your node](COMMANDS.md) — the conversational command surface
- [Seed Verification](SEED-VERIFICATION.md) — independently verify your 24-word backup
- [Troubleshooting](troubleshooting.md) — common problems and how to resolve them
- [OpenWrt Gateway Setup](openwrt-gateway-setup.md) — pairing an OpenWrt router and provisioning TollGate pay-as-you-go WiFi
- [Gamepad / Controller Navigation](GAMEPAD-NAV.md) — driving the UI from a controller
- [Pine voice commands](pine-voice-commands.md) — the voice-satellite phrase surface
+154
View File
@@ -0,0 +1,154 @@
# SESSION — companion 0.5.28: shipped, published, playbook (2026-08-31)
**For: the companion agent (next session) + anyone shipping a companion
release.** Session that closed the 2026-08-30 companion-agent queue (#61
residual, #128, #139) and shipped 0.5.28 end-to-end.
## Release state at session end — ALL LIVE
Companion **0.5.28 / versionCode 48**, main @ PR #149 (`9f1a289d`), deploy
handoff merged as PR #150 (`91374392`). Every public surface verified
byte-identical (`shasum -a 256` = `fc786b46c704c5752f04fe603371365524c749734f17bd8858cf02fa2dbc34ca`):
| Surface | URL | State |
|---|---|---|
| Gitea raw-on-main | `http://146.59.87.168:3000/lfg2025/archy/raw/branch/main/neode-ui/public/packages/archipelago-companion.apk` | ✅ 0.5.28, v1+v2+v3 verified on download |
| Foundation static `/packages/` (real-node QR URL) | `https://source.archipelago-foundation.org/packages/archipelago-companion.apk` | ✅ 0.5.28 |
| Foundation Gitea-raw proxy | `…/lfg2025/archy/raw/branch/main/…` | ✅ 0.5.28 (6h cache — may lag after pushes) |
| Demo `:2100` | `http://146.59.87.168:2100/packages/archipelago-companion.apk` | ✅ 0.5.28 (auto: CI + Portainer webhook) |
Only remaining live-surface step: **node web-bundle redeploys** so each
node's own served copy is 0.5.28 — archi-dev-box's standard step, written up
in `docs/HANDOFF-2026-08-31-companion-0.5.28-deploy.md` (its §1/§3 were
already done by the time of this doc — only §2 outstanding).
Tracker: #128 and #139 closed with what-shipped comments; #61 (already
closed) got a residual-fix follow-up. Signing cert unchanged (`d622e07e…`),
so phones update in place.
## What shipped in 0.5.28 (map)
- **#61 residual (web)**: `isCompanionApp()` gates on `CompanionBanner.vue`
render, `openCompanionIntro()` (useCompanionIntro.ts), and the overlay's
manual-open watcher; overlay moved to the canonical helper. Vitest suite
green (1013 tests).
- **#128 Backup & Restore**: `Android/rust/archy-fips-core/src/backup.rs`
(ADR-005 envelope, node-compatible), `BackupManager.kt`, hub sub-page
`ui/components/BackupSection.kt`. Doc: `companion-backup-restore.md`.
- **#139 Remote Signer**: `src/nostr.rs` (NIP-44 v2 + NIP-04 + BIP-340,
official vectors), `nostr/BunkerManager.kt` + `NostrSignerPreferences.kt`,
hub sub-page `ui/components/SignerSection.kt`, `nostrconnect://` deep link
via `SignerLaunch`. Harness: `Android/tools/nip46-test-client.py`.
Doc: `companion-nip46-remote-signer.md`.
- **Hub modal redesign** (field feedback): both features are sub-pages like
Nodes/FIPS; panel height cap 70%; scanner hosted by NESMenu outside the
panel; back-arrow → hub.
- **Extras**: node mesh ULA shown/copyable in the Nodes list (`MenuItem`
subtitle); `Android/tools/fipssh` (npub→ULA is pure: `fd ‖ sha256(pubkey)[0..15]`,
pinned by `npub_derives_the_same_mesh_ula_as_the_fips_identity` test).
- **Node-side handoffs written**: `HANDOFF-2026-08-31-ssh-over-mesh.md`
(SSH-over-mesh toggle) and the 0.5.28 deploy handoff.
## The deployment playbook (learned the hard way this session)
### Networking — everything goes through the Tor SOCKS proxy
Direct connections to `146.59.87.168` fail from this box ("Bad file
descriptor"); git works because `~/.gitconfig` sets
`proxy = socks5h://127.0.0.1:9050`. **For curl/Gitea API you must pass it
explicitly:**
```bash
curl -s --socks5-hostname 127.0.0.1:9050 ... # works
curl -s ... # HTTP 000, "unreachable"
```
This is why earlier sessions concluded "Gitea API unreachable" — wrong; it
just needs the proxy flag.
### Gitea API + auth
- Base: `http://146.59.87.168:3000/api/v1` (v1.27.1), via the proxy.
- The keychain git credential (`security find-internet-password -s
146.59.87.168`, acct `v4v`) is a **`write:repository`-only token** — fine
for git, CANNOT read/write issues.
- Issue ops need `write:issue`. This session the user pasted a broad token
(activitypub+misc+notification+organization+package+issue+repository) —
**revocation still pending** (it's in chat scrollback). Ask the user for a
scoped `write:issue` token next time.
### main is PROTECTED — ship via -ship branch + PR + API merge
`git push origin main` is rejected by pre-receive. The working sequence:
```bash
git fetch origin
git checkout main && git reset --hard origin/main # local main is STALE (see below)
git merge --no-ff companion/<ver> -m "Companion <ver> — …"
./Android/ship-companion.sh # builds, signs v1+v2+v3, stages APK+meta, commits
# its `git push` FAILS on protected main — expected. Push the branch instead:
git push origin main:companion/<ver>-ship
# then create + merge the PR via API:
curl ... POST repos/lfg2025/archy/pulls {"head":"companion/<ver>-ship","base":"main",...}
curl ... POST repos/lfg2025/archy/pulls/<n>/merge -d '{"Do":"merge"}'
```
(Refinement for next time: run `ship-companion.sh` ON the `-ship` branch
from the start — it pushes the current branch, which for a `-ship` branch
succeeds directly.)
- **Local `main` is the pre-open-source-import lineage** (1115 stale
commits, unrelated history). Always `reset --hard origin/main` before
using it; never merge into it without the reset.
- A **stale tag ref** (`v1.7.115-alpha`) can make `git fetch` fail
("did not send all necessary objects") — `rm .git/refs/tags/v1.7.115-alpha`.
- Last release's `-ship` branch for reference: `origin/companion/0.5.27-ship`.
### Build + verify (per release)
- Version lives in `Android/app/build.gradle.kts` (`versionCode` must
strictly increase; meta json is auto-generated by the publish script from
it). 0.5.28 → next is **0.5.29/vc49**.
- APK package is `com.archipelago.app.debug` (the served artifact IS the
debug build, committed repo keystore, cert SHA-256 `d622e07e…ec2664d`).
Local `Android/app/debug.keystore` is untracked but produces that cert —
verify per release: `apksigner verify --print-certs` on old vs new.
- Build: `cd Android && JAVA_HOME=/opt/homebrew/opt/openjdk@17
ANDROID_HOME=$HOME/Library/Android/sdk ./gradlew :app:assembleDebug`
(builds the Rust via cargo-ndk, NDK under `~/Library/Android/sdk/ndk/`).
Test build for the user: copy to `~/Desktop/archipelago-companion-<ver>.apk`.
- Rust: `cd Android/rust/archy-fips-core && cargo test --lib` (24 tests at
session end) + clippy. neode-ui: `npm ci` first (node_modules not kept),
`npx vitest run`, `npm run type-check`.
- Post-ship verify block: aapt2 badging, shasum vs Gitea raw, apksigner
v1/v2/v3, the three public URLs' meta json (table above), foundation
raw-proxy may serve up to 6h stale (cache-control: max-age=21600).
### Infrastructure facts
- `source.archipelago-foundation.org` = openresty on vps2 with **two
surfaces**: static `/packages/` (manual mirror; the real-node QR URL) and
a Gitea-raw proxy (6h cache, auto). Demo `:2100` redeploys automatically:
`.gitea/workflows/demo-images.yml` fires on `main` pushes touching
`neode-ui/**`, then calls the Portainer webhook.
- **No SSH to vps2 from this box**: `archy_146_release` key declined for
root/archipelago/dorian/lfg2025/deploy/git. Server-side work needs the
archi-dev-box agent or the user.
## Open items for next session
1. **Confirm node web-bundle redeploys** happened (archi-dev-box; deploy
handoff §2) — a paired node's own `/packages/` should serve vc48.
2. **Token revocation** (user) + request a `write:issue`-scoped one.
3. **Node-side roadmap** fed by this release: SSH-over-mesh toggle
(`HANDOFF-2026-08-31-ssh-over-mesh.md`), node NIP-46 client (login flow B),
node-side storage for companion backup envelopes.
4. **On-device follow-ups**: the user's full 0.5.28 pass — signer e2e via
the harness (`/tmp/nip46env/bin/python Android/tools/nip46-test-client.py`),
backup round-trip on a wipe, and the zxing-cpp decision trigger
(move-to-the-code; sketch is verified online:
`io.github.zxing-cpp:android:3.1.1`, still NOT-actioned by design).
5. Untracked on this box, deliberately left: `Android/app/debug.keystore`,
`docs/1.8-alpha-improvements-tracker.md`,
`docs/SESSION-1.8.0-OTA-PROGRESS.md`, `image-recipe/branding/source-logos/`
(other workstreams' files).
+88
View File
@@ -0,0 +1,88 @@
# Companion backup & restore — the phone side of a border crossing (#128)
**Status:** shipped in companion 0.5.28 (vc48). Issue: #128 ("Graphene phone
backup/restore — part of the companion app or passport prime combo").
## The problem
The companion holds real secrets: node addresses and login passwords, the
phone's FIPS mesh identity (which nodes peer with), and — since 0.5.28 — the
remote-signer key. Losing the phone, or wiping it to cross a border, loses all
of it. On GrapheneOS there is no cloud backup and there should be none here
either: the export is a plain file the user saves wherever they choose (USB
drive, computer, a folder synced their way), sealed with a passphrase.
## The envelope — the node's, not a second format
Backups use the node's ADR-005 encrypted-backup envelope
(`core/archipelago/src/backup/identity.rs`), byte-for-byte:
- Argon2id key derivation (RustCrypto `argon2`, default params — same as the
node's `Argon2::default()`), passphrase in, 16-byte random salt.
- ChaCha20-Poly1305 AEAD with a 12-byte random nonce.
- Envelope JSON:
`{"version": 1, "kind": "companion", "encrypted": true, "blob": "<base64(salt‖nonce‖ct)>", "timestamp": "<rfc3339>"}`
- The native code (`Android/rust/archy-fips-core/src/backup.rs`) is the same
crate family as the node's backup code; `decrypt` ignores unknown envelope
fields, so a **node** identity backup (which carries `did`/`pubkey`/`kid`)
also decrypts here — one envelope, two producers.
The encrypted payload is the companion's own JSON:
```json
{
"app": "archipelago-companion",
"payloadVersion": 1,
"appVersion": "0.5.28",
"createdAt": 1725100000,
"servers": ["<serialized ServerEntry>", …],
"active": "<serialized ServerEntry or null>",
"fips": {"secret","npub","address","peers","partyPeers","partyName","partyListen"},
"signer": {"secret": "<hex>"},
"flags": {"introSeen": true}
}
```
## Where the code lives
- **Crypto:** `Android/rust/archy-fips-core/src/backup.rs` (+ JNI
`NativeCore.backupEncrypt/Decrypt`). Host `cargo test` covers round-trip,
wrong-passphrase, tampered-blob, node-shape envelopes, and salt/nonce
freshness.
- **Payload/merge:** `BackupManager` (`Android/app/src/main/java/com/archipelago/app/data/BackupManager.kt`).
- **UI:** a hub sub-page (`ui/components/BackupSection.kt`, opened from the
three-finger hub menu like Nodes/FIPS) — SAF file picker
(`CreateDocument` for export, `OpenDocument` for import), passphrase
fields, verified-backup preview, result summary. The suggested export
name is `archy-companion-backup-YYYYMMDD-HHmmss.json`.
## Restore semantics — never silently destructive
| What | On restore |
|---|---|
| Servers | Upsert (`ServerPreferences.upsertServer`): same npub merges (even when every address changed), new ones append |
| Active server | Set only when this phone has none (the fresh-wipe case) |
| FIPS identity | Restored only when this phone has none; node peers UNION by npub (`FipsPreferences.mergePeersJson`); party peers merge by npub |
| Signer key | Restored only when this phone has none |
| introSeen flag | Restored (no re-onboarding after a restore) |
The identity rules exist because a phone that already paired has a live mesh
identity nodes peer with; swapping it in from a backup would strand the
current pairing.
## Test checklist (on-device)
- [ ] Export → file saved, `version: 1`, `kind: companion`, base64 blob ≥ 44 chars.
- [ ] Wrong passphrase on import → "wrong passphrase" error, no state change.
- [ ] Correct passphrase → preview shows the right server count; restore on a
second install (or after clearing app data) reconnects to the node
without re-pairing, mesh included.
- [ ] Re-scan the node's QR after restore → no duplicate entry.
- [ ] The old phone's password for a node restores (login works on the new phone).
## Roadmap notes (node-side, tracked separately)
Node-side storage/quota/scheduling for companion backups ("passport prime
combo") is roadmap territory — this issue's scope was the phone side. The
envelope is ready to be a drop-in for the node's existing backup RPCs when
that lands.
+108
View File
@@ -0,0 +1,108 @@
# Companion NIP-46 remote signer — the phone side of Nostr Bunker (#139)
**Status:** shipped in companion 0.5.28 (vc48). Issue: #139 ("Remote signer
with companion app?"). Background research:
[`nostr-signer-login-research.md`](nostr-signer-login-research.md) — flow B of
that document is exactly the flow this implements, with the companion playing
the role the research assigned to Amber.
## What shipped: the phone IS the bunker (remote signer)
The companion holds a nostr key (generate or import an `nsec`) and speaks
NIP-46 as the **remote signer**:
1. A NIP-46 client — the node's login page, per the research doc's flow B,
or any `nostrconnect://`-emitting app — shows its pairing QR.
2. The phone scans it (hub → **Remote Signer** → *Scan pairing QR*), or any
QR-scanner app hands the `nostrconnect://` URI over as a deep link
(registered in the manifest).
3. The phone connects to the client's relay(s), subscribes to kind-24133
events p-tagged to its own key, and sends the `connect` request carrying
the secret — the same handshake direction rust-nostr's reference bunker
uses (`NostrConnectRemoteSigner::send_connect_ack`), which is what the
node's eventual nostr-connect client will wait for.
4. Requests arrive NIP-44-encrypted. Handled methods:
- `connect` → "ack" (validates our pubkey + the pairing secret)
- `get_public_key` → our pubkey
- `describe` → method list
- `ping` → "pong"
- **`sign_event` → an approve/deny card — kind label, content, tags,
time. Nothing signs without a thumb on Approve.** Deny replies
`"denied"`; a second request while one is pending replies `"busy"`
instead of replacing the visible card.
- anything else → `"not authorized"` (nip04/nip44 encrypt/decrypt are
deliberately NOT granted in v1).
5. Responses go back over the same encrypted kind-24133 channel.
The session lives while the app does (the login handshake takes seconds);
remembered-session auto-reconnect is the research doc's deferred flow C, and
stays deferred. NIP-04 is accepted on receive as a fallback (deprecated but
still spoken by real clients); all sending is NIP-44 v2.
## Where the code lives
- **Crypto:** `Android/rust/archy-fips-core/src/nostr.rs` — nsec/npub bech32
keys, BIP-340 schnorr event signing (NIP-01 id serialization), NIP-44 v2
payloads, NIP-04 fallback, `nostrconnect://` parsing. Host `cargo test`
runs the official NIP-44 vectors (conversation/message keys, padded
lengths, byte-exact encrypt vectors), the official BIP-340 sign vectors,
and round-trip/tamper/failure cases.
- **JNI:** `com.archipelago.app.NativeCore` (same .so as the FIPS mesh).
- **Session:** `nostr/BunkerManager.kt` — OkHttp WebSocket relay client,
JSON-RPC dispatch, approve/deny state.
- **UI:** a hub sub-page (`ui/components/SignerSection.kt`, opened from the
three-finger hub menu like Nodes/FIPS) — key setup, npub/nsec display,
pairing scan, session status, the approve/deny card. The full-screen
pairing scanner (`QrGlassModal`) is hosted by NESMenu so it isn't clipped
to the panel's bounds. The `nostrconnect://` deep link routes to the
session and pops the hub open on the signer sub-page (`SignerLaunch`).
## Security notes (conscious deviations, reviewed)
- Incoming events are **not** signature-verified before decryption — the
same choice rust-nostr's reference bunker makes. The NIP-44 MAC is the
actual gate: forging content that decrypts with a valid MAC requires one
of the two conversation secrets. A future hardening pass may add event
verification first.
- The signer secret lives in app-private DataStore (same storage model as
the FIPS secret and node login passwords). It can additionally be sealed
inside an encrypted backup (see
[`companion-backup-restore.md`](companion-backup-restore.md)).
- `sign_event` approval is per-request and per-screen; there is no
"remember this client" auto-approve in v1.
## End-to-end test harness (the node side doesn't exist yet)
`Android/tools/nip46-test-client.py` plays the node's role: generates the
pairing QR in your terminal, runs the full handshake, requests
`get_public_key` + `sign_event`, and verifies the returned signature with an
independent pure-Python BIP-340 implementation (no code shared with the
phone's Rust core; both are pinned to the same official test vectors).
```bash
python3 -m venv /tmp/nip46env
/tmp/nip46env/bin/pip install websockets qrcode
/tmp/nip46env/bin/python Android/tools/nip46-test-client.py # --relay to override
```
Then on the phone: hub → Remote Signer → Generate key (once) → Scan pairing
QR → point at the terminal QR → Approve the incoming request. The harness
prints `END-TO-END PASS` when the phone-signed event verifies.
## Test checklist (on-device)
- [ ] Generate key → npub shows, copy works; import nsec → same npub.
- [ ] Harness handshake: pair → ack → `get_public_key` returns the phone's npub.
- [ ] `sign_event` request shows a legible card (kind label, content, tags);
Approve → harness verifies the schnorr signature; Deny → harness sees
`"denied"`.
- [ ] Deep link: open a `nostrconnect://…` URI from a QR app → SignerScreen
with the pairing already starting.
- [ ] Wrong/foreign QR → clear error, no state change.
## Roadmap (node-side, tracked separately)
The node-side bunker hosting/login flow (research doc flows A+B, the
`auth.login.nostr` slot, relay topology on the node's own strfry) is roadmap
territory via the `companion-agent`-labeled tracker issues; when it ships,
the phone side here already speaks its language.
+17 -8
View File
@@ -88,29 +88,29 @@ proprietary and Play-Services-backed.
## Integration sketch
> ⚠️ Coordinates and API surface below are from memory and were **not**
> verified against Maven Central — the machine this was written on had no
> network. Confirm the current artifact version and wrapper API on the first
> online Gradle sync before trusting the snippet.
> Verified 2026-08-31 against Maven Central and the wrapper source
> (`wrappers/android/zxingcpp/src/main/java/zxingcpp/BarcodeReader.kt` at
> `io.github.zxing-cpp:android:3.1.1`, the current release). Coordinates and
> API below are what the published artifact actually ships.
`Android/app/build.gradle.kts`:
```kotlin
// Replaces com.google.zxing:core for the live-camera path.
implementation("io.github.zxing-cpp:android:<pin-exact-version>")
implementation("io.github.zxing-cpp:android:3.1.1")
```
`QrCodeAnalyzer` collapses to roughly:
```kotlin
private val reader = BarcodeReader().apply {
private val reader = BarcodeReader(
options = BarcodeReader.Options(
formats = setOf(BarcodeFormat.QR_CODE),
formats = setOf(BarcodeReader.Format.QR_CODE),
tryHarder = true,
tryRotate = true,
tryInvert = true,
)
}
)
override fun analyze(image: ImageProxy) {
try {
@@ -121,6 +121,15 @@ override fun analyze(image: ImageProxy) {
}
```
API notes from the published wrapper: `BarcodeReader.read(ImageProxy)` takes
the CameraX `YUV_420_888` frame directly (it reads the Y plane + cropRect +
rotation itself — the manual crop/copy machinery really can go); options are
one constructor-argument data class; `Format.QR_CODE` is nested inside
`BarcodeReader` (not a top-level `BarcodeFormat`); results carry `text`,
`contentType`, `position` — and `lastReadTime` gives the per-call decode time
in ms, useful to measure the claimed 5–10× while evaluating. Keep
`com.google.zxing:core` for the still-image path regardless (below).
Keep `com.google.zxing:core` for now regardless: the still-image path
(`decodeQrFromUri` in `WalletQrScannerModal.kt`, used by "Upload image") and
`prewarmQrScanner` both use it, and neither is on the hot path.
+108
View File
@@ -0,0 +1,108 @@
# Incident + follow-up tracker — 2026-09-01 (post-HTTPS-work, post-LND-0.21.2 breakage)
Live incident spanning framework-pt and shorty-s after the HTTPS/launcher
work and the LND 0.18.4→0.21.2 pin bump. Root causes found on real nodes;
status updated as work lands. Each fix ships with a regression test so the
same class cannot silently return.
## A. Root causes (all verified live)
| # | Symptom | Root cause |
|---|---------|-----------|
| A1 | LND sends fail "Payment failed: Not Found" | LND 0.21 **removed** the deprecated `/v1/channels/transactions` REST route; backend still called it. Receive was fine; the "Failed to fetch" on framework-pt was A3 masking it. |
| A2 | Shorty NPM restart-loops (counter 3176) | Manifest conversion (fc68c5b6) dropped (a) the `/etc/letsencrypt` mount NPM's s6 boot demands, and (b) `NET_BIND_SERVICE` — its internal nginx binds 80/443/81 and the orchestrator runs `--cap-drop=ALL`. |
| A3 | framework-pt: every `/rpc/v1` fetch CORS-blocked, "Failed to fetch", dashboard "not responding", mempool/indeehub frames broken | nginx sent `Strict-Transport-Security: max-age=31536000; includeSubDomains` on **HTTPS**; browsers cached it, then silently upgraded the still-open **http** dashboard's fetches/frames to https → scheme change = cross-origin → CORS block. HTTP is a supported mode on purpose (self-signed cert, /ca.crt flow). |
| A4 | Mempool/IndeeHub/bitcoin-UI frames stay `http://` on HTTPS pages (mixed content, "does not connect") | `portAuth()` looked the launch port up under the launch alias (`mempool-web`, `lnd`, `bitcoin-knots`…); the signed catalog declares those ports under the manifest id that owns them (`archy-mempool-web`, `lnd-ui`, `bitcoin-ui`) → miss → launcher fell back to http. Cache also only warmed in Store/Discover views. |
| A5 | IndeeHub nostr sign-in dead over HTTPS | NIP-07 bridge compared `event.origin` for strict equality with the stored (http) app URL and replied to the **stored** URL as postMessage targetOrigin — both break when the frame was scheme-upgraded. |
| A6 | Portainer "disappeared" after restart/update, then demands a setup token "see server logs" | Update to 2.45.0 recreated the container; on a fresh DB Portainer ≥2.21 mints a one-time setup token printed ONLY in container logs — hostile appliance UX. The "disappearance" was the recreate + this unknown-token first screen. |
## B. Fixes (code)
| Fix | Files | Status |
|-----|-------|--------|
| B1 LND pay via `Router.SendPaymentV2` (`/v2/router/send`), pending-status + actionable failure reasons preserved | `core/archipelago/src/api/rpc/lnd/payments.rs` (+ unit tests) | ✅ code |
| B2 Portainer setup token surfaced in the existing credentials interstitial (`package.credentials` → AppSidebar card with copy) | `core/archipelago/src/api/rpc/package/install.rs` (+ unit tests) | ✅ code |
| B3 HSTS: none on :80, `max-age=0` on :443 (actively clears cached policy) | `image-recipe/configs/nginx-archipelago.conf` | ✅ code |
| B4 NPM manifest: `/etc/letsencrypt` mount + `NET_BIND_SERVICE` | `apps/nginx-proxy-manager/manifest.yml` | ✅ code |
| B5 `portAuth` alias resolution + unanimous port-wide fallback | `neode-ui/src/views/discover/curatedApps.ts` | ✅ code |
| B6 Catalog cache warmed at dashboard bootstrap | `neode-ui/src/App.vue` | ✅ |
| B7 NIP-07 bridge: host/port equality + reply to `event.origin` | `neode-ui/src/stores/appLauncher.ts` ✅ · `neode-ui/src/views/appSession/useNostrBridge.ts` ✅ | ✅ |
| B8 Stale LND 0.18.4 refs in test expectations | `tests/lifecycle/remote-lifecycle.sh` | ✅ |
## C. Regression tests ("never again")
| Test | Guards | Status |
|------|-------|--------|
| C1 Rust: router v2 response shape, nested errors, failure reasons | B1 | ✅ |
| C2 Rust: setup-token log extraction (live-captured 2.45.0 line shape) | B2 | ✅ |
| C3 bats: `lnd-api-compat` — POST `/v2/router/send` on the running LND must answer (never 404) | B1 vs image skew at gate time | ✅ (route probe verified live on shorty: HTTP 500 ≠ 404) |
| C4 bats: nginx must NOT send HSTS on :80; :443 must send `max-age=0` | B3 | ✅ |
| C5 neode-ui unit: portAuth alias + unanimous-scan (incl. bitcoin-knots→8334 https) | B5/B4-mixed-content | ✅ (6 tests) |
| C6 neode-ui unit: bridge origin equality ignores scheme | B7 | ✅ (2 tests) |
Backend suites: 34 targeted Rust tests green (payments v2 shape, setup-token
extraction, lnd wallet/info regressions); middleware/dispatcher suite green;
full neode-ui suite green (62 tests in the touched areas); production bundle
built and verified to embed the alias fix. `cargo fmt` applied.
## D. Deploy & live verification
| Step | Status |
|------|--------|
| D1 shorty NPM crash-loop stopped cleanly (user-stopped marker; public hosts keep serving via host nginx mirror) | ✅ 12:52Z |
| D2 shorty live nginx HSTS patch + reload | ✅ verified: :80 and :443 both answer `max-age=0` |
| D3 Regenerate catalog (releases/app-catalog.json + store copies) | ✅ semantic diff = exactly the two NPM fixes |
| D4 **User runs `scripts/sign-catalog.sh`** (signer built at /tmp/archy-sign-bin) | ✅ catalog signed + committed + pushed |
| D5 Commit + push (origin + gitea-vps2 OTA mirror) | ✅ 9 commits pushed |
| D6 Release v1.8.9-alpha: `scripts/create-release.sh 1.8.9-alpha` (mnemonic) → `scripts/publish-release-assets.sh 1.8.9-alpha gitea-vps2` | ✅ PUBLISHED (tag v1.8.9-alpha, releases/manifest.json live, backend+frontend assets verified by the script) |
| D7 OTA on shorty-s + framework-pt (Update button; shorty is on 1.8.8-alpha, daily check — hit Update now) | ⬜ user action |
| D8 shorty: clear the NPM user-stopped marker + Start (or it starts via the fixed catalog) | ✅ NPM LIVE-HEALED via the signed catalog: unit regenerated with both fixes, container up, admin UI HTTP 200 on :8081 (verified 15:42Z) |
| D9 framework-pt: Start Mempool — its containers are confirmed stopped (port 4080 refuses; gate answers on 7778/8334/50002/18083 so those apps will embed over https immediately) | ⬜ |
| D10 Post-deploy live checks: LND send+receive; mempool/IndeeHub/bitcoin-UI frames over https; NPM healthy + admin :8081 ✅; portainer token card on fresh DB; zero CORS errors | ⬜ after nodes update |
## E. Follow-ups discovered during the incident (ride the NEXT release, v1.8.10+)
- **LND channel-peer watchdog** (this release's headline platform fix): every
2 minutes the daemon reconnects peers of open channels that LND has not
re-established on its own (per-peer retry throttled to 10 minutes), using
the peer's advertised addresses from the public graph. Kills the whole
class this incident exposed — a channel unroutable ~17h after an LND update
while both nodes looked healthy. Unit tests pin the selection logic over the
live REST shapes.
- **Funding-modal honesty fix** (1464b1b2): the
Lightning "no channel" modal now states the node's real state — pending
channel confirming / balance on the far side / payment couldn't route /
genuinely no channels. Note the stale-direction defect it fixes: the
payment-failure mapper never set the direction, so a SEND failure showed
the RECEIVE-branch copy ("Receiving needs inbound liquidity…") — the exact
modal users saw while their node had a healthy 583k-outbound channel.
Both fixes have their v1.8.10 CHANGELOG + What's New entries staged so the
next `create-release.sh 1.8.10-alpha` runs clean first time.
- Nodes poll for OTA updates on `daily_check` — after publishing, tell the
user to hit Update rather than wait for the next check.
- `origin` remote had a stale pushurl with a dead token (pushes failed);
fixed to the canonical repo URL, stale `~/.git-credentials` entry with an
encoded port removed.
## F. Post-v1.8.9 verification on shorty-s (2026-09-01 evening)
- v1.8.9 applied; payment pipeline confirmed live: a 400,000 sat payment
SUCCEEDED through the v2 router route; the 404s are gone.
- App gate serves TLS on 4080/8334/18083/50002 (401 gate pages over https) —
https app frames now answer. Mempool over https requires a hard refresh
(PWA precaches the old bundle).
- **"No route to the recipient" on sends is real**: the invoices being tested
are from framework-pt, whose only channel (peer "Sandwich Farm",
0224c955…) is flagged `disabled` on BOTH policy sides in the routing graph
after today's node churn — the peer connection never re-established
(LND's reconnect backoff can stretch to hours). A disabled edge is
unroutable in both directions, so payments to/from framework-pt fail
regardless of shorty's 583k outbound. Fix: `lncli connect` the peer, wait
for the channel_update to re-enable the edge (~minutes), then re-test.
- The 577k attempt earlier failed for a different, correct reason: it exceeded
the channel's spendable balance (583,542 − 9,850 reserve ≈ 573k max).
framework-pt immediate workaround until its OTA lands: open the dashboard by
IP (`http://192.168.x.x`) instead of `framework-pt.local`, and/or clear the
cached policy once via `chrome://net-internals/#hsts` → Delete domain security
policies → `framework-pt.local`.
+299
View File
@@ -0,0 +1,299 @@
# OpenWrt Gateway Setup
How to connect an OpenWrt router to an Archipelago node and, optionally, turn
it into a pay-as-you-go WiFi gateway with **TollGate**. Written for a node
operator following the UI; a developer-facing RPC/architecture reference is
at the bottom.
This feature manages a **separate physical (or virtual) router** running
OpenWrt over SSH/UCI — it is not a containerized app. Archipelago itself does
not flash or install OpenWrt; you bring a router that already runs it.
## What you get
- **Status dashboard**: hostname, uptime, firmware release, WiFi interfaces,
WAN state — polled live from the router.
- **WAN/WISP wizard**: point the router's radio at an upstream WiFi network
(turns it into a wireless bridge/repeater) with DHCP + NAT configured for
you.
- **TollGate provisioning** (optional): installs the
[TollGate](https://tollgate.me) captive-portal package
(`tollgate-module-basic-go`) and stands up an `archipelago` SSID that
sells timed internet access for sats, settled against this node's local
Cashu mint.
## Prerequisites
1. **A router already flashed with OpenWrt.** Check the
[OpenWrt Table of Hardware](https://openwrt.org/toh/start) for your model
and follow OpenWrt's own install/flashing instructions — that part is
outside Archipelago's scope. See below for a worked example (GL.iNet
AX3000).
2. **SSH reachable.** Fresh OpenWrt images enable `dropbear` (SSH) on LAN by
default, listening as `root` with no password (or the password you set
during OpenWrt's first-boot wizard at `192.168.1.1`). Archipelago
connects with `ssh2` over a password (key-based auth is supported at the
library level but the UI only offers password so far).
3. **Same LAN as the Archipelago node**, at least for setup — plug the
router's LAN port into the same switch/network segment the node is on.
4. **For TollGate**: a running Cashu mint app (`nutshell`/`cashu-mint`) on
this node — provisioning defaults `mint_url` to
`http://<node-ip>:3338` and TollGate customers must be able to reach that
URL from outside the node's loopback.
## Worked example: flashing a GL.iNet AX3000 to stock OpenWrt
GL.iNet's "AX3000" travel router is the **Beryl AX (GL-MT3000)** —
MediaTek MT7981B (Cortex-A53), OpenWrt target `mediatek/filogic`. It ships
running a GL.iNet fork of OpenWrt with its own web UI and LuCI already
enabled, but the steps below replace that with stock/vanilla OpenWrt so it
matches the prebuilt TollGate `.ipk` architectures exactly
(`aarch64_cortex-a53`).
1. **Download the sysupgrade image** for the current stable release from
`https://downloads.openwrt.org/releases/<version>/targets/mediatek/filogic/`
— the file you want is
`openwrt-<version>-mediatek-filogic-glinet_gl-mt3000-squashfs-sysupgrade.bin`.
2. **Verify the checksum** against the `sha256sums` file in that same
directory before flashing anything.
3. **Flash from the GL.iNet UI**: on the router's default address
(`192.168.8.1`), go to **More Settings → Upgrade → Local Upgrade**, or
open **Advanced → LuCI** and use **System → Backup / Flash Firmware →
Flash new firmware image**.
4. Upload the `.bin` file. **Uncheck "Keep Settings"** — going from the
GL.iNet fork to stock OpenWrt needs a clean reset, not a config carry-over.
5. Confirm and wait ~3–5 minutes without power-cycling the router.
6. **After it reboots** you're on stock OpenWrt: LAN at `192.168.1.1`, DHCP
on, SSH (dropbear) open as `root` with **no password set yet** — set one
via LuCI at `192.168.1.1` or `passwd` over SSH before doing anything else.
From here, continue with the Prerequisites/Step 2 flow above to connect
it to the Archipelago node.
> The Archipelago UI's Connect form (Step 2) authenticates *with* a
> password — it has no flow for setting the initial one on a fresh,
> passwordless router. You have to set it out-of-band first. If you're
> working from the node's own local kiosk display rather than a normal
> desktop browser, there's no visible tab bar/address bar to open a new
> tab from — press **Ctrl+T** to open one anyway, navigate to
> `192.168.1.1`, and use LuCI's first-boot prompt to set the root
> password. Then switch back to the Archipelago tab and Connect with it.
**If the flash fails / the router doesn't come back**: filogic devices
don't use a reset-button recovery. Instead, connect to the router's LAN
port and, during boot, press a key within the first ~2 seconds to enter
U-Boot; per the OpenWrt wiki, typing `gl` then `httpd` at the U-Boot prompt
brings up a recovery web UI at `192.168.1.2` that accepts a firmware image.
## Step 1: Open the OpenWrt Gateway panel
1. In the Archipelago UI, go to **Server**.
2. Under the network status list, click **OpenWrt Gateway**
(`/dashboard/server/openwrt`).
If no router has been connected before, you'll land on the connect form.
## Step 2: Connect the router
You have two options:
- **Detect**: click **Detect** — this reads the node's own active wired
Ethernet interface, derives its subnet, and probes every host on it for
`TCP/22` + a valid `/etc/openwrt_release`. If it finds exactly one router
it fills in the host automatically; if it finds several you pick from the
list. A `/24` scan can take up to ~2 minutes (255 sequential probes at
500 ms each on hosts that don't respond).
- **Manual**: type the router's LAN IP (commonly `192.168.1.1` on a router
freshly bridged in, or whatever address it has on your network) plus the
SSH username (default `root`) and password.
Click **Connect**. On success the panel switches to the status dashboard and
the connection (host + credentials) is persisted server-side — you won't
need to re-enter them on future visits or from other views (e.g. the Home
dashboard's network tile also polls this without prompting again).
> Credentials are stored in `router_config.json` under the node's data
> directory alongside other node config. There's no separate secrets
> vault entry for this yet — treat the router's SSH password like any other
> node-local config.
## Step 3: (Optional) Configure WAN/WISP
Use this to make the OpenWrt router pull its internet connection from an
upstream WiFi network instead of a wired uplink — useful for a
battery/off-grid TollGate node or extending coverage from an existing
network.
1. From the status dashboard, start the **WAN setup** wizard.
2. **Scan** — the router's radio scans for visible networks (a few seconds
of SSH round-trips).
3. **Select network** — pick the upstream SSID from the list.
4. **Password** — enter the upstream network's WiFi password (encryption
defaults to `psk2`; leave blank only for open networks).
5. **DHCP / NAT** — review the LAN DHCP pool (default `.100`–`.249`) and
whether to enable NAT/masquerade on the WAN zone (leave this on unless
you have a specific reason not to).
6. **Connect** — this writes a `wwan` STA `wifi-iface` + `network` interface
over UCI, enables the radio if it was disabled (OpenWrt ships with
`radio0.disabled=1` on a fresh flash), and adds `wwan` to the WAN
firewall zone.
The dashboard's WAN panel shows the resulting association state, assigned
IP, and whether the router currently has internet reachability.
## Step 4: (Optional) Install TollGate
Once connected (and with a local Cashu mint app running), the dashboard
shows a **TollGate: not installed** panel with a single **Install TollGate**
button — there's no config form at this stage, it installs with defaults.
The panel itself warns: *"Router needs internet access to install TollGate
— configure WAN above first"* (Step 3), since the router has to reach the
internet to download the package.
1. Click **Install TollGate**. The button relabels to *"Installing… this
may take a few minutes"* while it works.
2. Under the hood this installs `tollgate-module-basic-go` on the router
(via `opkg` on OpenWrt ≤24.x, or a manual `.ipk` extract on 25.x images
where `opkg` isn't available), writes `/etc/tollgate/config.json`, and
creates the `archipelago` SSID — all with default pricing (10 sats per
1-minute step, minimum 1 step, `mint_url` auto-filled to
`http://<node-ip>:3338`, enabled).
3. On success you'll see *"TollGate provisioned successfully"* and the
panel switches to the installed view (Enabled/Disabled badge, current
price/step/mint).
### Configuring price, step size, or mint (after install)
The installed-state panel has an **Edit** button — this is the only place
you set price/step/mint, and it only appears once TollGate is already
installed:
1. Click **Edit**.
2. Set **Price** (sats), **Step size** (minutes — billed as `step_size_ms`
under the hood), **Minimum steps** a customer must buy at once, **Mint
URL** (leave as the auto-filled node URL unless pointing at an external
mint), and the **Enable TollGate** toggle.
3. Click **Save**. Changes are pushed to `/etc/tollgate/config.json` and the
daemon is restarted to pick them up — it does not hot-reload.
Anyone who joins the `archipelago` SSID sees TollGate's captive portal and
pays sats (via the configured Cashu mint) for timed access.
## Verifying a successful install
A clean install (flash → Connect → WAN/WISP → Install TollGate, all through
the UI as above) ends in this state — worth checking if you want to confirm
everything actually landed correctly rather than trusting the UI's success
toast alone:
- `tollgate-wrt` is running (`/etc/init.d/tollgate-wrt status` → `running`).
- nodogsplash's **rendered** config — not just the UCI source — has
`GatewayInterface br-tollgate`. Check the actual file the daemon was
started with (typically `/tmp/etc/nodogsplash_main.conf`), since that's
what's actually enforced, not `uci show nodogsplash`. This matters because
provisioning must stop nodogsplash and reconfigure it to gate the
`br-tollgate` bridge *before* starting it — installing the package by hand
(bypassing the UI/RPC flow) leaves nodogsplash on its default
`br-lan`-gating behavior instead, which locks out the router's own
admin/SSH access. If you ever see a router become unreachable right after
a TollGate install, this is the first thing to check.
- The router's own LAN (the interface you manage it over — SSH, ping) is
still reachable and untouched by the portal.
- TollGate's own log (`logread | grep tollgate-wrt`) shows successful mint
probes for each configured mint.
A `dev build detected (branch=unknown), injecting test mint:
https://nofee.testnut.cashu.space` line in that log means the installed
build considers itself a dev build and silently adds a test mint alongside
your configured one(s) — check the Edit panel's Mint URL afterward if you
don't want that test mint accepted.
### A note on network topology during setup
If the Archipelago node reaches the router over the same wired interface the
router uses as its LAN, expect the router to become the node's default
route on that interface once it has its own working WAN/WISP uplink — this
is normal and, once WAN is actually configured with internet access, works
fine end-to-end (the node's traffic routes out through the router's
uplink). It's only a problem *before* WAN is configured: a freshly flashed
or freshly factory-reset router has no upstream internet yet, so if it wins
the node's default-route race (lowest metric on its own interface) while
still offline, it creates a dead-end route and the node loses its own
connectivity (including anything tunneled, e.g. a VPN/mesh network the node
relies on) until that route is removed or the router gets its uplink
working. If you hit this, either wait until WAN/WISP is actually up before
letting the router's interface win the route race, or temporarily lower the
priority of that route until it is.
## Reconfiguring or moving to a different router
Use **Disconnect** on the status dashboard to return to the connect form —
this only clears the panel's client-side state, it doesn't delete the
persisted `router_config.json`, so reconnecting to the same router needs no
re-entry. To point at a *different* router, disconnect and connect with a
new host/credentials; the newly connected router becomes the persisted one.
## Troubleshooting
- **"No router configured"**: nothing has been connected yet, or the saved
config didn't include a host — go through Step 2 again.
- **Connect hangs or times out**: the router isn't reachable on `TCP/22`
from the node's network, or SSH auth failed. Confirm you can `ssh
root@<router-ip>` manually from the node (or a machine on the same LAN)
with the same credentials.
- **Router "moved networks" / stale saved host**: SSH/status calls are
bounded (5s TCP connect, 30s read/write) precisely so an unreachable
saved router can't stall other RPCs — but the dashboard will show a
connection error until you reconnect with the router's current address.
- **TollGate provision fails with "No pre-built TollGate package for
architecture..."**: your router's SoC isn't one of the prebuilt
`.ipk` targets (`mips_24kc`, `mipsel_24kc`, `aarch64_cortex-a53`,
`aarch64_cortex-a72`, `arm_cortex-a7`). You'll need a custom opkg feed or
to build `tollgate-module-basic-go` from source for your architecture.
- **TollGate download looks like it succeeded but provisioning still
fails**: the node sanity-checks the downloaded `.ipk` is at least 50 KB —
a smaller file usually means `wget` captured an HTML error page instead
(no internet access from the router, or a bad release URL).
- **Install fails right after a reboot or a fresh WAN setup** with `apk
update failed ... router may have no internet access` even though WAN
looks configured: this is usually just timing, not a real problem — the
router's WiFi-uplink association (`wwan`/`hakodosh`-style STA interface)
can take a few seconds longer to reconnect than the dashboard takes to
let you click Install. Wait ~10–15 seconds after WAN shows `sta_state:
up` and retry; it should succeed on the next attempt.
- **Install fails with `opkg not found at /usr/bin/opkg` (or similar) even
though the router clearly has `opkg`/`apk` installed**: fixed as of
2026-09-05 — the backend used to hardcode `/usr/bin/opkg`/`/usr/bin/apk`,
which some official OpenWrt builds don't symlink into `/bin`. If you're
running an Archipelago build from before that fix, update first.
---
## Developer reference
Backend crate: `core/openwrt` (`archipelago-openwrt`) — SSH/UCI plumbing,
WAN/WISP config, WiFi scanning, and TollGate install/config. See
[`architecture.md`](architecture.md) for where it sits in the workspace.
RPC methods (`core/archipelago/src/api/rpc/openwrt.rs`, dispatched in
`core/archipelago/src/api/rpc/dispatcher.rs`):
| Method | Purpose |
|---|---|
| `openwrt.scan` | Probe a subnet for OpenWrt routers (`subnet`, `prefix`, `ssh_user`, `ssh_password`) |
| `openwrt.get-status` | Full status: release, WiFi interfaces, WAN, TollGate state. No params → uses saved `router_config.json`; params with `host` also persist the connection |
| `openwrt.configure-wan` | Write WISP/WAN config (`ssid`, `password`, `encryption`, `dhcp_start`, `dhcp_limit`, `masq`) |
| `openwrt.scan-wifi` | Radio scan for visible upstream networks |
| `openwrt.provision-tollgate` | Install/reconfigure TollGate (`price_sats`, `step_size_ms`, `min_steps`, `mint_url`, `enabled`) |
Note: these are distinct from the unrelated `router.*` methods
(`router.discover`, `router.configure`, `router.list-forwards`, ...), which
handle UPnP/NAT-PMP port forwarding on the node's own upstream home router —
not the OpenWrt gateway feature described here.
Frontend: `neode-ui/src/views/server/OpenWrtGateway.vue`, routed at
`server/openwrt` (`neode-ui/src/router/index.ts`), linked from
`neode-ui/src/views/Server.vue`.
Persisted connection state: `router_config.json` in the node's data
directory (`core/archipelago/src/network/router.rs`:
`load_router_config`/`save_router_config`).
@@ -573,7 +573,7 @@ RUN mkdir -p /etc/polkit-1/rules.d && \
# already-deployed nodes over OTA (idempotent no-op here once applied).
RUN set -eu; \
apt-get update; \
apt-get install -y --no-install-recommends kdump-tools kexec-tools rasdaemon; \
apt-get install -y --no-install-recommends kdump-tools kexec-tools makedumpfile rasdaemon; \
apt-get clean; rm -rf /var/lib/apt/lists/*; \
CONF=/etc/default/kdump-tools; \
sed -i 's|^#\?USE_KDUMP=.*|USE_KDUMP="1"|' "$CONF"; \
+16 -2
View File
@@ -34,7 +34,14 @@ server {
add_header X-Frame-Options "SAMEORIGIN" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=(), payment=()" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
# NO HSTS on this node, by design (see the HTTPS block below for the
# active clear). The dashboard is deliberately reachable over plain
# HTTP on LANs/mDNS names where users have not installed the node CA —
# setup-node-ca.sh keeps port 80 serving for exactly that reason. A
# long-cache HSTS policy upgrades an already-open HTTP page's fetches to
# HTTPS; that scheme change is cross-origin, so every /rpc/v1 call died
# with "No Access-Control-Allow-Origin header" while the node was
# perfectly healthy (framework-pt, 2026-09-01: "Failed to fetch" storm).
add_header X-DNS-Prefetch-Control "off" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https://*.basemaps.cartocdn.com https://tile.openstreetmap.org; font-src 'self' data:; connect-src 'self' ws: wss: http://$host:* https:; frame-src 'self' http://$host:* https:; frame-ancestors 'self'; base-uri 'self'; form-action 'self';" always;
@@ -1009,7 +1016,14 @@ server {
add_header X-Frame-Options "SAMEORIGIN" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=(), payment=()" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
# HSTS actively CLEARED (max-age=0), not set: this origin's certificate is
# optional/self-signed and plain-HTTP access is a supported mode. Earlier
# builds sent max-age=31536000 includeSubDomains, and browsers that had
# visited HTTPS once kept silently upgrading the HTTP dashboard's
# subresources afterwards — every fetch became cross-origin by scheme and
# was CORS-blocked. max-age=0 over HTTPS deletes that cached policy;
# never raise it on this origin unless HTTP access is retired first.
add_header Strict-Transport-Security "max-age=0" always;
add_header X-DNS-Prefetch-Control "off" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https://*.basemaps.cartocdn.com https://tile.openstreetmap.org; font-src 'self' data:; connect-src 'self' ws: wss: http://$host:* https:; frame-src 'self' http://$host:* https:; frame-ancestors 'self'; base-uri 'self'; form-action 'self';" always;
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "neode-ui",
"version": "1.8.5-alpha",
"version": "1.8.10-alpha",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "neode-ui",
"version": "1.8.5-alpha",
"version": "1.8.10-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.8.5-alpha",
"version": "1.8.10-alpha",
"type": "module",
"scripts": {
"start": "./start-dev.sh",
+409 -373
View File
@@ -11,16 +11,47 @@
},
"apps": [
{
"id": "bitcoin-knots",
"title": "Bitcoin Knots",
"version": "28.1.0",
"description": "Full Bitcoin Knots node with dynamic prune/full-mode startup based on host disk.",
"icon": "/assets/img/app-icons/bitcoin-knots.webp",
"author": "Bitcoin Knots",
"id": "adguardhome",
"title": "AdGuard Home",
"version": "v0.107.79",
"description": "Network-wide ad and tracker blocking: a DNS server that filters every device on your LAN, with a web console for rules and client management.",
"icon": "",
"author": "AdGuard",
"category": "networking",
"tier": "optional",
"dockerImage": "source.archipelago-foundation.org/lfg2025/adguardhome:v0.107.79",
"repoUrl": "https://github.com/AdguardTeam/AdGuardHome"
},
{
"id": "alby-hub",
"title": "Alby Hub",
"version": "1.23.0",
"description": "Self-custodial Lightning wallet hub. Runs its own Lightning node on your Archipelago and connects your apps to it over Nostr Wallet Connect — one hub, every app pays through it.",
"icon": "/assets/img/app-icons/alby-hub.svg",
"author": "Alby",
"category": "money",
"tier": "core",
"dockerImage": "source.archipelago-foundation.org/lfg2025/bitcoin-knots:29.3.knots20260210",
"repoUrl": "https://github.com/bitcoinknots/bitcoin"
"tier": "optional",
"dockerImage": "source.archipelago-foundation.org/lfg2025/alby-hub:v1.24.0",
"repoUrl": "https://github.com/getAlby/hub"
},
{
"id": "barkd",
"title": "Ark Wallet",
"version": "0.3.0",
"description": "Ark protocol wallet daemon (barkd). Lets the node hold self-custodial off-chain bitcoin via an Ark server; the wallet talks to it over a local REST API. Signet by default while Ark matures.",
"icon": "/assets/img/app-icons/bark.png",
"author": "Second",
"category": "money",
"dockerImage": "source.archipelago-foundation.org/lfg2025/barkd:0.3.0",
"repoUrl": "https://gitlab.com/ark-bitcoin/bark",
"containerConfig": {
"ports": [
"3535:3535"
],
"volumes": [
"/var/lib/archipelago/barkd:/data"
]
}
},
{
"id": "bitcoin-core",
@@ -35,76 +66,16 @@
"repoUrl": "https://github.com/bitcoin/bitcoin"
},
{
"id": "lnd",
"title": "LND",
"version": "0.18.4",
"description": "Lightning Network implementation by Lightning Labs. Enables instant, low-cost Bitcoin payments.",
"icon": "/assets/img/app-icons/lnd.png",
"author": "Lightning Labs",
"id": "bitcoin-knots",
"title": "Bitcoin Knots",
"version": "28.1.0",
"description": "Full Bitcoin Knots node with dynamic prune/full-mode startup based on host disk.",
"icon": "/assets/img/app-icons/bitcoin-knots.webp",
"author": "Bitcoin Knots",
"category": "money",
"tier": "core",
"dockerImage": "source.archipelago-foundation.org/lfg2025/lnd:v0.18.4-beta",
"repoUrl": "https://github.com/lightningnetwork/lnd",
"requires": [
"bitcoin-knots"
]
},
{
"id": "btcpay-server",
"title": "BTCPay Server",
"version": "2.4.3",
"description": "Self-hosted Bitcoin payment processor. Accept Bitcoin payments without intermediaries.",
"icon": "/assets/img/app-icons/btcpay-server.png",
"author": "BTCPay Server Foundation",
"category": "commerce",
"tier": "core",
"dockerImage": "docker.io/btcpayserver/btcpayserver:2.4.3",
"repoUrl": "https://github.com/btcpayserver/btcpayserver",
"requires": [
"bitcoin-knots"
]
},
{
"id": "mempool",
"title": "Mempool Explorer",
"version": "3.0.0",
"description": "Bitcoin mempool and blockchain explorer. Real-time transaction and block visualization.",
"icon": "/assets/img/app-icons/mempool.webp",
"author": "Mempool",
"category": "money",
"tier": "core",
"dockerImage": "source.archipelago-foundation.org/lfg2025/mempool-frontend:v3.3.1",
"repoUrl": "https://github.com/mempool/mempool",
"requires": [
"bitcoin-knots",
"electrumx"
]
},
{
"id": "electrumx",
"title": "ElectrumX",
"version": "1.18.0",
"description": "Electrum server indexing Bitcoin chain data for lightweight wallet queries.",
"icon": "/assets/img/app-icons/electrumx.png",
"author": "Luke Childs",
"category": "money",
"tier": "core",
"dockerImage": "source.archipelago-foundation.org/lfg2025/electrumx:v1.18.0",
"repoUrl": "https://github.com/spesmilo/electrumx",
"requires": [
"bitcoin-knots"
]
},
{
"id": "indeedhub",
"title": "IndeeHub",
"version": "1.0.0",
"description": "Bitcoin documentary streaming platform featuring God Bless Bitcoin and other educational content about Bitcoin, sovereignty, and decentralized technology. Sign in with your Nostr identity.",
"icon": "/assets/img/app-icons/indeedhub.png",
"author": "IndeeHub",
"category": "community",
"dockerImage": "source.archipelago-foundation.org/lfg2025/indeedhub:1.0.0",
"repoUrl": "https://github.com/indeedhub/indeedhub"
"dockerImage": "source.archipelago-foundation.org/lfg2025/bitcoin-knots:29.3.knots20260210",
"repoUrl": "https://github.com/bitcoinknots/bitcoin"
},
{
"id": "botfights",
@@ -132,127 +103,46 @@
}
},
{
"id": "gitea",
"title": "Gitea",
"version": "1.23",
"description": "Self-hosted Git service with built-in container registry, CI/CD, and package hosting.",
"icon": "/assets/img/app-icons/gitea.svg",
"author": "Gitea",
"category": "development",
"dockerImage": "docker.io/gitea/gitea:1.23",
"repoUrl": "https://gitea.com",
"containerConfig": {
"ports": [
"3001:3000",
"2222:22"
],
"volumes": [
"/var/lib/archipelago/gitea/data:/data",
"/var/lib/archipelago/gitea/config:/etc/gitea"
],
"env": [
"GITEA__database__DB_TYPE=sqlite3",
"GITEA__server__SSH_PORT=2222",
"GITEA__server__SSH_LISTEN_PORT=22",
"GITEA__server__LFS_START_SERVER=true",
"GITEA__packages__ENABLED=true",
"GITEA__repository__ENABLE_PUSH_CREATE_USER=true",
"GITEA__repository__ENABLE_PUSH_CREATE_ORG=true",
"GITEA__security__X_FRAME_OPTIONS="
]
},
"tier": "optional"
},
{
"id": "filebrowser",
"title": "File Browser",
"version": "2.27.0",
"description": "Baseline Archipelago file manager service.",
"icon": "/assets/img/app-icons/file-browser.webp",
"author": "File Browser",
"category": "data",
"id": "btcpay-server",
"title": "BTCPay Server",
"version": "2.4.3",
"description": "Self-hosted Bitcoin payment processor. Accept Bitcoin payments without intermediaries.",
"icon": "/assets/img/app-icons/btcpay-server.png",
"author": "BTCPay Server Foundation",
"category": "commerce",
"tier": "core",
"dockerImage": "source.archipelago-foundation.org/lfg2025/filebrowser:v2.27.0",
"repoUrl": "https://github.com/filebrowser/filebrowser",
"containerConfig": {
"ports": [
"8083:80"
],
"volumes": [
"/var/lib/archipelago/filebrowser:/srv",
"/var/lib/archipelago/filebrowser-data:/data"
],
"args": [
"--database=/data/database.db",
"--root=/srv",
"--address=0.0.0.0",
"--port=80"
]
}
"dockerImage": "docker.io/btcpayserver/btcpayserver:2.4.3",
"repoUrl": "https://github.com/btcpayserver/btcpayserver",
"requires": [
"bitcoin-knots"
]
},
{
"id": "nostr-rs-relay",
"title": "Nostr Relay (Rust)",
"version": "0.10.0",
"description": "High-performance Nostr relay written in Rust. Host your own decentralized social media relay and earn networking profits.",
"icon": "/assets/img/app-icons/nostrudel.svg",
"author": "Nostr RS Relay",
"category": "community",
"tier": "recommended",
"dockerImage": "scsibug/nostr-rs-relay:0.10.0",
"repoUrl": "https://github.com/scsibug/nostr-rs-relay",
"containerConfig": {
"ports": [
"8081:8080"
],
"volumes": [
"/var/lib/archipelago/nostr-relay:/usr/src/app/db"
],
"env": [
"RELAY_NAME=Archipelago Nostr Relay",
"RELAY_DESCRIPTION=Self-hosted Nostr relay on Archipelago"
]
}
"id": "cuprate",
"title": "Cuprate",
"version": "0.1.0-preview",
"description": "Alternative Monero node implementation in Rust. Independently validates Monero consensus rules, providing a layer of security and redundancy for the network.",
"icon": "/assets/img/app-icons/cuprate.svg",
"author": "Cuprate contributors",
"category": "money",
"tier": "optional",
"dockerImage": "source.archipelago-foundation.org/lfg2025/cuprate:0.1.0-preview-18-g618ff14",
"repoUrl": "https://github.com/Cuprate/cuprate"
},
{
"id": "vaultwarden",
"title": "Vaultwarden",
"version": "1.30.0",
"description": "Self-hosted password vault with zero-knowledge encryption.",
"icon": "/assets/img/app-icons/vaultwarden.webp",
"author": "Vaultwarden",
"category": "data",
"tier": "recommended",
"dockerImage": "source.archipelago-foundation.org/lfg2025/vaultwarden:1.37.1-alpine",
"repoUrl": "https://github.com/dani-garcia/vaultwarden",
"containerConfig": {
"ports": [
"8082:80"
],
"volumes": [
"/var/lib/archipelago/vaultwarden:/data"
]
}
},
{
"id": "searxng",
"title": "SearXNG",
"version": "1.0.0",
"description": "Privacy-respecting metasearch engine. Search the web without tracking.",
"icon": "/assets/img/app-icons/searxng.png",
"author": "SearXNG",
"category": "data",
"tier": "recommended",
"dockerImage": "source.archipelago-foundation.org/lfg2025/searxng:latest",
"repoUrl": "https://github.com/searxng/searxng",
"containerConfig": {
"ports": [
"8888:8080"
],
"volumes": [
"/var/lib/archipelago/searxng:/etc/searxng"
]
}
"id": "electrumx",
"title": "ElectrumX",
"version": "1.18.0",
"description": "Electrum server indexing Bitcoin chain data for lightweight wallet queries.",
"icon": "/assets/img/app-icons/electrumx.png",
"author": "Luke Childs",
"category": "money",
"tier": "core",
"dockerImage": "source.archipelago-foundation.org/lfg2025/electrumx:v1.18.0",
"repoUrl": "https://github.com/spesmilo/electrumx",
"requires": [
"bitcoin-knots"
]
},
{
"id": "fedimint",
@@ -299,87 +189,63 @@
}
},
{
"id": "barkd",
"title": "Ark Wallet",
"version": "0.3.0",
"description": "Ark protocol wallet daemon (barkd). Lets the node hold self-custodial off-chain bitcoin via an Ark server; the wallet talks to it over a local REST API. Signet by default while Ark matures.",
"icon": "/assets/img/app-icons/bark.png",
"author": "Second",
"category": "money",
"dockerImage": "source.archipelago-foundation.org/lfg2025/barkd:0.3.0",
"repoUrl": "https://gitlab.com/ark-bitcoin/bark",
"id": "filebrowser",
"title": "File Browser",
"version": "2.63.23",
"description": "Baseline Archipelago file manager service.",
"icon": "/assets/img/app-icons/file-browser.webp",
"author": "File Browser",
"category": "data",
"tier": "core",
"dockerImage": "source.archipelago-foundation.org/lfg2025/filebrowser:v2.63.23",
"repoUrl": "https://github.com/filebrowser/filebrowser",
"containerConfig": {
"ports": [
"3535:3535"
"8083:80"
],
"volumes": [
"/var/lib/archipelago/barkd:/data"
"/var/lib/archipelago/filebrowser:/srv",
"/var/lib/archipelago/filebrowser-data:/data"
],
"args": [
"--database=/data/database.db",
"--root=/srv",
"--address=0.0.0.0",
"--port=80"
]
}
},
{
"id": "jellyfin",
"title": "Jellyfin",
"version": "10.8.13",
"description": "Free media server. Stream movies, music, and photos.",
"icon": "/assets/img/app-icons/jellyfin.webp",
"author": "Jellyfin",
"category": "data",
"dockerImage": "source.archipelago-foundation.org/lfg2025/jellyfin:10.11.11",
"repoUrl": "https://github.com/jellyfin/jellyfin",
"id": "gitea",
"title": "Gitea",
"version": "1.27.3",
"description": "Self-hosted Git service with built-in container registry, CI/CD, and package hosting.",
"icon": "/assets/img/app-icons/gitea.svg",
"author": "Gitea",
"category": "development",
"dockerImage": "source.archipelago-foundation.org/lfg2025/gitea:1.27.3",
"repoUrl": "https://gitea.com",
"containerConfig": {
"ports": [
"8096:8096"
"3001:3000",
"2222:22"
],
"volumes": [
"/var/lib/archipelago/jellyfin/config:/config",
"/var/lib/archipelago/jellyfin/cache:/cache"
]
}
},
{
"id": "immich",
"title": "Immich",
"version": "2.7.4",
"description": "Self-hosted photo and video backup with mobile apps and search.",
"icon": "/assets/img/app-icons/immich.png",
"author": "Immich",
"category": "data",
"dockerImage": "source.archipelago-foundation.org/lfg2025/immich-server:release",
"repoUrl": "https://github.com/immich-app/immich"
},
{
"id": "homeassistant",
"title": "Home Assistant",
"version": "2026.7.3",
"description": "Open source home automation platform. Control and monitor your smart home devices.",
"icon": "/assets/img/app-icons/homeassistant.png",
"author": "Home Assistant",
"category": "home",
"dockerImage": "source.archipelago-foundation.org/lfg2025/home-assistant:2026.8.2",
"repoUrl": "https://github.com/home-assistant/core",
"containerConfig": {
"ports": [
"8123:8123"
],
"volumes": [
"/var/lib/archipelago/home-assistant:/config"
"/var/lib/archipelago/gitea/data:/data",
"/var/lib/archipelago/gitea/config:/etc/gitea"
],
"env": [
"TZ=UTC"
"GITEA__database__DB_TYPE=sqlite3",
"GITEA__server__SSH_PORT=2222",
"GITEA__server__SSH_LISTEN_PORT=22",
"GITEA__server__LFS_START_SERVER=true",
"GITEA__packages__ENABLED=true",
"GITEA__repository__ENABLE_PUSH_CREATE_USER=true",
"GITEA__repository__ENABLE_PUSH_CREATE_ORG=true",
"GITEA__security__X_FRAME_OPTIONS="
]
}
},
{
"id": "pine",
"title": "Pine",
"version": "1.3.0",
"description": "A private voice assistant for your home. Pine runs speech-to-text (Whisper), text-to-speech (Piper) and wake-word detection (openWakeWord) on your own node and pairs with a PineVoice satellite speaker, so Home Assistant Assist works locally with nothing sent to the cloud. Ask it about your node — block height, sync, peers, Lightning balance — and, when a Claude API key is set, anything else.",
"icon": "/assets/img/app-icons/pine.svg",
"author": "Archipelago",
"category": "home",
"dockerImage": "docker.io/library/nginx:1.31.4-alpine",
"repoUrl": "https://github.com/rhasspy/wyoming"
},
"tier": "optional"
},
{
"id": "grafana",
@@ -405,6 +271,279 @@
]
}
},
{
"id": "homeassistant",
"title": "Home Assistant",
"version": "2026.8.3",
"description": "Open source home automation platform. Control and monitor your smart home devices.",
"icon": "/assets/img/app-icons/homeassistant.png",
"author": "Home Assistant",
"category": "home",
"dockerImage": "source.archipelago-foundation.org/lfg2025/home-assistant:2026.8.3",
"repoUrl": "https://github.com/home-assistant/core",
"containerConfig": {
"ports": [
"8123:8123"
],
"volumes": [
"/var/lib/archipelago/home-assistant:/config"
],
"env": [
"TZ=UTC"
]
}
},
{
"id": "immich",
"title": "Immich",
"version": "2.7.4",
"description": "Self-hosted photo and video backup with mobile apps and search.",
"icon": "/assets/img/app-icons/immich.png",
"author": "Immich",
"category": "data",
"dockerImage": "source.archipelago-foundation.org/lfg2025/immich-server:release",
"repoUrl": "https://github.com/immich-app/immich"
},
{
"id": "indeedhub",
"title": "IndeeHub",
"version": "1.0.0",
"description": "Bitcoin documentary streaming platform featuring God Bless Bitcoin and other educational content about Bitcoin, sovereignty, and decentralized technology. Sign in with your Nostr identity.",
"icon": "/assets/img/app-icons/indeedhub.png",
"author": "IndeeHub",
"category": "community",
"dockerImage": "source.archipelago-foundation.org/lfg2025/indeedhub:1.0.0",
"repoUrl": "https://github.com/indeedhub/indeedhub"
},
{
"id": "jellyfin",
"title": "Jellyfin",
"version": "10.8.13",
"description": "Free media server. Stream movies, music, and photos.",
"icon": "/assets/img/app-icons/jellyfin.webp",
"author": "Jellyfin",
"category": "data",
"dockerImage": "source.archipelago-foundation.org/lfg2025/jellyfin:10.11.11",
"repoUrl": "https://github.com/jellyfin/jellyfin",
"containerConfig": {
"ports": [
"8096:8096"
],
"volumes": [
"/var/lib/archipelago/jellyfin/config:/config",
"/var/lib/archipelago/jellyfin/cache:/cache"
]
}
},
{
"id": "lnd",
"title": "LND",
"version": "0.21.2",
"description": "Lightning Network implementation by Lightning Labs. Enables instant, low-cost Bitcoin payments.",
"icon": "/assets/img/app-icons/lnd.png",
"author": "Lightning Labs",
"category": "money",
"tier": "core",
"dockerImage": "source.archipelago-foundation.org/lfg2025/lnd:v0.21.2-beta",
"repoUrl": "https://github.com/lightningnetwork/lnd",
"requires": [
"bitcoin-knots"
]
},
{
"id": "mempool",
"title": "Mempool Explorer",
"version": "3.0.0",
"description": "Bitcoin mempool and blockchain explorer. Real-time transaction and block visualization.",
"icon": "/assets/img/app-icons/mempool.webp",
"author": "Mempool",
"category": "money",
"tier": "core",
"dockerImage": "source.archipelago-foundation.org/lfg2025/mempool-frontend:v3.3.1",
"repoUrl": "https://github.com/mempool/mempool",
"requires": [
"bitcoin-knots",
"electrumx"
]
},
{
"id": "netbird",
"title": "NetBird",
"version": "2.38.0",
"description": "Self-hosted WireGuard mesh VPN control plane with dashboard, embedded identity provider, management API, signal, relay, and STUN. The user-facing entry point — a TLS proxy in front of the dashboard + server.",
"icon": "/assets/img/app-icons/netbird.svg",
"author": "NetBird",
"category": "networking",
"tier": "recommended",
"dockerImage": "docker.io/library/nginx:1.31.4-alpine",
"repoUrl": "https://github.com/netbirdio/netbird",
"containerConfig": {
"ports": [
"8087:80",
"8086:80",
"3478:3478/udp"
],
"volumes": [
"/var/lib/archipelago/netbird:/var/lib/netbird"
],
"notes": "Installed as a two-container stack: netbird dashboard on 8087 and netbird-server control plane on 8086 plus UDP 3478. For production clients, publish a DNS name over HTTPS with gRPC/WebSocket routing."
}
},
{
"id": "nextcloud",
"title": "Nextcloud",
"version": "29",
"description": "Your own private cloud. File sync, calendars, contacts.",
"icon": "/assets/img/app-icons/nextcloud.webp",
"author": "Nextcloud",
"category": "data",
"dockerImage": "source.archipelago-foundation.org/lfg2025/nextcloud:29",
"repoUrl": "https://github.com/nextcloud/server",
"containerConfig": {
"ports": [
"8085:80"
],
"volumes": [
"/var/lib/archipelago/nextcloud:/var/www/html"
]
}
},
{
"id": "nginx-proxy-manager",
"title": "Nginx Proxy Manager",
"version": "2.12.1",
"description": "Reverse proxy with SSL. Beautiful web interface for managing proxies. On a node, this manages its admin UI and upstream configuration — the proxy's own :80/:443 listeners are not published (the node's web server owns those ports).",
"icon": "/assets/img/app-icons/nginx.svg",
"author": "Nginx Proxy Manager",
"category": "networking",
"tier": "optional",
"dockerImage": "source.archipelago-foundation.org/lfg2025/nginx-proxy-manager:latest",
"repoUrl": "https://github.com/NginxProxyManager/nginx-proxy-manager"
},
{
"id": "nostr-rs-relay",
"title": "Nostr Relay (Rust)",
"version": "0.10.0",
"description": "High-performance Nostr relay written in Rust. Host your own decentralized social media relay and earn networking profits.",
"icon": "/assets/img/app-icons/nostrudel.svg",
"author": "Nostr RS Relay",
"category": "community",
"tier": "recommended",
"dockerImage": "scsibug/nostr-rs-relay:0.10.0",
"repoUrl": "https://github.com/scsibug/nostr-rs-relay",
"containerConfig": {
"ports": [
"8081:8080"
],
"volumes": [
"/var/lib/archipelago/nostr-relay:/usr/src/app/db"
],
"env": [
"RELAY_NAME=Archipelago Nostr Relay",
"RELAY_DESCRIPTION=Self-hosted Nostr relay on Archipelago"
]
}
},
{
"id": "ollama",
"title": "Ollama",
"version": "0.5.4",
"description": "Run large language models locally. Download and run AI models like Llama, Mistral on your own hardware — served on the node's loopback for the AI assistant (Settings → Claude Auth → model backend), never exposed to the network.",
"icon": "/assets/img/app-icons/ollama.png",
"author": "Ollama",
"category": "community",
"tier": "optional",
"dockerImage": "source.archipelago-foundation.org/lfg2025/ollama:latest",
"repoUrl": "https://github.com/ollama/ollama"
},
{
"id": "phoenixd",
"title": "phoenixd",
"version": "0.9.0",
"description": "Headless Lightning daemon by ACINQ (the Phoenix wallet team). No screen of its own — it exposes a small local API that other apps and tools use to send and receive Lightning payments. Channel liquidity is managed automatically for a fee.",
"icon": "/assets/img/app-icons/phoenixd.svg",
"author": "ACINQ",
"category": "money",
"tier": "optional",
"dockerImage": "source.archipelago-foundation.org/lfg2025/phoenixd:0.9.0",
"repoUrl": "https://github.com/ACINQ/phoenixd"
},
{
"id": "photoprism",
"title": "PhotoPrism",
"version": "240915",
"description": "AI-powered photo management with facial recognition.",
"icon": "/assets/img/app-icons/photoprism.svg",
"author": "PhotoPrism",
"category": "data",
"dockerImage": "source.archipelago-foundation.org/lfg2025/photoprism:240915",
"repoUrl": "https://github.com/photoprism/photoprism",
"containerConfig": {
"ports": [
"2342:2342"
],
"volumes": [
"/var/lib/archipelago/photoprism:/photoprism/storage"
],
"env": [
"PHOTOPRISM_ADMIN_PASSWORD=archipelago",
"PHOTOPRISM_DEFAULT_LOCALE=en"
]
}
},
{
"id": "pine",
"title": "Pine",
"version": "1.3.0",
"description": "A private voice assistant for your home. Pine runs speech-to-text (Whisper), text-to-speech (Piper) and wake-word detection (openWakeWord) on your own node and pairs with a PineVoice satellite speaker, so Home Assistant Assist works locally with nothing sent to the cloud. Ask it about your node — block height, sync, peers, Lightning balance — and, when a Claude API key is set, anything else.",
"icon": "/assets/img/app-icons/pine.svg",
"author": "Archipelago",
"category": "home",
"dockerImage": "docker.io/library/nginx:1.31.4-alpine",
"repoUrl": "https://github.com/rhasspy/wyoming"
},
{
"id": "portainer",
"title": "Portainer",
"version": "2.45.0",
"description": "Container management web UI for the local Podman socket.",
"icon": "/assets/img/app-icons/portainer.webp",
"author": "Portainer",
"category": "development",
"tier": "optional",
"dockerImage": "source.archipelago-foundation.org/lfg2025/portainer:2.45.0",
"repoUrl": "https://github.com/portainer/portainer",
"containerConfig": {
"ports": [
"9000:9000"
],
"volumes": [
"/var/lib/archipelago/portainer:/data",
"/run/user/1000/podman/podman.sock:/var/run/docker.sock"
],
"notes": "Uses the manifest-owned Podman socket bind mount preparation path."
}
},
{
"id": "searxng",
"title": "SearXNG",
"version": "1.0.0",
"description": "Privacy-respecting metasearch engine. Search the web without tracking.",
"icon": "/assets/img/app-icons/searxng.png",
"author": "SearXNG",
"category": "data",
"tier": "recommended",
"dockerImage": "source.archipelago-foundation.org/lfg2025/searxng:latest",
"repoUrl": "https://github.com/searxng/searxng",
"containerConfig": {
"ports": [
"8888:8080"
],
"volumes": [
"/var/lib/archipelago/searxng:/etc/searxng"
]
}
},
{
"id": "tailscale",
"title": "Tailscale",
@@ -433,51 +572,6 @@
]
}
},
{
"id": "portainer",
"title": "Portainer",
"version": "2.19.4",
"description": "Container management web UI for the local Podman socket.",
"icon": "/assets/img/app-icons/portainer.webp",
"author": "Portainer",
"category": "development",
"tier": "optional",
"dockerImage": "source.archipelago-foundation.org/lfg2025/portainer:2.39.6",
"repoUrl": "https://github.com/portainer/portainer",
"containerConfig": {
"ports": [
"9000:9000"
],
"volumes": [
"/var/lib/archipelago/portainer:/data",
"/run/user/1000/podman/podman.sock:/var/run/docker.sock"
],
"notes": "Uses the manifest-owned Podman socket bind mount preparation path."
}
},
{
"id": "netbird",
"title": "NetBird",
"version": "2.38.0",
"description": "Self-hosted WireGuard mesh VPN control plane with dashboard, embedded identity provider, management API, signal, relay, and STUN. The user-facing entry point — a TLS proxy in front of the dashboard + server.",
"icon": "/assets/img/app-icons/netbird.svg",
"author": "NetBird",
"category": "networking",
"tier": "recommended",
"dockerImage": "docker.io/library/nginx:1.31.4-alpine",
"repoUrl": "https://github.com/netbirdio/netbird",
"containerConfig": {
"ports": [
"8087:80",
"8086:80",
"3478:3478/udp"
],
"volumes": [
"/var/lib/archipelago/netbird:/var/lib/netbird"
],
"notes": "Installed as a two-container stack: netbird dashboard on 8087 and netbird-server control plane on 8086 plus UDP 3478. For production clients, publish a DNS name over HTTPS with gRPC/WebSocket routing."
}
},
{
"id": "uptime-kuma",
"title": "Uptime Kuma",
@@ -507,82 +601,24 @@
}
},
{
"id": "photoprism",
"title": "PhotoPrism",
"version": "240915",
"description": "AI-powered photo management with facial recognition.",
"icon": "/assets/img/app-icons/photoprism.svg",
"author": "PhotoPrism",
"id": "vaultwarden",
"title": "Vaultwarden",
"version": "1.37.2",
"description": "Self-hosted password vault with zero-knowledge encryption.",
"icon": "/assets/img/app-icons/vaultwarden.webp",
"author": "Vaultwarden",
"category": "data",
"dockerImage": "source.archipelago-foundation.org/lfg2025/photoprism:240915",
"repoUrl": "https://github.com/photoprism/photoprism",
"tier": "recommended",
"dockerImage": "source.archipelago-foundation.org/lfg2025/vaultwarden:1.37.2-alpine",
"repoUrl": "https://github.com/dani-garcia/vaultwarden",
"containerConfig": {
"ports": [
"2342:2342"
"8082:80"
],
"volumes": [
"/var/lib/archipelago/photoprism:/photoprism/storage"
],
"env": [
"PHOTOPRISM_ADMIN_PASSWORD=archipelago",
"PHOTOPRISM_DEFAULT_LOCALE=en"
"/var/lib/archipelago/vaultwarden:/data"
]
}
},
{
"id": "nextcloud",
"title": "Nextcloud",
"version": "29",
"description": "Your own private cloud. File sync, calendars, contacts.",
"icon": "/assets/img/app-icons/nextcloud.webp",
"author": "Nextcloud",
"category": "data",
"dockerImage": "source.archipelago-foundation.org/lfg2025/nextcloud:29",
"repoUrl": "https://github.com/nextcloud/server",
"containerConfig": {
"ports": [
"8085:80"
],
"volumes": [
"/var/lib/archipelago/nextcloud:/var/www/html"
]
}
},
{
"id": "alby-hub",
"title": "Alby Hub",
"version": "1.23.0",
"description": "Self-custodial Lightning wallet hub. Runs its own Lightning node on your Archipelago and connects your apps to it over Nostr Wallet Connect — one hub, every app pays through it.",
"icon": "/assets/img/app-icons/alby-hub.svg",
"author": "Alby",
"category": "money",
"tier": "optional",
"dockerImage": "source.archipelago-foundation.org/lfg2025/alby-hub:v1.24.0",
"repoUrl": "https://github.com/getAlby/hub"
},
{
"id": "phoenixd",
"title": "phoenixd",
"version": "0.9.0",
"description": "Headless Lightning daemon by ACINQ (the Phoenix wallet team). No screen of its own — it exposes a small local API that other apps and tools use to send and receive Lightning payments. Channel liquidity is managed automatically for a fee.",
"icon": "/assets/img/app-icons/phoenixd.svg",
"author": "ACINQ",
"category": "money",
"tier": "optional",
"dockerImage": "source.archipelago-foundation.org/lfg2025/phoenixd:0.9.0",
"repoUrl": "https://github.com/ACINQ/phoenixd"
},
{
"id": "cuprate",
"title": "Cuprate",
"version": "0.1.0-preview",
"description": "Alternative Monero node implementation in Rust. Independently validates Monero consensus rules, providing a layer of security and redundancy for the network.",
"icon": "/assets/img/app-icons/cuprate.svg",
"author": "Cuprate contributors",
"category": "money",
"tier": "optional",
"dockerImage": "source.archipelago-foundation.org/lfg2025/cuprate:0.1.0-preview-18-g618ff14",
"repoUrl": "https://github.com/Cuprate/cuprate"
}
]
}
Binary file not shown.
@@ -1,4 +1,4 @@
{
"versionName": "0.5.27",
"versionCode": 47
"versionName": "0.5.28",
"versionCode": 48
}
+8
View File
@@ -117,6 +117,7 @@ import { useSpotlightStore } from '@/stores/spotlight'
import { useCLIStore } from '@/stores/cli'
import { useMessageToast } from '@/composables/useMessageToast'
import { useAppStore } from '@/stores/app'
import { fetchAppCatalog } from './views/discover/curatedApps'
import { useScreensaverStore } from '@/stores/screensaver'
import { useUIModeStore } from '@/stores/uiMode'
import { startRemoteRelay, stopRemoteRelay } from '@/api/remote-relay'
@@ -396,6 +397,13 @@ function onVisibilityChange() {
onMounted(async () => {
syncKioskSafeArea()
// Warm the signed-catalog cache before any app launch needs it: port auth
// (gate-fronted ⇒ TLS on the app port) decides whether an app frame opens
// over https on an HTTPS dashboard. The cache used to be filled only by
// the Store/Discover views, so a user who went straight to My Apps got an
// http:// frame URL — blocked as mixed content (mempool/indeehub "did not
// connect", 2026-09-01). fetchAppCatalog() memoizes with a 1h TTL.
void fetchAppCatalog()
// Light app-wide mesh poll so a freshly plugged-in radio surfaces the
// setup modal on any page (the Mesh view's own poll takes over there).
useMeshStore().startGlobalDetection()
@@ -143,6 +143,7 @@ import { ref, onMounted, onUnmounted, watch } from 'vue'
import * as QRCode from 'qrcode'
import { IS_DEMO, DEMO_PASSWORD } from '@/composables/useDemoIntro'
import { companionIntroRequested } from '@/composables/useCompanionIntro'
import { isCompanionApp } from '@/utils/openExternal'
import { useLoginTransitionStore } from '@/stores/loginTransition'
import { useServerStore } from '@/stores/server'
import { rpcClient } from '@/api/rpc-client'
@@ -205,10 +206,12 @@ const POST_INTRO_GRACE_MS = 2000
let calmTicker: ReturnType<typeof setInterval> | null = null
// Running inside the companion app's own WebView (it injects this JS bridge).
// Running inside the companion app's own WebView (it injects the JS bridge —
// detected with the canonical helper, not a raw window check, so the gate
// is identical everywhere the question is asked).
// The "get the companion app" pitch is nonsense there — the user is already in
// it. Server management for connected companions lives in the NESMenu instead.
const IN_COMPANION_APP = typeof (window as { ArchipelagoNative?: unknown }).ArchipelagoNative !== 'undefined'
const IN_COMPANION_APP = isCompanionApp()
onMounted(() => {
if (IN_COMPANION_APP) return
@@ -247,9 +250,13 @@ function maybeShow() {
}
// Manual open (App Store banner etc.) — ignores the once-per-browser gate.
// The trigger itself is already a no-op inside the companion (useCompanionIntro),
// and this watcher refuses to open there too, so no caller can ever pop the
// install pitch inside the app it installs (#61).
watch(companionIntroRequested, (requested) => {
if (!requested) return
companionIntroRequested.value = false
if (IN_COMPANION_APP) return
if (calmTicker) {
clearInterval(calmTicker)
calmTicker = null
@@ -10,7 +10,32 @@
z-index="z-[3600]"
@close="onClose"
>
<p v-if="lightning.status.value === 'no-funds'" class="text-sm text-white/70 leading-relaxed">
<p v-if="lightning.status.value === 'no-funds' && lightning.fundingReason.value === 'pending'" class="text-sm text-white/70 leading-relaxed">
Your new channel is <span class="text-white/90">waiting for its on-chain confirmations</span> —
that's why the network doesn't see it yet. It unlocks automatically once
confirmed (usually within about half an hour); nothing is needed from
you. This screen will work as soon as it lands.
</p>
<p v-else-if="lightning.status.value === 'no-funds' && lightning.fundingReason.value === 'far-side'" class="text-sm text-white/70 leading-relaxed">
<template v-if="lightning.fundingDirection.value === 'receive'">
You have channels, but <span class="text-white/90">all the balance is on your side</span> —
you can send, but there's nothing to be paid into right now. Receive a
payment by spending first, or open another channel to bring inbound
liquidity in.
</template>
<template v-else>
You have channels, but <span class="text-white/90">all the balance is on the far side</span> —
you can receive, but there's nothing to send right now. Someone has to
pay you first (or rebalance the channel), and sending unlocks on its own.
</template>
</p>
<p v-else-if="lightning.status.value === 'no-funds' && lightning.fundingReason.value === 'failed-payment'" class="text-sm text-white/70 leading-relaxed">
LND couldn't route this payment — most often there's
<span class="text-white/90">not enough outbound for this amount</span>, or no
route to the recipient at the fees offered. Smaller amounts sometimes
get through; check the channels screen to see what's actually spendable.
</p>
<p v-else-if="lightning.status.value === 'no-funds'" class="text-sm text-white/70 leading-relaxed">
Your Lightning node is running, but it has no payment channel yet.
<template v-if="lightning.fundingDirection.value === 'receive'">
Receiving needs <span class="text-white/90">inbound liquidity</span> — a
@@ -101,14 +126,31 @@
@click="openApps"
>Open My Apps</button>
<template v-else-if="lightning.status.value === 'no-funds'">
<button
class="flex-1 glass-button px-4 py-2 rounded-lg text-sm"
@click="openSetupGuide"
>Setup Guide</button>
<button
class="flex-1 glass-button glass-button-warning px-4 py-2 rounded-lg text-sm font-medium"
@click="openLightningSetup"
>Open a channel</button>
<!-- A confirming channel needs no action at all — offering "open a
channel" here would send the user to fix a problem they don't
have (and possibly open a second one). -->
<template v-if="lightning.fundingReason.value === 'pending'">
<button
class="flex-1 glass-button px-4 py-2 rounded-lg text-sm"
@click="onClose"
>Got it — I'll wait</button>
</template>
<template v-else>
<button
class="flex-1 glass-button px-4 py-2 rounded-lg text-sm"
@click="openSetupGuide"
>Setup Guide</button>
<button
v-if="lightning.fundingReason.value !== 'failed-payment'"
class="flex-1 glass-button glass-button-warning px-4 py-2 rounded-lg text-sm font-medium"
@click="openLightningSetup"
>Open a channel</button>
<button
v-else
class="flex-1 glass-button px-4 py-2 rounded-lg text-sm"
@click="onClose"
>Close</button>
</template>
</template>
</div>
</BaseModal>
@@ -155,7 +197,12 @@ const nodes: NodeChoice[] = [
const router = useRouter()
const modalTitle = computed(() => {
if (lightningStatusIs('no-funds')) return 'You need a Lightning channel'
if (lightningStatusIs('no-funds')) {
if (lightning.fundingReason.value === 'pending') return 'Channel confirming…'
if (lightning.fundingReason.value === 'far-side') return 'Balance is on the far side'
if (lightning.fundingReason.value === 'failed-payment') return 'Payment couldn\u2019t route'
return 'You need a Lightning channel'
}
if (lightningStatusIs('stopped')) return 'Lightning node not running'
return 'Lightning node required'
})
@@ -0,0 +1,41 @@
import { describe, it, expect, afterEach, beforeEach } from 'vitest'
import { companionIntroRequested, openCompanionIntro } from '../useCompanionIntro'
// #61: the manual intro trigger (App Store banner etc.) must be a no-op inside
// the companion app's WebView — the "install the companion" pitch is nonsense
// where the user is already running it. The auto-popup was already gated
// (CompanionIntroOverlay.onMounted); openCompanionIntro is the second, manual
// path and the banner render (CompanionBanner) the third.
type TestWindow = Window & { ArchipelagoNative?: unknown }
const w = window as TestWindow
beforeEach(() => {
companionIntroRequested.value = false
})
afterEach(() => {
delete w.ArchipelagoNative
})
describe('openCompanionIntro', () => {
it('raises the manual intro request in a plain browser/PWA', () => {
expect(companionIntroRequested.value).toBe(false)
openCompanionIntro()
expect(companionIntroRequested.value).toBe(true)
})
it('is a no-op inside the companion app (bridge with openInApp)', () => {
w.ArchipelagoNative = { openInApp: () => {}, openExternal: () => {} }
openCompanionIntro()
expect(companionIntroRequested.value).toBe(false)
})
it('still fires when the bridge exists but is not the companion shell', () => {
// Partial bridge (no openInApp) is not the companion app — a future
// embedder must still see the pitch.
w.ArchipelagoNative = { openExternal: () => {} }
openCompanionIntro()
expect(companionIntroRequested.value).toBe(true)
})
})

Some files were not shown because too many files have changed in this diff Show More