Compare commits

..
Author SHA1 Message Date
archipelago 3ec67b8f31 chore(apps): mirror-backed bumps — vaultwarden, nbxplorer, home-assistant (PENDING)
Prepared patch-level bumps with no data migration, held here until the
three images can be mirrored to source.archipelago-foundation.org/lfg2025
(currently blocked: the only registry-push credential on record for the
lfg2025 namespace is dead, and the ai account cannot push user-namespace
packages it does not own):

  vaultwarden       1.37.1-alpine -> 1.37.2-alpine  (docker.io/vaultwarden/server)
  archy-nbxplorer   2.6.0         -> 2.6.11         (docker.io/nicolasdorier/nbxplorer)
  home-assistant    2026.8.2      -> 2026.8.3       (docker.io/homeassistant/home-assistant)

All three target tags verified present upstream. To land: mirror the
images, merge this branch into main, regenerate + re-sign the catalog.
2026-08-30 16:23:05 -04:00
archipelago 7b88ba59b2 chore(apps): bump the pins that need no mirroring; curate Cuprate's store entry
Demo images / Build & push demo images (push) Failing after 40s
Pin bumps (all verified pullable from their public registries before
editing, so none can become an image-not-found on a node):

  strfry           1.1.1 -> 1.1.2              (dockurr/strfry, direct pull)
  btcpay-server    2.4.2 -> 2.4.3             (docker.io/btcpayserver, direct pull)
  netbird (nginx)  1.31.3-alpine -> 1.31.4-alpine
  pine   (nginx)   1.31.3-alpine -> 1.31.4-alpine

image-versions.sh moved in lockstep for BTCPAY_IMAGE — it is the baseline
the update badge compares against. Held back deliberately, per the risk
policy from the Aug-17 pass: gitea (four minors of DB migrations),
portainer (six minors), filebrowser (2.27 -> 2.63), fedimint/gateway
(0.8 -> 0.12, real migrations), lnd (money-critical), netbird-server/
netbird-dashboard (0.x, must move in lockstep), and everything with a
major jump or a data migration.

Cuprate also gets its curated store entry (category money, tier optional,
icon, repo) — same shape as the Alby Hub / phoenixd entries — synced
through generate-app-catalog.py into both store catalogs and the
app-session config. The fips launch-port list is unchanged (Cuprate has
no UI port; the generated file round-trips to the committed bytes after
cargo fmt).

Three further bumps are prepared and parked on the
app-bumps-mirror-pending branch, blocked only on a registry-push token:
vaultwarden 1.37.2-alpine, archy-nbxplorer 2.6.11, home-assistant
2026.8.3 — all mirror-backed, and the push credential on record for the
lfg2025 namespace is dead.

Drift gate: check-app-catalog-drift.py --release --strict clean
(31 store entries, 0 drift, 0 missing). appSessionConfig tests 7/7.
2026-08-30 16:22:26 -04:00
archipelago b12d1d3826 feat(apps): track the last untracked apps' upstreams
Five apps had no app.upstream block, so nothing could ever tell us
when their pins fell behind upstream:

  barkd           gitlab ark-bitcoin/bark   (GitLab-only project)
  immich-postgres ghcr  immich-app/postgres (image exists only on ghcr.io)
  indeedhub-minio github minio/minio
  pine-whisper    dockerhub rhasspy/wyoming-whisper
  lightning-stack manual — no public listing exists for
                   lightninglabs/lightning-stack anywhere (docker.io,
                   ghcr.io, github.com all checked), so it is tracked by hand

This adds two fetchers to scripts/check-upstream-releases.py to reach the
first two: latest_gitlab (GitLab releases API; strips the project-name
tag prefix, e.g. bark-0.6.2 -> 0.6.2) and latest_ghcr (anonymous pull
token + tags/list, the same handshake a docker pull performs).

Live-verified after the change:
  barkd            0.3.0 -> 0.6.2   (bump gated on ark_client.rs REST compat)
  immich-postgres  14-vectorchord0.4.3-pgvectors0.2.0 -> 17-vectorchord0.4.3-pgvector0.8.0
  indeedhub-minio  RELEASE.2024-11-07T00-52-20Z -> latest (date-opaque: UNCOMPARABLE, shown for hand comparison)
  pine-whisper     3.4.1 -> 3.6.0   (tuned-args revision needs re-basing, not just a pin move)

Offline coverage check: 59 apps, 0 untracked.
2026-08-30 16:22:11 -04:00
archipelago 698e915df2 Merge PR #141: package Cuprate, an alternative Monero node
Demo images / Build & push demo images (push) Failing after 37s
2026-08-30 14:18:42 -04:00
ssmithxandarchipelago a179df66d8 docs: add app update strategy, SSH access, and app wishlist to TODO
Flags the app update policy already noted as unresolved in
app-developer-guide.md, adds a section for SSH access strategy, and
starts an app wishlist (Cashu wallet, phoenixd) for packaging.
2026-08-30 14:01:20 -04:00
ssmithxandarchipelago 771ff0d28b docs: add TODO.md backlog and link from docs index
Captures unscoped forward-looking items (peering/federation model,
distributed git & OTA, nostr integration, platform/OS, app testing,
observability, and the dev/build process) so they're tracked outside
of ROADMAP.md's curated public summary.
2026-08-30 14:01:20 -04:00
92111385b7 fix(mesh): don't offer radio-only resource transfer to radio-unreachable peers
The federation fallback in the plain content-inline path wasn't enough —
mesh.transport-advice recommended the "resource-mesh" tier purely from our
own device being Reticulum-capable, without checking that THIS peer
actually has a radio route. For a federation-only contact (no radio twin)
that steered the frontend into send-content-inline's Reticulum
resource-transfer path, which has no dest_prefix to send to and fails with
"Peer is federation-only (no radio twin)" — reproduced after deploying the
first fix on a live node.

Adds MeshService::has_radio_route(contact_id), and gates both the
"resource-mesh" tier in mesh.transport-advice and the resource-transfer
branch in mesh.send-content-inline on it. Federation-only peers now fall
through to the has_tor branches, which route the frontend to
mesh.send-content (already correctly federation-aware) instead.

Landed from PR #133 (re-committed to drop private host details from the
original message; content identical).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-30 13:18:08 -04:00
a9e52fa310 fix(mesh): route send-content-inline over federation for radio-less peers
mesh.send-content-inline always called send_typed_wire (the LoRa/radio
path), which fails with "Peer is federation-only (no radio twin)" for
any contact reachable only via Tor federation — reproduced sending a
picture from the companion app to a federation-only peer. mesh.send-content
already resolves the peer's federation onion and falls back to
send_typed_wire_via_federation; mirror that same lookup here.

Landed from PR #133 (re-committed to drop private host details from the
original message; content identical).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-30 13:18:08 -04:00
archipelago b4714f1773 fix(store): defer multi-version app version choice (#129)
Demo images / Build & push demo images (push) Failing after 39s
2026-08-30 10:23:58 -04:00
archipelago d79ca54019 fix(wallet): disclose backup passphrase only when needed (#127) 2026-08-30 10:23:58 -04:00
archipelago 758332d63d fix(openwrt): make stale router config recoverable (#103) 2026-08-30 10:23:58 -04:00
archipelago ee5123af68 test(ui): satisfy strict build indexing
Demo images / Build & push demo images (push) Failing after 41s
2026-08-30 10:18:02 -04:00
archipelago a624d11b6a fix(mesh): make radio message notifications durable (#57) 2026-08-30 10:16:33 -04:00
archipelagoandClaude Opus 5 2c984fbd49 fix(ui): the IBD-finished toast no longer tells a node without LND to fund its wallet
Demo images / Build & push demo images (push) Failing after 52s
When Bitcoin's IBD completed mid-Lightning-goal, the watcher toasted
"you can now fund your wallet" — but the on-chain wallet lives in LND,
not Bitcoin Core. The watcher only checked that the goal had pending
manual steps, never that the install-LND step had completed, so a user
whose LND wasn't installed yet was pointed at a flow that could not
work: the fund modal's address comes from lnd.newaddress and does not
exist until LND is installed (issue #143).

The toast now checks LND's install state at fire time. With LND
installed the message is unchanged; without it, the toast says the
actual next step — install Lightning (LND) — and the Finish setup
button lands on the goal wizard, whose active step is the pending
install-LND one (the wizard itself was already correctly sequenced).

The watcher had no tests; added four pinning its contract: the two
message branches, silence with no in-progress goal, and silence when
the chain was already synced at page load.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-30 09:24:01 -04:00
archipelago c188d9de78 fix(lifecycle): abort unsafe declarative uninstall 2026-08-23 07:59:40 -04:00
archipelago 37a82fd2f9 fix(cuprate): avoid Penpot RPC port collision 2026-08-23 01:43:09 -04:00
archipelagoandClaude Opus 5 a9a30406df fix(disk): count reserved blocks as used, not free
Disk usage was computed as used/size, where size is the raw device size.
ext4 reserves 5% of the filesystem for root — 92.4 GiB of this node's
1.8 TiB — which size includes but nothing can allocate. Two consequences,
both live on archi-dev-box today:

The dashboard advertised 251 GiB free when only 159 GiB could actually be
written, and reported 86.2% usage against df's 90.8%.

Worse, disk_monitor triggers automatic cleanup (podman image prune) at
90%. The disk has been genuinely above that threshold while this returned
86.2%, so the cleanup never once fired — which is exactly how ~72 GB of
dangling images accumulated unnoticed, and why deleting apps appeared to
free nothing.

Both call sites now ask df for avail and use used/(used+avail): the same
figure df itself prints, and the space an operator can actually spend.
Callers deriving free as total - used now get avail.

Note this shifts disk_total_bytes in the analytics series down by the
reserve; historical samples are not comparable across this change.

Tests updated for the three-column output, plus a regression test built
from this box's real numbers asserting the corrected math crosses the 90%
threshold the old math missed. 15/15 disk_monitor tests pass.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 05:01:18 -04:00
archipelagoandClaude Opus 5 f1b5d2d267 fix(cuprate): stop publishing the unauthenticated unrestricted RPC
The manifest bound cuprated's unrestricted RPC (full node control) to
0.0.0.0 inside the container with
i_know_what_im_doing_allow_public_unrestricted_rpc = true, relying on
ports[].bind: 127.0.0.1 to keep it private. That only restricts the HOST
side. Verified live on archi-dev-box 2026-08-22: a peer container got a
valid unauthenticated get_info off container port 18081 — and still did
after cuprate was moved to its own network, because podman bridges route
to each other unless created with --opt isolate=true, which the
orchestrator's auto-create does not pass. Every app on the node could
therefore drive full node control with no credential.

The PR justified this as the pattern bitcoin-knots already uses, but
knots writes rpcuser/rpcpassword from generated secrets, so a 0.0.0.0
bind there still is not control without credentials. cuprated has no RPC
authentication at all, so the two are not equivalent.

Unrestricted RPC is now left at cuprated's own default — container
loopback only, published nowhere, reachable by nothing — which is what
upstream intends by refusing a non-local bind without an explicit
override. Restricted RPC (the safe-for-public subset wallets use) and p2p
are unchanged, and health_check moves to 18089 since 18184 is gone.

Re-verified after the change: peer container gets connection refused on
18081 (exit 7), restricted RPC and the health endpoint still answer, the
node still syncs, validator APPROVED, 76/76 container tests pass
including the unauthenticated-port canary (still 28 — an auth: local
port was removed, not an auth: none one).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 03:10:53 -04:00
ssmithxandClaude Sonnet 5 d6b48ce095 feat(apps): package Cuprate, an alternative Monero node
Full-node daemon: P2P + Monero's own restricted RPC (the safe-for-public
subset wallets use as a "remote node") are auth:none like bitcoin/electrumx's
equivalents; unrestricted RPC (full node control) stays gated auth:local.
readonly_root works cleanly since the upstream image is FROM scratch with
ownership fixed at build time — no runtime chown/setuid needed, unlike
bitcoin-knots/core.

Verified locally end-to-end before committing: built the upstream Dockerfile,
confirmed the generated Cuprated.toml against `cuprated --generate-config`/
`--dry-run`, and ran the real image with the manifest's exact ports/volumes —
including discovering that cuprated's own 127.0.0.1-default RPC bind is
unreachable through a published host port and needs to bind 0.0.0.0
internally with ports[].bind:127.0.0.1 doing the actual restriction, the
same pattern bitcoin-knots' RPC port already uses in this repo.

Bumps the unauthenticated_ports_are_all_accounted_for canary (26 -> 28) for
cuprate's two auth:none ports, per that test's own review-before-updating
contract.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-21 13:58:06 +00:00
archipelago 9c5164372e chore: release v1.8.4-alpha 2026-08-20 07:15:01 -04:00
archipelagoandClaude Opus 5 e38b148d8e fix(release): spell out how the mnemonic prompt actually submits
The signer reads stdin to EOF, so pressing Enter submits nothing and a
second paste simply appends to the first. Step [6b/8] said only "paste the
release master mnemonic when prompted", which gives no hint that Ctrl-D is
what ends the input — a 24-word phrase arrived today as "invalid word
count: 89", about four pastes concatenated by someone reasonably assuming
Enter had not worked.

sign-manifest.sh already explains this properly; create-release.sh now says
the same thing, including that pasting twice is itself a failure mode.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-20 06:27:42 -04:00
archipelagoandClaude Opus 5 e03a2fed89 fix(release): surface frontend build failures instead of hiding them
`npm run build 2>&1 | tail -3` threw away npm's exit status, so a failed
build was indistinguishable from a good one. The run continued and blamed
the next check instead — "the frontend build no-opped or its output is
stale" — which points at a stale dist rather than at the build error that
actually happened, and cost a diagnosis cycle today.

Success still prints the same quiet 3 lines; a failure now prints the real
error, keeps the full log, and aborts on the spot.

Verified both branches with a stubbed npm.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-20 05:24:37 -04:00
archipelagoandClaude Opus 5 3d7de3e902 fix(release): a dateless changelog header silently skipped the release
Demo images / Build & push demo images (push) Failing after 38s
create-release aborted at [4/8] with "web/dist/neode-ui does not contain
v1.8.4-alpha — the frontend build no-opped or its output is stale". The
build had not no-opped: it was fresh, and simply had no 1.8.4 string to
embed.

sync-whats-new.py only matches '## vX.Y.Z (YYYY-MM-DD)'. The entry read
'## v1.8.4-alpha (draft — date set at cut)', so the version was invisible
to it: the gate's whats-new-sync stage reported "87 versions, all present"
while the release being cut had no What's New block. That modal is the
only place a version string appears in the frontend, so the bundle carried
none and the freshness check — correctly — refused it, while naming the
wrong cause. Step [5/8] only greps for '^## v1.8.4-alpha (' so it passed
the draft too.

Three changes: date the v1.8.4-alpha entry, insert the modal block it was
owed, and make the sync tool refuse any version header without a real date
instead of skipping it. Skipping is what let a wrong "all present" through.

Verified: the draft header now fails the check with an explicit message,
the dated one passes (88 versions, up from 87), and a rebuilt bundle
contains 1.8.4-alpha where it did not before.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-20 03:01:39 -04:00
archipelagoandClaude Opus 5 60c1db98bb fix(ui-tests): raise the vitest timeout so a busy box cannot fail the gate
Demo images / Build & push demo images (push) Failing after 40s
Four unrelated tests failed the release gate at once today — every one of
them "Test timed out in 5000ms", none an assertion. Wall times were 6.3s,
16.5s, 5.5s and 36.2s for tests that normally finish in milliseconds
(useModalKeyboard's takes 349ms on an idle box), and the whole suite took
405s against its usual ~70s. The cause was CPU starvation from a
concurrent cargo build, not anything in the code.

The 5s default says nothing about these tests and everything about the
machine: this box also runs a live node, so a gate run can always collide
with a build or container churn. 20s survives that while still bounding a
genuine hang.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-20 02:06:14 -04:00
archipelagoandClaude Opus 5 f5b112c508 fix(gate): stop reporting a compile timeout as a test failure
cargo-test-weekly failed twice today with exit 124 at unit 427/429 — the
non-incremental test-profile build running out of wall clock mid-compile,
before a single test executed. The summary said only "FAIL: cargo-test-
weekly", which reads as a broken test and sends you hunting for one that
does not exist.

Two changes: the ceiling goes 1500s -> 3600s (580s was already found too
short; 1500s now dies on the biggest link on a loaded, swapping box), and
stage() names exit 124 as a timeout rather than printing a bare code.

Verified both reporting branches: a timed-out stage and an ordinary
non-zero exit.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-20 01:50:52 -04:00
archipelagoandClaude Opus 5 5ccef0ac2f feat(release): attach the installer ISO to the Gitea release automatically
Publishing the ISO was a manual step printed as a reminder at the end of
build-iso-release.sh: upload the ISO, its .sha256 and the signed checksum
JSON by hand. Only the OTA binary and frontend tarball were automated.

publish-release-assets.sh now uploads all three when an ISO for the
version exists in image-recipe/results/, with the same supply-chain rules
the OTA manifest already gets: the checksum JSON must be signed by the
pinned release root, the signature must cryptographically verify, and the
image must still match its own .sha256 (a truncated or half-copied ISO is
exactly what a signed checksum exists to expose). After upload it
confirms every asset landed at its exact local size.

The stage runs AFTER main is pushed, deliberately. The ISO is not
referenced by releases/manifest.json, so no node's OTA path depends on
it — running it last means a slow or failed multi-GB upload can never
delay or strand an OTA release that has already been verified. When no
ISO exists yet (the usual case, since the ISO build needs the tag this
script pushes) it explains how to build and attach one, and exits clean.

Uploads take a max-time argument: 4h and a progress bar for the ISO,
where the previous fixed 15-minute silent ceiling would have killed a
multi-GB transfer partway through.

Verified with a stubbed harness: no-ISO skip, missing .sha256, unsigned
checksum, wrong signing key, corrupted image, happy path, and a truncated
upload caught by the size check.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-20 01:33:54 -04:00
archipelagoandClaude Opus 5 e79ab37da7 chore(release): bump version to 1.8.4-alpha
Demo images / Build & push demo images (push) Failing after 40s
Left uncommitted by an aborted create-release run on 2026-08-19: the
version bump landed in the tree but the release never reached its tag or
manifest. Committing it so the tree is clean before the release is re-cut.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-20 01:04:04 -04:00
archipelagoandClaude Opus 5 d75963de10 fix(gate): show which UI test failed instead of swallowing it
The ui-unit-tests stage piped vitest through `tail -4`, which cut off the
failure block. A red gate reported "1 failed | 999 passed" and nothing
else — no file, no test name, no assertion — so the failure could not be
diagnosed after the run.

Success still prints the quiet 4-line summary; failure now dumps the full
log and keeps it on disk so a scrolled-off terminal isn't the end of it.

Verified both paths: green run unchanged, and a deliberately failing spec
now surfaces its file, test name, assertion and line number.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-19 14:33:09 -04:00
archipelagoandClaude Opus 5 c788dff42d style: apply cargo fmt so the release gate can run
The release gate's first real stage is `cargo fmt --check`, and it had
44 diffs across 15 files — enough to abort `create-release.sh` at step 0
before it touched a version number. Some of that drift is mine from the
last two days, some predates it in files I never opened
(bootstrap.rs, ghost_reaper.rs, openwrt/router.rs), and one is the
regenerated fips/app_ports.rs.

No behaviour change — rustfmt only.

Gate now: 8 of 9 green. The remaining red is cargo-test-weekly exiting
124, which is the 25-minute `timeout` expiring during a cold
CARGO_INCREMENTAL=0 rebuild on a loaded node — the tests never started.
Not a test failure.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-19 12:38:41 -04:00
archipelagoandClaude Opus 5 bd299318c0 chore(catalog): re-sign the catalog with the new pins, and fix a stale firewall list
Demo images / Build & push demo images (push) Failing after 41s
Regenerates both catalogs from the manifests so the 15 pin bumps become
real. The catalog overrides on-disk manifests on every node, so until
now those bumps were edited but inert.

There are two catalogs and regenerating one is not enough:
generate-app-catalog.sh writes releases/app-catalog.json (the signed one
nodes fetch), while generate-app-catalog.py writes app-catalog/catalog.json
and neode-ui/public/catalog.json (the source pair, the second baked into
the frontend app store). check-app-catalog-drift.py --release --strict
reads the *source* catalog, so regenerating only the release one left it
failing and would have aborted the ISO gate at stage 1 — after the
signing and tagging were already done. Drift is now 0.

The regeneration also rewrote fips/app_ports.rs, which had not been
regenerated since the initial open-source import. Diffing the port values
rather than the reformat: 36 -> 37, a single addition, **8187 — Alby
Hub**. Its port has never been in the FIPS firewall allow-list, and by
the same token neither has any app onboarded since that import. Nothing
else changed.

Catalog signed by the pinned release root and verified with
`ceremony verify`; registry trust floor checked before signing, both
hosts trusted by the deployed fleet.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-19 12:02:40 -04:00
archipelagoandClaude Opus 5 8bc161f40f fix(ecash): repair two mangled warning messages
Both import refusals reached the operator with runs of ~18 spaces mid
sentence — "Importing a different one                  means coins
minted…". The string literals had been written as single long lines with
the line-continuation whitespace baked in rather than escaped, so Rust
preserved it verbatim.

Only visible once the sanitizer stopped swallowing these messages, which
is its own small lesson: the text had been wrong since it was written and
nothing could show it.

Cosmetic, but not trivially so — this is the warning that stops someone
replacing the phrase their balance was minted under, and text that looks
broken is text people stop reading.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-17 11:31:52 -04:00
archipelagoandClaude Opus 5 c19c411b91 chore(apps): mirror and bump the upgrades that carry no data migration
With registry push access, the 24 mirror-backed apps stopped being
blocked. Ten images are now mirrored (single-platform amd64, matching
the existing convention) and their pins moved:

  alby-hub          v1.23.0       -> v1.24.0
  mempool-frontend  v3.0.1        -> v3.3.1     (mempool, archy-mempool-web)
  mempool-backend   v3.0.0        -> v3.3.1
  fedimintd         v0.10.0       -> v0.10.1
  gatewayd          v0.10.0       -> v0.10.1
  nostr-rs-relay    0.9.0         -> 0.10.0
  portainer         2.39.1        -> 2.39.6
  vaultwarden       1.30.0-alpine -> 1.37.1-alpine
  jellyfin          10.8.13       -> 10.11.11
  home-assistant    2026.7.3      -> 2026.8.2

Every one verified pullable from our mirror after copying, so none can
become an image-not-found on a node. image-versions.sh moved in lockstep
— it is the baseline the update badge compares against when the catalog
does not cover an app, and leaving it behind would have kept advertising
an update that had already been applied.

Chosen by risk, not by count: these are patch/minor bumps with no data
migration. The ones held back are held for a reason each — Postgres
15->18 and 16->18 refuse to start on an older cluster, Redis 7->8,
Valkey 7->9, Nextcloud 29->32 must go one major at a time, plus
uptime-kuma 1->2, grafana 10->13, electrumx 1->2, photoprism, and
core-lightning's three years of schema migrations. Those are each a
migration plan, not a pin edit. LND (v0.18.4 -> v0.21.2) is held
separately: it is only a minor bump by version but it migrates its
channel database irreversibly, and this box holds real funds.

Note the checker still reports several of these as behind, and that is
correct: it reads the *catalog* pin, which is what nodes actually act on.
These land when the catalog is regenerated and re-signed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-17 11:22:42 -04:00
archipelagoandClaude Opus 5 7d6e52537a chore(apps): bump the pins that can move without mirroring
Of the 33 apps behind upstream, these five pull straight from a public
registry, so their targets exist already and the bump is real work rather
than a promise:

  strfry          1.0.4        -> 1.1.1
  netbird (nginx) 1.27-alpine  -> 1.31.3-alpine
  pine    (nginx) 1.27-alpine  -> 1.31.3-alpine
  pine-piper      2.2.2        -> 2.4.2
  nostr-rs-relay  0.8.9        -> 0.10.0

All five targets verified present upstream with skopeo before editing, so
none of these can turn into an image-not-found on a node.

Deliberately NOT bumped here, though they are also direct-pull:
core-lightning (v23.08 -> v26.06, ~3 years of schema migrations), gitea
(four minors of DB migrations), and netbird-server/netbird-dashboard —
which have to move in lockstep and carry their own migrations. Those are
each a piece of work, not a line edit.

The other 24 are blocked on something else entirely: their images live in
our mirror and none of the upgrade targets have been mirrored yet, so a
pin bump alone would break every install. That needs registry push
credentials.

These take effect when the catalog is regenerated and re-signed — the
catalog overrides on-disk manifests, so editing here changes nothing on a
node until the signing ceremony.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-17 10:54:05 -04:00
archipelagoandClaude Opus 5 86923f05a5 fix(ecash): stop the sanitizer eating the import safety rails
Live-checking the import route on the node showed both of its refusals
arriving as "Operation failed. Check server logs for details."

That is not merely opaque here, it is unsafe. The two messages are the
feature's safety rails: "That is not a valid BIP-39 recovery phrase —
check for typos" is the only help someone gets when a pasted phrase has
a bad word, and "This wallet already has a backup phrase… reveal and
write down the current phrase first, then confirm to replace it" is the
warning that stops an operator orphaning the words their balance was
minted under. Masked, the first is unactionable and the second is
invisible — the confirmation checkbox would be the only clue that
anything was at stake.

Same for "no backup phrase yet, nothing to restore from" and the NUT-09
message naming a mint that cannot restore at all.

Caught only because the refusal paths were exercised against the live
node rather than trusted from the unit tests, which see the real message
and never meet the sanitizer.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-17 10:43:47 -04:00
archipelagoandClaude Opus 5 ee40880ce5 feat(ecash): import a backup phrase from another NUT-13 wallet
Demo images / Build & push demo images (push) Failing after 2m2s
Bring-your-own, the open question the migration plan left. Point this
wallet at a phrase you already hold — Minibits, Nutstash, cdk-cli — and
its coins become restorable here, which is the other half of "these
words are portable".

Replacing an established phrase is the one genuinely lossy thing this
module can do, so it is treated that way. The coins already held stay
spendable: they are proofs, not derivations, and nothing here touches
`ecash.json`. But they were minted under the *old* phrase, so a restore
will no longer find them. Hence an explicit confirm, a prompt to reveal
and write down the current phrase first, and — most importantly — the
replaced phrase is archived beside the wallet, never overwritten. It may
be the last copy of the words a balance was minted under, and quietly
destroying that is precisely what this module exists to prevent.

Re-importing the phrase already in use is a no-op rather than a
replacement, so it archives nothing.

Counters are deliberately left alone. They are per-keyset and
seed-relative, so under a new seed they merely start high, which costs
nothing because a restore scans from zero regardless. Resetting them
would be the dangerous choice on the day someone imports the phrase they
were already using.

`imported` is its own provenance rather than reusing `independent`: both
mean the node's recovery phrase does not cover the wallet, but only one
of them means the operator already knows where else the words live.

15 NUT-13 tests green, 1000 frontend tests green.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-17 10:09:19 -04:00
archipelagoandClaude Opus 5 c1a79fdd69 fix(apps): never recommend a release candidate, and flag major jumps
Two things the first run of this script got wrong, both found by reading
its own output rather than by a test.

It recommended MariaDB `13.0.1-ubi10-rc` — a release candidate — because
ordering strips the suffix, so an RC outranks every stable tag
numerically. Pre-releases are now excluded, with one exception that
matters here: a project whose stable line *is* suffixed. LND ships
`-beta` and always has, so a blanket exclusion would report it as
permanently current. The rule is therefore "no pre-release unless the pin
we are on is itself one", which keeps LND honest and MariaDB stable.

And "33 behind" is not an actionable list, because the entries are not
the same kind of work. A patch bump is a pin change; a major bump is
where the data migrations live — Postgres refuses to start on an older
cluster, Nextcloud requires one major at a time. Each row now says which
it is, and the summary names the majors separately.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-17 09:55:18 -04:00
archipelagoandClaude Opus 5 59440ef1ac fix(wallet): a seen receipt stays seen across refreshes
Demo images / Build & push demo images (push) Failing after 2m6s
fc98c1d8 replaced the five-minute timer with "stays until seen", but
kept "seen" in component state — so every page load forgot it and the
entire ecash history came back as new. That is worse than the timer it
replaced: the old behaviour at least let receipts go, this one resurrected
them on every refresh. Reported from the node, and correctly.

Acknowledgement now lives in localStorage, capped at 300 keys.

That opens the opposite trap: on a browser with nothing stored, treating
the whole history as unseen is the same wall of old receipts from the
other direction. So a first run seeds everything older than five minutes
as already seen — the window survives as a first-run heuristic, not as
an expiry. Unreadable storage takes the same path, because reading a
corrupt value as "nothing acknowledged" is the refresh bug wearing a hat.

Also guards the balance readout against NaN. `sats == null` does not
catch it, and arithmetic over a missing field produces it, so it would
have rendered as the literal text "NaN sats" — worse than the zero the
component exists to prevent, since a zero at least looks like a number.

Frontend: 1000 tests green.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-17 09:30:57 -04:00
archipelagoandClaude Opus 5 603291008b fix(test): restore the ecash network before bouncing the service
The restore proof's cleanup set the network back *after* restarting
archipelago, so the call landed on a socket that wasn't listening yet
and failed silently. A fully green run left the node parked on testnet —
the one outcome a cleanup path must never produce, and worse for being
invisible.

Network first, while the RPC is still up; then the wallet file, then the
restart, then wait for the service back so a check running straight
afterwards doesn't meet a dead socket.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-17 09:15:31 -04:00
archipelagoandClaude Opus 5 212e349b19 refine(wallet): the balance readout scans as one column, not a barcode
Demo images / Build & push demo images (push) Failing after 2m7s
Seeing it on the node settled the shape. Two rows of per-cell delays
read as a dense flicker — closer to a progress bar than a display, and
short enough against the row's text to look like an underline.

Three rows laid out column-first fixes both: the three cells of a column
now share a delay, so the lit column travels across as a single scan
line, and at 11px the matrix sits with the text rather than under it.

Verified in a real browser against the live node with the balance RPCs
held open: five placeholders, five distinct rail colours (white, orange,
yellow, purple, blue), 42 cells each, all animating, each announcing
what it is waiting for — and no "0 sats" anywhere on screen while the
calls were in flight. They gave way to real figures on arrival, with
Lightning's genuine 0 correctly shown as a figure rather than left
shimmering.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-17 09:05:33 -04:00
archipelagoandClaude Opus 5 fa6fe32ef9 feat(wallet): a balance that isn't loaded yet says so, in pixels
Demo images / Build & push demo images (push) Failing after 2m18s
An unloaded balance rendered as `0`. Zero is not a loading state — it is
a number, and it is the one number that frightens people. Someone
opening the dashboard while the RPCs were still in flight was told, in
the wallet's own typeface, that their money was gone.

There is no formatting fix for that. The fix is to stop claiming a
figure we do not have, so `null` now means "not known yet" and `0` means
"none", and the two are kept apart end to end: the refs start at null,
a rail becomes a number only when its call actually succeeds, and a
snapshot key that was never written stays unknown instead of becoming a
zero.

In place of the figure, a small dot-matrix scans in the rail's own
colour. It inherits currentColor, so on-chain shimmers orange, Lightning
yellow, Cashu purple, Fedimint blue and Ark teal with no colour table to
keep in sync — and it is sized to the figure it stands in for, so
nothing jumps when the real number lands. It carries role="status" and
names what it is waiting for; a shimmering box with no text is nothing
at all to a screen reader.

Two consequences worth stating. The total is withheld until every rail
that makes it up is known — summing nulls as zero would show a total
*lower* than the rails beneath it, which is worse than showing nothing
because it looks authoritative. And the Ark row stays hidden while its
balance is unknown, since "unknown" must not be read as "> 0" on the
many nodes with no Ark sidecar.

The LND app UI had the same bug in a different shape: its tiles start as
an em-dash, but renderBalances() runs on every poll including before the
first response, and `num(null && …)` is 0 — so the dashes were painted
over with "0 sats" almost immediately. Same treatment, in plain CSS.

Also fixes a stale assertion in AppHeroSection's suite, which has been
red since 9ccc325a changed "Restarting..." to a real ellipsis; and two
test proofs that used a plausible-looking hex string for `C`. The V3
codec never parses that field so it went unnoticed, but the V4 encoder
hands it to the reference implementation, which checks the point is
actually on secp256k1. Real curve points now.

Frontend: 996 tests green. Backend: 1436 green.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-17 08:54:12 -04:00
archipelagoandClaude Opus 5 fc98c1d8dd fix(wallet): an incoming payment no longer disappears before you look
Demo images / Build & push demo images (push) Failing after 2m10s
Chasing the "selecting incoming clears a pending token, and there's a
timeout if you don't click" report led here. Instant rails — Lightning,
Cashu, Fedimint, Ark — settle immediately, so there is no confirmation
to wait for and no natural moment for a receipt to leave the Incoming
badge. It was leaving on a five-minute wall clock instead.

So a payment could arrive, raise the badge, and evaporate before anyone
looked; and opening the panel a few minutes late showed nothing, because
the payment you came to check on had already aged out. Worse, once the
count hit zero the badge silently changed meaning — the same click that
opened the panel now navigated to the transactions view instead.

For ecash that is the worst case available. It leaves no public ledger
entry, so this panel was the only place the receipt was ever shown; once
it timed out there was nowhere left to look.

Instant-rail receipts now stay until they have actually been seen, which
is the same unread model the mesh inbox uses. Closing the panel is what
marks them seen, not opening it — marking on open would make a row
vanish under the cursor of someone still reading it. On-chain is
untouched: a confirmation count is a real signal and already does this
job.

Also keys the list on a derived id. Instant rails have no txid, so
`:key="tx.tx_hash"` was `""` for every one of them.

This is my reading of the reported symptoms rather than a confirmed
repro — the operator should check it matches what they saw.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-17 08:30:16 -04:00
archipelagoandClaude Opus 5 e30516316b fix(ecash): give every node a backup phrase, and prove restore works
Demo images / Build & push demo images (push) Failing after 2m11s
Running the route suite on this box surfaced that the backup was
unreachable here: `identity/master_seed.enc` is written during
onboarding, and any node onboarded before that step existed simply does
not have one. Reveal bailed with "this node has no encrypted seed
backup", and restore followed it down.

But the choice on such a node was never "derived phrase or independent
phrase" — it was "independent phrase or no backup at all", and a wallet
whose coins can be restored from words the operator holds beats one
whose coins die with a single file. So it now generates one, recorded as
`independent`, and every surface that shows it says plainly that
restoring the node will not bring the ecash back — only these words
will. `derivable_from_node_seed` lets the card say which kind you are
about to get *before* you write anything down.

Also: a mint that never implemented NUT-09 answered restore with a bare
404, which surfaced as "mint returned 404 with no further detail" —
true, and useless to someone trying to get their coins back. It now
names the limitation.

The route suite was reading `result.amount_sats` from mint-claim, which
answers with `minted_sats`. A working claim had been reporting as a
failure; that was one of the two reds carried over from yesterday.

The real gap, though, was that "recovered 0 sats" passes on a wallet
with nothing to find — exactly the shape of a backup that looks fine
until the day you need it. test-ecash-restore.sh does the test that
settles it: mint, **delete the wallet file**, restore, check the coins
came back. On this box: 87 sats before the wipe, 0 after, 61 recovered
from the phrase alone — every coin minted since the phrase existed, and
none of the 26 sats minted before it, which used random secrets and
never could come back. Testnet only, and it refuses to run otherwise.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-17 08:27:01 -04:00
archipelagoandClaude Opus 5 cbbd20e22e test(ecash): cover cashuB emission, the backup phrase, and restore
Four things the suite could not previously catch:

- The emitted token is cashuA. It is still valid, so nothing fails — the
  send succeeds and the receiver redeems it. The only symptom of cashuB
  encoding falling back is a warning in the journal nobody reads, which
  is exactly the kind of silent regression a route check exists for.
- The wallet has no backup phrase. Without one the coins live in exactly
  one file and nothing can bring them back.
- The phrase changes between reveals, which would orphan every coin
  minted under the previous one.
- Restore double-counts. It runs against a live wallet, so running it
  twice must leave the balance where it was.

Reveal is also asserted to refuse a wrong password: it is the one route
here that hands out key material, and a session alone must not be enough.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-17 08:06:27 -04:00
archipelagoandClaude Opus 5 eb48eab946 feat(apps): find out when an app has fallen behind upstream
Nodes offer an update when the signed catalog pins something newer than
what's running, and that machinery is fine. The missing step was the one
before it: nothing told *us* when upstream shipped. A pin could sit at
fedimintd v0.10.0 for months while every node in the fleet correctly and
confidently reported "up to date".

The reason nothing could tell us is that a manifest records only our
mirror — `source.archipelago-foundation.org/lfg2025/fedimintd:v0.10.0`
says nothing about the project it was mirrored from. So this adds an
optional `app.upstream` block naming the real source, and a script that
asks each one what it has released.

Running it answers the question that prompted this. Of 58 apps, 28 are
behind, including LND v0.18.4-beta against v0.21.2-beta, Bitcoin Core
28.4 against 31.1, and fedimintd/gatewayd v0.10.0 against v0.10.1.

Two choices worth stating. An app with no `upstream` block is reported
as UNTRACKED rather than skipped — a silent skip is how this stayed
invisible, and before this commit all 58 were silently skipped. And a
suggestion prefers our own tag variant: telling someone pinned to
`postgres:16.13-alpine` that the newest tag is `18.6-trixie` is true and
useless, because swapping the base image is a different decision from
bumping a version.

Five apps are deliberately left untracked (barkd, immich-postgres,
indeedhub-minio, lightning-stack, pine-whisper): I could not establish
their upstream with confidence, and a wrong `repo` produces a confident
wrong verdict, which is worse than an honest gap.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-17 08:04:33 -04:00
archipelagoandClaude Opus 5 59fffc809f feat(ecash): the wallet can now be restored from a phrase (NUT-13)
Demo images / Build & push demo images (push) Failing after 2m15s
Until now every Cashu proof this node held was backed by a secret drawn
from OsRng and written to exactly one file. Losing wallet/ecash.json
lost the coins outright — no phrase to write down, and nothing the mint
could do about it. Ecash is a bearer instrument, so "one file, no
backup" was the sharpest edge in the wallet.

NUT-13 derives each proof's secret and blinding factor from (seed,
keyset id, counter) instead. The wallet becomes a phrase, and the coins
can be re-derived and re-claimed — here or in any other NUT-13 wallet.

The phrase is its own 24 words, derived from the node master seed over a
fixed HKDF path. Both halves matter: it is still covered by the node's
recovery phrase, so there is nothing extra to write down; but it is
portable, so restoring ecash into Minibits or cdk-cli does not mean
handing over the key to the entire node.

It sits on disk unencrypted, deliberately. The master seed needs the
operator's password to open, which no background mint or swap can ask
for; and this file lives beside wallet/ecash.json, which already holds
spendable bearer secrets in plaintext. It regenerates exactly those
secrets, so it is the same sensitivity class as the file next to it.
0600, like identity/nostr_secret, which is derived and persisted the
same way.

Counters are reserved *before* the mint call and never rolled back. A
gap costs a restore scan a few extra probes; a reused counter costs a
coin, because two proofs with the same secret can only be spent once.

Restore is the half that cannot be done offline: a re-derived secret is
not money until the mint's signature over it exists. /v1/restore returns
those signatures; unblinding reconstitutes the proofs. It is additive
and idempotent — coins already held are skipped by secret, spent ones
are counted but not added — so it is safe to press on a working wallet,
which is when someone is most likely to reach for it.

Existing nodes activate on the first visit to Settings → Ecash backup
phrase: that password prompt is the only moment the master seed can
legitimately be opened. New nodes get it at onboarding. Until then the
behaviour is exactly as before — valid proofs, no backup — and the card
says so rather than implying a backup already exists.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-17 07:56:34 -04:00
archipelagoandClaude Opus 5 579287ba48 feat(ecash): emit cashuB tokens, and share one payment success screen
Most wallets — Minibits, Nutstash, cdk-cli — default to reading cashuB
(V4) now, so that is what we send. cashuA stays as the fallback rather
than the default: it is still valid everywhere, so a token this wallet
cannot express in V4 (a multi-mint one) is worth sending in V3 rather
than failing the send outright. That path warns, because by the time
`send_token_at` serializes, the proofs are already marked spent.

The V4 encoder is the reference implementation's, not ours. The envelope
puts the keyset id and signature on the wire as raw CBOR bytes under
single-letter keys, and a token subtly wrong there is money the receiver
cannot redeem — so upstream owns the encoding, the way it already owns
keyset-id resolution. Our own hand-written decoder reads what upstream
writes in the new test, which is agreement between two independent
implementations rather than a round trip through one codec.

Two refusals are deliberate and tested: a multi-mint token has no V4
form, and a truncated v2 keyset id must never be baked into a token we
emit (the framework-pt case) — it is only resolvable against the mint's
keyset list.

Also folds SendBitcoinModal onto the shared PaymentSuccessPane it had a
private copy of, so on-chain, Lightning and ecash all show the same
screen and the copyable-identifier row is defined once.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-17 07:56:15 -04:00
archipelagoandClaude Fable 5 f4a1c47429 feat(wallet): ecash gets the real payment success screen, with copyable proof
Demo images / Build & push demo images (push) Failing after 2m37s
Redeeming ecash reported success as one line of small green text, while an
on-chain or Lightning payment got the full moment — amount, verb, and the
identifiers you can copy. That asymmetry matters most for ecash: it leaves
no public ledger entry, so if the payment is ever questioned there is
nothing to look up afterwards. Whatever isn't copyable at that instant is
simply gone.

The success pane is extracted from SendBitcoinModal into a shared
PaymentSuccessPane so Cashu and Fedimint show the *same* screen rather
than a lookalike, and the copyable-row treatment is defined once. Each
caller passes the identifiers its protocol actually has; ecash receive now
shows the issuing mint (newly returned by wallet.ecash-receive) and the
redeemed token itself, clamped so a long token doesn't flood the pane.

Also: the test-ecash switch is a proper toggle (role="switch", keyboard
focusable) rather than a checkbox — it selects which purse the wallet is
looking at, so it should read as a mode you are in.

SendBitcoinModal still carries its own copy of the markup; consolidating it
onto the shared component is a follow-up, deliberately not done in the same
change as the money-path wiring.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-17 07:08:15 -04:00
archipelagoandClaude Fable 5 ffec7d3114 fix(ecash): pay the mint's input fee, and stop a damaged wallet from being erased
Two independent fixes, both found while exercising the routes headlessly.

**Mint fees (NUT-02).** A mint may charge a per-input fee and rejects any
swap whose outputs don't equal inputs minus that fee — `11005 Transaction
inputs should equal outputs less fee`, which is what sending hit against
testnut.cashu.space. We ignored the fee entirely, so the wallet could not
spend at ANY fee-charging mint; Minibits charges zero, which is why
production never saw it. `MintKeyset`/`KeysetInfo` now carry
`input_fee_ppk`, `swap_fee_for` computes the NUT-02 sum (rounded up), and
`MintClient::swap` reduces its outputs to cover it — applied there rather
than at each call site so send, receive and cross-mint swaps are all
covered at once. Inputs from a keyset the mint doesn't list contribute no
fee: the mint is the authority, and guessing high would burn the sender's
coins.

**Damaged-wallet erasure.** `load_wallet` used `unwrap_or_default()`, so a
truncated `ecash.json` read as an EMPTY wallet — and because the next
operation saves the wallet back, that empty state was then written over the
only copy of the proofs. A corrupt file became permanent loss. Now a file
that exists but doesn't parse fails with a message naming the file and
stating the coins are still in it, and the bytes are left untouched for
recovery; an empty file is still treated as a fresh wallet, since a create
that never got its first write is not damage. The accepted-mints list gets
the same treatment, where corruption would have silently reset the operator
to trusting only the default mint.

Writes are now atomic (temp + fsync + rename) for both files. The previous
plain write truncated the real file first, which is exactly how a wallet
ends up unparseable after a crash or power cut.

Tests cover: a damaged file errors and survives on disk, an empty file is
fresh, saving leaves no temp behind and round-trips, and — guarding the
on-disk contract against exactly this update — a verbatim pre-update wallet
file still loads with its balance, proofs and history intact.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-17 07:01:45 -04:00
archipelagoandClaude Fable 5 26638aa621 fix(ecash): sign with the mint's SAT keyset, not whichever came first
`get_active_sat_keyset` picked the first keyset with a non-empty key map,
and `MintKeyset` had no `unit` field to filter on — so on a multi-unit mint
the wallet signed sat-denominated mint/swap requests against a usd or eur
keyset. The mint refuses that with `11013 Unit unsupported`, which is
exactly what claiming minted coins hit against testnut.cashu.space (it
serves usd, eur, msat and sat keysets). Minibits is sat-only, so this
latent bug never surfaced in production — the test-mint switch found it on
its first run.

MintKeyset now carries `unit` and `active`, both defaulted so a sat-only
mint that omits them still parses, and selection filters to sat and prefers
an active keyset.

Also: pin BIP-39 seed derivation to the specification's own test vectors.
The node's entire identity hangs off `Mnemonic::to_seed("")`, and the
`bip39` crate is no longer version-pinned (the exact pin had to be relaxed
so `cashu` could resolve). A bump that changed derivation would silently
re-key every node on the fleet and orphan every backup; both vectors —
empty passphrase and the NFKD-exercising passphrase arm — now fail the
suite instead. Verified byte-identical under the newly resolved 2.2.2.

And the route script polls the mint's quote state before claiming: the test
mint settles its own invoices, but not instantly, so claiming immediately
raced the settlement and reported a spurious "Quote not paid".

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-17 06:07:27 -04:00
archipelagoandClaude Fable 5 be2cfb8293 feat(ecash): adopt the reference NUT-02 resolver + real/test network switch
Demo images / Build & push demo images (push) Failing after 2m26s
Executes steps 1-3 of docs/cashu-cdk-migration-plan.md, plus the test-coin
switch needed to exercise these routes without spending real sats.

Protocol layer: depend on `cashu` 0.17.5 (MIT, the crate CDK is built on,
default-features off, `wallet` only). Keyset ids now go through upstream's
`Id::from_short_keyset_id` / `ShortKeysetId` instead of the prefix match
hand-rolled in 2277fc46 — same repair, but implemented by the reference
code that defines the rule, so the next spec turn is a version bump rather
than another incident. `MintClient` feeds it the mint's `/v1/keysets` in
upstream's own `KeySetInfo` shape, parsing entries individually so one
keyset in an unmodelled unit can't block resolving the id we need.

Adding the crate required relaxing `bip39 = "=2.1.0"` to `"2.1"` (resolves
2.2.2): the exact pin held `unicode-normalization` at 0.1.22 and no
resolution existed otherwise. The pin carried no recorded rationale; seed
tests cover the bump.

Network switch: `wallet.ecash-network` / `wallet.ecash-set-network`, with a
Test mode toggle in Wallet Settings → Cashu. Cashu has no testnet, so this
points the wallet at the public `testnut` mint — but crucially each network
gets its OWN wallet and accepted-mints file, because test and real proofs
in one purse would be spendable interchangeably and the balance would be a
lie. Mainnet keeps the original filenames, so existing funds files are
untouched and switching is reversible: tests assert a real balance survives
a round trip through test mode.

Headless coverage: scripts/test-ecash-routes.sh drives every ecash RPC over
the real HTTP path (network get/set, balance, history, mint quote + claim,
send, receive, double-redeem refusal, garbage input, melt quote), restores
the node's original network on exit, and exits non-zero with the failure
count.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-17 05:04:25 -04:00
archipelagoandClaude Fable 5 03cf74696d docs(ecash): pin the seed-backup UX to the existing reveal pattern
Ecash gets its own BIP-39 mnemonic derived from the node master seed:
still covered by the node's recovery phrase, but portable into any NUT-13
wallet without exposing the master seed — so 'back up my ecash' is not the
same action as 'expose the key to everything'.

Surfaced exactly like the Lightning seed: the shared SeedRevealPanel, on
the app detail page and in Settings → Backup, behind the same
verify_reveal_auth password re-entry. Standard BIP-39, so the SeedQR tab
works (no aezeed flag).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-17 04:22:29 -04:00
archipelagoandClaude Fable 5 6e23b121ea docs(ecash): plan the move to the reference Cashu implementation
Scoped from the framework-pt keyset incident: adopt the `cashu` crate
(MIT, the crate CDK is built on) for the token codec, keyset ids, crypto,
DLEQ and NUT-13, while keeping ecash.rs's on-disk contract, MintClient's
Tor seam and error table, and our multi-mint routing. Records why the
full cdk WalletDatabase shim is the wrong trade over live funds, and how
ecash backup can derive from the node's existing seed.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-17 04:07:19 -04:00
archipelagoandClaude Fable 5 2277fc4684 fix(ecash): redeem tokens whose keyset id was truncated to the old length
A Minibits token could not be redeemed on framework-pt: the mint answered
POST /v1/swap with a bare 422, which the RPC sanitizer turned into
"Operation failed. Check server logs for details." The journal had the
real reason:

  inputs[0].id: NUT02: ID length invalid, expected 8 bytes (short/v1)
  or 33 bytes (v2)

The token carried keyset id 01fc0ec0e59cd6fa — exactly the first 8 bytes
of the mint's active 33-byte id 01fc0ec0e59cd6fa01b7a88f…a821. NUT-02 v2
ids are 33 bytes behind a 0x01 version byte; the sending wallet cut it to
the 8 bytes that were the whole id under v1. The mint reads the version,
expects 33 bytes, and rejects it — so the length complaint is right even
though 8 bytes is legal for a 0x00-prefixed v1 id.

The id only names which keyset signed a proof, and the short form is a
prefix of the full one, so it can be repaired: before swapping, any
8-byte 0x01-prefixed id is expanded against GET /v1/keysets (new
MintClient::get_keysets — it lists inactive keysets too, and coins from a
retired keyset stay spendable). Preferring the active keyset on a prefix
tie. Attempting this is safe: an id naming the wrong keyset fails
signature verification at the mint and no coins move. Anything already
valid, or with no unambiguous match, is passed through so the mint's own
error still reaches the operator.

Token decoding now also checks keyset ids locally, so an id that is not
hex or is neither NUT-02 length fails with a message naming the format
instead of a raw 422 from the mint.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-17 04:06:30 -04:00
archipelagoandClaude Fable 5 9ccc325a4d fix(container): reap ghost containers so an app can't be locked out of itself
Demo images / Build & push demo images (push) Successful in 3m24s
A ghost is a container whose process tree is still running while podman
has no record of it: the exit-command's `cleanup --rm` deletes the record,
conmon and the payload survive. It keeps owning exactly what the app needs
— the published host port and the file locks in its data dir — so the
replacement container either fails to bind ("address already in use") or
starts and dies on the lock, and Restart=always loops it there forever.
Nothing in the stack could see it: every podman-level stop/rm/recreate
misses a container podman lost.

Seen twice now: 752 restarts on a fleet node (2026-08-10) and again on the
dev box today, where Gitea flapped until it fell out of My Apps. Both were
cleared by hand; container-doctor.sh has the same logic but is an
out-of-band script the daemon never calls.

- New container::ghost_reaper: finds conmon processes whose 64-hex
  container id is absent from `podman ps -a --no-trunc -q`, then kills the
  payload's children and conmon (TERM, 5s grace, then KILL — the Gitea
  ghost ignored TERM). Id-based, never name-based: killing by name would
  hit the live managed container. A failed `podman ps` reaps nothing
  rather than treating every container as a ghost.
- Hooked at repair_before_package_start (covers package.start,
  package.restart and the orchestrator start path) and in the boot
  reconciler's 30s tick, so ghosts are cleared before an app is asked to
  start and swept for every app continuously.

Restart feedback: the lifecycle RPCs return {"status":"restarting"} in
milliseconds and work in the background, so "Restarting..." flashed for a
few frames and the buttons went idle while the app was still down — the
click read as a no-op. The hero buttons now show a spinner and hold it off
the node's own state (starting/stopping/restarting/updating, plus running
+ health=starting), and the just-clicked action is held until the backend
confirms it picked the work up, with a 12s cap so an unresponsive node
still releases the controls.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-16 13:45:45 -04:00
archipelagoandClaude Fable 5 b113fafee4 fix(ui): app-gate warning names FIPS alongside LAN, Tailscale and Tor
Demo images / Build & push demo images (push) Successful in 3m28s
The mesh is a reach path like the others; omitting it understated what
turning an app's gate off exposes.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-16 12:16:34 -04:00
archipelagoandClaude Fable 5 58cdea5e79 feat(appgate): apps with their own login can skip the node login
Demo images / Build & push demo images (push) Successful in 3m33s
Some apps carry a complete account system and are broken by an upstream
challenge: git clients speak basic-auth (not browser cookies), and a
BTCPay checkout link handed to a customer must open for that customer.
Both were behind the gate's login page — the "non-browser clients need an
access token" gap disclosed in five consecutive releases.

- New manifest port policy `auth: open`: the daemon still fronts the port
  exactly like `gated` (loopback pin, external binds, frame-header fixes,
  app-down retry page, Tor upstream) but serves it without the login
  challenge. Requires auth_rationale, same burden of proof as `none`.
  Gitea 3001 and BTCPay 23000 declare it.
- Runtime operator override per app (security.set-app-gate → app-configs/
  <id>.json "gateEnabled"), surfaced as Settings → app → Access control.
  Wins over the manifest in both directions and applies on the next
  request — no restart, and it works today on catalog-covered apps whose
  signed manifest still says `gated`.
- The gate resolves policy per-request from the live port map, so a
  toggle takes effect without waiting for the 60s rebind sweep. "Off"
  never releases the port: gated apps are loopback-pinned, so releasing
  would strand them, not open them.
- security.app-gate-status now reports gate_enabled + any override.
- New guard test pins the `auth: open` set (both entries reviewed); the
  `auth: none` count moves 25 → 26, absorbing pre-existing drift from the
  phoenixd onboarding (loopback JSON API with its own generated password).
- Docs: the manifest spec's ports row documented only host/container/
  protocol — bind, auth, auth_rationale and session_passthrough were
  undocumented. Added a full "Ports & the app gate" section plus a
  developer-guide entry telling app authors to enforce their own auth
  regardless, since the operator can flip the gate either way.

Verified live on archi-dev-box from an external address: gated → 401 gate
page; override off → Gitea 200 own page, BTCPay 302 to its own login,
git-over-HTTP info/refs 200; override on → 401 again; clear → default.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-16 11:40:07 -04:00
archipelagoandClaude Fable 5 9b789a64ad docs(changelog): RSSI readings depend on radio firmware reporting them
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-16 06:18:15 -04:00
archipelagoandClaude Fable 5 4a7f466ea6 feat(mesh): radio_state reports the radio's last-RX RSSI/SNR
r_stat_rssi/r_stat_snr straight from the RNode firmware's per-packet
stat reports — the direct way to tell "firmware reports signal stats"
from "it doesn't" when a peer's RSSI shows as unknown, and a natural
read-back for the LoRa panel.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-16 06:13:54 -04:00
archipelagoandClaude Fable 5 64205d23b7 docs(changelog): draft v1.8.4-alpha entries for the release-fix batch
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-16 06:09:39 -04:00
archipelagoandClaude Fable 5 3a3077529b feat(kiosk): companion remote drives app iframes via trusted CDP input
Demo images / Build & push demo images (push) Successful in 3m11s
Companion tap/scroll/type now works INSIDE cross-origin app iframes and
kiosk tabs. The web relay synthesizes untrusted DOM events in the top
document, which can never cross an origin boundary — so apps served
through the appgate were dead to the remote. The kiosk Chromium now
exposes a loopback-only CDP port (default origin check intact, no
--remote-allow-origins) and a backend bridge (api/handler/cdp.rs)
dispatches validated companion input as Input.dispatchKeyEvent /
dispatchMouseEvent / mouseWheel — trusted events that hit-test through
any frame, move real focus, and insert text like a physical device.

- Session keeper self-heals across kiosk Chromium restarts; inert on
  nodes without a kiosk unit (falls back to the existing relay path).
- The kiosk relay subscriber self-tags (?kiosk=1) and the backend mutes
  its key/click/scroll messages while the bridge is live, so input never
  applies twice; cursor moves still flow for the on-screen cursor.
- While companion input is active the native OS pointer is hidden
  (cursor:none, auto-restores 30s after the last event) so the dead
  physical-mouse cursor doesn't sit next to the virtual one.
- docs/tv-input-iframe-apps.md scope note updated: gamepad keys stay on
  uinput; CDP is for companion pointer/typing only.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-16 05:28:53 -04:00
archipelagoandClaude Fable 5 876ecc4bdf fix(ui): replace native confirm() dialogs with the global in-app modal
window.confirm blocks the JS event loop, which froze companion remote
input while open — the remote user could raise the mesh "Clear" prompt
(or reboot / backup-delete / uninstall confirms) and then never dismiss
it, because the synthetic events that would dismiss it queue behind the
dialog itself.

New promise-based appConfirm() (useAppConfirm.ts) + one AppConfirmModal
mounted globally in App.vue, built on BaseModal (Teleport-to-body,
full-viewport backdrop, glass card — the canonical modal contract). All
six native confirm() call sites migrated: mesh clear-all, mesh message
delete, dashboard reboot, backup delete, backup USB copy, app uninstall.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-16 05:28:53 -04:00
archipelagoandClaude Fable 5 458444d700 fix(mesh): report real RSSI/SNR for Reticulum peers instead of a fake 0
Every Reticulum-heard peer surfaced as rssi=0 — indistinguishable from a
real 0 dBm reading and, worse, from "heard over the TCP bridge with no
radio involved at all", which made a TCP-fed mesh look like working RF
during the 2026-08-16 radio diagnosis.

- Sidecar: announce handler now uses the 4-arg RNS dispatch to get the
  announce packet hash and reports per-announce rssi/snr from Reticulum's
  packet-stat cache; LXMF deliveries report message.rssi/snr/q (LXMF
  already populates them on direct RNode hops). All None over TCP or
  multi-hop — the honest RF-vs-internet discriminator.
- Rust: ReticulumPeer caches last_rssi/last_snr from announce and recv
  events (a TCP-relayed announce never blanks a real RF reading), and
  get_contacts surfaces them so refresh_contacts propagates real values.
- Identity discovery no longer hardcodes rssi 0: unknown is now None
  end-to-end and logged as such.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-16 04:52:04 -04:00
archipelagoandClaude Fable 5 519fa68c72 fix(federation): end the perpetual peer-joined "Invalid signature" storm
Root cause observed live 2026-08-16: onboarding/seed-restore rewrite
identity/node_key on disk but server_info.pubkey is only seeded at boot,
so until the next restart every peer-joined advertised the stale boot key
while signing with the new seed-derived key — deterministically rejected
by every receiver, once per 90s heal tick, forever.

- seed.generate / seed.restore now refresh server_info.pubkey in the live
  snapshot immediately (mirrors the DID-rotation handler).
- The 90s heal loop advertises the SAME key it signs with (disk identity,
  like federation sync already did) instead of the boot snapshot.
- notify_join no longer logs "delivered" for an HTTP-200 JSON-RPC
  rejection; in-band errors are terminal (identical signed bytes can
  never succeed on retry).
- The heal loop backs off per peer (doubling toward a daily re-assert)
  instead of re-notifying every 90s forever — Observer-held peers never
  appear in Trusted-only exported hints, so they_list_us could never
  become true for them.
- Receiver now binds the DID to the advertised pubkey (the old check was
  self-referential) and logs malformed signatures distinctly from
  genuine mismatches.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-16 04:45:39 -04:00
archipelagoandClaude Fable 5 809f7649a4 fix(mesh): plug-and-play radio detection in all situations
Three root causes from the 2026-08-16 framework-pt incident where a
replugged radio detected but never connected:

- detect_serial_devices scanned a hardcoded ttyUSB0-2/ttyACM0-2 list, so
  a radio enumerating at index 3+ was permanently invisible. Now scans
  /dev for all ttyUSB*/ttyACM* nodes (deterministic order, /dev/mesh-radio
  alias still first and still wins the dedup).
- An operator rnode-rf-settings.json port override silently outranked the
  device_path the user just chose in the detection modal. mesh.configure
  now clears a stale override when a different device is configured
  (symlink-resolved compare keeps /dev/mesh-radio aliases intact).
- Espressif native-USB boards (303a, ESP32-S2/S3/C3 RNodes) had no udev
  rule, so they never got the stable /dev/mesh-radio alias and a persisted
  alias path dangled after a port move.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-16 04:38:49 -04:00
archipelagoandClaude Fable 5 c5cd751bcf fix(nginx): a moved or slow-to-DHCP node no longer loses its whole web UI
setup-node-ca.sh writes one 'listen <addr>:443 ssl;' per LAN address at
the moment it runs (per-address on purpose — Tailscale holds :443 on the
tailnet address) and its idempotency guard never revisits them. nginx
REFUSES TO START while any listen address is missing, so this takes the
entire dashboard down, not just HTTPS:
  1. the node moves networks and the old address is gone; or
  2. nginx starts before DHCP assigns the address — and nginx.service
     ships no Restart=, making that single race permanent.
Both hit archi-dev-box today: nginx dead since boot on 'bind() to
192.168.63.240:443 failed (99: Cannot assign requested address)', the
dashboard simply unreachable, which is exactly the symptom a user with
no screen cannot diagnose.

run_nginx_listener_repair drops listeners for absent addresses, adds one
per present address (CGNAT excluded), installs behind  with
rollback, then starts nginx if it is down and gives it a
Restart=on-failure drop-in so the boot race stops being fatal.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-15 11:49:40 -04:00
archipelagoandClaude Fable 5 203c2b6e50 fix(async): finish the blocking-call sweep — scan, 3 SSH handlers, DNS
A codebase sweep for siblings of e282c059 (blocking network I/O parked
on the tokio runtime) found the openwrt fix was incomplete:

- openwrt.scan: scan_subnet is async in name only — up to 255 SEQUENTIAL
  blocking TCP probes at 500ms each (~2 min on a /24 that silently
  drops) plus a blocking SSH verify per candidate. One click of 'scan
  for routers' held a worker for that whole time. Now spawn_blocking.
- provision-tollgate / scan-wifi / configure-wan still ran their SSH
  exchanges inline; bounded_tcp caps each socket op but a session is
  many sequential ops (provision runs opkg install over SSH), so worst
  case was minutes. All three now spawn_blocking.
- network::check_dns: blocking glibc to_socket_addrs with no app-level
  bound, on every Server-tab load via network.diagnostics. Against a
  stale resolver — the moved-network case — that is 5-40s per refresh.
  Now spawn_blocking plus a 5s cap, so the tile reports 'no DNS'
  instead of hanging.

Verified false positives left alone: every other bare TcpStream::connect
targets 127.0.0.1 (fails instantly), and every remote reqwest client
already sets a timeout.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-15 11:03:08 -04:00
archipelagoandClaude Fable 5 6e89acced7 fix(network): SSDP discovery no longer parks a tokio worker for 3s
check_upnp_available uses a blocking std UdpSocket and, on a network
with no UPnP gateway (the normal case right after a node moves), runs
out its full 3s read timeout. Inline on the runtime that blocked a
worker on every call, from four call sites. Same class as the OpenWrt
SSH stall (e282c059), smaller blast radius — move it to spawn_blocking.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-15 10:22:44 -04:00
archipelagoandClaude Fable 5 e282c05911 fix(openwrt): unbounded blocking SSH connect no longer stalls the whole API
Router::connect/connect_password did a blocking std TcpStream::connect
with no timeout, inline on the tokio runtime. Against a router that
stayed behind when its node moved networks (framework-pt, 2026-08-15),
every dashboard poll of openwrt.get-status parked a worker thread for
the OS connect timeout (~2 min) — overlapping polls stalled unrelated
RPCs for 25s+ at a time, sessions timed out, and TOTP codes expired
before the backend verified them.

- bounded_tcp(): 5s connect timeout + 30s read/write timeouts on the
  session socket, shared by both connect paths.
- openwrt.get-status runs its SSH exchange on spawn_blocking, so even a
  slow router can only slow its own tile, never the API.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-15 09:52:03 -04:00
archipelagoandClaude Fable 5 9c675e5c7d fix(login): backend-unreachable no longer masquerades as a fresh node
Demo images / Build & push demo images (push) Successful in 3m4s
auth.isSetup failing (backend warming up after boot, transient proxy
blip) dropped Login.vue into its catch and showed 'Set Up Your Node' on
a fully-onboarded node — seen on framework-pt right after its network
move, and the same fail-open class RootRedirect already fixed for the
intro flash. Errors now fail toward the ordinary login form and a
background probe re-asks until the backend answers; a genuinely fresh
node flips to the setup form on the first successful probe.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-15 09:36:37 -04:00
archipelagoandClaude Fable 5 6833920778 feat(bitcoin): autoprune default raised 550 → 50000 MB
Small-disk nodes (<1000 GB data volume) keep the same dynamic
prune-vs-archival logic but now retain ~50 GB of recent blocks instead
of the bare 550 MB minimum. Takes effect for catalog-covered installs
at the next catalog regeneration + signing.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-15 09:23:57 -04:00
archipelagoandClaude Fable 5 ec2e6375ed feat(bootstrap): two OTA heals for network moves + registry renames
Both failure modes are from framework-pt relocating (2026-08-15):

- archy-ha-btc-rpc-proxy bound socat to the LAN IP baked in at unit
  generation; after a move the address no longer exists and the unit
  restart-looped forever (counter 2446). run_ha_rpc_proxy_bind_repair
  rewrites ExecStart to compute the bind address at each start, so
  Restart=always itself heals any future move.
- homeassistant's quadlet pointed at the domain image ref with --pull
  never while local storage held the same name:tag under the bare-IP
  registry ref (catalog signing rename) — 761 restarts on 'image not
  known'. run_pull_never_image_repair retags a matching local image;
  it deliberately never pulls.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-15 09:23:57 -04:00
archipelagoandClaude Fable 5 1587853ce2 fix(banner): console banner shows the reachable LAN address, not the WG tunnel IP
The welcome banner picked its address with 'hostname -I | awk {print $1}',
so a node with WireGuard up advertised 10.44.0.1 — its own tunnel address,
present on EVERY node — as its web ui / ssh address. Off-tunnel that is
unreachable, and after a headless box moves to a new network it is exactly
the wrong thing to trust (framework-pt, 2026-08-15).

- Pick the default route's source address; fall back to the first address
  that is not WireGuard 10.44/16, CGNAT 100.64/10, or loopback.
- Also print http://<hostname>.local when avahi is up — the one address
  that survives any DHCP change, which is the real answer for headless
  boxes that move between networks.
- scripts/welcome-banner.sh is the new canonical copy, embedded in the
  binary (tor-helper pattern): bootstrap::run_welcome_banner_sync rewrites
  /etc/profile.d/archipelago.sh on ISO-installed nodes at startup, so the
  fix reaches the deployed fleet with the next OTA instead of only fresh
  ISOs. Machines without an installer-baked banner are left untouched.
- Same fix inlined in the live ISO builder's PROFILE heredoc
  (image-recipe/_archived/build-auto-installer-iso.sh).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-15 08:37:13 -04:00
archipelagoandClaude Fable 5 56d6396142 feat(appgate): gate login gets the real dashboard badge + glass-button states
Demo images / Build & push demo images (push) Successful in 3m0s
- The badge is now the dashboard login's AnimatedLogo, square for square:
  inline SVG (20 white rects, 100ms stagger, 3s loop) inside the same
  gradient ring. The old <img> of favico-black-v2.svg baked a second ring
  into the ring and couldn't animate; the asset leaves the gate allowlist
  since nothing references it now.
- The submit button is .glass-button longhand: hover lift + lightening +
  rim glow, active press, disabled dim — the flat darken-only hover read
  as broken next to /login.
- Loading state: submitting flips the button to spinner + 'Signing in…'/
  'Verifying…' and disables it, via a single inline script admitted by
  CSP sha256 hash (not unsafe-inline; injected markup stays inert, and
  the page still works as a plain POST without JS).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-15 08:24:27 -04:00
archipelagoandClaude Fable 5 e0d8b9de74 fix(ui): login badge back to the original — gloss stays screensaver/intro only
The Kammergut gloss v3 opt-in had been applied to the /login badge as
well; per operator the glossed disc belongs ONLY on the screensaver and
the onboarding intro (and the splash tap-logo that fronts them). The
login page returns to the plain gradient-ring badge it always had, same
as the dashboard sidebar fix before it.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-15 08:24:19 -04:00
archipelagoandClaude Fable 5 d422218c6b chore(demo): rebuild bundled AIUI with the Routstr provider picker
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-14 13:41:17 -04:00
archipelagoandClaude Fable 5 a4be1b4b7d feat(aiui): Routstr tops the model picker with the full live catalog
New 'Routstr (sats)' category sits FIRST in the model dropdown
(operator request 2026-08-14), listing every model the node's
/aiui/api/routstr/models proxy returns (432 live today) — the picker
panel now scrolls (max-h 70vh) instead of overflowing. Selecting a
Routstr model routes the turn through the node's paid completions
proxy, and the explicit choice wins even when AIUI runs embedded in
Archy — a selection, not a fallback. Node refusals (no budget armed,
budget spent, wallet can't fund) surface verbatim in chat.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-14 13:41:17 -04:00
archipelagoandClaude Fable 5 e3bd340725 feat(aiui): Routstr as an explicit, session-gated AI provider path
The D-04 Routstr leg was fallback-only — never user-selectable, and its
Nostr discovery parses a docs-shaped event content ({endpoints, models,
pricing}) that live kind-38421 announcements don't actually carry
({name, about}), so it could never match a real provider. This adds the
explicit path AIUI's model picker needs: /aiui/api/routstr/models
passes through the live aggregator catalog (the instance routstr.com's
own frontend queries; the canonical api.routstr.com 404s), and
/aiui/api/routstr/chat/completions makes one paid, non-streaming,
OpenAI-shaped call — session-gated, egress-screened (S3), refused
without an armed operator budget (D-05), paid via auto_pay_token,
change and refused-request tokens redeemed back into the wallet so a
failed attempt nets zero (verified live: quoted=1 reclaimed=1 net=0).
nginx template gains the location in both server blocks (T-13-15).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-14 13:41:07 -04:00
archipelagoandClaude Fable 5 ced95a60d1 feat(wallet): Lightning gets the arrival screen; copy buttons unified
Demo images / Build & push demo images (push) Successful in 3m27s
- lnd.createinvoice now returns r_hash_hex; new lnd.invoicestatus RPC
  looks the invoice up (SETTLED + amt_paid_sat). E2E-verified on this
  box: real invoice minted, status polls settled:false until paid.
- Receive modal: Lightning polls settlement every 3s and flips to the
  on-chain-style success view — straight to the green check + amount
  (no broadcast step; settlement is final). Raw bolt11 text removed:
  QR + CopyButton only. State fully reset per open/close.
- CopyButton is now the wallet's only copy affordance: the ark-address
  and ecash-token holdouts swapped in, their ad-hoc handlers deleted.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-14 09:43:30 -04:00
archipelagoandClaude Fable 5 a0bd9e53f8 feat(settings): CA generation from the UI; Routstr panel beside the API key
Demo images / Build & push demo images (push) Successful in 3m36s
WebUI RULE (operator, 2026-08-14): never point users at a terminal. The
certificate section told users to run setup-node-ca.sh by hand — it now
has a Generate button backed by system.node-ca.generate, which runs the
idempotent script server-side (live-tested: generated and /ca.crt serves).
Routstr budget panel moves directly under the Claude API key card.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-14 09:19:05 -04:00
archipelagoandClaude Fable 5 6137762786 feat(settings): Routstr AI budget panel — the integration's missing switch
Demo images / Build & push demo images (push) Successful in 3m29s
The Routstr backend (Cashu-paid inference fallback, shipped 1.7.127) was
fully wired but permanently dormant: its D-05 gate requires an
operator-set sats allowance and nothing in the UI ever called
assistant.budget-get/set — default 0 meant never selected. New Settings
panel (below AI Data Access): allowance/spent/remaining, set-allowance
with 0-disables semantics, enabled/off badge. Backend untouched.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-14 08:57:53 -04:00
archipelagoandClaude Fable 5 8d1fda29fa feat(federation): peer requests take the stage — clustered and faced
Demo images / Build & push demo images (push) Successful in 3m10s
Requests were spread evenly around the orbit, so they could sit BEHIND
the globe: the blinking call-to-action was invisible and the chart read
as mis-scaled until the user hand-rotated. Now requests cluster tightly
at one stage angle (spacing shrinks as count grows) and, when a NEW
request arrives, the camera steers to face the cluster front-and-center
(depth ∝ sin(angle−rotY); front = angle+π/2) — arrival only, so a user
who rotates away isn't fought. Static/reduced-motion paths snap+render.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-14 07:36:38 -04:00
archipelago 135fb5650b chore: release v1.8.3-alpha
Demo images / Build & push demo images (push) Successful in 3m43s
2026-08-14 06:34:47 -04:00
archipelagoandClaude Fable 5 1de4a0943e docs(changelog): curate v1.8.3-alpha notes + What's New block
Demo images / Build & push demo images (push) Successful in 3m42s
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-14 05:13:43 -04:00
archipelagoandClaude Fable 5 b5e33784e6 fix(ui): kiosk map animates again + paints on resize; gloss scoped; icons get intrinsic size
Demo images / Build & push demo images (push) Successful in 3m42s
- NetworkMap3D: kiosks keep static PLACEMENT (the rAF-fragile intro was
  the blank-screen cause) but re-attach the half-rate ticker — the calm
  orbit is back; and measure() now renders explicitly when no ticker runs,
  so resizes repaint instead of leaving a stale/blank/mis-scaled
  projection (also fixes reduced-motion users on any screen).
- Gloss v3 scoped to .logo-gloss opt-in (screensaver, intro, login,
  splash tap-logo) — it had leaked onto every logo-gradient-border user,
  including the dashboard header, via AnimatedLogo's default border.
- normalize-app-icon.py output now carries intrinsic 512x512 dimensions:
  a viewBox-only SVG collapses to nothing in auto-sized tiles (the
  'transparent icon in My Apps' report); both app icons regenerated.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-14 05:11:54 -04:00
archipelago 2b7e92e770 chore: release v1.8.2-alpha
Demo images / Build & push demo images (push) Successful in 3m43s
2026-08-14 04:28:12 -04:00
archipelagoandClaude Fable 5 7c34df36cd feat(ui): app icons on the house canvas; detail page gets the tile treatment
Demo images / Build & push demo images (push) Successful in 3m33s
- alby-hub + phoenixd icons re-set with the standard 12% inner margin
  (they shipped edge-to-edge; every other icon carries whitespace).
- scripts/normalize-app-icon.py: wraps any third-party SVG mark onto the
  house canvas — the system applies the tile plate (archy-app-icon)
  automatically but deliberately no runtime inset, so the margin must be
  baked; the guide now says exactly that.
- MarketplaceAppDetails: the icon now carries archy-app-icon like the
  store tiles — the treatment no longer stops at the detail page.
- v1.8.2 changelog: third curated bullet (the ceremony gate requires 3).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-14 04:22:28 -04:00
archipelagoandClaude Fable 5 4b4e1ab1a3 feat(ui): Kammergut gloss v3 — wet black paint on the logo badge, approved
Demo images / Build & push demo images (push) Successful in 3m43s
Pure-CSS build (the plan-b SVG text filter embosses artifacts on a disc
— v1 rejected for exactly that): borderless painted disc with warm
Kammergut-toned light, dense gradient stops + turbulence grain dither
(banding), and a radial top bloom instead of a linear streak (a linear
streak's tips seamed against the rim — operator screenshot). Iterated
headlessly + on a live preview server; operator approved 2026-08-14.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-14 04:11:42 -04:00
archipelagoandClaude Fable 5 d05fa6988d fix(federation): kiosk map goes fully static — kills the blank-load stall
Demo images / Build & push demo images (push) Successful in 3m31s
The GSAP entrance intro needs healthy rAF delivery to reach opacity 1;
on a paint-starved kiosk it stalls and the federation/peers screen reads
as BLANK until a lucky refresh. Kiosks now take the existing staticMode
branch (no intro, no ticker — everything lands in place instantly); the
2D default and 2D/3D toggle stay. Half-rate tick kept for any future
non-static kiosk path.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-14 03:57:05 -04:00
archipelagoandClaude Fable 5 2399eeac66 feat(ui): auto-tab fallback — embed-refusing apps become tab apps
Demo images / Build & push demo images (push) Successful in 3m49s
An app whose frame never loads while its backend reports Running (the
embed-refusal signature: frame-busting JS, top-level-origin apps,
SameSite=Strict logins — everything the gate's header stripping cannot
fix) is remembered in localStorage; every later launch opens a tab
straight from the click (user gesture, so no popup blocker), and
opensInTab() gives it the tab-launch icon. A successful iframe load
clears the memory and entries expire after 7 days, so nodes that gain
embedding (gate improvements) get re-probed instead of being remembered
broken forever. Dev guide updated; v1.8.2 changelog + What's New curated.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-13 20:23:04 -04:00
archipelago 63cb9dd22c Revert "feat(ui): Kammergut gloss test on the logo badge inner circle"
Demo images / Build & push demo images (push) Successful in 3m51s
This reverts commit 6672d978f7.
2026-08-13 15:02:36 -04:00
archipelago 246916c77b chore: release v1.8.1-alpha
Demo images / Build & push demo images (push) Successful in 3m48s
2026-08-13 14:30:16 -04:00
archipelagoandClaude Fable 5 00416c3c24 feat(app-catalog): curated store entries for Alby Hub + phoenixd
The hand-curated app-catalog/catalog.json is the release gate's drift
baseline; the generator syncs fields but never adds entries, so the two
new apps needed appending — fields taken verbatim from their manifests
(drift check green, 30 catalog / 58 manifest apps).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-13 13:48:03 -04:00
archipelagoandClaude Fable 5 1dc6d3e0e3 feat(catalog): Alby Hub + phoenixd live; registry refs move to the domain
Signed catalog: 68 apps (alby-hub v1.23.0 + phoenixd 0.9.0 join), every
image ref rewritten from the retired bare-IP host to the Foundation
domain. Trust floor promoted in this same commit: all five active fleet
nodes confirmed on 1.8.0-alpha (which trusts the domain); archy-x250-beta
is root-pin-stranded pre-.122 and needs a re-image regardless.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-13 13:44:11 -04:00
archipelagoandClaude Fable 5 816a06747a docs(changelog): curate v1.8.1-alpha notes + What's New block
Demo images / Build & push demo images (push) Successful in 3m35s
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-13 09:26:46 -04:00
archipelagoandClaude Fable 5 9243babcdb feat(kiosk): graphics tiers + Settings knob; network map kiosk mode
Demo images / Build & push demo images (push) Successful in 3m51s
The animated federation map froze the framework-pt 4K TV: the launcher
held every machine to the HD 5500-era choppy-audio flags (single raster
thread, GpuRasterization banned) while the map wrote SVG attrs at 60fps.

- Launcher: two flag tiers. legacy = the proven conservative set; modern
  (Intel gen8+, 'NNth Gen' models, AMD Ryzen) = default raster threads +
  GPU rasterization. Classified from /proc/cpuinfo (11 model strings
  covered by tests in-session); KIOSK_GRAPHICS=performance|quality in
  kiosk-display.conf overrides; headless unchanged. Reaches deployed
  kiosks via the include_str! self-heal, same as the vsync fix.
- system.kiosk-display.get/set: carries a 'graphics' field alongside
  'preset'; setting one no longer clobbers the other.
- Settings → Display: Graphics picker (Auto / Compatibility / Quality).
- NetworkMap3D: kiosks default to the 2D projection (remembered toggle
  still works) and tick at half rate with carried-over deltas — same
  spin speed, half the paint cost.
- Changelog: curated Unreleased notes for all of the above + the gate
  frame-embedding fix.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-13 09:23:07 -04:00
archipelagoandClaude Fable 5 6672d978f7 feat(ui): Kammergut gloss test on the logo badge inner circle
Demo images / Build & push demo images (push) Successful in 3m46s
Black gloss paint from plan-b's Kammergut wordmark (verbatim #paintGloss
SVG filter + the .paint-3d sheen gradient) applied to
.logo-gradient-border::after — the circle behind the A on the
screensaver, intro, splash and login. Marked as a TEST in both files;
revert = git revert of this one commit.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-12 13:21:45 -04:00
archipelagoandClaude Fable 5 a80712963c feat(appgate): proxied apps become embeddable — gate neutralizes frame blocking
Apps that ship X-Frame-Options (Alby Hub: DENY) or a CSP frame-ancestors
directive rendered as a dead grey pane in the dashboard's embedded app
session; the historical fix was a bespoke per-app nginx strip proxy
(gitea). The gate now removes X-Frame-Options and strips ONLY the
frame-ancestors directive from proxied responses — the rest of the app's
CSP passes through untouched. The clickjacking threat those headers
address is handled the same way the gate's own pages handle it: every
proxied request is authenticated first, and the gate already declares
permissive frame-ancestors on its own responses. Unit-tested; verified
live on archi-dev-box (Alby Hub embeds, CSP intact).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-12 13:05:25 -04:00
archipelagoandClaude Fable 5 76e6f06995 fix(phoenixd): dot-free datadir + data_uid; docs: iframe rules
phoenixd: the orchestrator treats bind paths containing a dot as file
mounts and never creates their source dir, so the image's default
/phoenix/.phoenix target crash-looped the unit (statfs: no such file).
Datadir moved to /data via PHOENIX_DATADIR; data_uid 1000:1000 matches the
image's phoenix user — without it phoenixd dies on phoenix.conf
'Permission denied'. Both verified end-to-end on archi-dev-box: orch
install OK, seed.dat + db on the host, authenticated /getinfo answers.

alby-hub: launch flips to embedded — pairs with the gate change that
neutralizes upstream frame blocking.

Dev guide: iframe embedding rules (who blocks framing and why the gate
may strip it; when open_in_new_tab is legitimate; test in the embedded
session, never a tab).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-12 12:38:17 -04:00
archipelagoandClaude Fable 5 b7ba35477c docs(dev-guide): package.install needs dockerImage too; helper gotchas
Learned installing alby-hub/phoenixd for real: the id-only payload fails
with 'Missing dockerImage' (the store normally injects the image from the
catalog), the session helper silently reuses a stale cached session
without ARCHY_FORCE_LOGIN=1, needs jq, and its set -euo pipefail kills an
interactive shell chain without output — so the guide now wraps the flow
in a heredoc subshell.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-12 12:15:55 -04:00
archipelagoandClaude Fable 5 e87e8017bf docs(dev-guide): real pre-catalog testing flow on a live node
The old RPC example skipped login entirely and implied disk manifests show
up in the App Store. Documents: store lists signed-catalog + Nostr apps
only; the runtime-payload staging path (naive /opt/archipelago/apps copies
are deleted on every backend start); the rpc.bash session helper; and the
full lifecycle loop to run before submitting to the catalog.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-12 12:09:58 -04:00
archipelagoandClaude Fable 5 6168f6a7d0 fix(alby-hub): host port 8087→8187 — 8087 is netbird's
Caught by the orchestrator's collision check on archi-dev-box.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-12 11:57:23 -04:00
archipelagoandClaude Fable 5 fdd26ba1e3 feat(apps): Alby Hub 1.23.0 + phoenixd 0.9.0 manifests with official icons
Demo images / Build & push demo images (push) Successful in 4m20s
Both images mirrored to the Foundation registry. Alby Hub: gated web UI
on 8087, LDK data under /var/lib/archipelago/alby-hub. phoenixd: headless
loopback API on 9740 (own password auth), seed dir preserved under
/var/lib/archipelago/phoenixd. Not yet in the signed catalog — disk
manifests only, pending install verification on archi-dev-box.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-12 11:55:17 -04:00
archipelago a7a6528b08 chore: release v1.8.0-alpha
Demo images / Build & push demo images (push) Successful in 4m40s
2026-08-12 08:59:14 -04:00
archipelagoandClaude Fable 5 e751b7c6f9 feat(ui): What's New block for v1.8.0-alpha
Demo images / Build & push demo images (push) Successful in 3m43s
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-12 07:36:39 -04:00
archipelagoandClaude Fable 5 a500a75235 style: rustfmt update.rs — unblock release gate
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-12 07:35:54 -04:00
archipelagoandClaude Fable 5 71a57c3ec1 docs(changelog): curate v1.8.0-alpha notes — alpha goes open source
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-12 07:32:32 -04:00
Archipelago b67e1527a2 Archipelago — open-source initial import 2026-08-12 10:55:50 +00:00
334 changed files with 17408 additions and 2038 deletions
+93
View File
@@ -0,0 +1,93 @@
Copyright 2011 The Montserrat Project Authors (https://github.com/JulietaUla/Montserrat)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
+2 -2
View File
@@ -11,8 +11,8 @@ android {
applicationId = "com.archipelago.app" applicationId = "com.archipelago.app"
minSdk = 26 minSdk = 26
targetSdk = 35 targetSdk = 35
versionCode = 45 versionCode = 47
versionName = "0.5.25" versionName = "0.5.27"
vectorDrawables { vectorDrawables {
useSupportLibrary = true useSupportLibrary = true
@@ -1,5 +1,40 @@
package com.archipelago.app package com.archipelago.app
import android.app.Application import android.app.Application
import android.os.Looper
import android.webkit.WebView
import com.archipelago.app.data.ServerPreferences
import com.archipelago.app.fips.FipsNative
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
class ArchipelagoApp : Application() class ArchipelagoApp : Application() {
private val warmupScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
override fun onCreate() {
super.onCreate()
// Warmups that otherwise land inside the first frame:
// - FipsNative.available dlopens the 7 MB Rust core; referenced from
// composition (NESMenu, mesh auto-start), it blocked the UI thread.
// - The first DataStore read gates the nav graph's start destination;
// parsing it here means the launch gate resolves in the first
// emission instead of waiting on cold disk IO.
warmupScope.launch {
FipsNative.available
runCatching { ServerPreferences(this@ArchipelagoApp).launchState.first() }
}
// First WebView construction pays Chromium provider load (~150-400 ms
// cold). Absorb it while the main thread is idle before the kiosk
// needs it, instead of serially after the connection probe.
Looper.getMainLooper().queue.addIdleHandler {
runCatching { WebView(this).destroy() }
false // one-shot
}
}
}
@@ -9,6 +9,7 @@ import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import com.archipelago.app.ui.navigation.AppNavHost import com.archipelago.app.ui.navigation.AppNavHost
import com.archipelago.app.ui.screens.releaseKioskWebView
import com.archipelago.app.ui.theme.ArchipelagoTheme import com.archipelago.app.ui.theme.ArchipelagoTheme
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
@@ -19,7 +20,13 @@ class MainActivity : ComponentActivity() {
private val pendingPairUri = MutableStateFlow<String?>(null) private val pendingPairUri = MutableStateFlow<String?>(null)
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
installSplashScreen() // Hold the branded system splash until the nav graph has its launch
// state — without this the splash dropped at the first composed frame,
// which was EMPTY (the DataStore read hadn't landed): splash → black
// flash → UI on every launch.
var navReady = false
val splash = installSplashScreen()
splash.setKeepOnScreenCondition { !navReady }
enableEdgeToEdge() enableEdgeToEdge()
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
pendingPairUri.value = intent?.dataString pendingPairUri.value = intent?.dataString
@@ -29,6 +36,7 @@ class MainActivity : ComponentActivity() {
AppNavHost( AppNavHost(
pairUri = pairUri, pairUri = pairUri,
onPairUriConsumed = { pendingPairUri.value = null }, onPairUriConsumed = { pendingPairUri.value = null },
onReady = { navReady = true },
) )
} }
} }
@@ -38,4 +46,14 @@ class MainActivity : ComponentActivity() {
super.onNewIntent(intent) super.onNewIntent(intent)
pendingPairUri.value = intent.dataString pendingPairUri.value = intent.dataString
} }
override fun onDestroy() {
super.onDestroy()
// Swiped out of recents (or otherwise finished) — let go of the
// retained kiosk WebView so the next launch starts clean. Without
// this the FIPS service keeps the process (and the static WebView)
// alive, and "close the app" no longer restarted it. isFinishing
// keeps config changes (rotation) on the fast reattach path.
if (isFinishing) releaseKioskWebView()
}
} }
@@ -9,6 +9,7 @@ import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.core.stringSetPreferencesKey import androidx.datastore.preferences.core.stringSetPreferencesKey
import androidx.datastore.preferences.preferencesDataStore import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.map
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "server_prefs") private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "server_prefs")
@@ -29,6 +30,18 @@ data class ServerEntry(
/** Label to show in lists — the user-given name, or the address if unnamed. */ /** Label to show in lists — the user-given name, or the address if unnamed. */
fun displayName(): String = name.ifBlank { address } fun displayName(): String = name.ifBlank { address }
/**
* Is this node reachable over the Archipelago FIPS mesh?
*
* A node that advertised either identity (npub) or a mesh address (ULA)
* came from a FIPS-capable pairing QR. Anything else — a hand-entered LAN
* box, someone else's server behind their own VPN — is a plain HTTP
* target, and the companion must NOT raise its own tunnel for it: Android
* allows exactly one VPN at a time, so doing so would silently take the
* tunnel away from whatever the user actually uses to reach that node.
*/
fun isFipsNode(): Boolean = npub.isNotBlank() || meshIp.isNotBlank()
/** Bracket bare IPv6 literals (the mesh ULA) so they form valid URLs. */ /** Bracket bare IPv6 literals (the mesh ULA) so they form valid URLs. */
private fun urlHost(host: String): String = private fun urlHost(host: String): String =
if (host.contains(":") && !host.startsWith("[")) "[$host]" else host if (host.contains(":") && !host.startsWith("[")) "[$host]" else host
@@ -89,9 +102,9 @@ class ServerPreferences(private val context: Context) {
private val introSeenKey = booleanPreferencesKey("intro_seen") private val introSeenKey = booleanPreferencesKey("intro_seen")
private val gestureHintSeenKey = booleanPreferencesKey("gesture_hint_seen") private val gestureHintSeenKey = booleanPreferencesKey("gesture_hint_seen")
val activeServer: Flow<ServerEntry?> = context.dataStore.data.map { prefs -> private fun activeServerFrom(prefs: Preferences): ServerEntry? {
val address = prefs[activeAddressKey] ?: return@map null val address = prefs[activeAddressKey] ?: return null
ServerEntry( return ServerEntry(
address = address, address = address,
useHttps = prefs[activeHttpsKey] ?: false, useHttps = prefs[activeHttpsKey] ?: false,
port = prefs[activePortKey] ?: "", port = prefs[activePortKey] ?: "",
@@ -102,19 +115,52 @@ class ServerPreferences(private val context: Context) {
) )
} }
// distinctUntilChanged on every flow: DataStore emits on EVERY write to the
// file regardless of key, and each spurious emission recomposed whatever
// screen collected it (the kiosk recomposed on gesture-hint writes).
val activeServer: Flow<ServerEntry?> = context.dataStore.data
.map { prefs -> activeServerFrom(prefs) }
.distinctUntilChanged()
val savedServers: Flow<List<ServerEntry>> = context.dataStore.data.map { prefs -> val savedServers: Flow<List<ServerEntry>> = context.dataStore.data.map { prefs ->
val raw = prefs[savedServersKey] ?: emptySet() val raw = prefs[savedServersKey] ?: emptySet()
raw.mapNotNull { ServerEntry.deserialize(it) } // Sorted so set-iteration order can't produce a structurally different
} // list for the same servers (which defeats distinctUntilChanged).
raw.mapNotNull { ServerEntry.deserialize(it) }.sortedBy { it.displayName() }
}.distinctUntilChanged()
val introSeen: Flow<Boolean> = context.dataStore.data.map { prefs -> val introSeen: Flow<Boolean> = context.dataStore.data.map { prefs ->
prefs[introSeenKey] ?: false prefs[introSeenKey] ?: false
} }.distinctUntilChanged()
/** One-shot flag for the three-finger-hold teaching overlay. */ /** One-shot flag for the three-finger-hold teaching overlay. */
val gestureHintSeen: Flow<Boolean> = context.dataStore.data.map { prefs -> val gestureHintSeen: Flow<Boolean> = context.dataStore.data.map { prefs ->
prefs[gestureHintSeenKey] ?: false prefs[gestureHintSeenKey] ?: false
} }.distinctUntilChanged()
/** Everything the nav graph needs to pick a start destination, derived
* from ONE DataStore emission. Collecting introSeen and activeServer as
* two separate flows let them land in different frames — the intro flag
* could resolve first and flash the Connect screen at a paired user
* before the active server arrived. */
data class LaunchState(
val introSeen: Boolean,
val activeServer: ServerEntry?,
/** Every saved node — the launch gate needs the COUNT to decide
* whether to ask which one to connect to. */
val savedServers: List<ServerEntry>,
)
val launchState: Flow<LaunchState> = context.dataStore.data.map { prefs ->
LaunchState(
introSeen = prefs[introSeenKey] ?: false,
activeServer = activeServerFrom(prefs),
savedServers = (prefs[savedServersKey] ?: emptySet())
.mapNotNull { ServerEntry.deserialize(it) }
.sortedBy { it.displayName() },
)
}.distinctUntilChanged()
suspend fun setActiveServer(server: ServerEntry) { suspend fun setActiveServer(server: ServerEntry) {
context.dataStore.edit { prefs -> context.dataStore.edit { prefs ->
@@ -37,6 +37,7 @@ class ArchyVpnService : VpnService() {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private var warmerJob: Job? = null private var warmerJob: Job? = null
private var handoffKickJob: Job? = null
// Seamless transport handoff (Wi-Fi ⇄ 5G ⇄ future BLE). Without this the // Seamless transport handoff (Wi-Fi ⇄ 5G ⇄ future BLE). Without this the
// tunnel's underlying network stays pinned to the interface that was // tunnel's underlying network stays pinned to the interface that was
@@ -204,14 +205,20 @@ class ArchyVpnService : VpnService() {
/** /**
* Track the phone's default network and hand the mesh over to it as the * Track the phone's default network and hand the mesh over to it as the
* phone roams (Wi-Fi ⇄ 5G, and later BLE). Two actions per change: * phone roams (Wi-Fi ⇄ 5G). Two actions per change:
* 1. setUnderlyingNetworks(new) — the tunnel's packets follow the live * 1. setUnderlyingNetworks(new) — the tunnel's packets follow the live
* network instead of dying on the one it launched with. * network instead of dying on the one it launched with.
* 2. re-home the mesh — kick the session warmer so discovery + sessions * 2. re-home the mesh — kick the session warmer so discovery + sessions
* rebuild on the new path immediately; the node's own fast-reconnect * rebuild on the new path; the node's own fast-reconnect (1s) redials
* (1s) redials peers over the new route. * peers over the new route.
* onAvailable also fires for the FIRST network, which is how the initial * onAvailable also fires for the FIRST network, which is how the initial
* underlying network gets set. * underlying network gets set.
*
* requestNetwork, NOT registerDefaultNetworkCallback: this app is routed
* through its own TUN, so its "default network" IS the VPN — a default
* callback fires once with our own tunnel and never again on Wi-Fi ⇄ 5G.
* A NetworkRequest's default capabilities include NOT_VPN, so requestNetwork
* tracks the best real transport underneath instead.
*/ */
private fun registerNetworkHandoff() { private fun registerNetworkHandoff() {
if (networkCallback != null) return if (networkCallback != null) return
@@ -236,10 +243,6 @@ class ArchyVpnService : VpnService() {
} }
} }
networkCallback = cb networkCallback = cb
// requestNetwork tracks the BEST network of the request; when the
// phone moves Wi-Fi→5G the callback re-fires onAvailable with the new
// one. (registerDefaultNetworkCallback would also work; requestNetwork
// lets us extend to BLE-capable transports later.)
runCatching { cm.requestNetwork(request, cb) } runCatching { cm.requestNetwork(request, cb) }
} }
@@ -251,13 +254,22 @@ class ArchyVpnService : VpnService() {
runCatching { setUnderlyingNetworks(arrayOf(network)) } runCatching { setUnderlyingNetworks(arrayOf(network)) }
if (changed && FipsNative.isRunning()) { if (changed && FipsNative.isRunning()) {
Log.i(TAG, "network handoff → re-homing mesh on new default network") Log.i(TAG, "network handoff → re-homing mesh on new default network")
// Fresh warmer pass drives immediate rediscovery/session rebuild // Coalesced, not immediate: marginal Wi-Fi flaps the default
// on the new path instead of waiting out dead-link timeouts. // Wi-Fi ⇄ cell in bursts, and an aggressive warmer pass per flip
startSessionWarmer() // meant near-constant session churn — the "reconnects a lot"
// report. The re-pin above still happens on every change; only
// the rediscovery kick waits for the network to hold still.
handoffKickJob?.cancel()
handoffKickJob = scope.launch {
delay(2_000)
if (FipsNative.isRunning()) startSessionWarmer()
}
} }
} }
private fun unregisterNetworkHandoff() { private fun unregisterNetworkHandoff() {
handoffKickJob?.cancel()
handoffKickJob = null
val cm = connectivityManager val cm = connectivityManager
val cb = networkCallback val cb = networkCallback
if (cm != null && cb != null) { if (cm != null && cb != null) {
@@ -3,8 +3,10 @@ package com.archipelago.app.fips
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
import android.net.VpnService import android.net.VpnService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.withContext
/** /**
* Glue between pairing and the mesh: persists the node peer from a scanned * Glue between pairing and the mesh: persists the node peer from a scanned
@@ -36,20 +38,27 @@ object FipsManager {
* No-op on devices without the native lib (non-arm64). * No-op on devices without the native lib (non-arm64).
*/ */
suspend fun registerNode(context: Context, info: FipsPairInfo?, alias: String) { suspend fun registerNode(context: Context, info: FipsPairInfo?, alias: String) {
if (info == null || !FipsNative.available) return if (info == null) return
val prefs = FipsPreferences(context) // Every caller reaches this from a Compose scope — i.e. the MAIN
ensureIdentity(prefs) // thread — the instant a pairing QR decodes. Everything below is
prefs.upsertNodePeer(info, alias) // main-hostile: touching FipsNative dlopens the 7 MB mesh core,
peersDirty = true // ensureIdentity runs native ed25519 keygen, and VpnService.prepare
// Restart the mesh with the new peer RIGHT NOW when consent already // is a binder round-trip. Left on the UI thread it froze the frame
// exists — relying on the consentNeeded collector left a running // right after the camera got the code, which reads as "the scanner
// mesh on the OLD peer list whenever the collector wasn't active // is slow" when the scan itself already succeeded.
// (fresh pairings looked dead until a full app restart). val consent = withContext(Dispatchers.IO) {
if (VpnService.prepare(context) == null) { if (!FipsNative.available) return@withContext null
startService(context) val prefs = FipsPreferences(context)
} else { ensureIdentity(prefs)
_consentNeeded.value = true prefs.upsertNodePeer(info, alias)
} peersDirty = true
// Restart the mesh with the new peer RIGHT NOW when consent already
// exists — relying on the consentNeeded collector left a running
// mesh on the OLD peer list whenever the collector wasn't active
// (fresh pairings looked dead until a full app restart).
VpnService.prepare(context) == null
} ?: return
if (consent) startService(context) else _consentNeeded.value = true
} }
/** Generate-once mesh identity. Returns null only if the RNG/native fails. */ /** Generate-once mesh identity. Returns null only if the RNG/native fails. */
@@ -67,11 +76,17 @@ object FipsManager {
* through AppNavHost instead. * through AppNavHost instead.
*/ */
suspend fun autoStartIfReady(context: Context) { suspend fun autoStartIfReady(context: Context) {
if (!FipsNative.available) return // Self-dispatching for the same reason as registerNode: callers reach
val prefs = FipsPreferences(context) // this from Compose scopes, and dlopen + binder must not ride the UI
if (prefs.identity() == null || !prefs.hasPeers()) return // thread (the connect path calls it while the scanner is still up).
if (VpnService.prepare(context) != null) return // consent missing — don't prompt here val ready = withContext(Dispatchers.IO) {
startService(context) if (!FipsNative.available) return@withContext false
val prefs = FipsPreferences(context)
if (prefs.identity() == null || !prefs.hasPeers()) return@withContext false
// consent missing — don't prompt here
VpnService.prepare(context) == null
}
if (ready) startService(context)
} }
fun startService(context: Context) { fun startService(context: Context) {
@@ -1,37 +1,46 @@
package com.archipelago.app.ui.components package com.archipelago.app.ui.components
import androidx.compose.foundation.Image
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.size
import androidx.compose.material3.CircularProgressIndicator import androidx.compose.foundation.layout.width
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip import androidx.compose.ui.res.painterResource
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.sp
import com.archipelago.app.ui.screens.PixelArtLogo import com.archipelago.app.R
import com.archipelago.app.ui.theme.BitcoinOrange import com.archipelago.app.ui.theme.BitcoinOrange
import com.archipelago.app.ui.theme.SurfaceBlack import com.archipelago.app.ui.theme.SurfaceBlack
import com.archipelago.app.ui.theme.TextMuted import com.archipelago.app.ui.theme.TextMuted
import com.archipelago.app.ui.theme.TextPrimary
/** /**
* The branded "F*CK IPs" full-screen loader — shown whenever the app is * Full-screen loader shown while the app is dialing a node.
* dialing the node over the mesh (relaunch race, post-scan first connect), *
* instead of an anonymous spinner. The point of the brand: what's loading * Two faces, because they are two different promises:
* is a connection to a cryptographic identity, not an IP. * - [mesh] `true` — a FIPS node: the branded "F*CK IPs" screen, because what
* is loading really is a connection to a cryptographic identity, not an IP.
* - [mesh] `false` — a plain node reached over the network like anything
* else. No mesh branding at all: claiming the mesh is carrying a connection
* it isn't is worse than an anonymous spinner.
*/ */
@Composable @Composable
fun MeshLoadingScreen(message: String = "Dialing your node by its key — no IPs harmed") { fun MeshLoadingScreen(
mesh: Boolean = true,
nodeName: String = "",
done: Boolean = false,
) {
Box( Box(
Modifier Modifier
.fillMaxSize() .fillMaxSize()
@@ -39,39 +48,39 @@ fun MeshLoadingScreen(message: String = "Dialing your node by its key — no IPs
contentAlignment = Alignment.Center, contentAlignment = Alignment.Center,
) { ) {
Column(horizontalAlignment = Alignment.CenterHorizontally) { Column(horizontalAlignment = Alignment.CenterHorizontally) {
// The brand's circle-container logo (as on the connect screen / // The app's own badge — the same ringed mark as the launcher icon
// web login): pixel-art "a" centered in a black disc. // and the system splash, so launch → splash → this screen is one
Box( // continuous identity.
Modifier Image(
.size(120.dp) painter = painterResource(id = R.drawable.ic_logo),
.clip(androidx.compose.foundation.shape.CircleShape) contentDescription = null,
.background(Color.Black) modifier = Modifier.size(112.dp),
.border( )
1.dp, Spacer(Modifier.height(24.dp))
Color.White.copy(alpha = 0.14f),
androidx.compose.foundation.shape.CircleShape,
),
contentAlignment = Alignment.Center,
) {
PixelArtLogo(Modifier.size(64.dp))
}
Spacer(Modifier.height(20.dp))
Text( Text(
text = "F*CK IPs MESH", text = if (mesh) "F*CK IPS MESH" else "CONNECTING",
color = BitcoinOrange, color = BitcoinOrange,
fontSize = 18.sp, fontSize = 16.sp,
fontWeight = FontWeight.Bold, fontWeight = FontWeight.Bold,
letterSpacing = 4.sp, letterSpacing = 4.sp,
) )
Spacer(Modifier.height(8.dp)) Spacer(Modifier.height(10.dp))
Text( Text(
text = message, text = when {
color = TextMuted, mesh -> "Dialing your node by its key — no IPs harmed"
nodeName.isNotBlank() -> "Reaching $nodeName"
else -> "Reaching your node"
},
color = if (done) TextPrimary else TextMuted,
fontSize = 13.sp, fontSize = 13.sp,
textAlign = TextAlign.Center, textAlign = TextAlign.Center,
modifier = Modifier.padding(horizontal = 32.dp),
)
Spacer(Modifier.height(28.dp))
SlidingLoader(
modifier = Modifier.width(220.dp),
done = done,
) )
Spacer(Modifier.height(24.dp))
CircularProgressIndicator(color = BitcoinOrange)
} }
} }
} }
@@ -30,6 +30,7 @@ import androidx.compose.material.icons.filled.Dashboard
import androidx.compose.material.icons.filled.Dns import androidx.compose.material.icons.filled.Dns
import androidx.compose.material.icons.filled.Groups import androidx.compose.material.icons.filled.Groups
import androidx.compose.material.icons.filled.Keyboard import androidx.compose.material.icons.filled.Keyboard
import androidx.compose.material.icons.filled.RestartAlt
import androidx.compose.material.icons.filled.SportsEsports import androidx.compose.material.icons.filled.SportsEsports
import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.shape.RoundedCornerShape
@@ -70,6 +71,7 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.sp
import com.archipelago.app.R import com.archipelago.app.R
import com.archipelago.app.data.ServerEntry import com.archipelago.app.data.ServerEntry
import com.archipelago.app.ui.screens.restartCompanionApp
import com.archipelago.app.ui.theme.BitcoinOrange import com.archipelago.app.ui.theme.BitcoinOrange
import com.archipelago.app.ui.theme.SurfaceDark import com.archipelago.app.ui.theme.SurfaceDark
import com.archipelago.app.ui.theme.TextMuted import com.archipelago.app.ui.theme.TextMuted
@@ -221,7 +223,11 @@ private fun MenuPanel(
HubCard(Icons.Default.Dns, "Nodes", activeServer?.displayName() ?: "Add or switch servers") { HubCard(Icons.Default.Dns, "Nodes", activeServer?.displayName() ?: "Add or switch servers") {
page = HubPage.NODES page = HubPage.NODES
} }
if (FipsNative.available) { // Mesh oversight only when this session is actually on the
// mesh. Offering "FIPS Mesh" while connected to a plain node
// (whose traffic is going nowhere near the tunnel) advertises
// a connection the user doesn't have.
if (FipsNative.available && activeServer?.isFipsNode() == true) {
HubCard(Icons.Default.Bolt, "FIPS Mesh", "Mesh identity & status") { page = HubPage.FIPS } HubCard(Icons.Default.Bolt, "FIPS Mesh", "Mesh identity & status") { page = HubPage.FIPS }
} }
if (onMeshParty != null) { if (onMeshParty != null) {
@@ -229,6 +235,36 @@ private fun MenuPanel(
} }
// Dark/Classic style lives on the remote/keyboard screen next to // Dark/Classic style lives on the remote/keyboard screen next to
// the settings button — not here. // the settings button — not here.
// Small version chip at the hub's foot — the one place a
// connected user can always check what build they're on.
val hubContext = LocalContext.current
// Restart: the dashboard WebView is retained across
// remote ⇄ dashboard (that's the point), which also means a
// wedged page can't be cleared by leaving the screen. This
// throws the page away and relaunches the app clean — the mesh
// service keeps running.
HubCard(Icons.Default.RestartAlt, "Restart", "Reload the app from scratch") {
onDismiss()
restartCompanionApp(hubContext)
}
val versionLabel = remember {
runCatching {
hubContext.packageManager
.getPackageInfo(hubContext.packageName, 0).versionName
}.getOrNull()?.let { "Companion v$it" } ?: ""
}
if (versionLabel.isNotEmpty()) {
Text(
versionLabel,
color = TextMuted.copy(alpha = 0.6f),
fontSize = 11.sp,
letterSpacing = 1.sp,
textAlign = TextAlign.Center,
modifier = Modifier.fillMaxWidth().padding(top = 6.dp),
)
}
} }
HubPage.NODES -> { HubPage.NODES -> {
@@ -1,14 +1,24 @@
package com.archipelago.app.ui.components package com.archipelago.app.ui.components
import android.Manifest import android.Manifest
import android.content.Context
import android.content.pm.PackageManager import android.content.pm.PackageManager
import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.CameraManager
import android.hardware.camera2.CameraMetadata
import android.hardware.camera2.CaptureRequest
import android.os.Process
import androidx.activity.compose.BackHandler import androidx.activity.compose.BackHandler
import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.result.contract.ActivityResultContracts
import androidx.camera.camera2.interop.Camera2Interop
import androidx.camera.camera2.interop.ExperimentalCamera2Interop
import androidx.camera.core.CameraSelector import androidx.camera.core.CameraSelector
import androidx.camera.core.FocusMeteringAction
import androidx.camera.core.ImageAnalysis import androidx.camera.core.ImageAnalysis
import androidx.camera.core.ImageProxy import androidx.camera.core.ImageProxy
import androidx.camera.core.Preview import androidx.camera.core.Preview
import androidx.camera.core.SurfaceOrientedMeteringPointFactory
import androidx.camera.lifecycle.ProcessCameraProvider import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView import androidx.camera.view.PreviewView
import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.AnimatedVisibility
@@ -16,22 +26,26 @@ import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut import androidx.compose.animation.fadeOut
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.border import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawing import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.FlashOff
import androidx.compose.material.icons.filled.FlashOn
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
@@ -46,10 +60,15 @@ import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalHapticFeedback
import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView import androidx.compose.ui.viewinterop.AndroidView
@@ -59,23 +78,26 @@ import com.archipelago.app.data.PairResult
import com.archipelago.app.data.ServerQrParser import com.archipelago.app.data.ServerQrParser
import com.archipelago.app.ui.screens.GlassButton import com.archipelago.app.ui.screens.GlassButton
import com.archipelago.app.ui.theme.BitcoinOrange import com.archipelago.app.ui.theme.BitcoinOrange
import com.archipelago.app.ui.theme.TextMuted
import com.archipelago.app.ui.theme.TextPrimary
import com.google.zxing.BarcodeFormat import com.google.zxing.BarcodeFormat
import com.google.zxing.BinaryBitmap import com.google.zxing.BinaryBitmap
import com.google.zxing.DecodeHintType import com.google.zxing.DecodeHintType
import com.google.zxing.MultiFormatReader import com.google.zxing.MultiFormatReader
import com.google.zxing.NotFoundException
import com.google.zxing.PlanarYUVLuminanceSource import com.google.zxing.PlanarYUVLuminanceSource
import com.google.zxing.common.GlobalHistogramBinarizer
import com.google.zxing.common.HybridBinarizer import com.google.zxing.common.HybridBinarizer
import com.google.zxing.qrcode.QRCodeReader
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import java.util.concurrent.Executors import java.util.concurrent.Executors
/** /**
* Full-screen camera overlay that scans the node pairing QR * Scans the node pairing QR (docs/companion-pairing-qr.md) and reports the
* (docs/companion-pairing-qr.md) and reports the decoded server entry. * decoded server entry. Handles the camera permission itself; foreign/invalid
* Handles the camera permission itself; foreign/invalid codes show a hint * codes show a hint in the status strip and scanning continues.
* and scanning continues. *
* Visually this is the SAME glass modal the web wallet uses (neode-ui's
* WalletScanModal) — scrim, glass card, square preview, orange viewfinder,
* status strip — so pairing from the app and scanning from the web UI look
* like one product rather than two different scanners.
*/ */
@Composable @Composable
fun QrScannerOverlay( fun QrScannerOverlay(
@@ -83,28 +105,14 @@ fun QrScannerOverlay(
onDismiss: () -> Unit, onDismiss: () -> Unit,
onServerScanned: (PairResult.Success) -> Unit, onServerScanned: (PairResult.Success) -> Unit,
) { ) {
val context = LocalContext.current val haptics = LocalHapticFeedback.current
var hasPermission by remember {
mutableStateOf(
ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) ==
PackageManager.PERMISSION_GRANTED
)
}
var hintRes by remember { mutableStateOf<Int?>(null) } var hintRes by remember { mutableStateOf<Int?>(null) }
var handled by remember { mutableStateOf(false) } var handled by remember { mutableStateOf(false) }
val permissionLauncher = rememberLauncherForActivityResult(
ActivityResultContracts.RequestPermission()
) { granted -> hasPermission = granted }
LaunchedEffect(visible) { LaunchedEffect(visible) {
if (visible) { if (visible) {
handled = false handled = false
hintRes = null hintRes = null
val granted = ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) ==
PackageManager.PERMISSION_GRANTED
hasPermission = granted
if (!granted) permissionLauncher.launch(Manifest.permission.CAMERA)
} }
} }
@@ -116,125 +124,331 @@ fun QrScannerOverlay(
} }
} }
QrGlassModal(
visible = visible,
title = stringResource(R.string.scan_node_qr),
status = hintRes?.let { stringResource(it) to true },
idleHint = stringResource(R.string.scan_qr_hint),
permissionRationale = stringResource(R.string.camera_permission_needed),
onDismiss = onDismiss,
onDecoded = { text ->
if (!handled) {
when (val result = ServerQrParser.parse(text)) {
is PairResult.Success -> {
handled = true
// Confirm the hit in the hand — the eye is still on the
// code, not on the screen.
haptics.performHapticFeedback(HapticFeedbackType.LongPress)
onServerScanned(result)
}
is PairResult.UnsupportedVersion -> hintRes = R.string.update_app_for_qr
is PairResult.Invalid -> hintRes = R.string.invalid_pairing_qr
}
}
},
)
}
/**
* The shared native scanner shell — one visual contract for every camera the
* app opens (pairing, wallet), mirroring neode-ui's WalletScanModal so the
* native and web scanners are indistinguishable:
* - black/60 scrim, dismiss on tap-outside
* - glass card (rounded 24, white/10 hairline) capped at 420dp
* - square preview with the 62% orange viewfinder and a darkened surround
* - a status strip that carries hints and errors
* - an optional footer (the wallet's "Upload image")
*/
@Composable
internal fun QrGlassModal(
visible: Boolean,
title: String,
// message + isError; null falls back to [idleHint].
status: Pair<String, Boolean>?,
idleHint: String,
permissionRationale: String,
onDismiss: () -> Unit,
onDecoded: (String) -> Unit,
footer: @Composable (() -> Unit)? = null,
) {
val context = LocalContext.current
var hasPermission by remember {
mutableStateOf(
ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) ==
PackageManager.PERMISSION_GRANTED
)
}
var torchOn by remember { mutableStateOf(false) }
var hasTorch by remember { mutableStateOf(false) }
val permissionLauncher = rememberLauncherForActivityResult(
ActivityResultContracts.RequestPermission()
) { granted -> hasPermission = granted }
LaunchedEffect(visible) {
if (visible) {
val granted = ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) ==
PackageManager.PERMISSION_GRANTED
hasPermission = granted
if (!granted) permissionLauncher.launch(Manifest.permission.CAMERA)
} else {
torchOn = false
}
}
AnimatedVisibility(visible = visible, enter = fadeIn(), exit = fadeOut()) { AnimatedVisibility(visible = visible, enter = fadeIn(), exit = fadeOut()) {
BackHandler { onDismiss() } BackHandler { onDismiss() }
Box( Box(
Modifier Modifier
.fillMaxSize() .fillMaxSize()
.background(Color.Black), .background(Color.Black.copy(alpha = 0.6f))
.clickable(
interactionSource = remember { MutableInteractionSource() },
indication = null,
onClick = onDismiss,
),
contentAlignment = Alignment.Center,
) { ) {
if (hasPermission) {
CameraQrPreview(
onDecoded = { text ->
if (!handled) {
when (val result = ServerQrParser.parse(text)) {
is PairResult.Success -> {
handled = true
onServerScanned(result)
}
is PairResult.UnsupportedVersion -> hintRes = R.string.update_app_for_qr
is PairResult.Invalid -> hintRes = R.string.invalid_pairing_qr
}
}
},
)
// Aim frame
Box(
Modifier
.align(Alignment.Center)
.size(260.dp)
.border(2.dp, BitcoinOrange.copy(alpha = 0.85f), RoundedCornerShape(20.dp)),
)
} else {
Column(
Modifier
.align(Alignment.Center)
.padding(horizontal = 32.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(16.dp),
) {
Text(
text = stringResource(R.string.camera_permission_needed),
color = TextPrimary,
style = MaterialTheme.typography.bodyLarge,
textAlign = TextAlign.Center,
)
GlassButton(
text = stringResource(R.string.grant_camera_access),
onClick = { permissionLauncher.launch(Manifest.permission.CAMERA) },
modifier = Modifier.fillMaxWidth().height(56.dp),
)
}
}
// Top bar: title + close
Row(
Modifier
.fillMaxWidth()
.windowInsetsPadding(WindowInsets.safeDrawing)
.padding(horizontal = 8.dp, vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
) {
Text(
text = stringResource(R.string.scan_node_qr),
color = TextPrimary,
style = MaterialTheme.typography.titleMedium,
modifier = Modifier.padding(start = 12.dp),
)
IconButton(onClick = onDismiss) {
Icon(Icons.Default.Close, stringResource(R.string.close), tint = TextPrimary)
}
}
// Bottom hints
Column( Column(
Modifier Modifier
.align(Alignment.BottomCenter) .padding(16.dp)
.windowInsetsPadding(WindowInsets.safeDrawing) .widthIn(max = 420.dp)
.padding(horizontal = 32.dp, vertical = 24.dp), .fillMaxWidth()
horizontalAlignment = Alignment.CenterHorizontally, .clip(RoundedCornerShape(24.dp))
.background(Color(0xF212151C))
.border(1.dp, Color.White.copy(alpha = 0.10f), RoundedCornerShape(24.dp))
.clickable(
interactionSource = remember { MutableInteractionSource() },
indication = null,
onClick = {}, // swallow — only the scrim dismisses
)
.padding(24.dp),
) { ) {
hintRes?.let { res -> Row(
Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
) {
Text( Text(
text = stringResource(res), text = title,
color = BitcoinOrange, style = MaterialTheme.typography.titleLarge,
style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.SemiBold,
textAlign = TextAlign.Center, color = Color.White,
) )
Spacer(Modifier.height(8.dp)) IconButton(onClick = onDismiss) {
Icon(
Icons.Default.Close,
stringResource(R.string.close),
tint = Color.White.copy(alpha = 0.7f),
)
}
} }
if (hasPermission) {
Spacer(Modifier.height(8.dp))
Box(
Modifier
.fillMaxWidth()
.aspectRatio(1f)
.clip(RoundedCornerShape(12.dp))
.background(Color.Black.copy(alpha = 0.4f))
.border(1.dp, Color.White.copy(alpha = 0.10f), RoundedCornerShape(12.dp)),
contentAlignment = Alignment.Center,
) {
if (hasPermission) {
CameraQrPreview(
onDecoded = onDecoded,
torchOn = torchOn,
onTorchAvailable = { hasTorch = it },
)
// Viewfinder — 62% of the preview, matching the web
// modal's .scan-viewfinder, and matching the ROI the
// decoder actually reads (QR_ROI_FRACTION).
Box(
Modifier
.fillMaxSize(QR_ROI_FRACTION)
.border(
2.dp,
BitcoinOrange.copy(alpha = 0.85f),
RoundedCornerShape(16.dp),
),
)
if (hasTorch) {
IconButton(
onClick = { torchOn = !torchOn },
modifier = Modifier
.align(Alignment.TopEnd)
.padding(6.dp)
.clip(RoundedCornerShape(50))
.background(Color.Black.copy(alpha = 0.45f)),
) {
Icon(
if (torchOn) Icons.Default.FlashOn else Icons.Default.FlashOff,
stringResource(
if (torchOn) R.string.torch_off else R.string.torch_on,
),
tint = if (torchOn) BitcoinOrange else Color.White.copy(alpha = 0.85f),
)
}
}
} else {
Column(
Modifier.padding(horizontal = 24.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
Text(
text = permissionRationale,
color = Color.White.copy(alpha = 0.7f),
style = MaterialTheme.typography.bodyMedium,
textAlign = TextAlign.Center,
)
GlassButton(
text = stringResource(R.string.grant_camera_access),
onClick = { permissionLauncher.launch(Manifest.permission.CAMERA) },
modifier = Modifier.fillMaxWidth().height(48.dp),
)
}
}
}
Spacer(Modifier.height(16.dp))
Box(
Modifier
.fillMaxWidth()
.clip(RoundedCornerShape(8.dp))
.background(Color.White.copy(alpha = 0.05f))
.padding(12.dp)
.defaultMinSize(minHeight = 24.dp),
contentAlignment = Alignment.Center,
) {
Text( Text(
text = stringResource(R.string.scan_qr_hint), text = status?.first?.takeIf { it.isNotBlank() } ?: idleHint,
color = TextMuted, style = MaterialTheme.typography.bodySmall,
style = MaterialTheme.typography.bodyMedium, color = if (status?.second == true) {
Color(0xFFF87171)
} else {
Color.White.copy(alpha = 0.6f)
},
textAlign = TextAlign.Center, textAlign = TextAlign.Center,
) )
} }
if (footer != null) {
Spacer(Modifier.height(16.dp))
footer()
}
} }
} }
} }
} }
/** Shared by the pairing scanner and the wallet scan modal. */ /**
* Warm the CameraX provider and the ZXing decode path before the user ever
* asks for a scan, so opening the scanner doesn't pay provider init + class
* loading on the critical path. Does NOT open the camera: no permission is
* needed, no LED lights up, nothing is recorded — [ProcessCameraProvider]
* init is process-wide and cached, and the synthetic decode below just walks
* a blank 32x32 frame to class-load the binarizer/detector.
*
* Called once per process from the kiosk WebView (first page load) and by the
* page via `ArchipelagoQr.prewarm()`.
*/
internal fun prewarmQrScanner(context: Context) {
if (!qrPrewarmed.compareAndSet(false, true)) return
val app = context.applicationContext
runCatching { ProcessCameraProvider.getInstance(app) }
// Off the UI thread: the first decode attempt loads a dozen ZXing classes.
Executors.newSingleThreadExecutor().let { exec ->
exec.execute {
runCatching {
val blank = ByteArray(32 * 32)
val reader = MultiFormatReader().apply {
setHints(mapOf(DecodeHintType.POSSIBLE_FORMATS to listOf(BarcodeFormat.QR_CODE)))
}
val source = PlanarYUVLuminanceSource(blank, 32, 32, 0, 0, 32, 32, false)
reader.decodeWithState(BinaryBitmap(HybridBinarizer(source)))
}
}
exec.shutdown()
}
}
private val qrPrewarmed = java.util.concurrent.atomic.AtomicBoolean(false)
/**
* Fraction of the preview's shorter edge that both the on-screen viewfinder
* and the decoder's region of interest use. Keeping them identical is the
* point: the user aims at the box, and the box is exactly what gets decoded.
*/
internal const val QR_ROI_FRACTION = 0.62f
/**
* Shared by the pairing scanner and the wallet scan modal.
*
* [torchOn] drives the flash; [onTorchAvailable] reports whether this camera
* has one at all (the caller only draws its toggle when it does).
*
* ## Why this looks the way it does
*
* The previous version hunted: a scheduled tick alternated the optical zoom
* between 1x and 1.5x and re-fired `startFocusAndMetering(...disableAutoCancel())`
* every 2 seconds. Both are camera-hostile:
*
* - Every zoom step restarts AE/AF convergence, so the sensor spends the
* seconds right after it delivering soft frames — precisely the frames the
* decoder needs to be sharp. The visible symptom is the "zooms in and out
* and takes ages" report.
* - `disableAutoCancel()` leaves AF **locked** at whatever it converged on
* instead of handing the lens back to continuous AF, so a re-aim never
* refocused on its own; the next timer tick then kicked off another full
* sweep from a locked position — a lens that hunts forever.
*
* A stock camera app does neither. It leaves CameraX's continuous AF alone,
* refocuses on tap, and never touches zoom. This does the same, with one
* concession to the "hand-held QR is a static scene" case: if nothing has
* decoded for a few seconds, ONE auto-cancelling focus nudge is issued (and
* then not again for a while), which re-arms continuous AF instead of
* fighting it.
*/
@Composable @Composable
internal fun CameraQrPreview(onDecoded: (String) -> Unit) { internal fun CameraQrPreview(
onDecoded: (String) -> Unit,
torchOn: Boolean = false,
onTorchAvailable: (Boolean) -> Unit = {},
) {
val context = LocalContext.current val context = LocalContext.current
val lifecycleOwner = LocalLifecycleOwner.current val lifecycleOwner = LocalLifecycleOwner.current
val currentOnDecoded by rememberUpdatedState(onDecoded) val currentOnDecoded by rememberUpdatedState(onDecoded)
val currentOnTorchAvailable by rememberUpdatedState(onTorchAvailable)
var camera by remember { mutableStateOf<androidx.camera.core.Camera?>(null) }
val previewView = remember { val previewView = remember {
PreviewView(context).apply { PreviewView(context).apply {
scaleType = PreviewView.ScaleType.FILL_CENTER scaleType = PreviewView.ScaleType.FILL_CENTER
// TextureView, not the SurfaceView default: SurfaceView punches a // TextureView, not the SurfaceView default: SurfaceView punches a
// hole in the window, which black-flashes inside Compose fades and // hole in the window, which black-flashes inside Compose fades and
// ignores rounded-corner clipping (wallet modal). // ignores rounded-corner clipping (the glass modal).
implementationMode = PreviewView.ImplementationMode.COMPATIBLE implementationMode = PreviewView.ImplementationMode.COMPATIBLE
} }
} }
// Set by the analyzer on every decode; the focus nudge below reads it to
// tell "nothing in view" from "reading fine, leave the camera alone".
val lastDecodeAt = remember { java.util.concurrent.atomic.AtomicLong(0L) }
// A tap-to-focus wins over the periodic centre AF for a few seconds.
val lastTapFocusAt = remember { java.util.concurrent.atomic.AtomicLong(0L) }
DisposableEffect(Unit) { DisposableEffect(Unit) {
val analysisExecutor = Executors.newSingleThreadExecutor() // Analysis runs at display priority: the decode thread competes with
// the FIPS mesh service's native workers in this same process, and a
// background-priority analyzer is exactly how a sharp, well-framed
// code still takes seconds to land.
val analysisExecutor = Executors.newSingleThreadExecutor { r ->
Thread {
Process.setThreadPriority(Process.THREAD_PRIORITY_DISPLAY)
r.run()
}.apply { name = "qr-analyzer" }
}
val mainExecutor = ContextCompat.getMainExecutor(context) val mainExecutor = ContextCompat.getMainExecutor(context)
val providerFuture = ProcessCameraProvider.getInstance(context) val providerFuture = ProcessCameraProvider.getInstance(context)
var provider: ProcessCameraProvider? = null var provider: ProcessCameraProvider? = null
@@ -243,15 +457,18 @@ internal fun CameraQrPreview(onDecoded: (String) -> Unit) {
providerFuture.addListener({ providerFuture.addListener({
val p = providerFuture.get() val p = providerFuture.get()
provider = p provider = p
val preview = Preview.Builder().build().also { val previewBuilder = Preview.Builder()
tuneForBarcodes(previewBuilder, context)
val preview = previewBuilder.build().also {
it.setSurfaceProvider(previewView.surfaceProvider) it.setSurfaceProvider(previewView.surfaceProvider)
} }
// Dense Lightning-invoice QRs need BOTH enough pixels per module and // Dense Lightning-invoice QRs need BOTH enough pixels per module and
// sharp focus. 1280x720 + a far-focused camera (e.g. Pixel 9a's main // sharp focus. 1280x720 left dense invoices undecodable while sparse
// lens, which won't focus close) left dense invoices undecodable // address QRs still read — the "scanner doesn't pick up invoices"
// while sparse address QRs still read — the "scanner doesn't pick up // report. 1920x1080 roughly doubles module resolution. The analyzer
// invoices" report. 1920x1080 roughly doubles module resolution so a // never binarizes the full 2 MP: it reads the centre ROI at this
// QR held at the camera's actual focus distance still resolves. // resolution (for dense codes) and the whole frame at half of it
// (for coverage), so the big frame costs little.
@Suppress("DEPRECATION") @Suppress("DEPRECATION")
val analysis = ImageAnalysis.Builder() val analysis = ImageAnalysis.Builder()
.setTargetResolution(android.util.Size(1920, 1080)) .setTargetResolution(android.util.Size(1920, 1080))
@@ -260,25 +477,47 @@ internal fun CameraQrPreview(onDecoded: (String) -> Unit) {
.also { .also {
it.setAnalyzer( it.setAnalyzer(
analysisExecutor, analysisExecutor,
QrCodeAnalyzer { text -> mainExecutor.execute { currentOnDecoded(text) } }, QrCodeAnalyzer { text ->
lastDecodeAt.set(System.currentTimeMillis())
mainExecutor.execute { currentOnDecoded(text) }
},
) )
} }
try { try {
p.unbindAll() p.unbindAll()
val cam = p.bindToLifecycle(lifecycleOwner, CameraSelector.DEFAULT_BACK_CAMERA, preview, analysis) val cam = p.bindToLifecycle(lifecycleOwner, CameraSelector.DEFAULT_BACK_CAMERA, preview, analysis)
// Force a centre autofocus on a repeating tick. A hand-held QR is camera = cam
// a static scene, so continuous-AF often never retriggers and the currentOnTorchAvailable(cam.cameraInfo.hasFlashUnit())
// lens sits at its resting (far) focus — fatal for dense codes. // Start the clock at bind time so the nudge below waits for the
// A normalized centre point works before the view is measured. // user to actually aim before it does anything.
val point = androidx.camera.core.SurfaceOrientedMeteringPointFactory(1f, 1f) lastDecodeAt.set(System.currentTimeMillis())
.createPoint(0.5f, 0.5f) // Centre point, normalized — valid before the view is measured.
val focusAction = androidx.camera.core.FocusMeteringAction.Builder( val point = SurfaceOrientedMeteringPointFactory(1f, 1f).createPoint(0.5f, 0.5f)
point, // A one-shot AF action puts the lens in AUTO — i.e. LOCKED —
androidx.camera.core.FocusMeteringAction.FLAG_AF, // until it auto-cancels. The default 5s lock is far too long
).disableAutoCancel().build() // here: it spans exactly the window where the user is swinging
// the phone towards the code, and a locked lens cannot follow
// them. Hand control back after 1s so CONTINUOUS_PICTURE (set
// explicitly in tuneForBarcodes) does the real work, which is
// what actually tracks a moving aim.
val focusAction = FocusMeteringAction.Builder(point, FocusMeteringAction.FLAG_AF)
.setAutoCancelDuration(1, java.util.concurrent.TimeUnit.SECONDS)
.build()
var lastNudgeAt = 0L
focusScheduler.scheduleWithFixedDelay({ focusScheduler.scheduleWithFixedDelay({
runCatching { cam.cameraControl.startFocusAndMetering(focusAction) } val now = System.currentTimeMillis()
}, 0, 2, java.util.concurrent.TimeUnit.SECONDS) // The nudge only exists for the one case continuous AF
// genuinely misses: the phone held perfectly still on a
// code while the lens sits at its resting focus, with no
// scene change to trigger a sweep.
if (now - lastDecodeAt.get() > 2_000 &&
now - lastNudgeAt > 3_000 &&
now - lastTapFocusAt.get() > 3_000
) {
lastNudgeAt = now
runCatching { cam.cameraControl.startFocusAndMetering(focusAction) }
}
}, 1, 1, java.util.concurrent.TimeUnit.SECONDS)
} catch (_: Exception) { } catch (_: Exception) {
// Camera unavailable — the user can dismiss and enter details manually. // Camera unavailable — the user can dismiss and enter details manually.
} }
@@ -286,66 +525,251 @@ internal fun CameraQrPreview(onDecoded: (String) -> Unit) {
onDispose { onDispose {
focusScheduler.shutdownNow() focusScheduler.shutdownNow()
runCatching { camera?.cameraControl?.enableTorch(false) }
camera = null
provider?.unbindAll() provider?.unbindAll()
analysisExecutor.shutdown() analysisExecutor.shutdown()
} }
} }
AndroidView(factory = { previewView }, modifier = Modifier.fillMaxSize()) // Torch follows the caller's state (and switches off when the view goes).
} LaunchedEffect(camera, torchOn) {
runCatching { camera?.cameraControl?.enableTorch(torchOn) }
/** ZXing-based QR decoder over the camera's Y (luminance) plane. */
private class QrCodeAnalyzer(private val onDecoded: (String) -> Unit) : ImageAnalysis.Analyzer {
private val reader = MultiFormatReader().apply {
setHints(
mapOf(
DecodeHintType.POSSIBLE_FORMATS to listOf(BarcodeFormat.QR_CODE),
// Screen-displayed QRs come with moiré, glare, and soft focus at
// close range — the exhaustive search is worth the milliseconds.
DecodeHintType.TRY_HARDER to true,
)
)
} }
private var lastAttempt = 0L AndroidView(
factory = { previewView },
modifier = Modifier
.fillMaxSize()
// Tap-to-focus: the ROI assumes the code is centred; a tap lets the
// user point at one that isn't, or re-trigger AF the instant
// they've framed it.
.pointerInput(camera) {
detectTapGestures { offset ->
val cam = camera ?: return@detectTapGestures
val factory = previewView.meteringPointFactory
val action = FocusMeteringAction.Builder(
factory.createPoint(offset.x, offset.y),
FocusMeteringAction.FLAG_AF or FocusMeteringAction.FLAG_AE,
).build()
lastTapFocusAt.set(System.currentTimeMillis())
runCatching { cam.cameraControl.startFocusAndMetering(action) }
}
},
)
}
/**
* Configure the capture session the way a dedicated barcode scanner does,
* rather than the way a photo app does.
*
* The single most valuable knob is **CONTROL_AE_TARGET_FPS_RANGE**. Left
* alone, auto-exposure indoors happily drops the sensor to 10–15 fps and
* takes 60–100 ms exposures — every hand-held frame is then motion-blurred,
* and a blurred QR is not a slow decode, it is *no* decode. The user waves
* the phone about waiting for a lock that cannot happen. Pinning the lower
* bound of the AE range as high as the device allows caps exposure time
* (~33 ms at 30 fps), so frames come out sharp; AE compensates with gain
* instead, and ZXing tolerates noise far better than it tolerates blur.
* (Dark rooms get grainier as a result — that is what the torch button is
* for, and grainy-but-sharp still decodes where smooth-but-smeared never
* does.)
*
* CONTINUOUS_PICTURE is set explicitly so that when a tap-to-focus action
* expires, CameraX restores continuous AF rather than whatever the device
* defaults to; FAST noise/edge processing shaves ISP latency per frame.
*
* All of it is best-effort — an OEM that rejects a key just keeps its default.
*/
@androidx.annotation.OptIn(ExperimentalCamera2Interop::class)
private fun tuneForBarcodes(builder: Preview.Builder, context: Context) {
runCatching {
val ext = Camera2Interop.Extender(builder)
ext.setCaptureRequestOption(
CaptureRequest.CONTROL_AF_MODE,
CameraMetadata.CONTROL_AF_MODE_CONTINUOUS_PICTURE,
)
ext.setCaptureRequestOption(
CaptureRequest.NOISE_REDUCTION_MODE,
CameraMetadata.NOISE_REDUCTION_MODE_FAST,
)
ext.setCaptureRequestOption(
CaptureRequest.EDGE_MODE,
CameraMetadata.EDGE_MODE_FAST,
)
highestSteadyFpsRange(context)?.let {
ext.setCaptureRequestOption(CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE, it)
}
}
}
/**
* The back camera's AE range with the highest floor, ignoring anything that
* runs past 30 fps (those are the high-speed/slow-motion modes, which cost
* light for frames we do not need).
*/
private fun highestSteadyFpsRange(context: Context): android.util.Range<Int>? = runCatching {
val manager = context.getSystemService(CameraManager::class.java) ?: return@runCatching null
val backId = manager.cameraIdList.firstOrNull { id ->
manager.getCameraCharacteristics(id)
.get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_BACK
} ?: return@runCatching null
manager.getCameraCharacteristics(backId)
.get(CameraCharacteristics.CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES)
?.filter { it.upper <= 30 }
?.maxWithOrNull(compareBy({ it.lower }, { it.upper }))
}.getOrNull()
/**
* ZXing decoder over the camera's Y (luminance) plane.
*
* ## The rule this class exists to obey
*
* **Every frame costs the same, and every frame sees the whole scene.**
*
* That sounds obvious; the previous version violated both halves and produced
* a scanner with a very specific failure: it locked on instantly if the code
* was already in view when the camera opened, but crawled if you opened it
* and then moved to the code. The cause was an escalation ladder — each frame
* that failed to decode unlocked progressively more expensive searches, up to
* a TRY_HARDER pass over the full 2 MP frame plus an inverted retry, easily
* 150–300 ms of work.
*
* So the moment the user began hunting for the code, the analyzer dropped from
* ~30 attempts per second to ~4, each one on a motion-blurred frame. By the
* time they framed the code and held still, the pipeline was busy grinding
* through an exhaustive search of an old, blurry frame. Escalating on failure
* is exactly backwards: failure means the user is still aiming, which is when
* the scanner must be at its *fastest*, not its most thorough.
*
* ## What runs now, on every single frame
*
* 1. **Centre ROI at full resolution** ([QR_ROI_FRACTION], ~0.45 MP). Full
* sensor detail, so dense Lightning invoices keep their pixels-per-module.
* 2. **The whole frame at half resolution** (~0.5 MP). This is what fixes the
* "move to the code" case: coverage is no longer limited to the viewfinder
* box on the fast path, so a code that is merely *near* the middle decodes
* immediately instead of waiting for a slow tier to come around. A code
* big enough to be off-centre is big enough to survive the 2x downscale.
* 3. **One alternating second binarizer** — GlobalHistogram over the ROI on
* even frames, over the half-frame on odd ones. Hybrid is tuned for
* shadowed paper; most codes this app scans are on a *screen* (the node's
* pairing popup, another phone's wallet) where a global threshold is both
* cheaper and more reliable. Alternating keeps the per-frame budget flat.
*
* Two rare extras, both bounded so they can never dent the loop above: an
* inverted ROI pass every 8th frame (light-on-dark codes), and one TRY_HARDER
* pass over the half-frame at most once a second (skewed/damaged codes).
*
* Steady-state that is ~35 ms per frame — around 27 attempts per second, and
* it does not degrade the longer the user hunts.
*
* Buffers are allocated once and reused: the original path allocated a fresh
* ~2 MB array per frame, 60 MB/s of garbage at 30 fps, with GC pauses landing
* mid-decode.
*/
private class QrCodeAnalyzer(private val onDecoded: (String) -> Unit) : ImageAnalysis.Analyzer {
// QRCodeReader directly rather than MultiFormatReader: with a single
// format in play the dispatch and per-call state reset are pure overhead.
private val reader = QRCodeReader()
private val plainHints = mapOf<DecodeHintType, Any>(
DecodeHintType.POSSIBLE_FORMATS to listOf(BarcodeFormat.QR_CODE),
)
private val hardHints = mapOf<DecodeHintType, Any>(
DecodeHintType.POSSIBLE_FORMATS to listOf(BarcodeFormat.QR_CODE),
DecodeHintType.TRY_HARDER to true,
)
private var roiBuffer = ByteArray(0)
private var halfBuffer = ByteArray(0)
private var frame = 0L
private var lastHardAt = 0L
private fun read(
source: PlanarYUVLuminanceSource,
global: Boolean = false,
hard: Boolean = false,
inverted: Boolean = false,
): String? {
val src = if (inverted) source.invert() else source
val bitmap = BinaryBitmap(
if (global) GlobalHistogramBinarizer(src) else HybridBinarizer(src),
)
return runCatching {
reader.decode(bitmap, if (hard) hardHints else plainHints).text
}.getOrNull().also { reader.reset() }
}
override fun analyze(image: ImageProxy) { override fun analyze(image: ImageProxy) {
// Decode ~7x/s, not on every frame: TRY_HARDER (plus the inverted
// retry) pegs a core when run at camera rate, and that CPU contention
// is what made the preview itself stutter. KEEP_ONLY_LATEST means the
// frames skipped here are simply dropped, so decodes stay current.
val now = System.currentTimeMillis()
if (now - lastAttempt < 140) {
image.close()
return
}
lastAttempt = now
try { try {
val plane = image.planes[0] val plane = image.planes[0]
val buffer = plane.buffer val buffer = plane.buffer
// Copy into a rowStride-wide array; the last row of the plane buffer val stride = plane.rowStride
// may be short of the full stride, so the tail stays zero-padded. // YUV_420_888 permits an interleaved Y plane. Rare, but a device
val data = ByteArray(plane.rowStride * image.height) // that does it would otherwise hand the decoder pure noise.
buffer.get(data, 0, minOf(buffer.remaining(), data.size)) val pixelStride = plane.pixelStride
val source = PlanarYUVLuminanceSource( val width = image.width
data, plane.rowStride, image.height, val height = image.height
0, 0, image.width, image.height, frame++
false,
) buffer.rewind()
val result = try { val available = buffer.remaining()
reader.decodeWithState(BinaryBitmap(HybridBinarizer(source)))
} catch (_: NotFoundException) { // ── 1. Centre ROI, full resolution ──────────────────────────────
// Dark-themed pages can render light-on-dark QRs — retry inverted. val side = (minOf(width, height) * QR_ROI_FRACTION).toInt().coerceAtLeast(1)
reader.reset() val left = (width - side) / 2
reader.decodeWithState(BinaryBitmap(HybridBinarizer(source.invert()))) val top = (height - side) / 2
if (roiBuffer.size != side * side) roiBuffer = ByteArray(side * side)
for (row in 0 until side) {
val srcPos = (top + row) * stride + left * pixelStride
if (srcPos + side * pixelStride > available) break
if (pixelStride == 1) {
buffer.position(srcPos)
buffer.get(roiBuffer, row * side, side)
} else {
val dst = row * side
for (col in 0 until side) {
roiBuffer[dst + col] = buffer.get(srcPos + col * pixelStride)
}
}
}
val roi = PlanarYUVLuminanceSource(roiBuffer, side, side, 0, 0, side, side, false)
read(roi)?.let { onDecoded(it); return }
// ── 2. Whole frame, half resolution ─────────────────────────────
val hw = width / 2
val hh = height / 2
if (halfBuffer.size != hw * hh) halfBuffer = ByteArray(hw * hh)
var truncated = false
for (row in 0 until hh) {
val srcRow = row * 2 * stride
val dst = row * hw
for (col in 0 until hw) {
val srcPos = srcRow + col * 2 * pixelStride
if (srcPos >= available) { truncated = true; break }
halfBuffer[dst + col] = buffer.get(srcPos)
}
if (truncated) break
}
val half = PlanarYUVLuminanceSource(halfBuffer, hw, hh, 0, 0, hw, hh, false)
read(half)?.let { onDecoded(it); return }
// ── 3. Alternating second binarizer ─────────────────────────────
val second = if (frame % 2 == 0L) roi else half
read(second, global = true)?.let { onDecoded(it); return }
// ── Bounded extras ──────────────────────────────────────────────
if (frame % 8 == 0L) {
read(roi, inverted = true)?.let { onDecoded(it); return }
}
val now = System.currentTimeMillis()
if (now - lastHardAt >= 1_000) {
lastHardAt = now
read(half, hard = true)?.let { onDecoded(it); return }
} }
onDecoded(result.text)
} catch (_: NotFoundException) {
// No QR in this frame — keep scanning.
} catch (_: Exception) { } catch (_: Exception) {
// Malformed frame; skip it. // Malformed frame; skip it.
} finally { } finally {
reader.reset()
image.close() image.close()
} }
} }
@@ -0,0 +1,119 @@
package com.archipelago.app.ui.components
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.keyframes
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.archipelago.app.ui.theme.BitcoinOrange
/** green-400 — the same "done" colour the web install overlay lands on. */
private val DoneGreen = Color(0xFF4ADE80)
/**
* The Archipelago loading bar: a stripe that runs side to side inside a dim
* track and lands as a solid green bar when the work completes.
*
* This is a direct port of the platform's install-progress overlay
* (neode-ui SystemUpdate.vue `.install-overlay-bar-anim`): a third-width
* orange stripe on a white/10 track, 1.8s ease-in-out, going full green on
* success. Using the same loader natively is what makes the companion feel
* like the same product as the node UI rather than a stock Android app.
*
* @param done finished successfully — the bar fills solid green.
* @param stalled waiting on the user / something external — the bar parks
* half-full in a dimmed orange instead of animating, so it
* reads as "this needs you", not "still working".
*/
@Composable
fun SlidingLoader(
modifier: Modifier = Modifier,
done: Boolean = false,
stalled: Boolean = false,
height: Dp = 8.dp,
) {
val doneProgress by animateFloatAsState(
targetValue = if (done) 1f else 0f,
animationSpec = tween(320),
label = "loaderDone",
)
BoxWithConstraints(
modifier
.fillMaxWidth()
.height(height)
.clip(RoundedCornerShape(percent = 50))
.background(Color.White.copy(alpha = 0.10f)),
) {
val trackWidth = maxWidth
val stripeWidth = trackWidth / 3
val stripePx = with(LocalDensity.current) { stripeWidth.toPx() }
if (doneProgress < 1f) {
if (stalled) {
Box(
Modifier
.fillMaxWidth(0.5f)
.fillMaxHeight()
.clip(RoundedCornerShape(percent = 50))
.background(BitcoinOrange.copy(alpha = 0.6f)),
)
} else {
// Keyframes copied from the web overlay: -100% → 120% → 300%
// of the STRIPE's own width, which is what gives the bar its
// fast sweep out and lazy re-entry.
val transition = rememberInfiniteTransition(label = "loaderSlide")
val offset by transition.animateFloat(
initialValue = -1f,
targetValue = 3f,
animationSpec = infiniteRepeatable(
animation = keyframes {
durationMillis = 1800
(-1f) at 0
1.2f at 900
3f at 1800
},
repeatMode = RepeatMode.Restart,
),
label = "loaderOffset",
)
Box(
Modifier
.fillMaxWidth(1f / 3f)
.fillMaxHeight()
.graphicsLayer { translationX = offset * stripePx }
.clip(RoundedCornerShape(percent = 50))
.background(BitcoinOrange),
)
}
}
if (doneProgress > 0f) {
Box(
Modifier
.fillMaxWidth()
.fillMaxHeight()
.graphicsLayer { alpha = doneProgress }
.background(DoneGreen),
)
}
}
}
@@ -1,58 +1,26 @@
package com.archipelago.app.ui.components package com.archipelago.app.ui.components
import android.Manifest
import android.content.Context import android.content.Context
import android.content.pm.PackageManager
import android.graphics.BitmapFactory import android.graphics.BitmapFactory
import android.net.Uri import android.net.Uri
import androidx.activity.compose.BackHandler
import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
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.aspectRatio
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalHapticFeedback
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
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.dp
import androidx.core.content.ContextCompat
import com.archipelago.app.R import com.archipelago.app.R
import com.archipelago.app.ui.screens.GlassButton import com.archipelago.app.ui.screens.GlassButton
import com.archipelago.app.ui.theme.BitcoinOrange
import com.google.zxing.BarcodeFormat import com.google.zxing.BarcodeFormat
import com.google.zxing.BinaryBitmap import com.google.zxing.BinaryBitmap
import com.google.zxing.DecodeHintType import com.google.zxing.DecodeHintType
@@ -62,10 +30,10 @@ import com.google.zxing.RGBLuminanceSource
import com.google.zxing.common.HybridBinarizer import com.google.zxing.common.HybridBinarizer
/** /**
* Native replacement for the web wallet's scan pane — same visual design as * Native replacement for the web wallet's scan pane — the shared [QrGlassModal]
* neode-ui's WalletScanModal (dark glass card, square preview, orange * shell (same visual design as neode-ui's WalletScanModal) with the camera and
* viewfinder, status strip) but the camera and decoding run natively, so the * decoding running natively, so the preview doesn't lag the way getUserMedia
* preview doesn't lag the way getUserMedia does inside a WebView. * does inside a WebView.
* *
* Decoded text is handed back to the page ([onDecoded]) which does all the * Decoded text is handed back to the page ([onDecoded]) which does all the
* detection/spend logic; the page in turn streams status lines (animated-QR * detection/spend logic; the page in turn streams status lines (animated-QR
@@ -80,15 +48,7 @@ fun WalletQrScannerModal(
onDismiss: () -> Unit, onDismiss: () -> Unit,
) { ) {
val context = LocalContext.current val context = LocalContext.current
var hasPermission by remember { val haptics = LocalHapticFeedback.current
mutableStateOf(
ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) ==
PackageManager.PERMISSION_GRANTED
)
}
val permissionLauncher = rememberLauncherForActivityResult(
ActivityResultContracts.RequestPermission()
) { granted -> hasPermission = granted }
// Local error from a failed image upload; a fresh web status replaces it. // Local error from a failed image upload; a fresh web status replaces it.
var uploadError by remember { mutableStateOf<String?>(null) } var uploadError by remember { mutableStateOf<String?>(null) }
@@ -107,155 +67,50 @@ fun WalletQrScannerModal(
} }
} }
LaunchedEffect(visible) { LaunchedEffect(visible) { if (visible) uploadError = null }
if (visible) {
uploadError = null
val granted = ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) ==
PackageManager.PERMISSION_GRANTED
hasPermission = granted
if (!granted) permissionLauncher.launch(Manifest.permission.CAMERA)
}
}
LaunchedEffect(status) { if (status != null) uploadError = null } LaunchedEffect(status) { if (status != null) uploadError = null }
AnimatedVisibility(visible = visible, enter = fadeIn(), exit = fadeOut()) { // Throttle repeat frames: a static QR decodes many times a second but the
BackHandler { onDismiss() } // page only needs one; animated QRs still stream because each frame's
Box( // text differs.
Modifier var lastText by remember { mutableStateOf("") }
.fillMaxSize() var lastSentAt by remember { mutableStateOf(0L) }
.background(Color.Black.copy(alpha = 0.6f)) LaunchedEffect(visible) {
.clickable( if (visible) {
interactionSource = remember { MutableInteractionSource() }, lastText = ""
indication = null, lastSentAt = 0L
onClick = onDismiss,
),
contentAlignment = Alignment.Center,
) {
Column(
Modifier
.padding(16.dp)
.widthIn(max = 420.dp)
.fillMaxWidth()
.clip(RoundedCornerShape(24.dp))
.background(Color(0xF212151C))
.border(1.dp, Color.White.copy(alpha = 0.10f), RoundedCornerShape(24.dp))
.clickable(
interactionSource = remember { MutableInteractionSource() },
indication = null,
onClick = {}, // swallow — only the scrim dismisses
)
.padding(24.dp),
) {
// Header — mirrors the web modal's title row
Row(
Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
) {
Text(
text = stringResource(R.string.scan_to_send),
style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.SemiBold,
color = Color.White,
)
IconButton(onClick = onDismiss) {
Icon(
Icons.Default.Close,
stringResource(R.string.close),
tint = Color.White.copy(alpha = 0.7f),
)
}
}
Spacer(Modifier.height(8.dp))
// Square camera preview with the orange viewfinder
Box(
Modifier
.fillMaxWidth()
.aspectRatio(1f)
.clip(RoundedCornerShape(12.dp))
.background(Color.Black.copy(alpha = 0.4f))
.border(1.dp, Color.White.copy(alpha = 0.10f), RoundedCornerShape(12.dp)),
contentAlignment = Alignment.Center,
) {
if (hasPermission) {
// Throttle repeat frames: a static QR decodes ~20x/s but
// the page only needs one; animated QRs still stream
// because each frame's text differs.
var lastText by remember { mutableStateOf("") }
var lastSentAt by remember { mutableStateOf(0L) }
CameraQrPreview(onDecoded = { text ->
val now = System.currentTimeMillis()
if (text != lastText || now - lastSentAt > 250) {
lastText = text
lastSentAt = now
onDecoded(text)
}
})
Box(
Modifier
.fillMaxSize(0.62f)
.border(
2.dp,
BitcoinOrange.copy(alpha = 0.85f),
RoundedCornerShape(16.dp),
),
)
} else {
Column(
Modifier.padding(horizontal = 24.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
Text(
text = stringResource(R.string.camera_permission_needed),
color = Color.White.copy(alpha = 0.7f),
style = MaterialTheme.typography.bodyMedium,
textAlign = TextAlign.Center,
)
GlassButton(
text = stringResource(R.string.grant_camera_access),
onClick = { permissionLauncher.launch(Manifest.permission.CAMERA) },
modifier = Modifier.fillMaxWidth().height(48.dp),
)
}
}
}
Spacer(Modifier.height(16.dp))
// Status strip — same slot the web modal uses for hints/errors
val message = uploadError ?: status?.first
val isError = uploadError != null || status?.second == true
Box(
Modifier
.fillMaxWidth()
.clip(RoundedCornerShape(8.dp))
.background(Color.White.copy(alpha = 0.05f))
.padding(12.dp)
.defaultMinSize(minHeight = 24.dp),
contentAlignment = Alignment.Center,
) {
Text(
text = message?.takeIf { it.isNotBlank() }
?: stringResource(R.string.scan_wallet_hint),
style = MaterialTheme.typography.bodySmall,
color = if (isError) Color(0xFFF87171) else Color.White.copy(alpha = 0.6f),
textAlign = TextAlign.Center,
)
}
Spacer(Modifier.height(16.dp))
GlassButton(
text = stringResource(R.string.upload_qr_image),
onClick = { imagePicker.launch("image/*") },
modifier = Modifier.fillMaxWidth().height(48.dp),
)
}
} }
} }
QrGlassModal(
visible = visible,
title = stringResource(R.string.scan_to_send),
status = uploadError?.let { it to true } ?: status,
idleHint = stringResource(R.string.scan_wallet_hint),
permissionRationale = stringResource(R.string.camera_permission_needed),
onDismiss = onDismiss,
onDecoded = { text ->
val now = System.currentTimeMillis()
if (text != lastText || now - lastSentAt > 250) {
// Buzz on the FIRST hit only: an animated QR streams a new
// frame every few ms, and one buzz each would be a drill in
// the hand.
if (lastText.isEmpty()) {
haptics.performHapticFeedback(HapticFeedbackType.LongPress)
}
lastText = text
lastSentAt = now
onDecoded(text)
}
},
footer = {
GlassButton(
text = stringResource(R.string.upload_qr_image),
onClick = { imagePicker.launch("image/*") },
modifier = Modifier.fillMaxWidth().height(48.dp),
)
},
)
} }
/** Decode a QR from a picked image, downsampled so huge photos stay cheap. */ /** Decode a QR from a picked image, downsampled so huge photos stay cheap. */
@@ -24,14 +24,18 @@ import com.archipelago.app.data.ServerQrParser
import com.archipelago.app.fips.FipsManager import com.archipelago.app.fips.FipsManager
import com.archipelago.app.ui.screens.FlareScreen import com.archipelago.app.ui.screens.FlareScreen
import com.archipelago.app.ui.screens.IntroScreen import com.archipelago.app.ui.screens.IntroScreen
import com.archipelago.app.ui.screens.NodePickerScreen
import com.archipelago.app.ui.screens.PartyScreen import com.archipelago.app.ui.screens.PartyScreen
import com.archipelago.app.ui.screens.RemoteInputScreen import com.archipelago.app.ui.screens.RemoteInputScreen
import com.archipelago.app.ui.screens.ServerConnectScreen import com.archipelago.app.ui.screens.ServerConnectScreen
import com.archipelago.app.ui.screens.WebViewScreen import com.archipelago.app.ui.screens.WebViewScreen
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
object Routes { object Routes {
const val INTRO = "intro" const val INTRO = "intro"
const val NODE_PICKER = "node_picker"
const val SERVER_CONNECT = "server_connect" const val SERVER_CONNECT = "server_connect"
const val WEB_VIEW = "web_view" const val WEB_VIEW = "web_view"
const val REMOTE_INPUT = "remote_input" const val REMOTE_INPUT = "remote_input"
@@ -39,18 +43,38 @@ object Routes {
const val FLARE = "flare" const val FLARE = "flare"
} }
/**
* Process-scoped "have we already asked which node?" flag.
*
* The picker is a COLD-START question: opening the app fresh (or after the
* mesh service and its process were killed) is exactly when the user may want
* a different node than last time. An Activity recreation inside a live
* process — rotation, theme change — must not re-ask, and neither must a
* simple return from the background, so the flag lives with the process
* rather than in saved state.
*/
private object LaunchGate {
@Volatile
var nodeChoiceMade: Boolean = false
}
@Composable @Composable
fun AppNavHost( fun AppNavHost(
pairUri: String? = null, pairUri: String? = null,
onPairUriConsumed: () -> Unit = {}, onPairUriConsumed: () -> Unit = {},
onReady: () -> Unit = {},
) { ) {
val context = LocalContext.current val context = LocalContext.current
val prefs = remember { ServerPreferences(context) } val prefs = remember { ServerPreferences(context) }
val navController = rememberNavController() val navController = rememberNavController()
val scope = rememberCoroutineScope() val scope = rememberCoroutineScope()
val introSeen by prefs.introSeen.collectAsState(initial = null) // One combined emission — introSeen and activeServer resolving in separate
val activeServer by prefs.activeServer.collectAsState(initial = null) // frames used to flash the Connect screen at paired users on launch.
val launchState by prefs.launchState.collectAsState(initial = null)
val introSeen = launchState?.introSeen
val activeServer = launchState?.activeServer
val savedServers = launchState?.savedServers ?: emptyList()
// Pairing entry from a deep link that carried no password — prefills the // Pairing entry from a deep link that carried no password — prefills the
// connect form so the user lands on the password prompt for that server. // connect form so the user lands on the password prompt for that server.
@@ -79,12 +103,30 @@ fun AppNavHost(
} }
} }
// Paired + previously consented → the mesh comes back silently on launch. if (introSeen == null) return
LaunchedEffect(Unit) {
FipsManager.autoStartIfReady(context) // Ask which node when the user keeps more than one and this is a cold
// start. Anything else (single node, mid-process Activity recreation,
// a pairing deep link) goes straight through as before.
val needsNodeChoice = introSeen == true &&
!LaunchGate.nodeChoiceMade &&
savedServers.size > 1
// Paired + previously consented → the mesh comes back silently on launch,
// but ONLY once the session's node is known to be a FIPS node. Bringing
// the tunnel up before that took Android's single VPN slot away from
// whatever the user uses to reach a non-mesh node. Off the main
// dispatcher: this path dlopens the 7 MB fips core and does a binder
// round-trip (VpnService.prepare).
LaunchedEffect(needsNodeChoice, activeServer?.npub, activeServer?.meshIp) {
if (needsNodeChoice) return@LaunchedEffect
if (activeServer?.isFipsNode() != true) return@LaunchedEffect
withContext(Dispatchers.IO) { FipsManager.autoStartIfReady(context) }
} }
if (introSeen == null) return // Launch state resolved — MainActivity holds the system splash until now,
// so the first visible frame is the real UI, never a black gap.
LaunchedEffect(Unit) { onReady() }
// Declared after the introSeen gate so it can't fire before the NavHost // Declared after the introSeen gate so it can't fire before the NavHost
// below has set the nav graph; pairUri stays pending until consumed here. // below has set the nav graph; pairUri stays pending until consumed here.
@@ -118,6 +160,7 @@ fun AppNavHost(
val startDestination = when { val startDestination = when {
introSeen == false -> Routes.INTRO introSeen == false -> Routes.INTRO
needsNodeChoice -> Routes.NODE_PICKER
activeServer != null -> Routes.WEB_VIEW activeServer != null -> Routes.WEB_VIEW
else -> Routes.SERVER_CONNECT else -> Routes.SERVER_CONNECT
} }
@@ -126,6 +169,37 @@ fun AppNavHost(
navController = navController, navController = navController,
startDestination = startDestination, startDestination = startDestination,
) { ) {
composable(Routes.NODE_PICKER) {
NodePickerScreen(
servers = savedServers,
lastActive = activeServer,
onPick = { server ->
LaunchGate.nodeChoiceMade = true
scope.launch {
prefs.setActiveServer(server)
// The mesh follows the choice, and ONLY the choice.
// A non-mesh node gets the tunnel taken down: Android
// hands out one VPN slot, and holding it hostage is
// what broke reaching nodes behind a different VPN.
withContext(Dispatchers.IO) {
if (server.isFipsNode()) {
FipsManager.autoStartIfReady(context)
} else {
FipsManager.stopService(context)
}
}
navController.navigate(Routes.WEB_VIEW) {
popUpTo(0) { inclusive = true }
}
}
},
onAddNode = {
LaunchGate.nodeChoiceMade = true
navController.navigate(Routes.SERVER_CONNECT)
},
)
}
composable(Routes.INTRO) { composable(Routes.INTRO) {
IntroScreen( IntroScreen(
onMeshParty = { onMeshParty = {
@@ -107,7 +107,11 @@ fun FlareScreen(onBack: () -> Unit) {
} }
val peer = peers.firstOrNull { it.npub == selectedNpub } val peer = peers.firstOrNull { it.npub == selectedNpub }
val messages = allMessages.filter { it.peerNpub == selectedNpub } // derivedStateOf: filtering inline re-ran over the whole store on every
// recomposition — including one per keystroke in the composer.
val messages by remember(selectedNpub) {
androidx.compose.runtime.derivedStateOf { allMessages.filter { it.peerNpub == selectedNpub } }
}
val listState = rememberLazyListState() val listState = rememberLazyListState()
LaunchedEffect(messages.size) { LaunchedEffect(messages.size) {
if (messages.isNotEmpty()) listState.animateScrollToItem(messages.size - 1) if (messages.isNotEmpty()) listState.animateScrollToItem(messages.size - 1)
@@ -305,7 +309,13 @@ private fun MessageBubble(msg: FlareMessage) {
.padding(horizontal = 12.dp, vertical = 8.dp), .padding(horizontal = 12.dp, vertical = 8.dp),
) { ) {
if (msg.photoPath.isNotBlank()) { if (msg.photoPath.isNotBlank()) {
val bmp = remember(msg.photoPath) { BitmapFactory.decodeFile(msg.photoPath) } // Decoded off-main and downsampled to the bubble width —
// full-size decode in remember{} ran on the UI thread mid-
// scroll and held ~8 MB per visible photo (OOM territory).
var bmp by remember(msg.photoPath) { mutableStateOf<android.graphics.Bitmap?>(null) }
LaunchedEffect(msg.photoPath) {
bmp = withContext(Dispatchers.IO) { decodeSampledPhoto(msg.photoPath, 600) }
}
bmp?.let { bmp?.let {
Image( Image(
bitmap = it.asImageBitmap(), bitmap = it.asImageBitmap(),
@@ -336,6 +346,19 @@ private fun MessageBubble(msg: FlareMessage) {
} }
/** Decode, downscale (≤1600px) and JPEG-compress a picked photo off-main. */ /** Decode, downscale (≤1600px) and JPEG-compress a picked photo off-main. */
/** Decode a stored beamed photo at roughly [maxPx] on the long edge — the
* bubble renders at ~300 dp, so the stored 1600 px original is 25× the
* pixels needed. Blocking — call on IO. */
private fun decodeSampledPhoto(path: String, maxPx: Int): android.graphics.Bitmap? = try {
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeFile(path, bounds)
var sample = 1
while (maxOf(bounds.outWidth, bounds.outHeight) / (sample * 2) >= maxPx) sample *= 2
BitmapFactory.decodeFile(path, BitmapFactory.Options().apply { inSampleSize = sample })
} catch (_: Exception) {
null
}
private suspend fun compressPhoto(context: android.content.Context, uri: Uri): ByteArray? = private suspend fun compressPhoto(context: android.content.Context, uri: Uri): ByteArray? =
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
try { try {
@@ -37,6 +37,7 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.alpha
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size import androidx.compose.ui.geometry.Size
@@ -65,9 +66,10 @@ fun IntroScreen(
var showContent by remember { mutableStateOf(false) } var showContent by remember { mutableStateOf(false) }
LaunchedEffect(Unit) { LaunchedEffect(Unit) {
logoAlpha.animateTo(1f, animationSpec = tween(800)) // Content fades in WITH the logo, not after it — the serial
delay(300) // 800ms + 300ms sequence held "Get Started" off-screen for 1.1s.
showContent = true showContent = true
logoAlpha.animateTo(1f, animationSpec = tween(450))
} }
Box( Box(
@@ -111,7 +113,9 @@ fun IntroScreen(
contentDescription = "Archipelago", contentDescription = "Archipelago",
modifier = Modifier modifier = Modifier
.size(160.dp) .size(160.dp)
.alpha(logoAlpha.value), // graphicsLayer defers the alpha read to the draw phase —
// .alpha(value) recomposed the whole screen per frame.
.graphicsLayer { alpha = logoAlpha.value },
) )
Spacer(modifier = Modifier.height(48.dp)) Spacer(modifier = Modifier.height(48.dp))
@@ -0,0 +1,226 @@
package com.archipelago.app.ui.screens
import androidx.compose.foundation.Image
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.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawing
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Bolt
import androidx.compose.material.icons.filled.Lock
import androidx.compose.material.icons.filled.LockOpen
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
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.R
import com.archipelago.app.data.ServerEntry
import com.archipelago.app.ui.theme.BitcoinOrange
import com.archipelago.app.ui.theme.SuccessGreen
import com.archipelago.app.ui.theme.SurfaceBlack
import com.archipelago.app.ui.theme.TextMuted
import com.archipelago.app.ui.theme.TextPrimary
/**
* "Which node?" — shown at launch when more than one node is saved.
*
* The companion used to dive straight back into whichever node was last
* active, which is wrong the moment a user keeps more than one: they arrive
* somewhere they didn't choose, and (worse) the FIPS tunnel came up before
* anyone said which network this session belongs to. Picking first makes the
* choice explicit and lets the mesh stay down for nodes that aren't on it.
*
* [onPick] carries the entry; the caller decides what the mesh does about it.
*/
@Composable
fun NodePickerScreen(
servers: List<ServerEntry>,
lastActive: ServerEntry?,
onPick: (ServerEntry) -> Unit,
onAddNode: () -> Unit,
) {
Box(
modifier = Modifier
.fillMaxSize()
.background(SurfaceBlack),
) {
Image(
painter = painterResource(id = R.drawable.bg_synthwave),
contentDescription = null,
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.Crop,
)
Box(
modifier = Modifier
.fillMaxSize()
.background(
Brush.verticalGradient(
colors = listOf(
Color.Black.copy(alpha = 0.65f),
Color.Black.copy(alpha = 0.5f),
Color.Black.copy(alpha = 0.85f),
),
)
),
)
Column(
modifier = Modifier
.fillMaxSize()
.windowInsetsPadding(WindowInsets.safeDrawing)
.verticalScroll(rememberScrollState())
.padding(horizontal = 24.dp)
.padding(top = 48.dp, bottom = 32.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(12.dp, Alignment.CenterVertically),
) {
Image(
painter = painterResource(id = R.drawable.ic_logo),
contentDescription = "Archipelago",
modifier = Modifier.size(88.dp),
)
Spacer(Modifier.height(4.dp))
Text(
text = stringResource(R.string.pick_node_title),
style = MaterialTheme.typography.headlineMedium,
color = TextPrimary,
textAlign = TextAlign.Center,
)
Text(
text = stringResource(R.string.pick_node_hint),
style = MaterialTheme.typography.bodyMedium,
color = TextMuted,
textAlign = TextAlign.Center,
)
Spacer(Modifier.height(8.dp))
servers.forEach { server ->
NodeCard(
server = server,
isLast = lastActive?.sameNode(server) == true,
onClick = { onPick(server) },
)
}
Spacer(Modifier.height(8.dp))
GlassButton(
text = stringResource(R.string.pick_node_add),
onClick = onAddNode,
modifier = Modifier.fillMaxWidth().height(52.dp),
)
}
}
}
@Composable
private fun NodeCard(
server: ServerEntry,
isLast: Boolean,
onClick: () -> Unit,
) {
Row(
modifier = Modifier
.fillMaxWidth()
.clip(RoundedCornerShape(14.dp))
.background(Color.Black.copy(alpha = 0.6f))
.background(
Brush.verticalGradient(
colors = listOf(
Color.White.copy(alpha = 0.08f),
Color.White.copy(alpha = 0.02f),
),
)
)
.border(
1.dp,
if (isLast) BitcoinOrange.copy(alpha = 0.35f) else Color.White.copy(alpha = 0.1f),
RoundedCornerShape(14.dp),
)
.clickable { onClick() }
.padding(horizontal = 16.dp, vertical = 16.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Icon(
imageVector = if (server.useHttps) Icons.Default.Lock else Icons.Default.LockOpen,
contentDescription = null,
modifier = Modifier.size(20.dp),
tint = if (server.useHttps) SuccessGreen else BitcoinOrange,
)
Spacer(Modifier.width(12.dp))
Column(Modifier.weight(1f)) {
Text(
text = server.displayName(),
style = MaterialTheme.typography.titleMedium,
color = TextPrimary,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
val secondary = buildString {
if (server.name.isNotBlank()) append(server.address)
if (server.port.isNotBlank()) {
if (isNotEmpty()) append(":${server.port}") else append("Port ${server.port}")
}
}
if (secondary.isNotBlank()) {
Text(
text = secondary,
style = MaterialTheme.typography.labelMedium,
color = TextMuted,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
}
// The one thing that actually changes behaviour on this screen: a mesh
// node brings the FIPS tunnel up, a plain one deliberately does not.
if (server.isFipsNode()) {
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
imageVector = Icons.Default.Bolt,
contentDescription = null,
modifier = Modifier.size(14.dp),
tint = BitcoinOrange,
)
Spacer(Modifier.width(4.dp))
Text(
text = "FIPS",
color = BitcoinOrange,
fontSize = 11.sp,
letterSpacing = 1.sp,
style = MaterialTheme.typography.labelMedium,
)
}
}
}
}
@@ -123,9 +123,12 @@ fun PartyScreen(
name = prefs.partyName() name = prefs.partyName()
// The hotspot/WiFi address can change while this screen is open // The hotspot/WiFi address can change while this screen is open
// (e.g. the user flips the hotspot on mid-demo) — keep it fresh. // (e.g. the user flips the hotspot on mid-demo) — keep it fresh.
// Tight only at first (the hotspot-flip window); interface walks
// allocate, so back off once the screen has been open a while.
var round = 0
while (true) { while (true) {
localIp = withContext(Dispatchers.IO) { PartyQr.localWifiIpv4() } localIp = withContext(Dispatchers.IO) { PartyQr.localWifiIpv4() }
delay(3_000) delay(if (round++ < 10) 3_000 else 30_000)
} }
} }
@@ -138,7 +141,16 @@ fun PartyScreen(
port = PartyQr.PARTY_UDP_PORT, port = PartyQr.PARTY_UDP_PORT,
) )
} }
val qrBitmap = remember(qrPayload) { qrPayload?.let { renderQr(it) } } // QR encode + bitmap fill off the composition: done in remember{} it ran
// on the UI thread PER KEYSTROKE of the name field (the payload embeds the
// name) — a ZXing encode plus a megabyte-plus allocation per character.
// The 250 ms delay is a free debounce via coroutine cancellation.
var qrBitmap by remember { mutableStateOf<android.graphics.Bitmap?>(null) }
LaunchedEffect(qrPayload) {
if (qrPayload == null) { qrBitmap = null; return@LaunchedEffect }
if (qrBitmap != null) delay(250)
qrBitmap = withContext(Dispatchers.Default) { renderQr(qrPayload) }
}
BackHandler { BackHandler {
when { when {
@@ -337,7 +349,12 @@ fun PartyScreen(
contentAlignment = Alignment.Center, contentAlignment = Alignment.Center,
) { ) {
Column(horizontalAlignment = Alignment.CenterHorizontally) { Column(horizontalAlignment = Alignment.CenterHorizontally) {
val dlQr = remember { renderQr(APP_DOWNLOAD_URL) } // Encoded off-main; done in remember{} it dropped the
// overlay's first fade-in frame.
var dlQr by remember { mutableStateOf<android.graphics.Bitmap?>(null) }
LaunchedEffect(Unit) {
dlQr = withContext(Dispatchers.Default) { renderQr(APP_DOWNLOAD_URL) }
}
dlQr?.let { bmp -> dlQr?.let { bmp ->
Box( Box(
Modifier Modifier
@@ -364,7 +381,7 @@ fun PartyScreen(
"…or send the APK file directly", "…or send the APK file directly",
color = BitcoinOrange, color = BitcoinOrange,
fontSize = 13.sp, fontSize = 13.sp,
modifier = Modifier.clickable { shareCompanionApk(context) }.padding(8.dp), modifier = Modifier.clickable { scope.launch { shareCompanionApk(context) } }.padding(8.dp),
) )
Spacer(Modifier.height(6.dp)) Spacer(Modifier.height(6.dp))
Text("Close", color = TextMuted, fontSize = 14.sp, modifier = Modifier.clickable { showShareQr = false }.padding(8.dp)) Text("Close", color = TextMuted, fontSize = 14.sp, modifier = Modifier.clickable { showShareQr = false }.padding(8.dp))
@@ -473,8 +490,9 @@ fun PartyScreen(
} }
} }
/** Render a QR payload as a bitmap (dark modules on white). */ /** Render a QR payload as a bitmap (dark modules on white). 512 px covers the
private fun renderQr(payload: String, size: Int = 640): Bitmap? = try { * 240.dp display size at any density; 640 was a third more pixels for nothing. */
private fun renderQr(payload: String, size: Int = 512): Bitmap? = try {
val matrix = QRCodeWriter().encode( val matrix = QRCodeWriter().encode(
payload, payload,
BarcodeFormat.QR_CODE, BarcodeFormat.QR_CODE,
@@ -494,16 +512,23 @@ private fun renderQr(payload: String, size: Int = 640): Bitmap? = try {
} }
/** Share this install's own APK via the system share sheet — a nearby friend /** Share this install's own APK via the system share sheet — a nearby friend
* gets the companion with no internet at all (Quick Share / Bluetooth). */ * gets the companion with no internet at all (Quick Share / Bluetooth).
private fun shareCompanionApk(context: android.content.Context) { * The ~27 MB copy runs on IO — inline in the click handler it froze the UI
* for seconds (ANR territory on slow flash). Copied once per install; the
* cached file is reused while its size still matches the source. */
private suspend fun shareCompanionApk(context: android.content.Context) {
try { try {
val src = java.io.File(context.applicationInfo.sourceDir) val uri = withContext(Dispatchers.IO) {
val dir = java.io.File(context.cacheDir, "share").apply { mkdirs() } val src = java.io.File(context.applicationInfo.sourceDir)
val out = java.io.File(dir, "archipelago-companion.apk") val dir = java.io.File(context.cacheDir, "share").apply { mkdirs() }
src.copyTo(out, overwrite = true) val out = java.io.File(dir, "archipelago-companion.apk")
val uri = androidx.core.content.FileProvider.getUriForFile( if (!out.exists() || out.length() != src.length()) {
context, "${context.packageName}.fileprovider", out, src.copyTo(out, overwrite = true)
) }
androidx.core.content.FileProvider.getUriForFile(
context, "${context.packageName}.fileprovider", out,
)
}
val send = android.content.Intent(android.content.Intent.ACTION_SEND).apply { val send = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
type = "application/vnd.android.package-archive" type = "application/vnd.android.package-archive"
putExtra(android.content.Intent.EXTRA_STREAM, uri) putExtra(android.content.Intent.EXTRA_STREAM, uri)
@@ -33,7 +33,6 @@ import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Edit import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.Lock import androidx.compose.material.icons.filled.Lock
import androidx.compose.material.icons.filled.LockOpen import androidx.compose.material.icons.filled.LockOpen
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
@@ -76,6 +75,7 @@ import com.archipelago.app.data.ServerEntry
import com.archipelago.app.data.ServerPreferences import com.archipelago.app.data.ServerPreferences
import com.archipelago.app.fips.FipsManager import com.archipelago.app.fips.FipsManager
import com.archipelago.app.ui.components.MeshLoadingScreen import com.archipelago.app.ui.components.MeshLoadingScreen
import com.archipelago.app.ui.components.SlidingLoader
import com.archipelago.app.ui.components.QrScannerOverlay import com.archipelago.app.ui.components.QrScannerOverlay
import com.archipelago.app.ui.theme.BitcoinOrange import com.archipelago.app.ui.theme.BitcoinOrange
import com.archipelago.app.ui.theme.ErrorRed import com.archipelago.app.ui.theme.ErrorRed
@@ -86,6 +86,7 @@ import com.archipelago.app.ui.theme.TextMuted
import com.archipelago.app.ui.theme.TextPrimary import com.archipelago.app.ui.theme.TextPrimary
import com.archipelago.app.ui.theme.TextSecondary import com.archipelago.app.ui.theme.TextSecondary
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
@@ -108,6 +109,20 @@ fun ServerConnectScreen(
val scope = rememberCoroutineScope() val scope = rememberCoroutineScope()
val keyboard = LocalSoftwareKeyboardController.current val keyboard = LocalSoftwareKeyboardController.current
val savedServers by prefs.savedServers.collectAsState(initial = emptyList())
// Warm the mesh tunnel the moment the screen appears — starting it only
// after the LAN probe failed put full tunnel bring-up + session discovery
// inside the user's wait. By connect-tap time it's usually already up.
//
// Only when there is actually a mesh node to warm for, though: raising the
// tunnel on a phone whose saved nodes are all plain HTTP boxes takes
// Android's single VPN slot for nothing.
LaunchedEffect(savedServers.any { it.isFipsNode() }) {
if (savedServers.none { it.isFipsNode() }) return@LaunchedEffect
withContext(Dispatchers.IO) { FipsManager.autoStartIfReady(context) }
}
var name by remember { mutableStateOf("") } var name by remember { mutableStateOf("") }
var address by remember { mutableStateOf("") } var address by remember { mutableStateOf("") }
var port by remember { mutableStateOf("") } var port by remember { mutableStateOf("") }
@@ -121,8 +136,13 @@ fun ServerConnectScreen(
// Landing shows Scan/Manual choice; the form appears in manual mode or while editing. // Landing shows Scan/Manual choice; the form appears in manual mode or while editing.
var manualMode by remember { mutableStateOf(false) } var manualMode by remember { mutableStateOf(false) }
var showScanner by remember { mutableStateOf(false) } var showScanner by remember { mutableStateOf(false) }
// Is the connect currently running aimed at a mesh node? Drives whether
val savedServers by prefs.savedServers.collectAsState(initial = emptyList()) // the loader wears the FIPS brand — see MeshLoadingScreen.
var connectingOverMesh by remember { mutableStateOf(false) }
var connectingName by remember { mutableStateOf("") }
// Brief green landing on the loader before the kiosk takes over, matching
// the platform's install overlay.
var connectSucceeded by remember { mutableStateOf(false) }
fun clearForm() { fun clearForm() {
name = "" name = ""
@@ -171,40 +191,60 @@ fun ServerConnectScreen(
} }
isConnecting = true isConnecting = true
errorMessage = null errorMessage = null
connectingOverMesh = server.isFipsNode()
connectingName = server.displayName()
connectSucceeded = false
scope.launch { scope.launch {
var reachable = testConnection(server) // LAN and mesh race IN PARALLEL — the serial LAN-then-mesh chain
// burned a guaranteed-dead 5 s LAN probe before the mesh path even
// LAN address didn't answer — phone off-LAN (5G) or DHCP moved the // started (the off-LAN QR-pairing case, exactly where speed shows).
// node. The scanned IP was only ever a dial hint; the node's real // The scanned IP was only ever a dial hint; the node's real
// identity is its npub and its ULA is reachable from anywhere over // identity is its npub and its ULA is reachable from anywhere over
// the mesh. Bring the tunnel up and probe the ULA before failing. // the mesh. Mesh discovery + first session can take 15s+ through
if (!reachable && server.meshIp.isNotBlank()) { // the public tree (per node diagnosis), and on a
// first-ever pairing the VPN consent dialog is on screen at the
// same time — so the mesh side keeps probing inside its budget
// while the tunnel (already started at screen entry, and kicked
// again here) warms up underneath.
val meshServer = server.meshIp.takeIf { it.isNotBlank() }?.let {
FipsManager.autoStartIfReady(context) FipsManager.autoStartIfReady(context)
val meshServer = server.copy( server.copy(address = it, useHttps = false, port = "")
address = server.meshIp, }
useHttps = false, val reachable = kotlinx.coroutines.coroutineScope {
port = "", val lan = async { testConnection(server, timeoutMs = 4_000) }
) val mesh = async {
// Mesh discovery + first session can take 15s+ through the if (meshServer == null) return@async false
// public tree (per node diagnosis), and on a val deadline = System.currentTimeMillis() + 45_000
// first-ever pairing the VPN consent dialog is on screen at var ok = false
// the same time — so probe patiently inside a 60s budget with while (!ok && System.currentTimeMillis() < deadline) {
// per-attempt timeouts wide enough to ride out TCP ok = testConnection(meshServer, timeoutMs = 8_000)
// retransmit backoff. The VPN service pre-warms the session if (!ok) delay(2000)
// in parallel (ArchyVpnService.startSessionWarmer). }
val deadline = System.currentTimeMillis() + 60_000 ok
while (!reachable && System.currentTimeMillis() < deadline) { }
reachable = testConnection(meshServer, timeoutMs = 15_000) val first = kotlinx.coroutines.selects.select<Boolean> {
if (!reachable) delay(3000) lan.onAwait { it }
mesh.onAwait { it }
}
if (first) {
lan.cancel(); mesh.cancel()
true
} else {
// One side gave up — the verdict is whatever the other says.
if (lan.isCompleted) mesh.await() else lan.await()
} }
} }
isConnecting = false
if (reachable) { if (reachable) {
// Land the loader green before handing over, so the last thing
// seen is "done", not a bar cut mid-sweep.
connectSucceeded = true
prefs.setActiveServer(server) prefs.setActiveServer(server)
delay(320)
isConnecting = false
onConnected(server.toUrl()) onConnected(server.toUrl())
} else { } else {
isConnecting = false
errorMessage = context.getString(R.string.connection_failed) errorMessage = context.getString(R.string.connection_failed)
} }
} }
@@ -293,7 +333,7 @@ fun ServerConnectScreen(
Spacer(modifier = Modifier.height(4.dp)) Spacer(modifier = Modifier.height(4.dp))
Text( Text(
text = if (editingServer != null) stringResource(R.string.edit_server_title) else "Connect to Server", text = if (editingServer != null) stringResource(R.string.edit_server_title) else stringResource(R.string.connect_to_node),
style = MaterialTheme.typography.headlineMedium, style = MaterialTheme.typography.headlineMedium,
color = TextPrimary, color = TextPrimary,
textAlign = TextAlign.Center, textAlign = TextAlign.Center,
@@ -577,10 +617,9 @@ fun ServerConnectScreen(
} }
if (isConnecting) { if (isConnecting) {
CircularProgressIndicator( SlidingLoader(
modifier = Modifier.size(24.dp), modifier = Modifier.fillMaxWidth(),
color = Color.White.copy(alpha = 0.6f), done = connectSucceeded,
strokeWidth = 2.dp,
) )
} }
@@ -617,7 +656,11 @@ fun ServerConnectScreen(
// establishing (LAN probe → tunnel up → ULA probe can take a while). // establishing (LAN probe → tunnel up → ULA probe can take a while).
// The small inline spinner stays for context; this owns the screen. // The small inline spinner stays for context; this owns the screen.
if (isConnecting) { if (isConnecting) {
MeshLoadingScreen() MeshLoadingScreen(
mesh = connectingOverMesh,
nodeName = connectingName,
done = connectSucceeded,
)
} }
} }
} }
@@ -686,6 +729,17 @@ private fun sanitizeAddress(input: String): String {
.trimEnd('/') .trimEnd('/')
} }
// Built once — the connect loop probed up to 20 times, and each attempt was
// paying a fresh SSLContext + SecureRandom init.
private val trustAllSslFactory: javax.net.ssl.SSLSocketFactory by lazy {
val trustAll = arrayOf<javax.net.ssl.TrustManager>(object : X509TrustManager {
override fun checkClientTrusted(chain: Array<java.security.cert.X509Certificate>?, authType: String?) {}
override fun checkServerTrusted(chain: Array<java.security.cert.X509Certificate>?, authType: String?) {}
override fun getAcceptedIssuers(): Array<java.security.cert.X509Certificate> = arrayOf()
})
SSLContext.getInstance("TLS").apply { init(null, trustAll, java.security.SecureRandom()) }.socketFactory
}
/** Test RPC connectivity. Accepts self-signed certs for local LAN servers. /** Test RPC connectivity. Accepts self-signed certs for local LAN servers.
* [timeoutMs] is per-phase (connect / read) — mesh probes need far more * [timeoutMs] is per-phase (connect / read) — mesh probes need far more
* patience than LAN ones (first session through the tree can take 15s+). */ * patience than LAN ones (first session through the tree can take 15s+). */
@@ -697,14 +751,7 @@ private suspend fun testConnection(server: ServerEntry, timeoutMs: Int = 5000):
// Trust self-signed certs for local HTTPS (Archipelago nodes rarely have CA certs) // Trust self-signed certs for local HTTPS (Archipelago nodes rarely have CA certs)
if (connection is HttpsURLConnection) { if (connection is HttpsURLConnection) {
val trustAll = arrayOf<javax.net.ssl.TrustManager>(object : X509TrustManager { connection.sslSocketFactory = trustAllSslFactory
override fun checkClientTrusted(chain: Array<java.security.cert.X509Certificate>?, authType: String?) {}
override fun checkServerTrusted(chain: Array<java.security.cert.X509Certificate>?, authType: String?) {}
override fun getAcceptedIssuers(): Array<java.security.cert.X509Certificate> = arrayOf()
})
val sc = SSLContext.getInstance("TLS")
sc.init(null, trustAll, java.security.SecureRandom())
connection.sslSocketFactory = sc.socketFactory
connection.hostnameVerifier = javax.net.ssl.HostnameVerifier { _, _ -> true } connection.hostnameVerifier = javax.net.ssl.HostnameVerifier { _, _ -> true }
} }
File diff suppressed because it is too large Load Diff
@@ -2,56 +2,95 @@ package com.archipelago.app.ui.theme
import androidx.compose.material3.Typography import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.sp
import com.archipelago.app.R
/**
* The platform's brand face. neode-ui sets `font-archipelago: Montserrat` and
* uses it for every heading, title and button label, with body copy left to
* `Avenir Next, system-ui` — which on Android resolves to the system sans
* anyway. Mirroring that split exactly is what makes companion text read as
* the same product as the node UI.
*
* Montserrat is SIL OFL 1.1 (see Android/MONTSERRAT-OFL.txt); the files are
* the ones already vendored for the web UI, so both halves ship the same
* outlines.
*/
val Montserrat = FontFamily(
Font(R.font.montserrat_medium, FontWeight.Medium),
Font(R.font.montserrat_semibold, FontWeight.SemiBold),
Font(R.font.montserrat_bold, FontWeight.Bold),
Font(R.font.montserrat_extrabold, FontWeight.ExtraBold),
)
val Typography = Typography( val Typography = Typography(
// ── Display / headings: Montserrat, tight and heavy like the web hero
// copy (the platform sets tracking negative on its big type).
displayLarge = TextStyle( displayLarge = TextStyle(
fontWeight = FontWeight.Bold, fontFamily = Montserrat,
fontWeight = FontWeight.ExtraBold,
fontSize = 32.sp, fontSize = 32.sp,
lineHeight = 40.sp, lineHeight = 40.sp,
letterSpacing = (-0.5).sp, letterSpacing = (-0.8).sp,
), ),
headlineLarge = TextStyle( headlineLarge = TextStyle(
fontWeight = FontWeight.SemiBold, fontFamily = Montserrat,
fontWeight = FontWeight.Bold,
fontSize = 28.sp, fontSize = 28.sp,
lineHeight = 36.sp, lineHeight = 36.sp,
letterSpacing = (-0.5).sp,
), ),
headlineMedium = TextStyle( headlineMedium = TextStyle(
fontWeight = FontWeight.SemiBold, fontFamily = Montserrat,
fontWeight = FontWeight.Bold,
fontSize = 24.sp, fontSize = 24.sp,
lineHeight = 32.sp, lineHeight = 32.sp,
letterSpacing = (-0.4).sp,
), ),
titleLarge = TextStyle( titleLarge = TextStyle(
fontWeight = FontWeight.Medium, fontFamily = Montserrat,
fontWeight = FontWeight.SemiBold,
fontSize = 20.sp, fontSize = 20.sp,
lineHeight = 28.sp, lineHeight = 28.sp,
letterSpacing = (-0.2).sp,
), ),
titleMedium = TextStyle( titleMedium = TextStyle(
fontWeight = FontWeight.Medium, fontFamily = Montserrat,
fontWeight = FontWeight.SemiBold,
fontSize = 16.sp, fontSize = 16.sp,
lineHeight = 24.sp, lineHeight = 24.sp,
letterSpacing = 0.15.sp,
), ),
// ── Body: system sans, exactly as the web falls back to.
bodyLarge = TextStyle( bodyLarge = TextStyle(
fontWeight = FontWeight.Normal, fontWeight = FontWeight.Normal,
fontSize = 16.sp, fontSize = 16.sp,
lineHeight = 24.sp, lineHeight = 24.sp,
letterSpacing = 0.5.sp, letterSpacing = 0.2.sp,
), ),
bodyMedium = TextStyle( bodyMedium = TextStyle(
fontWeight = FontWeight.Normal, fontWeight = FontWeight.Normal,
fontSize = 14.sp, fontSize = 14.sp,
lineHeight = 20.sp, lineHeight = 20.sp,
letterSpacing = 0.25.sp, letterSpacing = 0.1.sp,
), ),
bodySmall = TextStyle(
fontWeight = FontWeight.Normal,
fontSize = 13.sp,
lineHeight = 18.sp,
),
// ── Buttons / labels: Montserrat again, matching .glass-button.
labelLarge = TextStyle( labelLarge = TextStyle(
fontFamily = Montserrat,
fontWeight = FontWeight.SemiBold, fontWeight = FontWeight.SemiBold,
fontSize = 14.sp, fontSize = 14.sp,
lineHeight = 20.sp, lineHeight = 20.sp,
letterSpacing = 0.1.sp, letterSpacing = 0.1.sp,
), ),
labelMedium = TextStyle( labelMedium = TextStyle(
fontFamily = Montserrat,
fontWeight = FontWeight.Medium, fontWeight = FontWeight.Medium,
fontSize = 12.sp, fontSize = 12.sp,
lineHeight = 16.sp, lineHeight = 16.sp,
@@ -1,36 +1,52 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<!-- Archipelago pixel-art "A" for splash screen --> <!-- System splash icon — deliberately the SAME mark as the adaptive launcher
<vector xmlns:android="http://schemas.android.com/apk/res/android" icon (ic_launcher_background.xml): dark disc + metallic ring + white
android:width="108dp" Archipelago grid. Tapping the icon and watching the splash should show
android:height="108dp" one badge, not two different logos.
android:viewportWidth="1024"
android:viewportHeight="1024">
Geometry is copied from the launcher: the Android 12 splash draws its icon
on a 288dp canvas whose inner 2/3 is the safe area — the same 0.667 ratio
the adaptive-icon mask uses — so the launcher's 0.65 (ring) / 0.55 (grid)
group scales land identically here. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="288dp"
android:height="288dp"
android:viewportWidth="752"
android:viewportHeight="752">
<!-- Dark disc + gradient ring (#000 -> #666), matching logo.svg -->
<group <group
android:pivotX="512" android:pivotX="376"
android:pivotY="512" android:pivotY="376"
android:scaleX="0.65"
android:scaleY="0.65">
<path
android:fillColor="#0A0A0A"
android:strokeWidth="22.8834"
android:pathData="M11.441,375.669a364.227,364.227 0 1,0 728.454,0a364.227,364.227 0 1,0 -728.454,0z">
<aapt:attr name="android:strokeColor">
<gradient
android:type="linear"
android:startX="751.337"
android:startY="751.338"
android:endX="0"
android:endY="0.000976562">
<item android:offset="0" android:color="#FF000000" />
<item android:offset="1" android:color="#FF666666" />
</gradient>
</aapt:attr>
</path>
</group>
<!-- White Archipelago grid -->
<group
android:pivotX="376"
android:pivotY="376"
android:scaleX="0.55" android:scaleX="0.55"
android:scaleY="0.55"> android:scaleY="0.55">
<path
<path android:fillColor="#FFFFFF" android:pathData="M357.614,318h71.007v70.936h-71.007z" /> android:fillColor="#FFFFFF"
<path android:fillColor="#FFFFFF" android:pathData="M436.152,318h72.082v70.936h-72.082z" /> android:pathData="M253.805,278.37V222.28H309.853V278.37H253.805ZM315.797,278.37V222.28H372.694V278.37H315.797ZM378.639,278.37V222.28H435.536V278.37H378.639ZM441.481,278.37V222.28H497.529V278.37H441.481ZM441.481,341.259V284.319H497.529V341.259H441.481ZM503.473,341.259V284.319H560.37V341.259H503.473ZM190.963,404.148V347.208H247.86V404.148H190.963ZM253.805,404.148V347.208H309.853V404.148H253.805ZM315.797,404.148V347.208H372.694V404.148H315.797ZM378.639,404.148V347.208H435.536V404.148H378.639ZM441.481,404.148V347.208H497.529V404.148H441.481ZM503.473,404.148V347.208H560.37V404.148H503.473ZM190.963,466.187V410.097H247.86V466.187H190.963ZM253.805,466.187V410.097H309.853V466.187H253.805ZM441.481,466.187V410.097H497.529V466.187H441.481ZM503.473,466.187V410.097H560.37V466.187H503.473ZM253.805,529.076V472.136H309.853V529.076H253.805ZM315.797,529.076V472.136H372.694V529.076H315.797ZM378.639,529.076V472.136H435.536V529.076H378.639ZM441.481,529.076V472.136H497.529V529.076H441.481Z" />
<path android:fillColor="#FFFFFF" android:pathData="M515.766,318h72.082v70.936h-72.082z" />
<path android:fillColor="#FFFFFF" android:pathData="M595.379,318h71.007v70.936h-71.007z" />
<path android:fillColor="#FFFFFF" android:pathData="M595.379,396.46h71.007v72.011h-71.007z" />
<path android:fillColor="#FFFFFF" android:pathData="M673.917,396.46h72.083v72.011h-72.083z" />
<path android:fillColor="#FFFFFF" android:pathData="M278,475.994h72.083v72.012h-72.083z" />
<path android:fillColor="#FFFFFF" android:pathData="M357.614,475.994h71.007v72.012h-71.007z" />
<path android:fillColor="#FFFFFF" android:pathData="M436.152,475.994h72.082v72.012h-72.082z" />
<path android:fillColor="#FFFFFF" android:pathData="M515.766,475.994h72.082v72.012h-72.082z" />
<path android:fillColor="#FFFFFF" android:pathData="M595.379,475.994h71.007v72.012h-71.007z" />
<path android:fillColor="#FFFFFF" android:pathData="M673.917,475.994h72.083v72.012h-72.083z" />
<path android:fillColor="#FFFFFF" android:pathData="M278,555.529h72.083v70.936h-72.083z" />
<path android:fillColor="#FFFFFF" android:pathData="M357.614,555.529h71.007v70.936h-71.007z" />
<path android:fillColor="#FFFFFF" android:pathData="M595.379,555.529h71.007v70.936h-71.007z" />
<path android:fillColor="#FFFFFF" android:pathData="M673.917,555.529h72.083v70.936h-72.083z" />
<path android:fillColor="#FFFFFF" android:pathData="M357.614,633.989h71.007v72.011h-71.007z" />
<path android:fillColor="#FFFFFF" android:pathData="M436.152,633.989h72.082v72.011h-72.082z" />
<path android:fillColor="#FFFFFF" android:pathData="M515.766,633.989h72.082v72.011h-72.082z" />
<path android:fillColor="#FFFFFF" android:pathData="M595.379,633.989h71.007v72.011h-71.007z" />
</group> </group>
</vector> </vector>
Binary file not shown.
Binary file not shown.
@@ -49,4 +49,12 @@
<string name="scan_wallet_hint">Point the camera at a Lightning invoice, Bitcoin address, Cashu or Fedimint code</string> <string name="scan_wallet_hint">Point the camera at a Lightning invoice, Bitcoin address, Cashu or Fedimint code</string>
<string name="upload_qr_image">Upload image</string> <string name="upload_qr_image">Upload image</string>
<string name="no_qr_in_image">No QR code found in that image — try another, closer and well-lit</string> <string name="no_qr_in_image">No QR code found in that image — try another, closer and well-lit</string>
<string name="torch_on">Turn on the torch</string>
<string name="torch_off">Turn off the torch</string>
<!-- Launch node picker (more than one node saved) -->
<string name="pick_node_title">Which node?</string>
<string name="pick_node_hint">Choose the Archipelago this session connects to. The FIPS mesh only comes up for mesh nodes.</string>
<string name="pick_node_add">Add another node</string>
<string name="connect_to_node">Connect to your node</string>
</resources> </resources>
+57
View File
@@ -1,5 +1,62 @@
# Changelog # Changelog
## v1.8.4-alpha (2026-08-20)
- **Apps with their own login can now skip the node's login screen — Gitea and BTCPay Server do so out of the box.** Some apps bring a complete account system of their own, and putting the node's password page in front of them broke real workflows: git clients can't answer a browser login, and a BTCPay checkout link handed to a customer must open for that customer. These apps are now served directly on their own login, while the node still fronts the connection for everything else it does (embedding fixes, the "app is restarting" page, Tor). Every app gets a new **Settings → app → Access control** switch, so you can put the node login back in front of any app — or take it away from one — with one click, effective immediately. App developers declare the default in their manifest (`auth: open`), documented in the developer guide.
- **The phone remote now works inside apps on the TV — tap, scroll, and type everywhere.** The companion remote and keyboard drove the dashboard beautifully but died at the edge of any app screen (Gitea, BTCPay, and friends): for the browser, each app is a separate website embedded in the page, and simulated input is forbidden from crossing that wall. The on-screen display now accepts the remote's input the way a real mouse and keyboard arrive — below the page, through the browser itself — so it lands anywhere on screen, app screens and tabs included. Taps click, two-finger scrolling scrolls the app, and typing goes into whichever field you tapped. Existing kiosks pick this up with the update, no reinstall needed.
- **While you're driving with the phone remote, the old mouse pointer gets out of the way.** The computer's own pointer used to sit frozen wherever the physical mouse last left it — a second, dead cursor next to the live orange one. It now hides while the remote is in use and returns half a minute after the last remote input.
- **"Are you sure?" questions no longer freeze the remote.** A handful of confirmations (clearing mesh history, rebooting, deleting a backup, uninstalling an app) used the browser's built-in popup, which stops the whole page — including remote input — until someone clicks it with a real mouse. From the couch, that meant asking a question you couldn't answer. All of them are now proper in-app windows in the house style, fully driveable by remote.
- **A mesh radio now connects no matter which port it's plugged into — or replugged into.** Moving a radio to a different USB port could leave the mesh silently down: the node only checked a short fixed list of port names (a radio landing outside it was invisible), a hand-set serial-port override quietly outranked the device you'd just approved in the "Radio detected" window, and one whole family of boards (Espressif-based radios like recent Heltec/T-Deck models) never received a stable device name at all — the exact combination found live on a fleet machine this week. All three are fixed: every serial port is scanned, choosing a radio in the detection window clears any stale override, and Espressif boards get the same stable name as everyone else.
- **Mesh signal strength is honest now.** Every peer heard over Reticulum radio reported a signal strength of exactly 0 — which is also what you'd see with no radio at all, and what peers reached over the internet showed. Real receptions now show their true signal reading, and anything that arrived over a relay or the internet says so by showing none — so "the radio is working" and "the internet is doing the radio's job" no longer look identical. (The reading depends on the radio's firmware reporting it; boards that don't report per-packet signal stats show "unknown" rather than a made-up number, and the new radio diagnostics show at a glance whether yours reports them.)
- **A background error that repeated every 90 seconds, forever, is gone.** After setting up a node from its recovery phrase, the node kept introducing itself to its federation partners with its old temporary identity papers while signing with its new ones — every partner rejected the introduction, and both sides logged an error about it every minute and a half until the next restart. The identity switch now updates everything at once, a rejected introduction is no longer misreported as delivered, and a partner who has already answered is no longer re-asked on every cycle.
## v1.8.3-alpha (2026-08-14)
- **The network map on TVs: no more blank page, no more frozen page — and it moves again.** The map's entrance animation needed a smoothness that TV kiosk hardware can't always deliver, so the page could sit blank until a refresh; the previous fix cured the freeze by stopping the animation entirely, which went too far. Now the map appears instantly with everything already in place, then resumes its calm orbital motion at a gentler pace suited to TVs. Resizing or rotating any screen also redraws the map properly instead of leaving it tiny, stretched, or empty.
- **The dashboard's corner logo is back to normal.** The new glossy paint finish was meant for the big emblem on the screensaver, intro, and login screens — it had quietly spread to the small logo in the dashboard header, where it looked wrong. Each screen now gets exactly the treatment intended for it.
- **App icons no longer vanish in My Apps.** The freshly restyled Alby Hub and phoenixd icons could render as blank squares in some views — a subtlety in how the icon files declared their size. Fixed at the source, and the icon tool app developers use now produces immune files.
## v1.8.2-alpha (2026-08-13)
- **An app that can't be shown inside the dashboard now becomes a tab app by itself.** A few apps refuse to render inside another page no matter what — they break out with their own code or insist on owning the whole browser window. Opening one used to mean staring at a grey pane. Now the dashboard notices, offers the app in its own tab, and remembers: from then on that app's button opens a tab directly (with the little launch icon that tab apps carry), first click, every time. If a later update makes the app embeddable after all, the dashboard notices that too and goes back to embedding it.
- **The logo emblem got its glossy black paint finish — properly this time.** The circle behind the A on the screensaver, intro, and login now wears a deep wet-paint look: warm light blooming from the top edge, fine grain so the dark tones stay smooth instead of banding, and no more ring border. (An earlier rougher version of this experiment briefly shipped by accident and then vanished depending on which screen you were on — this is the finished, deliberate one, everywhere.)
- **New app icons now match the store's look, on every screen.** Alby Hub and phoenixd arrived with edge-to-edge logos that ignored the breathing room every other app icon has, and the app detail page skipped the icon backdrop entirely. Both icons are re-set on the standard canvas, the detail page now applies the same icon treatment as the store tiles, and app developers get a one-command tool that puts any logo onto the house canvas automatically.
## v1.8.1-alpha (2026-08-13)
- **Apps that refused to open inside the dashboard now embed like everything else.** Some apps ship browser headers that forbid being shown inside another page — correct hardening on the open web, but inside Archipelago it produced a dead grey pane when you opened them from My Apps (Alby Hub was the first to hit it). The app gate, which already checks your login on every request to an app, now removes just those framing headers on the way through; each app's own content-security rules pass through untouched. No more per-app proxy workarounds.
- **The network map no longer freezes kiosk TVs.** The animated federation map at 4K was too much for the deliberately conservative graphics settings the on-screen display used on every machine — settings chosen years back to stop audio crackle on much older hardware. Two fixes: on kiosk screens the map now opens in its flat 2D view (the 3D globe is one tap away, and remembered) and animates at half rate — invisible from the couch, half the work. And the display itself now recognizes what machine it runs on: older kiosk boxes keep the proven careful settings, modern ones finally get real GPU rendering.
- **New Settings → Display → Graphics choice for the on-screen display.** Auto (recommended) picks the right rendering mode for the machine by itself; Compatibility forces the most conservative mode if a screen ever stutters, tears, or crackles; Quality forces full GPU rendering on hardware the automatic detection doesn't recognize. Changing it restarts the on-screen display, like the size presets.
## v1.8.0-alpha (2026-08-12)
- **Archipelago is now open source.** The full source code of the node you are running — the orchestrator, the dashboard, the app platform, the mesh, the release tooling — is published for anyone to read, build and audit at source.archipelago-foundation.org/lfg2025/archy. A node that holds your money, your files and your communications should not ask to be taken on faith: from this release onward you, or anyone you trust, can see exactly what it does and follow every change we make in the open.
- **Installing an update is reliable again, and tells you what happened when it isn't.** Some nodes could download an update but never apply it — the button stayed on "Install", and no amount of retrying worked. The cause: applying the update consumed the downloaded files as it went, so if any one step hit a snag partway through, the leftover files were incomplete and every later attempt failed the safety re-check forever, needing a technician to recover. Applying no longer consumes the download — a failed apply can always be retried from the same files — and the pieces are now applied in a fixed order with the program itself last, so a hiccup can't leave a half-swapped node. When an apply does fail, the screen now shows the real reason and what to do ("download the update again"), and offers Download again instead of a dead "Install" button, rather than a generic "it failed".
- **Video on the kiosk stops tearing.** The kiosk's display had no vertical sync at all, so fast motion — IndeedHub films especially — showed horizontal tearing lines. The display driver now syncs every frame to the panel (no extra hardware needed, existing kiosks pick it up with this update), and on machines with a GPU, video decoding moves off the CPU onto the video hardware — smoother playback that also leaves more headroom for audio, not less.
- **The Back button finally does what you expect.** Pressing Back — the mouse's side button on a kiosk, a swipe on a phone, the toolbar button in any browser — used to navigate the screen underneath an open window, or leave the dashboard entirely. Back now closes the topmost open window first, one per press, exactly like a native app; closing a window yourself never leaves a phantom entry that makes you press Back twice.
- **No more bare IP addresses in your update or app-registry settings.** The update mirrors and the app registry each listed the same server twice — once by its proper name, once as a raw `http://146…` address left over from before the domain existed. The raw-address entries are retired: new nodes never see them, and existing nodes clean them out of their saved lists automatically on the next read. Everything now goes through the named, TLS-protected origin — which was always the same machine.
- **The phone companion app downloads over the proper domain.** The download QR pointed at a raw address over plain HTTP; it now points at the same file on the https domain. Scanning it gets you an encrypted download from a named server.
- **The Receive window now tells you when the money is on its way.** Previously it showed a QR code and left you to check elsewhere whether anything happened. Now, the moment the sender's transaction is broadcast, the QR gives way to a clock: the amount, the transaction ID (tap to copy), and a note that the funds arrive on their own — with a single Done button. If you keep the window open, the clock becomes a green check at the first confirmation. Verified live on a real node: payment detected within seconds of broadcast.
## v1.7.129-alpha (2026-08-10)
- **Every app is now supervised the same way — the last stragglers moved under systemd.** Five apps (Jellyfin, Nextcloud, Home Assistant, Uptime Kuma, Vaultwarden) still ran outside the node's per-app service management for a technical reason: their networking style died with whatever process started it, so they were kept alive by a separate workaround. That workaround is retired: these apps now migrate themselves onto the same managed units as everything else — own service, restart-on-anything, a ten-second breather between restarts so their networking can release its ports cleanly. The migration happens automatically on the node's next housekeeping pass, touches no app data, and was watched live on a real node: both test apps moved over on the first pass and came back healthy.
- **Leftover companion screens are cleaned up again — driven by real records this time.** When an app is uninstalled, its helper screen (the UI tile that fronts it) should go too. That cleanup was switched off in an earlier release after it wrongly removed the Bitcoin screen from a node whose Bitcoin was installed — it had been guessing "installed" from what happened to be running, and a separate bug made a running app look absent. The node now keeps a durable record of what you have installed, written at install time and cleared only by a real uninstall, and the cleanup consults only that record. If the record can't be read, the cleanup does nothing at all — "I couldn't check" is never treated as "nothing is installed" — and a helper must be orphaned for a sustained period before it is touched.
- **A warning that fired every minute on every node is gone.** The app catalog and the node disagreed about where Grafana's software comes from, so the node ignored the catalog's answer and logged a complaint roughly every 75 seconds, forever. The catalog was right — Grafana is served from the fleet's own registry, like Bitcoin Knots — and the node's records now agree with it.
- **The federation map became a real map.** The network view is now a 3D orbital scene of your federation — nodes as a point-cloud globe with calm motion, auto-fit centring, and a 2D top-down toggle that portrait and mobile screens use by default, with the scene filling the viewport instead of sitting in a letterbox. Inbound peer requests appear live on the map as blinking nodes you can accept or reject in place, and revisiting the view no longer replays the whole intro — the scene updates in place.
- **An app that's mid-restart shows a page that says so — and comes back by itself.** When an app's screen was briefly unreachable behind the gate, the browser got a bare error; it now gets a named page for that app that retries on its own until the app answers.
- Known gaps, disclosed rather than buried: three voice-assistant ports remain open without authentication. Non-browser clients — phone apps for Vaultwarden, Home Assistant or Jellyfin, and git over the web — meet the login page and need an access token. The 5x real-node lifecycle gate was not run for this release; the supervision migration and the cleanup re-enable were verified live on one node (both apps migrated and healthy, cleanup correctly idle).
## v1.7.128-alpha (2026-08-10)
- **The discovery list stops showing ghosts.** Every reinstall of a node mints a new discovery identity, and the old identity's announcement could never be removed from the public relays — nothing holds its key anymore — so the "Discoverable nodes" list slowly filled with entries that led nowhere. Announcements now expire: your node re-announces itself twice a day, each announcement carries a 48-hour expiry that relays honour, anything older than that is ignored when reading, and switching discovery off — or factory-resetting the node — actively overwrites the announcement before it can become a ghost. Old ghosts from earlier versions stop being shown immediately and age off the relays on their own.
- **You can name your node when you make it discoverable.** Turning discovery on now asks for an optional display name — it travels inside the public announcement, so other nodes' discovery lists show "Dorian's basement node" instead of a bare npub. The name is public by construction, capped at 32 characters, and blank is fine: you list as npub only. Toggling discovery off and on remembers the name; you can clear it the same way you set it.
- **The discoverability panel now shows what the network actually sees: your node's npub.** It previously showed your Tor address — which is precisely the thing the announcement never contains (your address stays private until you approve a peer). The npub, the identity other nodes discover you by and send peering requests to, is now displayed there with a copy button.
- **The seed screen stops flashing while the node starts.** During first boot, the lock icon and "server starting" text blinked in and out every few seconds while the node came up — each silent retry briefly emptied the screen. The waiting state now holds steady, with its elapsed timer, until the node answers.
- **A node that already has an identity now explains itself on the seed screen.** Reaching seed creation on a provisioned node used to surface a developer message about "the authenticated system.factory-reset". It now says what you can actually do: sign in normally, or factory-reset the node from Settings to start it over.
- Known gaps, disclosed rather than buried: three voice-assistant ports remain open without authentication. Non-browser clients — phone apps for Vaultwarden, Home Assistant or Jellyfin, and git over the web — meet the login page and need an access token. The 5x real-node lifecycle gate was not run for this release; the changes were verified by operator UAT on a live node.
## v1.7.127-alpha (2026-08-09) ## v1.7.127-alpha (2026-08-09)
- **Your node now has its own assistant.** This is the first release to ship AIUI: a conversational screen that can answer from your node's own content — your films, music and files come first, the open web second — and can act on the node itself: install or remove an app, check what's running, or queue up your media, all through a fixed list of vetted actions rather than free rein. It is off-limits to your data until you say otherwise: every data category starts closed, grants are made in Settings → AI Data Access and live on the node itself, and anything that changes the node asks you to confirm in the dashboard's own chrome first — a declined action stays declined. What leaves the node is screened: your API key is stored encrypted and never written in plain text, credential-shaped strings are scrubbed from app logs before the model sees them, your public address and Wi-Fi name are stripped from network answers, web search is gated behind your login session, and cloud-bound text passes a secret scan on the way out. Three model backends are supported — Anthropic's API, a local Ollama, and pay-per-use Routstr with a hard prepaid budget ceiling — and mesh peers can reach the same loop with `!ai`. - **Your node now has its own assistant.** This is the first release to ship AIUI: a conversational screen that can answer from your node's own content — your films, music and files come first, the open web second — and can act on the node itself: install or remove an app, check what's running, or queue up your media, all through a fixed list of vetted actions rather than free rein. It is off-limits to your data until you say otherwise: every data category starts closed, grants are made in Settings → AI Data Access and live on the node itself, and anything that changes the node asks you to confirm in the dashboard's own chrome first — a declined action stays declined. What leaves the node is screened: your API key is stored encrypted and never written in plain text, credential-shaped strings are scrubbed from app logs before the model sees them, your public address and Wi-Fi name are stripped from network answers, web search is gated behind your login session, and cloud-bound text passes a secret scan on the way out. Three model backends are supported — Anthropic's API, a local Ollama, and pay-per-use Routstr with a hard prepaid budget ceiling — and mesh peers can reach the same loop with `!ai`.
@@ -93,10 +93,11 @@ describe('useAI', () => {
expect(activeModel.value).toBe('echo') expect(activeModel.value).toBe('echo')
}) })
it('lists available providers with models', () => { it('lists available providers with models, Routstr first', () => {
const { availableProviders } = useAI() const { availableProviders } = useAI()
expect(availableProviders.value.length).toBe(3) expect(availableProviders.value.length).toBe(4)
const ids = availableProviders.value.map(p => p.id) const ids = availableProviders.value.map(p => p.id)
expect(ids[0]).toBe('routstr')
expect(ids).toContain('claude') expect(ids).toContain('claude')
expect(ids).toContain('openrouter') expect(ids).toContain('openrouter')
expect(ids).toContain('mock') expect(ids).toContain('mock')
@@ -119,7 +119,7 @@
<Transition name="picker"> <Transition name="picker">
<div <div
v-if="showModelPicker" v-if="showModelPicker"
class="fixed z-[9999] path-glass-card header-overlay-panel p-3 space-y-3 animate-fade-up-fast shadow-2xl min-w-[220px]" class="fixed z-[9999] path-glass-card header-overlay-panel p-3 space-y-3 animate-fade-up-fast shadow-2xl min-w-[220px] max-h-[70vh] overflow-y-auto"
:style="modelPickerDropdownStyle" :style="modelPickerDropdownStyle"
@click.stop @click.stop
> >
@@ -332,7 +332,7 @@ const modelDisplayName = computed(() => {
}) })
function selectModel(providerId: string, modelId: string) { function selectModel(providerId: string, modelId: string) {
setProvider(providerId as 'claude' | 'openrouter' | 'mock') setProvider(providerId as 'routstr' | 'claude' | 'openrouter' | 'mock')
setModel(modelId) setModel(modelId)
showModelPicker.value = false showModelPicker.value = false
} }
+118 -5
View File
@@ -13,12 +13,14 @@ import { useCodeContext } from '@/composables/useCodeContext'
import { apiFetch } from '@/utils/api-fetch' import { apiFetch } from '@/utils/api-fetch'
import { useSettingsStore } from '@/stores/settings' import { useSettingsStore } from '@/stores/settings'
type Provider = 'claude' | 'openrouter' | 'mock' type Provider = 'routstr' | 'claude' | 'openrouter' | 'mock'
// API paths are relative to the base URL so they work both in dev (/) and Archy (/aiui/) // API paths are relative to the base URL so they work both in dev (/) and Archy (/aiui/)
const BASE = import.meta.env.BASE_URL || '/' const BASE = import.meta.env.BASE_URL || '/'
const CLAUDE_PATH = `${BASE}api/claude/v1/messages` const CLAUDE_PATH = `${BASE}api/claude/v1/messages`
const OPENROUTER_PATH = `${BASE}api/openrouter` const OPENROUTER_PATH = `${BASE}api/openrouter`
const ROUTSTR_MODELS_PATH = `${BASE}api/routstr/models`
const ROUTSTR_CHAT_PATH = `${BASE}api/routstr/chat/completions`
import { mockFilms } from '@/mocks/films' import { mockFilms } from '@/mocks/films'
import { mockSongs } from '@/mocks/songs' import { mockSongs } from '@/mocks/songs'
@@ -148,8 +150,41 @@ function looksLikeMissingApiKey(err: string): boolean {
) )
} }
// ─── Routstr model catalog (fetched from the node's session-gated proxy) ───
// The node forwards the live Routstr aggregator's /v1/models; entries carry
// sats_pricing so completions are Cashu-paid against the operator's budget.
const routstrModels = ref<{ id: string; name: string }[]>([])
let routstrModelsFetched = false
async function refreshRoutstrModels() {
if (routstrModelsFetched) return
routstrModelsFetched = true
try {
const res = await apiFetch(ROUTSTR_MODELS_PATH)
if (!res.ok) return
const data = await res.json()
if (Array.isArray(data?.data)) {
routstrModels.value = data.data
.filter((m: Record<string, unknown>) => typeof m.id === 'string')
.map((m: Record<string, unknown>) => ({
id: m.id as string,
name: (m.name as string) || (m.id as string),
}))
}
} catch {
routstrModelsFetched = false // allow a retry on the next send/open
}
}
const availableProviders = computed(() => { const availableProviders = computed(() => {
const providers: { id: Provider; name: string; models: { id: string; name: string }[] }[] = [ const providers: { id: Provider; name: string; models: { id: string; name: string }[] }[] = [
{
id: 'routstr',
name: 'Routstr (sats)',
models: routstrModels.value.length > 0
? routstrModels.value
: [{ id: 'routstr-unavailable', name: 'No models — node offline?' }],
},
{ {
id: 'claude', id: 'claude',
name: 'Claude (Max)', name: 'Claude (Max)',
@@ -381,6 +416,71 @@ async function streamOpenRouter(
}, onError, signal) }, onError, signal)
} }
/**
* Routstr: one paid, NON-streaming, OpenAI-shaped completion through the
* node's session-gated `/aiui/api/routstr/` forwarder. The node quotes a
* price from the live catalog, pays with a Cashu token against the
* operator's budget (Settings → System → Routstr AI budget), redeems the
* change, and passes the provider's JSON back. The full answer is emitted
* as a single token — streaming across a paid hop is the planned follow-up.
*/
async function streamRoutstr(
messages: ChatMessage[],
onToken: (text: string) => void,
onError: (err: string) => void,
systemPrompt: string,
signal?: AbortSignal,
): Promise<void> {
const wireMessages = [
{ role: 'system' as const, content: systemPrompt },
...messages.map((m) => ({ role: m.role as 'user' | 'assistant', content: m.content })),
]
const res = await apiFetch(ROUTSTR_CHAT_PATH, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: activeModel.value,
messages: wireMessages,
stream: false,
}),
signal,
})
const bodyText = await res.text().catch(() => '')
if (!res.ok) {
// The node's refusals carry a plain-language error.message (budget not
// set, budget spent, wallet can't fund) — surface it verbatim.
let msg = `Routstr error ${res.status}`
try {
const parsed = JSON.parse(bodyText)
// Node refusals use {error:{message}}; the upstream provider nests
// its own as {detail:{error:{message}}} or a plain {detail:"..."}.
const detail = parsed?.detail
msg =
parsed?.error?.message ??
detail?.error?.message ??
(typeof detail === 'string' ? detail : undefined) ??
msg
} catch { /* keep the status-only message */ }
onError(msg)
return
}
if (signal?.aborted) return
try {
const parsed = JSON.parse(bodyText)
const text = parsed?.choices?.[0]?.message?.content
if (typeof text === 'string' && text.length > 0) {
onToken(text)
} else {
onError('Routstr returned an empty response')
}
} catch {
onError('Routstr returned a malformed response')
}
}
/** /**
* Embedded-mode chat delegation (D-01/D-17): when AIUI is running inside * Embedded-mode chat delegation (D-01/D-17): when AIUI is running inside
* Archy, the model call, the tool-calling loop, and the model key all live * Archy, the model call, the tool-calling loop, and the model key all live
@@ -619,7 +719,11 @@ export async function streamWithModel(
activeModel.value = model activeModel.value = model
try { try {
if (useArchy().isEmbedded.value) { if (provider === 'routstr') {
// Explicitly chosen Routstr wins even embedded in Archy — the whole
// point of the picker entry is that it is a selection, not a fallback.
await streamRoutstr(history, onToken, onError, 'You are a helpful assistant.', signal)
} else if (useArchy().isEmbedded.value) {
// D-17: embedded mode delegates the loop, the tools and the key to // D-17: embedded mode delegates the loop, the tools and the key to
// Archy — provider/model selection here doesn't apply node-side. // Archy — provider/model selection here doesn't apply node-side.
await streamViaArchy(history, onToken, onError, signal) await streamViaArchy(history, onToken, onError, signal)
@@ -638,8 +742,9 @@ export async function streamWithModel(
export function useAI() { export function useAI() {
const chatStore = useChatStore() const chatStore = useChatStore()
// Fetch Wavlake catalog on first use (non-blocking) // Fetch Wavlake + Routstr catalogs on first use (non-blocking)
refreshWavlakeCatalog() refreshWavlakeCatalog()
refreshRoutstrModels()
function stopGeneration() { function stopGeneration() {
if (currentAbort) { if (currentAbort) {
@@ -712,7 +817,11 @@ export function useAI() {
const genParams = getConversationParams(chatStore) const genParams = getConversationParams(chatStore)
try { try {
if (useArchy().isEmbedded.value) { if (provider === 'routstr') {
// Explicitly chosen Routstr wins even embedded in Archy — a
// selection, not a fallback.
await streamRoutstr(history, onToken, onError, systemPrompt, signal)
} else if (useArchy().isEmbedded.value) {
// D-17: embedded mode delegates the loop, the tools and the key to // D-17: embedded mode delegates the loop, the tools and the key to
// Archy — provider/model selection here doesn't apply node-side. // Archy — provider/model selection here doesn't apply node-side.
await streamViaArchy(history, onToken, onError, signal) await streamViaArchy(history, onToken, onError, signal)
@@ -828,7 +937,11 @@ export function useAI() {
const genParams = getConversationParams(chatStore) const genParams = getConversationParams(chatStore)
try { try {
if (useArchy().isEmbedded.value) { if (provider === 'routstr') {
// Explicitly chosen Routstr wins even embedded in Archy — a
// selection, not a fallback.
await streamRoutstr(history, onToken, onError, systemPrompt, signal)
} else if (useArchy().isEmbedded.value) {
// D-17: embedded mode delegates the loop, the tools and the key to // D-17: embedded mode delegates the loop, the tools and the key to
// Archy — provider/model selection here doesn't apply node-side. // Archy — provider/model selection here doesn't apply node-side.
await streamViaArchy(history, onToken, onError, signal) await streamViaArchy(history, onToken, onError, signal)
+50 -14
View File
@@ -52,13 +52,13 @@
{ {
"id": "btcpay-server", "id": "btcpay-server",
"title": "BTCPay Server", "title": "BTCPay Server",
"version": "2.4.2", "version": "2.4.3",
"description": "Self-hosted Bitcoin payment processor. Accept Bitcoin payments without intermediaries.", "description": "Self-hosted Bitcoin payment processor. Accept Bitcoin payments without intermediaries.",
"icon": "/assets/img/app-icons/btcpay-server.png", "icon": "/assets/img/app-icons/btcpay-server.png",
"author": "BTCPay Server Foundation", "author": "BTCPay Server Foundation",
"category": "commerce", "category": "commerce",
"tier": "core", "tier": "core",
"dockerImage": "docker.io/btcpayserver/btcpayserver:2.4.2", "dockerImage": "docker.io/btcpayserver/btcpayserver:2.4.3",
"repoUrl": "https://github.com/btcpayserver/btcpayserver", "repoUrl": "https://github.com/btcpayserver/btcpayserver",
"requires": [ "requires": [
"bitcoin-knots" "bitcoin-knots"
@@ -73,7 +73,7 @@
"author": "Mempool", "author": "Mempool",
"category": "money", "category": "money",
"tier": "core", "tier": "core",
"dockerImage": "source.archipelago-foundation.org/lfg2025/mempool-frontend:v3.0.1", "dockerImage": "source.archipelago-foundation.org/lfg2025/mempool-frontend:v3.3.1",
"repoUrl": "https://github.com/mempool/mempool", "repoUrl": "https://github.com/mempool/mempool",
"requires": [ "requires": [
"bitcoin-knots", "bitcoin-knots",
@@ -193,13 +193,13 @@
{ {
"id": "nostr-rs-relay", "id": "nostr-rs-relay",
"title": "Nostr Relay (Rust)", "title": "Nostr Relay (Rust)",
"version": "0.8.0", "version": "0.10.0",
"description": "High-performance Nostr relay written in Rust. Host your own decentralized social media relay and earn networking profits.", "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", "icon": "/assets/img/app-icons/nostrudel.svg",
"author": "Nostr RS Relay", "author": "Nostr RS Relay",
"category": "community", "category": "community",
"tier": "recommended", "tier": "recommended",
"dockerImage": "scsibug/nostr-rs-relay:0.8.9", "dockerImage": "scsibug/nostr-rs-relay:0.10.0",
"repoUrl": "https://github.com/scsibug/nostr-rs-relay", "repoUrl": "https://github.com/scsibug/nostr-rs-relay",
"containerConfig": { "containerConfig": {
"ports": [ "ports": [
@@ -223,7 +223,7 @@
"author": "Vaultwarden", "author": "Vaultwarden",
"category": "data", "category": "data",
"tier": "recommended", "tier": "recommended",
"dockerImage": "source.archipelago-foundation.org/lfg2025/vaultwarden:1.30.0-alpine", "dockerImage": "source.archipelago-foundation.org/lfg2025/vaultwarden:1.37.1-alpine",
"repoUrl": "https://github.com/dani-garcia/vaultwarden", "repoUrl": "https://github.com/dani-garcia/vaultwarden",
"containerConfig": { "containerConfig": {
"ports": [ "ports": [
@@ -262,7 +262,7 @@
"icon": "/assets/img/app-icons/fedimint.png", "icon": "/assets/img/app-icons/fedimint.png",
"author": "Fedimint", "author": "Fedimint",
"category": "money", "category": "money",
"dockerImage": "source.archipelago-foundation.org/lfg2025/fedimintd:v0.10.0", "dockerImage": "source.archipelago-foundation.org/lfg2025/fedimintd:v0.10.1",
"repoUrl": "https://github.com/fedimint/fedimint" "repoUrl": "https://github.com/fedimint/fedimint"
}, },
{ {
@@ -285,7 +285,7 @@
"icon": "/assets/img/app-icons/fedimint.png", "icon": "/assets/img/app-icons/fedimint.png",
"author": "Fedimint", "author": "Fedimint",
"category": "money", "category": "money",
"dockerImage": "source.archipelago-foundation.org/lfg2025/gatewayd:v0.10.0", "dockerImage": "source.archipelago-foundation.org/lfg2025/gatewayd:v0.10.1",
"repoUrl": "https://github.com/fedimint/fedimint", "repoUrl": "https://github.com/fedimint/fedimint",
"containerConfig": { "containerConfig": {
"ports": [ "ports": [
@@ -325,7 +325,7 @@
"icon": "/assets/img/app-icons/jellyfin.webp", "icon": "/assets/img/app-icons/jellyfin.webp",
"author": "Jellyfin", "author": "Jellyfin",
"category": "data", "category": "data",
"dockerImage": "source.archipelago-foundation.org/lfg2025/jellyfin:10.8.13", "dockerImage": "source.archipelago-foundation.org/lfg2025/jellyfin:10.11.11",
"repoUrl": "https://github.com/jellyfin/jellyfin", "repoUrl": "https://github.com/jellyfin/jellyfin",
"containerConfig": { "containerConfig": {
"ports": [ "ports": [
@@ -356,7 +356,7 @@
"icon": "/assets/img/app-icons/homeassistant.png", "icon": "/assets/img/app-icons/homeassistant.png",
"author": "Home Assistant", "author": "Home Assistant",
"category": "home", "category": "home",
"dockerImage": "source.archipelago-foundation.org/lfg2025/home-assistant:2026.7.3", "dockerImage": "source.archipelago-foundation.org/lfg2025/home-assistant:2026.8.2",
"repoUrl": "https://github.com/home-assistant/core", "repoUrl": "https://github.com/home-assistant/core",
"containerConfig": { "containerConfig": {
"ports": [ "ports": [
@@ -378,7 +378,7 @@
"icon": "/assets/img/app-icons/pine.svg", "icon": "/assets/img/app-icons/pine.svg",
"author": "Archipelago", "author": "Archipelago",
"category": "home", "category": "home",
"dockerImage": "docker.io/library/nginx:1.27-alpine", "dockerImage": "docker.io/library/nginx:1.31.4-alpine",
"repoUrl": "https://github.com/rhasspy/wyoming" "repoUrl": "https://github.com/rhasspy/wyoming"
}, },
{ {
@@ -390,7 +390,7 @@
"author": "Grafana Labs", "author": "Grafana Labs",
"category": "data", "category": "data",
"tier": "recommended", "tier": "recommended",
"dockerImage": "grafana/grafana:10.2.0", "dockerImage": "source.archipelago-foundation.org/lfg2025/grafana:10.2.0",
"repoUrl": "https://github.com/grafana/grafana", "repoUrl": "https://github.com/grafana/grafana",
"containerConfig": { "containerConfig": {
"ports": [ "ports": [
@@ -442,7 +442,7 @@
"author": "Portainer", "author": "Portainer",
"category": "development", "category": "development",
"tier": "optional", "tier": "optional",
"dockerImage": "source.archipelago-foundation.org/lfg2025/portainer:2.39.1", "dockerImage": "source.archipelago-foundation.org/lfg2025/portainer:2.39.6",
"repoUrl": "https://github.com/portainer/portainer", "repoUrl": "https://github.com/portainer/portainer",
"containerConfig": { "containerConfig": {
"ports": [ "ports": [
@@ -464,7 +464,7 @@
"author": "NetBird", "author": "NetBird",
"category": "networking", "category": "networking",
"tier": "recommended", "tier": "recommended",
"dockerImage": "docker.io/library/nginx:1.27-alpine", "dockerImage": "docker.io/library/nginx:1.31.4-alpine",
"repoUrl": "https://github.com/netbirdio/netbird", "repoUrl": "https://github.com/netbirdio/netbird",
"containerConfig": { "containerConfig": {
"ports": [ "ports": [
@@ -547,6 +547,42 @@
"/var/lib/archipelago/nextcloud:/var/www/html" "/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"
} }
] ]
} }
+3
View File
@@ -2,6 +2,9 @@ app:
id: aiui id: aiui
name: AI Assistant name: AI Assistant
version: 0.1.0 version: 0.1.0
# Built by this project — there is no upstream release feed to watch.
upstream:
kind: internal
description: Conversational AI interface for Archipelago. Quarantined — communicates only via context broker. description: Conversational AI interface for Archipelago. Quarantined — communicates only via context broker.
internal: true # System-managed, not shown in App Store internal: true # System-managed, not shown in App Store
+81
View File
@@ -0,0 +1,81 @@
app:
id: alby-hub
name: Alby Hub
version: 1.23.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.
upstream:
kind: github
repo: getAlby/hub
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.
category: money
container:
image: source.archipelago-foundation.org/lfg2025/alby-hub:v1.24.0
pull_policy: if-not-present
dependencies:
- storage: 1Gi
resources:
cpu_limit: 1
memory_limit: 512Mi
disk_limit: 2Gi
security:
capabilities: []
readonly_root: true
no_new_privileges: true
network_policy: bridge
ports:
- host: 8187
container: 8080
protocol: tcp
bind: 127.0.0.1
auth: gated
volumes:
- type: bind
source: /var/lib/archipelago/alby-hub
target: /data
options: [rw]
environment:
- WORK_DIR=/data
- PORT=8080
# LDK peers are dialed outbound-only in v1; no inbound p2p port is
# advertised, so no extra port mapping is needed for payments to work.
- LOG_LEVEL=info
health_check:
type: http
endpoint: http://localhost:8080
path: /
interval: 30s
timeout: 5s
retries: 5
interfaces:
main:
name: Web UI
description: Alby Hub wallet interface
type: ui
port: 8187
protocol: http
metadata:
icon: /assets/img/app-icons/alby-hub.svg
repo: https://github.com/getAlby/hub
tier: optional
launch:
# Embedded: the gate neutralizes Alby Hub's X-Frame-Options: DENY on
# proxied responses. Nodes older than the gate fix show a blocked
# frame — flip to true only if targeting such nodes.
open_in_new_tab: false
features:
- Self-custodial Lightning node (LDK) with a friendly wallet UI
- Connect wallets and apps via Nostr Wallet Connect (NWC)
- Per-app budgets and isolated sub-wallets
- Works with the Alby browser extension and mobile app
+6
View File
@@ -2,6 +2,12 @@ app:
id: archy-btcpay-db id: archy-btcpay-db
name: BTCPay Postgres name: BTCPay Postgres
version: "15.17" version: "15.17"
# 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.
upstream:
kind: dockerhub
repo: library/postgres
description: Postgres backend for BTCPay and NBXplorer. description: Postgres backend for BTCPay and NBXplorer.
container: container:
+6
View File
@@ -2,6 +2,12 @@ app:
id: archy-mempool-db id: archy-mempool-db
name: Mempool MariaDB name: Mempool MariaDB
version: 11.4.10 version: 11.4.10
# 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.
upstream:
kind: dockerhub
repo: library/mariadb
description: MariaDB backend for the mempool explorer stack. description: MariaDB backend for the mempool explorer stack.
container: container:
+7 -1
View File
@@ -2,11 +2,17 @@ app:
id: archy-mempool-web id: archy-mempool-web
name: Mempool Web name: Mempool Web
version: 3.0.1 version: 3.0.1
# 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.
upstream:
kind: github
repo: mempool/mempool
description: Frontend web UI for mempool explorer. description: Frontend web UI for mempool explorer.
container_name: mempool container_name: mempool
container: container:
image: source.archipelago-foundation.org/lfg2025/mempool-frontend:v3.0.1 image: source.archipelago-foundation.org/lfg2025/mempool-frontend:v3.3.1
pull_policy: if-not-present pull_policy: if-not-present
network: archy-net network: archy-net
+8 -2
View File
@@ -1,11 +1,17 @@
app: app:
id: archy-nbxplorer id: archy-nbxplorer
name: NBXplorer name: NBXplorer
version: 2.6.0 version: 2.6.11
# 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.
upstream:
kind: github
repo: dgarage/NBXplorer
description: BTCPay blockchain indexer service. description: BTCPay blockchain indexer service.
container: container:
image: source.archipelago-foundation.org/lfg2025/nbxplorer:2.6.0 image: source.archipelago-foundation.org/lfg2025/nbxplorer:2.6.11
pull_policy: if-not-present pull_policy: if-not-present
network: archy-net network: archy-net
secret_env: secret_env:
+8
View File
@@ -2,6 +2,14 @@ app:
id: barkd id: barkd
name: Ark Wallet name: Ark Wallet
version: 0.3.0 version: 0.3.0
# Where this app comes from, so scripts/check-upstream-releases.py can
# tell us when the pin below has fallen behind. bark ships on GitLab only
# (no GitHub mirror), so the gitlab fetcher is the one that can see it.
# NOTE: a version bump is code work, not a pin move — the REST shapes are
# coded in core/archipelago/src/wallet/ark_client.rs (see Dockerfile note).
upstream:
kind: gitlab
repo: ark-bitcoin/bark
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. 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.
container: container:
+7 -1
View File
@@ -2,6 +2,12 @@ app:
id: bitcoin-core id: bitcoin-core
name: Bitcoin Core name: Bitcoin Core
version: 28.4.0 version: 28.4.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.
upstream:
kind: github
repo: bitcoin/bitcoin
description: Reference Bitcoin Core node with dynamic prune/full-mode startup based on host disk. description: Reference Bitcoin Core node with dynamic prune/full-mode startup based on host disk.
container_name: bitcoin-core container_name: bitcoin-core
@@ -49,7 +55,7 @@ app:
RPC_TXRELAY_FLAGS="$RPC_TXRELAY_FLAGS -rpcauth=$RPC_TXRELAY_AUTH -rpcwhitelist=txrelay:sendrawtransaction,submitpackage,testmempoolaccept,getmempoolinfo,getrawmempool,getmempoolentry,getnetworkinfo,getblockchaininfo,getblockcount,getblockhash,getblock,getblockheader,getrawtransaction,gettxout,gettxspendingprevout,decoderawtransaction,decodescript,estimatesmartfee,uptime,ping,getconnectioncount,getpeerinfo,getindexinfo,getdeploymentinfo,getchaintips"; RPC_TXRELAY_FLAGS="$RPC_TXRELAY_FLAGS -rpcauth=$RPC_TXRELAY_AUTH -rpcwhitelist=txrelay:sendrawtransaction,submitpackage,testmempoolaccept,getmempoolinfo,getrawmempool,getmempoolentry,getnetworkinfo,getblockchaininfo,getblockcount,getblockhash,getblock,getblockheader,getrawtransaction,gettxout,gettxspendingprevout,decoderawtransaction,decodescript,estimatesmartfee,uptime,ping,getconnectioncount,getpeerinfo,getindexinfo,getdeploymentinfo,getchaintips";
fi; fi;
if [ "${DISK_GB_VALUE:-0}" -lt 1000 ]; then if [ "${DISK_GB_VALUE:-0}" -lt 1000 ]; then
exec "$BITCOIND" -datadir=/home/bitcoin/.bitcoin -conf="$RPC_CONF" -allowignoredconf=1 -printtoconsole=0 -server=1 -prune=550 -rpcallowip=0.0.0.0/0 -rpcbind=0.0.0.0:8332 -listen=1 -bind=0.0.0.0:8333 -dbcache=1024 -par=0 -maxconnections=125 $RPC_HEADROOM $RPC_TXRELAY_FLAGS; exec "$BITCOIND" -datadir=/home/bitcoin/.bitcoin -conf="$RPC_CONF" -allowignoredconf=1 -printtoconsole=0 -server=1 -prune=50000 -rpcallowip=0.0.0.0/0 -rpcbind=0.0.0.0:8332 -listen=1 -bind=0.0.0.0:8333 -dbcache=1024 -par=0 -maxconnections=125 $RPC_HEADROOM $RPC_TXRELAY_FLAGS;
else else
exec "$BITCOIND" -datadir=/home/bitcoin/.bitcoin -conf="$RPC_CONF" -allowignoredconf=1 -printtoconsole=0 -server=1 -txindex=1 -rpcallowip=0.0.0.0/0 -rpcbind=0.0.0.0:8332 -listen=1 -bind=0.0.0.0:8333 -dbcache=4096 -par=0 -maxconnections=125 $RPC_HEADROOM $RPC_TXRELAY_FLAGS; exec "$BITCOIND" -datadir=/home/bitcoin/.bitcoin -conf="$RPC_CONF" -allowignoredconf=1 -printtoconsole=0 -server=1 -txindex=1 -rpcallowip=0.0.0.0/0 -rpcbind=0.0.0.0:8332 -listen=1 -bind=0.0.0.0:8333 -dbcache=4096 -par=0 -maxconnections=125 $RPC_HEADROOM $RPC_TXRELAY_FLAGS;
fi fi
+7 -1
View File
@@ -2,6 +2,12 @@ app:
id: bitcoin-knots id: bitcoin-knots
name: Bitcoin Knots name: Bitcoin Knots
version: 28.1.0 version: 28.1.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.
upstream:
kind: github
repo: bitcoinknots/bitcoin
description: Full Bitcoin Knots node with dynamic prune/full-mode startup based on host disk. description: Full Bitcoin Knots node with dynamic prune/full-mode startup based on host disk.
container_name: bitcoin-knots container_name: bitcoin-knots
@@ -55,7 +61,7 @@ app:
RPC_TXRELAY_FLAGS="$RPC_TXRELAY_FLAGS -rpcauth=$RPC_TXRELAY_AUTH -rpcwhitelist=txrelay:sendrawtransaction,submitpackage,testmempoolaccept,getmempoolinfo,getrawmempool,getmempoolentry,getnetworkinfo,getblockchaininfo,getblockcount,getblockhash,getblock,getblockheader,getrawtransaction,gettxout,gettxspendingprevout,decoderawtransaction,decodescript,estimatesmartfee,uptime,ping,getconnectioncount,getpeerinfo,getindexinfo,getdeploymentinfo,getchaintips"; RPC_TXRELAY_FLAGS="$RPC_TXRELAY_FLAGS -rpcauth=$RPC_TXRELAY_AUTH -rpcwhitelist=txrelay:sendrawtransaction,submitpackage,testmempoolaccept,getmempoolinfo,getrawmempool,getmempoolentry,getnetworkinfo,getblockchaininfo,getblockcount,getblockhash,getblock,getblockheader,getrawtransaction,gettxout,gettxspendingprevout,decoderawtransaction,decodescript,estimatesmartfee,uptime,ping,getconnectioncount,getpeerinfo,getindexinfo,getdeploymentinfo,getchaintips";
fi; fi;
if [ "${DISK_GB_VALUE:-0}" -lt 1000 ]; then if [ "${DISK_GB_VALUE:-0}" -lt 1000 ]; then
exec "$BITCOIND" -datadir=/home/bitcoin/.bitcoin -conf="$RPC_CONF" -allowignoredconf=1 -printtoconsole=0 -server=1 -prune=550 -rpcallowip=0.0.0.0/0 -rpcbind=0.0.0.0:8332 -listen=1 -bind=0.0.0.0:8333 -dbcache=2048 -par=0 -maxconnections=125 $RPC_HEADROOM $RPC_TXRELAY_FLAGS; exec "$BITCOIND" -datadir=/home/bitcoin/.bitcoin -conf="$RPC_CONF" -allowignoredconf=1 -printtoconsole=0 -server=1 -prune=50000 -rpcallowip=0.0.0.0/0 -rpcbind=0.0.0.0:8332 -listen=1 -bind=0.0.0.0:8333 -dbcache=2048 -par=0 -maxconnections=125 $RPC_HEADROOM $RPC_TXRELAY_FLAGS;
else else
exec "$BITCOIND" -datadir=/home/bitcoin/.bitcoin -conf="$RPC_CONF" -allowignoredconf=1 -printtoconsole=0 -server=1 -txindex=1 -rpcallowip=0.0.0.0/0 -rpcbind=0.0.0.0:8332 -listen=1 -bind=0.0.0.0:8333 -dbcache=4096 -par=0 -maxconnections=125 $RPC_HEADROOM $RPC_TXRELAY_FLAGS; exec "$BITCOIND" -datadir=/home/bitcoin/.bitcoin -conf="$RPC_CONF" -allowignoredconf=1 -printtoconsole=0 -server=1 -txindex=1 -rpcallowip=0.0.0.0/0 -rpcbind=0.0.0.0:8332 -listen=1 -bind=0.0.0.0:8333 -dbcache=4096 -par=0 -maxconnections=125 $RPC_HEADROOM $RPC_TXRELAY_FLAGS;
fi fi
+3
View File
@@ -2,6 +2,9 @@ app:
id: bitcoin-ui id: bitcoin-ui
name: Bitcoin UI name: Bitcoin UI
version: 1.0.0 version: 1.0.0
# Built by this project — there is no upstream release feed to watch.
upstream:
kind: internal
description: | description: |
Archipelago-native HTTP proxy + static site for interacting with the Archipelago-native HTTP proxy + static site for interacting with the
Bitcoin Core / Bitcoin Knots JSON-RPC. Runs nginx inside a container Bitcoin Core / Bitcoin Knots JSON-RPC. Runs nginx inside a container
+3
View File
@@ -2,6 +2,9 @@ app:
id: botfights id: botfights
name: BotFights name: BotFights
version: 1.2.11 version: 1.2.11
# Built by this project — there is no upstream release feed to watch.
upstream:
kind: internal
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. 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.
category: community category: community
+19 -3
View File
@@ -1,11 +1,17 @@
app: app:
id: btcpay-server id: btcpay-server
name: BTCPay Server name: BTCPay Server
version: 2.4.2 version: 2.4.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.
upstream:
kind: github
repo: btcpayserver/btcpayserver
description: Self-hosted Bitcoin payment processor. Accept Bitcoin payments without intermediaries. description: Self-hosted Bitcoin payment processor. Accept Bitcoin payments without intermediaries.
container: container:
image: docker.io/btcpayserver/btcpayserver:2.4.2 image: docker.io/btcpayserver/btcpayserver:2.4.3
pull_policy: if-not-present pull_policy: if-not-present
network: archy-net network: archy-net
secret_env: secret_env:
@@ -46,7 +52,17 @@ app:
container: 49392 container: 49392
protocol: tcp protocol: tcp
bind: 127.0.0.1 bind: 127.0.0.1
auth: gated # open, not gated: BTCPay has its own account system, and its public
# surfaces (checkout/invoice pages, payment buttons, webhooks) must be
# reachable by anonymous payers and machines — a dashboard login in
# front of a checkout link breaks the product. The gate still fronts
# the port; the operator can force the dashboard login back on from
# Settings → BTCPay Server → Access control.
auth: open
auth_rationale: >-
BTCPay enforces its own login for administration, and its checkout,
invoice and webhook endpoints are designed to be reached by
anonymous payers and payment processors.
volumes: volumes:
- type: bind - type: bind
+6
View File
@@ -2,6 +2,12 @@ app:
id: core-lightning id: core-lightning
name: Core Lightning (CLN) name: Core Lightning (CLN)
version: 23.08.2 version: 23.08.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.
upstream:
kind: github
repo: ElementsProject/lightning
description: Lightning Network implementation in C. Lightweight alternative to LND. description: Lightning Network implementation in C. Lightweight alternative to LND.
container: container:
+157
View File
@@ -0,0 +1,157 @@
app:
id: cuprate
name: Cuprate
# Matches the crate's own Cargo.toml version (binaries/cuprated/Cargo.toml).
# Cuprate has no stable release yet — this is explicitly work-in-progress
# software (see upstream README). The image tag below pins the exact
# commit built, since "0.1.0-preview" alone is not reproducible.
version: 0.1.0-preview
# 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.
upstream:
kind: github
repo: Cuprate/cuprate
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
# no newer tagged release as of this writing. Re-pin to a tagged release
# once upstream cuts one.
image: source.archipelago-foundation.org/lfg2025/cuprate:0.1.0-preview-18-g618ff14
pull_policy: if-not-present
network: archy-net
# The image's own ENTRYPOINT is ["/usr/local/bin/cuprated"]; these are
# appended as its argv, matching the project's own systemd unit
# (cuprated.service) invocation exactly.
custom_args: ["--config-file", "/home/cuprate/Cuprated.toml"]
# The image (FROM scratch) creates uid:gid 1000:1000 for the `cuprate`
# user at build time and runs as it unconditionally (USER 1000:1000,
# no shell to switch users at runtime) — same pattern as
# apps/phoenixd, apps/electrumx, apps/nostr-rs-relay, apps/portainer,
# apps/barkd. The bind-mounted data dir must be owned by that literal
# uid or cuprated dies on a permission error the first time it writes.
data_uid: "1000:1000"
dependencies:
# Monero mainnet is ~250GiB unpruned as of 2026 and growing a few GB a
# month; cuprated's pruning support is not confirmed stable yet (the
# `pruning` crate exists in the workspace but nothing in this config
# surface toggles it), so this sizes for a full unpruned chain plus
# headroom rather than assuming pruning is available.
- storage: 300Gi
resources:
cpu_limit: 0
memory_limit: 4Gi
disk_limit: 300Gi
security:
# FROM scratch, no package manager/shell, ownership fixed at build time
# — unlike bitcoin-knots this needs no runtime chown/setuid dance, so it
# can run fully read-only with an empty capability set.
capabilities: []
readonly_root: true
no_new_privileges: true
network_policy: isolated
ports:
# P2P. Cuprate's own default listen address is already 0.0.0.0
# (p2p.clear_net.listen_on), so no config override is needed — only the
# host-side port differs from Monero's canonical 18080 because that
# number is already taken on this fleet by lnd's REST port.
- host: 18183
container: 18080
protocol: tcp
auth: none
auth_rationale: >-
Monero p2p gossip. Peers are anonymous by design and speak the Monero wire protocol, not HTTP.
# Unrestricted RPC (full node control) is deliberately NOT published.
# cuprated has no RPC authentication, and for a published port to reach
# it the service would have to bind 0.0.0.0 inside the container — at
# which point every other app can reach it directly on 18081, since
# ports[].bind only restricts the HOST side and podman bridges route to
# each other (verified live 2026-08-22: a peer container on archy-net
# got an unauthenticated get_info, from a *different* network). That is
# unlike bitcoin-knots, whose 0.0.0.0 RPC still demands the rpcuser /
# rpcpassword it writes from generated secrets. So unrestricted RPC is
# left at cuprated's own default — container loopback only, reachable by
# nothing — which is also what upstream intends by refusing a non-local
# bind without an explicit i_know_what_im_doing override.
# Restricted RPC: Monero's own purpose-built safe-for-public subset —
# what wallets use when connecting to a "remote node". Disabled by
# cuprated's own default; enabled via files[] below. A dashboard login
# would break wallet clients connecting programmatically, same
# reasoning as electrumx's port. The daemon still uses its canonical
# container port 18089, but Penpot already owns host port 18089, so this
# maps the public host port to the free 18090 instead.
- host: 18090
container: 18089
protocol: tcp
auth: none
auth_rationale: >-
Monero restricted RPC — the subset upstream considers safe for public/remote-node use. Wallets (Feather, monero-wallet-rpc, GUI) connect directly over plain HTTP JSON-RPC and cannot hold a dashboard session cookie.
volumes:
- type: bind
source: /var/lib/archipelago/cuprate
target: /home/cuprate
options: [rw]
# Settings that need to differ from cuprated's own documented defaults
# (verified against `cuprated --generate-config` and `--dry-run` locally,
# 2026-08-21):
# - target_max_memory: cuprated's own default auto-detects total *host*
# RAM via sysinfo, which inside a memory-limited container would let
# it size caches far past what resources.memory_limit above actually
# grants — same class of problem bitcoin-knots' -dbcache sizing
# comment addresses. Set explicitly, comfortably under the 4Gi limit.
# - rpc.restricted.enable: cuprated ships this off by default; flip on
# so the auth:none host port above actually serves something instead
# of refusing every connection. port stays at its documented default
# (canonical 18089), and advertise stays false — this node is not
# opting in to being listed as a public remote node over the p2p
# network, just reachable if someone points a wallet at it directly.
# - rpc.unrestricted.address + the allow-public flag: cuprated's own
# default (127.0.0.1) looks like the obviously-correct choice for a
# port meant to stay loopback-only, but verified live (2026-08-21)
# that a service bound literally to 127.0.0.1 *inside* the container
# is unreachable through the host's published port — connections
# reset regardless of how long the daemon has been up. Binding
# 0.0.0.0 inside and letting ports[].bind: 127.0.0.1 below be the
# actual restriction is the same pattern apps/bitcoin-knots already
# 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.
files:
- path: /var/lib/archipelago/cuprate/Cuprated.toml
content: |
network = "Mainnet"
target_max_memory = 3000000000
[rpc.restricted]
enable = true
overwrite: false
health_check:
type: tcp
# Restricted RPC — the only RPC surface published now.
endpoint: localhost:18090
interval: 30s
timeout: 5s
retries: 3
start_period: 5m
metadata:
icon: /assets/img/app-icons/cuprate.svg
category: money
tier: optional
author: Cuprate
repo: https://github.com/Cuprate/cuprate
+3
View File
@@ -2,6 +2,9 @@ app:
id: did-wallet id: did-wallet
name: Web5 DID Wallet name: Web5 DID Wallet
version: 1.0.0 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. description: Web5 wallet with Decentralized Identifier (DID) support. Manage your digital identity and Web5 assets.
container: container:
+3
View File
@@ -2,6 +2,9 @@ app:
id: electrs-ui id: electrs-ui
name: Electrs UI name: Electrs UI
version: 1.0.0 version: 1.0.0
# Built by this project — there is no upstream release feed to watch.
upstream:
kind: internal
description: | description: |
Archipelago-native HTTP frontend for electrs/electrumx status. Runs Archipelago-native HTTP frontend for electrs/electrumx status. Runs
nginx inside a container, serves static assets, and proxies nginx inside a container, serves static assets, and proxies
+6
View File
@@ -2,6 +2,12 @@ app:
id: electrumx id: electrumx
name: ElectrumX name: ElectrumX
version: 1.18.0 version: 1.18.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.
upstream:
kind: github
repo: spesmilo/electrumx
description: Electrum server indexing Bitcoin chain data for lightweight wallet queries. description: Electrum server indexing Bitcoin chain data for lightweight wallet queries.
container: container:
+6
View File
@@ -2,6 +2,12 @@ app:
id: fedimint-clientd id: fedimint-clientd
name: Fedimint Client name: Fedimint Client
version: 0.8.0 version: 0.8.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.
upstream:
kind: github
repo: fedimint/fedimint-clientd
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. 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.
container: container:
+7 -1
View File
@@ -2,10 +2,16 @@ app:
id: fedimint-gateway id: fedimint-gateway
name: Fedimint Gateway name: Fedimint Gateway
version: 0.10.0 version: 0.10.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.
upstream:
kind: github
repo: fedimint/fedimint
description: Fedimint gateway service with automatic LND-or-LDK backend selection. description: Fedimint gateway service with automatic LND-or-LDK backend selection.
container: container:
image: source.archipelago-foundation.org/lfg2025/gatewayd:v0.10.0 image: source.archipelago-foundation.org/lfg2025/gatewayd:v0.10.1
pull_policy: if-not-present pull_policy: if-not-present
network: archy-net network: archy-net
entrypoint: ["sh", "-lc"] entrypoint: ["sh", "-lc"]
+7 -1
View File
@@ -2,10 +2,16 @@ app:
id: fedimint id: fedimint
name: Fedimint Guardian name: Fedimint Guardian
version: 0.10.0 version: 0.10.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.
upstream:
kind: github
repo: fedimint/fedimint
description: Federated Bitcoin minting service with built-in Guardian UI. Privacy-preserving Bitcoin custody. description: Federated Bitcoin minting service with built-in Guardian UI. Privacy-preserving Bitcoin custody.
container: container:
image: source.archipelago-foundation.org/lfg2025/fedimintd:v0.10.0 image: source.archipelago-foundation.org/lfg2025/fedimintd:v0.10.1
pull_policy: if-not-present pull_policy: if-not-present
network: archy-net network: archy-net
entrypoint: ["sh", "-lc"] entrypoint: ["sh", "-lc"]
+6
View File
@@ -2,6 +2,12 @@ app:
id: filebrowser id: filebrowser
name: File Browser name: File Browser
version: 2.27.0 version: 2.27.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.
upstream:
kind: github
repo: filebrowser/filebrowser
description: Baseline Archipelago file manager service. description: Baseline Archipelago file manager service.
container: container:
+3
View File
@@ -2,6 +2,9 @@ app:
id: fips-ui id: fips-ui
name: FIPS Mesh name: FIPS Mesh
version: 1.0.0 version: 1.0.0
# Built by this project — there is no upstream release feed to watch.
upstream:
kind: internal
description: | description: |
Archipelago-native dashboard for the FIPS mesh transport. Runs nginx Archipelago-native dashboard for the FIPS mesh transport. Runs nginx
inside a container with host networking, serves a static dashboard on inside a container with host networking, serves a static dashboard on
+16 -1
View File
@@ -2,6 +2,12 @@ app:
id: gitea id: gitea
name: Gitea name: Gitea
version: "1.23" version: "1.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.
upstream:
kind: github
repo: go-gitea/gitea
description: Self-hosted Git service with built-in container registry, CI/CD, and package hosting. description: Self-hosted Git service with built-in container registry, CI/CD, and package hosting.
category: development category: development
@@ -27,7 +33,16 @@ app:
container: 3000 container: 3000
protocol: tcp protocol: tcp
bind: 127.0.0.1 bind: 127.0.0.1
auth: gated # open, not gated: Gitea carries a complete login of its own, and git
# clients speak HTTP basic-auth — a cookie challenge in front of
# git-over-HTTP breaks every clone/push. The gate still fronts the
# port (iframe header fixes, retry page, Tor); the operator can force
# the dashboard login back on from Settings → Gitea → Access control.
auth: open
auth_rationale: >-
Gitea enforces its own account login on every page and API route;
git clients authenticate with basic-auth/tokens and cannot complete
a browser login challenge.
- host: 2222 - host: 2222
container: 22 container: 22
protocol: tcp protocol: tcp
+7 -1
View File
@@ -2,10 +2,16 @@ app:
id: grafana id: grafana
name: Grafana name: Grafana
version: 10.2.0 version: 10.2.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.
upstream:
kind: github
repo: grafana/grafana
description: Analytics and monitoring platform. Visualize metrics and create dashboards. description: Analytics and monitoring platform. Visualize metrics and create dashboards.
container: container:
image: grafana/grafana:10.2.0 image: source.archipelago-foundation.org/lfg2025/grafana:10.2.0
image_signature: cosign://... image_signature: cosign://...
pull_policy: if-not-present pull_policy: if-not-present
data_uid: "472:472" data_uid: "472:472"
+8 -2
View File
@@ -1,11 +1,17 @@
app: app:
id: homeassistant id: homeassistant
name: Home Assistant 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.
upstream:
kind: github
repo: home-assistant/core
description: Open source home automation platform. Control and monitor your smart home devices. description: Open source home automation platform. Control and monitor your smart home devices.
container: container:
image: source.archipelago-foundation.org/lfg2025/home-assistant:2026.7.3 image: source.archipelago-foundation.org/lfg2025/home-assistant:2026.8.3
pull_policy: if-not-present pull_policy: if-not-present
network: pasta network: pasta
+6
View File
@@ -2,6 +2,12 @@ app:
id: immich-postgres id: immich-postgres
name: Immich Postgres name: Immich Postgres
version: "14-vectorchord0.4.3-pgvectors0.2.0" version: "14-vectorchord0.4.3-pgvectors0.2.0"
# Upstream is the Immich-built Postgres image, published only on ghcr.io
# (no GitHub release tags, no Docker Hub repo) — the ghcr fetcher in
# scripts/check-upstream-releases.py is the only one that can see it.
upstream:
kind: ghcr
repo: immich-app/postgres
description: Postgres (pgvecto.rs / vectorchord) backend for Immich. description: Postgres (pgvecto.rs / vectorchord) backend for Immich.
# Container named immich_postgres (underscore) to match the runtime's existing # Container named immich_postgres (underscore) to match the runtime's existing
+6
View File
@@ -2,6 +2,12 @@ app:
id: immich-redis id: immich-redis
name: Immich Redis name: Immich Redis
version: "7-alpine" version: "7-alpine"
# 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.
upstream:
kind: dockerhub
repo: valkey/valkey
description: Valkey (Redis-compatible) cache for Immich. description: Valkey (Redis-compatible) cache for Immich.
# Container named immich_redis (underscore) to match runtime per-app references # Container named immich_redis (underscore) to match runtime per-app references
+6
View File
@@ -2,6 +2,12 @@ app:
id: immich id: immich
name: Immich name: Immich
version: "2.7.4" version: "2.7.4"
# 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.
upstream:
kind: github
repo: immich-app/immich
description: Self-hosted photo and video backup with mobile apps and search. description: Self-hosted photo and video backup with mobile apps and search.
# app_id "immich" = the user-facing launcher (matches the catalog entry's title # app_id "immich" = the user-facing launcher (matches the catalog entry's title
+3
View File
@@ -2,6 +2,9 @@ app:
id: indeedhub-api id: indeedhub-api
name: IndeedHub API name: IndeedHub API
version: "1.0.0" version: "1.0.0"
# Built by this project — there is no upstream release feed to watch.
upstream:
kind: internal
description: IndeedHub backend API (Nostr auth, media, payments). description: IndeedHub backend API (Nostr auth, media, payments).
category: community category: community
+3
View File
@@ -2,6 +2,9 @@ app:
id: indeedhub-ffmpeg id: indeedhub-ffmpeg
name: IndeedHub FFmpeg Worker name: IndeedHub FFmpeg Worker
version: "1.0.0" version: "1.0.0"
# Built by this project — there is no upstream release feed to watch.
upstream:
kind: internal
description: IndeedHub background media transcoding worker. description: IndeedHub background media transcoding worker.
category: community category: community
+6
View File
@@ -2,6 +2,12 @@ app:
id: indeedhub-minio id: indeedhub-minio
name: IndeedHub MinIO name: IndeedHub MinIO
version: "RELEASE.2024-11-07T00-52-20Z" version: "RELEASE.2024-11-07T00-52-20Z"
# MinIO's release tags are date-opaque (RELEASE.YYYY-MM-DD…), so the
# checker reports them as UNCOMPARABLE rather than ordering them — the
# latest tag is still shown for hand comparison, which is the point.
upstream:
kind: github
repo: minio/minio
description: MinIO S3-compatible object storage for IndeedHub media. description: MinIO S3-compatible object storage for IndeedHub media.
category: community category: community
+6
View File
@@ -2,6 +2,12 @@ app:
id: indeedhub-postgres id: indeedhub-postgres
name: IndeedHub Postgres name: IndeedHub Postgres
version: "16.13-alpine" version: "16.13-alpine"
# 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.
upstream:
kind: dockerhub
repo: library/postgres
description: Postgres database backend for IndeedHub. description: Postgres database backend for IndeedHub.
category: community category: community
+6
View File
@@ -2,6 +2,12 @@ app:
id: indeedhub-redis id: indeedhub-redis
name: IndeedHub Redis name: IndeedHub Redis
version: "7.4.8-alpine" version: "7.4.8-alpine"
# 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.
upstream:
kind: dockerhub
repo: library/redis
description: Redis queue/cache backend for IndeedHub. description: Redis queue/cache backend for IndeedHub.
category: community category: community
+7 -1
View File
@@ -2,6 +2,12 @@ app:
id: indeedhub-relay id: indeedhub-relay
name: IndeedHub Nostr Relay name: IndeedHub Nostr Relay
version: "0.9.0" version: "0.9.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.
upstream:
kind: github
repo: scsibug/nostr-rs-relay
description: nostr-rs-relay backing IndeedHub's Nostr identity + comments. description: nostr-rs-relay backing IndeedHub's Nostr identity + comments.
category: community category: community
@@ -11,7 +17,7 @@ app:
container_name: indeedhub-relay container_name: indeedhub-relay
container: container:
image: source.archipelago-foundation.org/lfg2025/nostr-rs-relay:0.9.0 image: source.archipelago-foundation.org/lfg2025/nostr-rs-relay:0.10.0
pull_policy: if-not-present pull_policy: if-not-present
network: indeedhub-net network: indeedhub-net
network_aliases: [relay] network_aliases: [relay]
+3
View File
@@ -2,6 +2,9 @@ app:
id: indeedhub id: indeedhub
name: IndeeHub name: IndeeHub
version: "1.0.0" version: "1.0.0"
# Built by this project — there is no upstream release feed to watch.
upstream:
kind: internal
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. 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.
category: community category: community
+7 -1
View File
@@ -2,10 +2,16 @@ app:
id: jellyfin id: jellyfin
name: Jellyfin name: Jellyfin
version: 10.8.13 version: 10.8.13
# 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.
upstream:
kind: github
repo: jellyfin/jellyfin
description: Free media server. Stream movies, music, and photos. description: Free media server. Stream movies, music, and photos.
container: container:
image: source.archipelago-foundation.org/lfg2025/jellyfin:10.8.13 image: source.archipelago-foundation.org/lfg2025/jellyfin:10.11.11
pull_policy: if-not-present pull_policy: if-not-present
network: pasta network: pasta
+6
View File
@@ -2,6 +2,12 @@ app:
id: lightning-stack id: lightning-stack
name: Lightning Stack name: Lightning Stack
version: 0.12.0 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. description: Complete Lightning Network implementation. Includes LND, CLN, and management tools.
container: container:
+3
View File
@@ -2,6 +2,9 @@ app:
id: lnd-ui id: lnd-ui
name: LND UI name: LND UI
version: 1.0.0 version: 1.0.0
# Built by this project — there is no upstream release feed to watch.
upstream:
kind: internal
description: | description: |
Archipelago-native HTTP frontend for LND. Runs nginx inside a Archipelago-native HTTP frontend for LND. Runs nginx inside a
container and serves static assets. LND connection info is fetched container and serves static assets. LND connection info is fetched
+6
View File
@@ -2,6 +2,12 @@ app:
id: lnd id: lnd
name: LND name: LND
version: 0.18.4 version: 0.18.4
# 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.
upstream:
kind: github
repo: lightningnetwork/lnd
description: Lightning Network implementation by Lightning Labs. Enables instant, low-cost Bitcoin payments. description: Lightning Network implementation by Lightning Labs. Enables instant, low-cost Bitcoin payments.
container: container:
+7 -1
View File
@@ -2,10 +2,16 @@ app:
id: mempool-api id: mempool-api
name: Mempool API name: Mempool API
version: 3.0.0 version: 3.0.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.
upstream:
kind: github
repo: mempool/mempool
description: Backend API for mempool explorer. description: Backend API for mempool explorer.
container: container:
image: source.archipelago-foundation.org/lfg2025/mempool-backend:v3.0.0 image: source.archipelago-foundation.org/lfg2025/mempool-backend:v3.3.1
pull_policy: if-not-present pull_policy: if-not-present
network: archy-net network: archy-net
# CORE_RPC_HOST must follow the node's actual Bitcoin container — Knots or # CORE_RPC_HOST must follow the node's actual Bitcoin container — Knots or
+7 -1
View File
@@ -2,10 +2,16 @@ app:
id: mempool id: mempool
name: Mempool Explorer name: Mempool Explorer
version: 3.0.0 version: 3.0.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.
upstream:
kind: github
repo: mempool/mempool
description: Bitcoin mempool and blockchain explorer. Real-time transaction and block visualization. description: Bitcoin mempool and blockchain explorer. Real-time transaction and block visualization.
container: container:
image: source.archipelago-foundation.org/lfg2025/mempool-frontend:v3.0.1 image: source.archipelago-foundation.org/lfg2025/mempool-frontend:v3.3.1
image_signature: cosign://... image_signature: cosign://...
pull_policy: if-not-present pull_policy: if-not-present
+3
View File
@@ -2,6 +2,9 @@ app:
id: morphos-server id: morphos-server
name: MorphOS Server name: MorphOS Server
version: 1.0.0 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. description: MorphOS server platform. Decentralized application server.
container: container:
+6
View File
@@ -2,6 +2,12 @@ app:
id: netbird-dashboard id: netbird-dashboard
name: NetBird Dashboard name: NetBird Dashboard
version: "2.38.0" version: "2.38.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.
upstream:
kind: github
repo: netbirdio/dashboard
description: NetBird management dashboard (SPA). Internal stack member served through the netbird proxy. description: NetBird management dashboard (SPA). Internal stack member served through the netbird proxy.
category: networking category: networking
+6
View File
@@ -2,6 +2,12 @@ app:
id: netbird-server id: netbird-server
name: NetBird Server name: NetBird Server
version: "0.71.2" version: "0.71.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.
upstream:
kind: github
repo: netbirdio/netbird
description: NetBird combined management / signal / relay server with an embedded identity provider and STUN. Backend for the self-hosted NetBird mesh VPN. description: NetBird combined management / signal / relay server with an embedded identity provider and STUN. Backend for the self-hosted NetBird mesh VPN.
category: networking category: networking
+7 -1
View File
@@ -2,6 +2,12 @@ app:
id: netbird id: netbird
name: NetBird name: NetBird
version: "2.38.0" version: "2.38.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.
upstream:
kind: dockerhub
repo: library/nginx
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. 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.
category: networking category: networking
@@ -12,7 +18,7 @@ app:
container_name: netbird container_name: netbird
container: container:
image: docker.io/library/nginx:1.27-alpine image: docker.io/library/nginx:1.31.4-alpine
pull_policy: if-not-present pull_policy: if-not-present
network: netbird-net network: netbird-net
# Self-signed TLS cert materialised before create — the dashboard needs a # Self-signed TLS cert materialised before create — the dashboard needs a
+6
View File
@@ -2,6 +2,12 @@ app:
id: nextcloud id: nextcloud
name: Nextcloud name: Nextcloud
version: "29" version: "29"
# 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.
upstream:
kind: github
repo: nextcloud/server
description: Your own private cloud. File sync, calendars, contacts. description: Your own private cloud. File sync, calendars, contacts.
container: container:
+8 -2
View File
@@ -1,11 +1,17 @@
app: app:
id: nostr-rs-relay id: nostr-rs-relay
name: Nostr Relay (Rust) name: Nostr Relay (Rust)
version: 0.8.0 version: 0.10.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.
upstream:
kind: github
repo: scsibug/nostr-rs-relay
description: High-performance Nostr relay written in Rust. Host your own decentralized social media relay and earn networking profits. description: High-performance Nostr relay written in Rust. Host your own decentralized social media relay and earn networking profits.
container: container:
image: scsibug/nostr-rs-relay:0.8.9 image: scsibug/nostr-rs-relay:0.10.0
image_signature: cosign://... image_signature: cosign://...
pull_policy: verify-signature pull_policy: verify-signature
data_uid: "1000:1000" data_uid: "1000:1000"
+81
View File
@@ -0,0 +1,81 @@
app:
id: phoenixd
name: phoenixd
version: 0.9.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.
upstream:
kind: github
repo: ACINQ/phoenixd
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.
category: money
container:
# Image entrypoint already runs with --agree-to-terms-of-service and
# --http-bind-ip 0.0.0.0, as user "phoenix"; no custom args needed.
image: source.archipelago-foundation.org/lfg2025/phoenixd:0.9.0
pull_policy: if-not-present
# The image runs as user phoenix (1000:1000); the datadir bind source
# must be chowned to that identity or phoenixd dies on
# "Failed to open /data/phoenix.conf with Permission denied".
data_uid: "1000:1000"
dependencies:
- storage: 500Mi
resources:
cpu_limit: 1
memory_limit: 512Mi
disk_limit: 1Gi
security:
capabilities: []
readonly_root: true
no_new_privileges: true
network_policy: bridge
ports:
- host: 9740
container: 9740
protocol: tcp
bind: 127.0.0.1
auth: none
auth_rationale: >-
Loopback-only JSON API, not a web page. Every request is
authenticated by the http password phoenixd generates in its own
data directory on first run; the app gate's browser login page
would break the API clients this port exists for.
volumes:
# The wallet seed (seed.dat) and phoenix.conf live here. This directory
# must survive reinstall/migration like any other app data dir —
# losing it means losing funds.
# Target is /data (via PHOENIX_DATADIR below), NOT the image's default
# /phoenix/.phoenix: the orchestrator treats any bind path containing a
# dot as a file mount and skips creating its source directory, so a
# hidden-dir target never gets its host dir and the unit crash-loops.
- type: bind
source: /var/lib/archipelago/phoenixd
target: /data
options: [rw]
environment:
- PHOENIX_DATADIR=/data
health_check:
type: tcp
endpoint: localhost:9740
interval: 30s
timeout: 5s
retries: 5
metadata:
icon: /assets/img/app-icons/phoenixd.svg
repo: https://github.com/ACINQ/phoenixd
tier: optional
features:
- Ultra-light Lightning node — no bitcoin node required
- Automated channel and liquidity management (fees apply)
- Simple HTTP API + websockets for payments
- Backed by the team behind the Phoenix mobile wallet
+6
View File
@@ -2,6 +2,12 @@ app:
id: photoprism id: photoprism
name: PhotoPrism name: PhotoPrism
version: "240915" version: "240915"
# 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.
upstream:
kind: github
repo: photoprism/photoprism
description: AI-powered photo management with facial recognition. description: AI-powered photo management with facial recognition.
container: container:
+6
View File
@@ -2,6 +2,12 @@ app:
id: pine-openwakeword id: pine-openwakeword
name: Pine Wake Word (openWakeWord) name: Pine Wake Word (openWakeWord)
version: "2.1.0" version: "2.1.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.
upstream:
kind: github
repo: rhasspy/wyoming-openwakeword
description: Wyoming-protocol openWakeWord wake-word engine. Internal Pine voice-assistant stack member — lets Assist pipelines run wake-word detection on the node (groundwork for the custom "Yo Archy" wake word; stock models like "ok nabu" ship with the image). description: Wyoming-protocol openWakeWord wake-word engine. Internal Pine voice-assistant stack member — lets Assist pipelines run wake-word detection on the node (groundwork for the custom "Yo Archy" wake word; stock models like "ok nabu" ship with the image).
category: home category: home
+8 -2
View File
@@ -1,7 +1,13 @@
app: app:
id: pine-piper id: pine-piper
name: Pine Piper (TTS) name: Pine Piper (TTS)
version: "2.2.2" version: "2.4.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.
upstream:
kind: github
repo: rhasspy/wyoming-piper
description: Wyoming-protocol Piper text-to-speech engine. Internal Pine voice-assistant stack member — gives Home Assistant Assist a natural voice for spoken responses on the PineVoice satellite. description: Wyoming-protocol Piper text-to-speech engine. Internal Pine voice-assistant stack member — gives Home Assistant Assist a natural voice for spoken responses on the PineVoice satellite.
category: home category: home
@@ -12,7 +18,7 @@ app:
container_name: pine-piper container_name: pine-piper
container: container:
image: docker.io/rhasspy/wyoming-piper:2.2.2 image: docker.io/rhasspy/wyoming-piper:2.4.2
pull_policy: if-not-present pull_policy: if-not-present
network: archy-net network: archy-net
network_aliases: [pine-piper] network_aliases: [pine-piper]
+8
View File
@@ -6,6 +6,14 @@ app:
# pick up the args change; the pre-release form "3.4.1-1" would compare # 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. # LOWER than 3.4.1 under semver and never roll out.
version: "3.4.2" version: "3.4.2"
# 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
# comment above) — BEHIND here means the image tag moved and the tuned
# revision needs re-basing onto it, not just a pin bump.
upstream:
kind: dockerhub
repo: rhasspy/wyoming-whisper
description: Wyoming-protocol faster-whisper speech-to-text engine. Internal Pine voice-assistant stack member — turns speech captured by a PineVoice satellite into text for Home Assistant Assist. description: Wyoming-protocol faster-whisper speech-to-text engine. Internal Pine voice-assistant stack member — turns speech captured by a PineVoice satellite into text for Home Assistant Assist.
category: home category: home
+7 -1
View File
@@ -2,6 +2,12 @@ app:
id: pine id: pine
name: Pine name: Pine
version: "1.3.0" version: "1.3.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.
upstream:
kind: dockerhub
repo: library/nginx
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. 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.
category: home category: home
@@ -13,7 +19,7 @@ app:
container_name: pine container_name: pine
container: container:
image: docker.io/library/nginx:1.27-alpine image: docker.io/library/nginx:1.31.4-alpine
pull_policy: if-not-present pull_policy: if-not-present
network: archy-net network: archy-net
network_aliases: [pine] network_aliases: [pine]
+7 -1
View File
@@ -2,11 +2,17 @@ app:
id: portainer id: portainer
name: Portainer name: Portainer
version: 2.19.4 version: 2.19.4
# 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.
upstream:
kind: github
repo: portainer/portainer
description: Container management web UI for the local Podman socket. description: Container management web UI for the local Podman socket.
category: development category: development
container: container:
image: source.archipelago-foundation.org/lfg2025/portainer:2.39.1 image: source.archipelago-foundation.org/lfg2025/portainer:2.39.6
pull_policy: if-not-present pull_policy: if-not-present
data_uid: "1000:1000" data_uid: "1000:1000"
+3
View File
@@ -2,6 +2,9 @@ app:
id: router id: router
name: Mesh Router name: Mesh Router
version: 1.0.0 version: 1.0.0
# Built by this project — there is no upstream release feed to watch.
upstream:
kind: internal
description: Mesh routing and local network management. Provides device discovery, routing, and network topology visualization. description: Mesh routing and local network management. Provides device discovery, routing, and network topology visualization.
container: container:
+6
View File
@@ -2,6 +2,12 @@ app:
id: searxng id: searxng
name: SearXNG name: SearXNG
version: 1.0.0 version: 1.0.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.
upstream:
kind: github
repo: searxng/searxng
description: Privacy-respecting metasearch engine. Search the web without tracking. description: Privacy-respecting metasearch engine. Search the web without tracking.
container: container:
+8 -2
View File
@@ -1,11 +1,17 @@
app: app:
id: strfry id: strfry
name: Strfry Nostr Relay name: Strfry Nostr Relay
version: 0.9.0 version: 1.1.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.
upstream:
kind: github
repo: hoytech/strfry
description: Lightweight Nostr relay written in C++. Alternative to nostr-rs-relay with lower resource usage. description: Lightweight Nostr relay written in C++. Alternative to nostr-rs-relay with lower resource usage.
container: container:
image: dockurr/strfry:1.0.4 image: dockurr/strfry:1.1.2
image_signature: cosign://... image_signature: cosign://...
pull_policy: verify-signature pull_policy: verify-signature
+6
View File
@@ -2,6 +2,12 @@ app:
id: uptime-kuma id: uptime-kuma
name: Uptime Kuma name: Uptime Kuma
version: 1.23.0 version: 1.23.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.
upstream:
kind: github
repo: louislam/uptime-kuma
description: Self-hosted uptime monitoring. description: Self-hosted uptime monitoring.
container: container:
+8 -2
View File
@@ -1,11 +1,17 @@
app: app:
id: vaultwarden id: vaultwarden
name: 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.
upstream:
kind: github
repo: dani-garcia/vaultwarden
description: Self-hosted password vault with zero-knowledge encryption. description: Self-hosted password vault with zero-knowledge encryption.
container: container:
image: source.archipelago-foundation.org/lfg2025/vaultwarden:1.30.0-alpine image: source.archipelago-foundation.org/lfg2025/vaultwarden:1.37.2-alpine
pull_policy: if-not-present pull_policy: if-not-present
network: pasta network: pasta
+398 -58
View File
@@ -104,7 +104,7 @@ dependencies = [
[[package]] [[package]]
name = "archipelago" name = "archipelago"
version = "1.7.126-alpha" version = "1.8.4-alpha"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"archipelago-container", "archipelago-container",
@@ -120,6 +120,7 @@ dependencies = [
"blake3", "blake3",
"bs58", "bs58",
"bytes", "bytes",
"cashu",
"chacha20poly1305", "chacha20poly1305",
"chrono", "chrono",
"ciborium", "ciborium",
@@ -186,7 +187,7 @@ dependencies = [
"futures", "futures",
"hex", "hex",
"hyper 0.14.32", "hyper 0.14.32",
"indexmap", "indexmap 2.13.0",
"log", "log",
"reqwest 0.11.27", "reqwest 0.11.27",
"serde", "serde",
@@ -450,8 +451,8 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2c8d66485a3a2ea485c1913c4572ce0256067a5377ac8c75c4960e1cda98605f" checksum = "2c8d66485a3a2ea485c1913c4572ce0256067a5377ac8c75c4960e1cda98605f"
dependencies = [ dependencies = [
"bitcoin-internals 0.3.0", "bitcoin-internals",
"bitcoin_hashes 0.14.1", "bitcoin_hashes",
] ]
[[package]] [[package]]
@@ -499,11 +500,11 @@ checksum = "597bb81c80a54b6a4381b23faba8d7774b144c94cbd1d6fe3f1329bd776554ab"
[[package]] [[package]]
name = "bip39" name = "bip39"
version = "2.1.0" version = "2.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33415e24172c1b7d6066f6d999545375ab8e1d95421d6784bdfff9496f292387" checksum = "90dbd31c98227229239363921e60fcf5e558e43ec69094d46fc4996f08d1d5bc"
dependencies = [ dependencies = [
"bitcoin_hashes 0.13.0", "bitcoin_hashes",
"rand 0.8.5", "rand 0.8.5",
"rand_core 0.6.4", "rand_core 0.6.4",
"serde", "serde",
@@ -526,27 +527,26 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce6bc65742dea50536e35ad42492b234c27904a27f0abdcbce605015cb4ea026" checksum = "ce6bc65742dea50536e35ad42492b234c27904a27f0abdcbce605015cb4ea026"
dependencies = [ dependencies = [
"base58ck", "base58ck",
"base64 0.21.7",
"bech32", "bech32",
"bitcoin-internals 0.3.0", "bitcoin-internals",
"bitcoin-io", "bitcoin-io",
"bitcoin-units", "bitcoin-units",
"bitcoin_hashes 0.14.1", "bitcoin_hashes",
"hex-conservative 0.2.2", "hex-conservative",
"hex_lit", "hex_lit",
"secp256k1", "secp256k1",
"serde",
] ]
[[package]]
name = "bitcoin-internals"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9425c3bf7089c983facbae04de54513cce73b41c7f9ff8c845b54e7bc64ebbfb"
[[package]] [[package]]
name = "bitcoin-internals" name = "bitcoin-internals"
version = "0.3.0" version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "30bdbe14aa07b06e6cfeffc529a1f099e5fbe249524f8125358604df99a4bed2" checksum = "30bdbe14aa07b06e6cfeffc529a1f099e5fbe249524f8125358604df99a4bed2"
dependencies = [
"serde",
]
[[package]] [[package]]
name = "bitcoin-io" name = "bitcoin-io"
@@ -560,17 +560,8 @@ version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5285c8bcaa25876d07f37e3d30c303f2609179716e11d688f51e8f1fe70063e2" checksum = "5285c8bcaa25876d07f37e3d30c303f2609179716e11d688f51e8f1fe70063e2"
dependencies = [ dependencies = [
"bitcoin-internals 0.3.0", "bitcoin-internals",
] "serde",
[[package]]
name = "bitcoin_hashes"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1930a4dabfebb8d7d9992db18ebe3ae2876f0a305fab206fd168df931ede293b"
dependencies = [
"bitcoin-internals 0.2.0",
"hex-conservative 0.1.2",
] ]
[[package]] [[package]]
@@ -580,7 +571,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26ec84b80c482df901772e931a9a681e26a1b9ee2302edeff23cb30328745c8b" checksum = "26ec84b80c482df901772e931a9a681e26a1b9ee2302edeff23cb30328745c8b"
dependencies = [ dependencies = [
"bitcoin-io", "bitcoin-io",
"hex-conservative 0.2.2", "hex-conservative",
"serde", "serde",
] ]
@@ -707,6 +698,32 @@ dependencies = [
"serde", "serde",
] ]
[[package]]
name = "cashu"
version = "0.17.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8bd7216af2b980e203d10677076d8c6c5c30610cbdea6549b8a9020cfa0cf47b"
dependencies = [
"bitcoin",
"cbor-diag",
"ciborium",
"lightning",
"lightning-invoice",
"once_cell",
"serde",
"serde_json",
"serde_with",
"strum 0.27.2",
"strum_macros 0.27.2",
"thiserror 2.0.18",
"tracing",
"unicode-normalization",
"url",
"uuid",
"web-time",
"zeroize",
]
[[package]] [[package]]
name = "cbc" name = "cbc"
version = "0.1.2" version = "0.1.2"
@@ -716,6 +733,25 @@ dependencies = [
"cipher", "cipher",
] ]
[[package]]
name = "cbor-diag"
version = "0.1.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc245b6ecd09b23901a4fbad1ad975701fd5061ceaef6afa93a2d70605a64429"
dependencies = [
"bs58",
"chrono",
"data-encoding",
"half",
"nom",
"num-bigint",
"num-rational",
"num-traits",
"separator",
"url",
"uuid",
]
[[package]] [[package]]
name = "cc" name = "cc"
version = "1.2.54" version = "1.2.54"
@@ -1092,8 +1128,18 @@ version = "0.20.11"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee" checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee"
dependencies = [ dependencies = [
"darling_core", "darling_core 0.20.11",
"darling_macro", "darling_macro 0.20.11",
]
[[package]]
name = "darling"
version = "0.23.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "25ae13da2f202d56bd7f91c25fba009e7717a1e4a1cc98a76d844b65ae912e9d"
dependencies = [
"darling_core 0.23.0",
"darling_macro 0.23.0",
] ]
[[package]] [[package]]
@@ -1110,13 +1156,37 @@ dependencies = [
"syn 2.0.114", "syn 2.0.114",
] ]
[[package]]
name = "darling_core"
version = "0.23.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9865a50f7c335f53564bb694ef660825eb8610e0a53d3e11bf1b0d3df31e03b0"
dependencies = [
"ident_case",
"proc-macro2",
"quote",
"strsim",
"syn 2.0.114",
]
[[package]] [[package]]
name = "darling_macro" name = "darling_macro"
version = "0.20.11" version = "0.20.11"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead"
dependencies = [ dependencies = [
"darling_core", "darling_core 0.20.11",
"quote",
"syn 2.0.114",
]
[[package]]
name = "darling_macro"
version = "0.23.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3984ec7bd6cfa798e62b4a642426a5be0e68f9401cfc2a01e3fa9ea2fcdb8d"
dependencies = [
"darling_core 0.23.0",
"quote", "quote",
"syn 2.0.114", "syn 2.0.114",
] ]
@@ -1147,6 +1217,37 @@ dependencies = [
"syn 2.0.114", "syn 2.0.114",
] ]
[[package]]
name = "defmt"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2953bfe4f93bbd20cc71198842756f77d161884c99ebbabc41d80231ded88d1"
dependencies = [
"bitflags 1.3.2",
"defmt-macros",
]
[[package]]
name = "defmt-macros"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bad9c72e7ca2137e0dc3813245a0d282fd6daad32fd800af018306a9169b5fe8"
dependencies = [
"defmt-parser",
"proc-macro2",
"quote",
"syn 2.0.114",
]
[[package]]
name = "defmt-parser"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e"
dependencies = [
"thiserror 2.0.18",
]
[[package]] [[package]]
name = "der" name = "der"
version = "0.7.10" version = "0.7.10"
@@ -1187,6 +1288,9 @@ name = "deranged"
version = "0.5.8" version = "0.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
dependencies = [
"serde_core",
]
[[package]] [[package]]
name = "derive_arbitrary" name = "derive_arbitrary"
@@ -1214,7 +1318,7 @@ version = "0.20.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2d5bcf7b024d6835cfb3d473887cd966994907effbe9227e8c8219824d06c4e8" checksum = "2d5bcf7b024d6835cfb3d473887cd966994907effbe9227e8c8219824d06c4e8"
dependencies = [ dependencies = [
"darling", "darling 0.20.11",
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.114", "syn 2.0.114",
@@ -1314,6 +1418,18 @@ dependencies = [
"winapi", "winapi",
] ]
[[package]]
name = "dnssec-prover"
version = "0.6.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "869bf72abc8c654b350aa8d881c5d9957b85e1e1ed6569c10cd68e9f505d5435"
[[package]]
name = "dyn-clone"
version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"
[[package]] [[package]]
name = "ed25519" name = "ed25519"
version = "2.2.3" version = "2.2.3"
@@ -1774,7 +1890,7 @@ dependencies = [
"futures-sink", "futures-sink",
"futures-util", "futures-util",
"http 0.2.12", "http 0.2.12",
"indexmap", "indexmap 2.13.0",
"slab", "slab",
"tokio", "tokio",
"tokio-util", "tokio-util",
@@ -1793,7 +1909,7 @@ dependencies = [
"futures-core", "futures-core",
"futures-sink", "futures-sink",
"http 1.4.0", "http 1.4.0",
"indexmap", "indexmap 2.13.0",
"slab", "slab",
"tokio", "tokio",
"tokio-util", "tokio-util",
@@ -1829,6 +1945,12 @@ dependencies = [
"ahash", "ahash",
] ]
[[package]]
name = "hashbrown"
version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "43a3c133739dddd0d2990f9a4bdf8eb4b21ef50e4851ca85ab661199821d510e"
[[package]] [[package]]
name = "hashbrown" name = "hashbrown"
version = "0.15.5" version = "0.15.5"
@@ -1887,12 +2009,6 @@ version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
[[package]]
name = "hex-conservative"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "212ab92002354b4819390025006c897e8140934349e8635c9b077f47b4dcbd20"
[[package]] [[package]]
name = "hex-conservative" name = "hex-conservative"
version = "0.2.2" version = "0.2.2"
@@ -2391,6 +2507,17 @@ dependencies = [
"num-traits", "num-traits",
] ]
[[package]]
name = "indexmap"
version = "1.9.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99"
dependencies = [
"autocfg",
"hashbrown 0.12.3",
"serde",
]
[[package]] [[package]]
name = "indexmap" name = "indexmap"
version = "2.13.0" version = "2.13.0"
@@ -2507,7 +2634,7 @@ dependencies = [
"rustls-pki-types", "rustls-pki-types",
"serde", "serde",
"smallvec", "smallvec",
"strum", "strum 0.28.0",
"time", "time",
"tokio", "tokio",
"tokio-stream", "tokio-stream",
@@ -2595,7 +2722,7 @@ dependencies = [
"rand 0.10.1", "rand 0.10.1",
"rustls 0.23.36", "rustls 0.23.36",
"simple-dns", "simple-dns",
"strum", "strum 0.28.0",
"tokio", "tokio",
"tracing", "tracing",
"url", "url",
@@ -2675,7 +2802,7 @@ dependencies = [
"rustls-pki-types", "rustls-pki-types",
"serde", "serde",
"serde_bytes", "serde_bytes",
"strum", "strum 0.28.0",
"tokio", "tokio",
"tokio-rustls 0.26.4", "tokio-rustls 0.26.4",
"tokio-util", "tokio-util",
@@ -2765,6 +2892,59 @@ version = "1.0.17"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2" checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2"
[[package]]
name = "jiff"
version = "0.2.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "668b7183bd07af9a4885f5c35b0cc5c83c4607a913c16b7e17291832910d2dcc"
dependencies = [
"defmt",
"jiff-core",
"jiff-static",
"jiff-tzdb-platform",
"log",
"portable-atomic",
"portable-atomic-util",
"serde_core",
"windows-link",
]
[[package]]
name = "jiff-core"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7feca88439efe53da3754500c1851dedf3cb36c524dd5cf8225cc0794de95d09"
dependencies = [
"defmt",
]
[[package]]
name = "jiff-static"
version = "0.2.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a69dcb3a21cfb32ce1cd056169337ca284af0766dd766e7878819b251a49204"
dependencies = [
"jiff-core",
"proc-macro2",
"quote",
"syn 2.0.114",
]
[[package]]
name = "jiff-tzdb"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "142bd39932ad231f10513df9ab62661fead8719872150b7ad02a2df79f4e141e"
[[package]]
name = "jiff-tzdb-platform"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "875a5a69ac2bab1a891711cf5eccbec1ce0341ea805560dcd90b7a2e925132e8"
dependencies = [
"jiff-tzdb",
]
[[package]] [[package]]
name = "jni" name = "jni"
version = "0.21.1" version = "0.21.1"
@@ -2911,6 +3091,55 @@ dependencies = [
"vcpkg", "vcpkg",
] ]
[[package]]
name = "lightning"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2ab16d2a714c0b26d7230bd388ac383a30fce231c8927c62752afc0471a36dc6"
dependencies = [
"bech32",
"bitcoin",
"dnssec-prover",
"hashbrown 0.13.2",
"libm",
"lightning-invoice",
"lightning-macros",
"lightning-types",
"possiblyrandom",
]
[[package]]
name = "lightning-invoice"
version = "0.34.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47d83bd798e04ab9eecc8bbef1fa17d3808859bcdc0406bd16c55d51c8834444"
dependencies = [
"bech32",
"bitcoin",
"lightning-types",
"serde",
]
[[package]]
name = "lightning-macros"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d4c717494cdc2c8bb85bee7113031248f5f6c64f8802b33c1c9e2d98e594aa71"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.114",
]
[[package]]
name = "lightning-types"
version = "0.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c77c676d4a34cceb2ae3756916e446b4d17f9430a24107e099981f0f9aec77e6"
dependencies = [
"bitcoin",
]
[[package]] [[package]]
name = "linux-raw-sys" name = "linux-raw-sys"
version = "0.11.0" version = "0.11.0"
@@ -3415,7 +3644,7 @@ dependencies = [
"base64 0.22.1", "base64 0.22.1",
"bech32", "bech32",
"bip39", "bip39",
"bitcoin_hashes 0.14.1", "bitcoin_hashes",
"cbc", "cbc",
"chacha20 0.9.1", "chacha20 0.9.1",
"chacha20poly1305", "chacha20poly1305",
@@ -3517,6 +3746,17 @@ dependencies = [
"num-traits", "num-traits",
] ]
[[package]]
name = "num-rational"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"
dependencies = [
"num-bigint",
"num-integer",
"num-traits",
]
[[package]] [[package]]
name = "num-traits" name = "num-traits"
version = "0.2.19" version = "0.2.19"
@@ -3896,7 +4136,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "092791278e026273c1b65bbdcfbba3a300f2994c896bd01ab01da613c29c46f1" checksum = "092791278e026273c1b65bbdcfbba3a300f2994c896bd01ab01da613c29c46f1"
dependencies = [ dependencies = [
"base64 0.22.1", "base64 0.22.1",
"indexmap", "indexmap 2.13.0",
"quick-xml", "quick-xml",
"serde", "serde",
"time", "time",
@@ -3934,6 +4174,15 @@ dependencies = [
"serde", "serde",
] ]
[[package]]
name = "portable-atomic-util"
version = "0.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a106d1259c23fac8e543272398ae0e3c0b8d33c88ed73d0cc71b0f1d902618"
dependencies = [
"portable-atomic",
]
[[package]] [[package]]
name = "portmapper" name = "portmapper"
version = "0.19.0" version = "0.19.0"
@@ -3973,6 +4222,15 @@ dependencies = [
"winapi", "winapi",
] ]
[[package]]
name = "possiblyrandom"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c564dbf654befd49035528299f1208a40508f6e07efb11c163444e304e4484f"
dependencies = [
"getrandom 0.2.17",
]
[[package]] [[package]]
name = "postcard" name = "postcard"
version = "1.1.3" version = "1.1.3"
@@ -4643,6 +4901,30 @@ dependencies = [
"windows-sys 0.61.2", "windows-sys 0.61.2",
] ]
[[package]]
name = "schemars"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4cd191f9397d57d581cddd31014772520aa448f65ef991055d7f61582c65165f"
dependencies = [
"dyn-clone",
"ref-cast",
"serde",
"serde_json",
]
[[package]]
name = "schemars"
version = "1.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "687274d293b6cdc6e73e0fee520bf2049650090d7164f87672d212a3c530cf4a"
dependencies = [
"dyn-clone",
"ref-cast",
"serde",
"serde_json",
]
[[package]] [[package]]
name = "scoped-tls" name = "scoped-tls"
version = "1.0.1" version = "1.0.1"
@@ -4692,7 +4974,7 @@ version = "0.29.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9465315bc9d4566e1724f0fffcbcc446268cb522e60f9a27bcded6b19c108113" checksum = "9465315bc9d4566e1724f0fffcbcc446268cb522e60f9a27bcded6b19c108113"
dependencies = [ dependencies = [
"bitcoin_hashes 0.14.1", "bitcoin_hashes",
"rand 0.8.5", "rand 0.8.5",
"secp256k1-sys", "secp256k1-sys",
"serde", "serde",
@@ -4758,6 +5040,12 @@ version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd0b0ec5f1c1ca621c432a25813d8d60c88abe6d3e08a3eb9cf37d97a0fe3d73" checksum = "cd0b0ec5f1c1ca621c432a25813d8d60c88abe6d3e08a3eb9cf37d97a0fe3d73"
[[package]]
name = "separator"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f97841a747eef040fcd2e7b3b9a220a7205926e60488e673d9e4926d27772ce5"
[[package]] [[package]]
name = "serde" name = "serde"
version = "1.0.228" version = "1.0.228"
@@ -4842,13 +5130,46 @@ dependencies = [
"serde", "serde",
] ]
[[package]]
name = "serde_with"
version = "3.22.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee78f1fbe43ac4a0e47aadb3dbd357b69eb0d3793e948624cd03dd2750ab1c0a"
dependencies = [
"base64 0.22.1",
"bs58",
"chrono",
"hex",
"indexmap 1.9.3",
"indexmap 2.13.0",
"jiff",
"schemars 0.9.0",
"schemars 1.2.2",
"serde_core",
"serde_json",
"serde_with_macros",
"time",
]
[[package]]
name = "serde_with_macros"
version = "3.22.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8705578779c2b6bd90d84d66eb2e206b708b1a4d7b9f17641b293545bf1c7e46"
dependencies = [
"darling 0.23.0",
"proc-macro2",
"quote",
"syn 2.0.114",
]
[[package]] [[package]]
name = "serde_yaml" name = "serde_yaml"
version = "0.9.34+deprecated" version = "0.9.34+deprecated"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47" checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47"
dependencies = [ dependencies = [
"indexmap", "indexmap 2.13.0",
"itoa", "itoa",
"ryu", "ryu",
"serde", "serde",
@@ -5137,13 +5458,31 @@ version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "strum"
version = "0.27.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af23d6f6c1a224baef9d3f61e287d2761385a5b88fdab4eb4c6f11aeb54c4bcf"
[[package]] [[package]]
name = "strum" name = "strum"
version = "0.28.0" version = "0.28.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd" checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd"
dependencies = [ dependencies = [
"strum_macros", "strum_macros 0.28.0",
]
[[package]]
name = "strum_macros"
version = "0.27.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7695ce3845ea4b33927c055a39dc438a45b059f7c1b3d91d38d10355fb8cbca7"
dependencies = [
"heck",
"proc-macro2",
"quote",
"syn 2.0.114",
] ]
[[package]] [[package]]
@@ -5606,7 +5945,7 @@ version = "0.22.27"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a"
dependencies = [ dependencies = [
"indexmap", "indexmap 2.13.0",
"serde", "serde",
"serde_spanned", "serde_spanned",
"toml_datetime 0.6.11", "toml_datetime 0.6.11",
@@ -5620,7 +5959,7 @@ version = "0.25.12+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2153edc6955a6c354fad8f5efd38b6a8769bdccf9fe50f8e1329f81b0baa5d7" checksum = "d2153edc6955a6c354fad8f5efd38b6a8769bdccf9fe50f8e1329f81b0baa5d7"
dependencies = [ dependencies = [
"indexmap", "indexmap 2.13.0",
"toml_datetime 1.1.1+spec-1.1.0", "toml_datetime 1.1.1+spec-1.1.0",
"toml_parser", "toml_parser",
"winnow 1.0.3", "winnow 1.0.3",
@@ -5823,9 +6162,9 @@ checksum = "9312f7c4f6ff9069b165498234ce8be658059c6728633667c526e27dc2cf1df5"
[[package]] [[package]]
name = "unicode-normalization" name = "unicode-normalization"
version = "0.1.22" version = "0.1.25"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c5713f0fc4b5db668a2ac63cdb7bb4469d8c9fed047b1d0292cc7b0ce2ba921" checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8"
dependencies = [ dependencies = [
"tinyvec", "tinyvec",
] ]
@@ -5903,6 +6242,7 @@ checksum = "e2e054861b4bd027cd373e18e8d8d8e6548085000e41290d95ce0c373a654b4a"
dependencies = [ dependencies = [
"getrandom 0.3.4", "getrandom 0.3.4",
"js-sys", "js-sys",
"serde_core",
"wasm-bindgen", "wasm-bindgen",
] ]
@@ -6080,7 +6420,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"indexmap", "indexmap 2.13.0",
"wasm-encoder", "wasm-encoder",
"wasmparser", "wasmparser",
] ]
@@ -6119,7 +6459,7 @@ checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe"
dependencies = [ dependencies = [
"bitflags 2.13.0", "bitflags 2.13.0",
"hashbrown 0.15.5", "hashbrown 0.15.5",
"indexmap", "indexmap 2.13.0",
"semver", "semver",
] ]
@@ -6678,7 +7018,7 @@ checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"heck", "heck",
"indexmap", "indexmap 2.13.0",
"prettyplease", "prettyplease",
"syn 2.0.114", "syn 2.0.114",
"wasm-metadata", "wasm-metadata",
@@ -6709,7 +7049,7 @@ checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"bitflags 2.13.0", "bitflags 2.13.0",
"indexmap", "indexmap 2.13.0",
"log", "log",
"serde", "serde",
"serde_derive", "serde_derive",
@@ -6728,7 +7068,7 @@ checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"id-arena", "id-arena",
"indexmap", "indexmap 2.13.0",
"log", "log",
"semver", "semver",
"serde", "serde",
@@ -6959,7 +7299,7 @@ dependencies = [
"crossbeam-utils", "crossbeam-utils",
"displaydoc", "displaydoc",
"flate2", "flate2",
"indexmap", "indexmap 2.13.0",
"memchr", "memchr",
"thiserror 2.0.18", "thiserror 2.0.18",
"zopfli", "zopfli",
+3 -2
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "archipelago" name = "archipelago"
version = "1.7.127-alpha" version = "1.8.4-alpha"
edition = "2021" edition = "2021"
license.workspace = true license.workspace = true
description = "Archipelago Bitcoin Node OS - Native backend" description = "Archipelago Bitcoin Node OS - Native backend"
@@ -72,7 +72,7 @@ bs58 = "0.5"
chrono = "0.4" chrono = "0.4"
# BIP-39 mnemonic seed generation + BIP-32 HD key derivation # BIP-39 mnemonic seed generation + BIP-32 HD key derivation
bip39 = { version = "=2.1.0", features = ["rand"] } bip39 = { version = "2.1", features = ["rand"] }
bitcoin = { version = "=0.32.5", features = ["rand-std"] } bitcoin = { version = "=0.32.5", features = ["rand-std"] }
# Configuration # Configuration
@@ -143,6 +143,7 @@ async-trait = "0.1"
iroh = { version = "1", optional = true } iroh = { version = "1", optional = true }
iroh-blobs = { version = "0.103", optional = true } iroh-blobs = { version = "0.103", optional = true }
lofty = "0.24.0" lofty = "0.24.0"
cashu = { version = "0.17.5", default-features = false, features = ["wallet"] }
[dev-dependencies] [dev-dependencies]
tokio-test = "0.4" tokio-test = "0.4"
+429
View File
@@ -0,0 +1,429 @@
//! CDP input bridge — forwards companion remote input into the local kiosk
//! Chromium as *trusted*, browser-level input via the DevTools protocol.
//!
//! Why this exists: the web relay path (`remote-relay.ts`) synthesizes DOM
//! events in the top document, and synthetic events can never cross into a
//! cross-origin iframe — so on the kiosk, companion taps/keys/scrolls died at
//! the border of every containerized app's frame. CDP `Input.dispatch*`
//! events enter the browser's real input pipeline: they hit-test through any
//! frame, move focus, and insert text exactly like a physical device, which
//! is the only correct way to drive app iframes (tracked in the unified task
//! tracker; supersedes the earlier "no CDP" note in
//! `docs/tv-input-iframe-apps.md`, which was about gamepad *keys* only).
//!
//! The kiosk launcher opens Chromium with `--remote-debugging-port=9222`
//! bound to loopback. This keeper task discovers the page target, holds one
//! WebSocket to it, and reconnects whenever the kiosk restarts (the launcher
//! supervises Chromium in a loop, so the debugger URL changes under us).
//! When the bridge is not connected (non-kiosk installs, kiosk booting),
//! `is_active()` is false and callers fall back to the web relay unchanged.
//!
//! Security: the CDP port is loopback-only and Chromium's default origin
//! check stands (we deliberately do NOT pass `--remote-allow-origins`, so
//! browser pages can't open the debug socket; our raw client sends no
//! Origin header and is accepted).
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;
use futures_util::{SinkExt, StreamExt};
use serde_json::{json, Value};
use tokio::sync::mpsc;
use tokio_tungstenite::tungstenite::Message;
use tracing::{debug, info, warn};
const CDP_HTTP: &str = "http://127.0.0.1:9222";
/// Marker whose presence means this node drives a local kiosk display.
const KIOSK_UNIT: &str = "/etc/systemd/system/archipelago-kiosk.service";
/// One relay scroll step ≈ this many CSS pixels (matches remote-relay.ts).
const SCROLL_STEP_PX: f64 = 100.0;
/// Cloneable handle the WS handlers use to feed validated relay JSON into
/// the keeper task.
#[derive(Clone)]
pub struct CdpBridge {
tx: mpsc::Sender<String>,
connected: Arc<AtomicBool>,
}
impl CdpBridge {
/// Spawn the session keeper and return the shared handle.
pub fn spawn() -> Self {
let (tx, rx) = mpsc::channel::<String>(256);
let connected = Arc::new(AtomicBool::new(false));
tokio::spawn(run_keeper(rx, connected.clone()));
Self { tx, connected }
}
/// True only while a live CDP session to the kiosk Chromium exists.
pub fn is_active(&self) -> bool {
self.connected.load(Ordering::Relaxed)
}
/// Queue a validated relay input message (the exact JSON that goes to the
/// broadcast channel) for CDP dispatch. Best-effort: if the keeper is
/// behind or gone the message is dropped — input is transient by nature.
pub fn send(&self, relay_json: &str) {
let _ = self.tx.try_send(relay_json.to_string());
}
}
/// Virtual cursor state, server-side. The web relay keeps this in the kiosk
/// page (`cursorX`/`cursorY`); CDP needs its own copy because trusted mouse
/// events carry absolute viewport coordinates.
struct Cursor {
x: f64,
y: f64,
w: f64,
h: f64,
}
async fn run_keeper(mut rx: mpsc::Receiver<String>, connected: Arc<AtomicBool>) {
loop {
// Cheap gate: no kiosk unit on this node → nothing to drive. Keep
// draining queued input so the channel never backs up.
if tokio::fs::metadata(KIOSK_UNIT).await.is_err() {
drain_for(&mut rx, Duration::from_secs(60)).await;
continue;
}
let Some(ws_url) = discover_page_target().await else {
// Kiosk configured but Chromium not up (or CDP flag not rolled
// out yet) — retry gently.
drain_for(&mut rx, Duration::from_secs(15)).await;
continue;
};
match drive_session(&ws_url, &mut rx, &connected).await {
Ok(()) => info!("CDP kiosk input session ended cleanly"),
Err(e) => debug!(error = %e, "CDP kiosk input session dropped — will re-discover"),
}
connected.store(false, Ordering::Relaxed);
tokio::time::sleep(Duration::from_secs(3)).await;
}
}
/// Discard queued input for `d` — used while no kiosk session exists so the
/// bounded channel can't fill with stale events.
async fn drain_for(rx: &mut mpsc::Receiver<String>, d: Duration) {
let _ = tokio::time::timeout(d, async { while rx.recv().await.is_some() {} }).await;
}
/// Find the kiosk page target's WebSocket debugger URL. Prefers the page on
/// localhost (the kiosk app) over e.g. devtools/extension targets.
async fn discover_page_target() -> Option<String> {
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(3))
.build()
.ok()?;
let list: Vec<Value> = client
.get(format!("{CDP_HTTP}/json/list"))
.send()
.await
.ok()?
.json()
.await
.ok()?;
let pages: Vec<&Value> = list
.iter()
.filter(|t| t.get("type").and_then(Value::as_str) == Some("page"))
.collect();
let preferred = pages
.iter()
.find(|t| {
t.get("url")
.and_then(Value::as_str)
.is_some_and(|u| u.contains("localhost") || u.contains("127.0.0.1"))
})
.or_else(|| pages.first());
preferred?
.get("webSocketDebuggerUrl")
.and_then(Value::as_str)
.map(str::to_string)
}
async fn drive_session(
ws_url: &str,
rx: &mut mpsc::Receiver<String>,
connected: &Arc<AtomicBool>,
) -> anyhow::Result<()> {
let (ws, _) = tokio_tungstenite::connect_async(ws_url).await?;
let (mut sink, mut stream) = ws.split();
let mut next_id: u64 = 0;
let mut id = move || {
next_id += 1;
next_id
};
// Viewport size for cursor clamping. Best-effort: fall back to 1080p if
// the metrics call fails — clamping is a nicety, not a correctness need.
sink.send(Message::Text(
json!({"id": id(), "method": "Page.getLayoutMetrics"}).to_string(),
))
.await?;
let (mut vw, mut vh) = (1920.0_f64, 1080.0_f64);
if let Ok(Some(Ok(Message::Text(txt)))) =
tokio::time::timeout(Duration::from_secs(3), stream.next()).await
{
if let Ok(v) = serde_json::from_str::<Value>(&txt) {
if let Some(vp) = v.pointer("/result/cssLayoutViewport") {
vw = vp.get("clientWidth").and_then(Value::as_f64).unwrap_or(vw);
vh = vp.get("clientHeight").and_then(Value::as_f64).unwrap_or(vh);
}
}
}
let mut cursor = Cursor {
x: vw / 2.0,
y: vh / 2.0,
w: vw,
h: vh,
};
connected.store(true, Ordering::Relaxed);
info!(viewport = %format!("{vw}x{vh}"), "CDP kiosk input bridge connected");
loop {
tokio::select! {
cmd = rx.recv() => {
let Some(cmd) = cmd else { return Ok(()) };
for frame in translate(&cmd, &mut cursor, &mut id) {
sink.send(Message::Text(frame.to_string())).await?;
}
}
msg = stream.next() => {
match msg {
// Responses/events — nothing to correlate, but a read
// error or close means Chromium restarted.
Some(Ok(_)) => {}
Some(Err(e)) => return Err(e.into()),
None => anyhow::bail!("CDP socket closed"),
}
}
}
}
}
/// Translate one validated relay input message into CDP command frames.
fn translate(raw: &str, cursor: &mut Cursor, id: &mut impl FnMut() -> u64) -> Vec<Value> {
let Ok(msg) = serde_json::from_str::<Value>(raw) else {
return vec![];
};
match msg.get("t").and_then(Value::as_str) {
Some("m") => {
let dx = msg.get("x").and_then(Value::as_i64).unwrap_or(0) as f64;
let dy = msg.get("y").and_then(Value::as_i64).unwrap_or(0) as f64;
cursor.x = (cursor.x + dx).clamp(0.0, cursor.w - 1.0);
cursor.y = (cursor.y + dy).clamp(0.0, cursor.h - 1.0);
vec![mouse_event(id(), "mouseMoved", cursor, "none", 0, 1)]
}
Some("c") => {
let b = msg
.get("b")
.and_then(Value::as_u64)
.unwrap_or(1)
.clamp(1, 3);
let (button, buttons) = match b {
2 => ("middle", 4),
3 => ("right", 2),
_ => ("left", 1),
};
vec![
// Hover first so the press lands on current hit-test state.
mouse_event(id(), "mouseMoved", cursor, "none", 0, 1),
mouse_event(id(), "mousePressed", cursor, button, buttons, 1),
mouse_event(id(), "mouseReleased", cursor, button, 0, 1),
]
}
Some("s") => {
let dy = msg.get("y").and_then(Value::as_i64).unwrap_or(0) as f64 * SCROLL_STEP_PX;
vec![json!({
"id": id(),
"method": "Input.dispatchMouseEvent",
"params": {
"type": "mouseWheel",
"x": cursor.x, "y": cursor.y,
"deltaX": 0.0, "deltaY": dy,
"pointerType": "mouse",
}
})]
}
Some("k") => {
let Some(k) = msg.get("k").and_then(Value::as_str) else {
return vec![];
};
key_events(k, id)
}
_ => vec![],
}
}
fn mouse_event(
id: u64,
kind: &str,
cursor: &Cursor,
button: &str,
buttons: u32,
clicks: u32,
) -> Value {
json!({
"id": id,
"method": "Input.dispatchMouseEvent",
"params": {
"type": kind,
"x": cursor.x, "y": cursor.y,
"button": button,
"buttons": buttons,
"clickCount": if kind == "mousePressed" || kind == "mouseReleased" { clicks } else { 0 },
"pointerType": "mouse",
}
})
}
/// xdotool named key → (DOM key, DOM code, Windows virtual-key code).
fn named_key(k: &str) -> Option<(&'static str, &'static str, i32)> {
Some(match k {
"Return" => ("Enter", "Enter", 13),
"BackSpace" => ("Backspace", "Backspace", 8),
"Escape" => ("Escape", "Escape", 27),
"Tab" => ("Tab", "Tab", 9),
"Delete" => ("Delete", "Delete", 46),
"Up" => ("ArrowUp", "ArrowUp", 38),
"Down" => ("ArrowDown", "ArrowDown", 40),
"Left" => ("ArrowLeft", "ArrowLeft", 37),
"Right" => ("ArrowRight", "ArrowRight", 39),
"Home" => ("Home", "Home", 36),
"End" => ("End", "End", 35),
"Prior" => ("PageUp", "PageUp", 33),
"Next" => ("PageDown", "PageDown", 34),
"F1" => ("F1", "F1", 112),
"F2" => ("F2", "F2", 113),
"F3" => ("F3", "F3", 114),
"F4" => ("F4", "F4", 115),
"F5" => ("F5", "F5", 116),
"F6" => ("F6", "F6", 117),
"F7" => ("F7", "F7", 118),
"F8" => ("F8", "F8", 119),
"F9" => ("F9", "F9", 120),
"F10" => ("F10", "F10", 121),
"F11" => ("F11", "F11", 122),
"F12" => ("F12", "F12", 123),
_ => return None,
})
}
/// xdotool symbol name → printable char (the relay whitelist speaks xdotool).
fn symbol_char(k: &str) -> Option<char> {
Some(match k {
"space" => ' ',
"exclam" => '!',
"at" => '@',
"numbersign" => '#',
"dollar" => '$',
"percent" => '%',
"asciicircum" => '^',
"ampersand" => '&',
"asterisk" => '*',
"parenleft" => '(',
"parenright" => ')',
"underscore" => '_',
"plus" => '+',
"braceleft" => '{',
"braceright" => '}',
"bar" => '|',
"colon" => ':',
"quotedbl" => '"',
"less" => '<',
"greater" => '>',
"question" => '?',
"asciitilde" => '~',
"minus" => '-',
"equal" => '=',
"bracketleft" => '[',
"bracketright" => ']',
"backslash" => '\\',
"semicolon" => ';',
"apostrophe" => '\'',
"grave" => '`',
"comma" => ',',
"period" => '.',
"slash" => '/',
_ => return None,
})
}
/// Build the CDP frame pair (keyDown, keyUp) for one relay key name,
/// including `modifier+base` combos. A keyDown that carries `text` both
/// fires real keydown/keypress AND inserts the character — exactly how a
/// physical keystroke behaves, so games see the key and fields get the text.
fn key_events(k: &str, id: &mut impl FnMut() -> u64) -> Vec<Value> {
let (modifiers, base) = match k.split_once('+') {
Some((m, b)) => (
match m {
"alt" => 1,
"ctrl" => 2,
"super" => 4,
"shift" => 8,
_ => 0,
},
b,
),
None => (0, k),
};
let (key, code, vk, text): (String, Option<&str>, i32, Option<String>) =
if let Some((key, code, vk)) = named_key(base) {
// Enter carries "\r" like a real keyboard so single-line inputs
// submit and textareas newline.
let text = (key == "Enter").then(|| "\r".to_string());
(key.to_string(), Some(code), vk, text)
} else {
let ch = if base.chars().count() == 1 {
base.chars().next()
} else {
symbol_char(base)
};
let Some(mut ch) = ch else {
return vec![];
};
if modifiers == 8 && ch.is_ascii_alphabetic() {
ch = ch.to_ascii_uppercase();
}
let vk = ch.to_ascii_uppercase() as i32;
// Ctrl/Alt/Super chords are shortcuts, not typing — no text.
let text = (modifiers & !8 == 0).then(|| ch.to_string());
(ch.to_string(), None, vk, text)
};
let mut down = json!({
"id": id(),
"method": "Input.dispatchKeyEvent",
"params": {
"type": "keyDown",
"key": key,
"modifiers": modifiers,
"windowsVirtualKeyCode": vk,
"nativeVirtualKeyCode": vk,
}
});
if let Some(code) = code {
down["params"]["code"] = json!(code);
}
if let Some(t) = &text {
down["params"]["text"] = json!(t);
down["params"]["unmodifiedText"] = json!(t);
}
let mut up = json!({
"id": id(),
"method": "Input.dispatchKeyEvent",
"params": {
"type": "keyUp",
"key": key,
"modifiers": modifiers,
"windowsVirtualKeyCode": vk,
"nativeVirtualKeyCode": vk,
}
});
if let Some(code) = code {
up["params"]["code"] = json!(code);
}
vec![down, up]
}
+18
View File
@@ -1,4 +1,5 @@
mod blob; mod blob;
mod cdp;
mod content; mod content;
mod dwn; mod dwn;
mod model_proxy; mod model_proxy;
@@ -6,6 +7,7 @@ mod node_message;
mod proxy; mod proxy;
mod remote_input; mod remote_input;
mod remote_relay; mod remote_relay;
mod routstr_proxy;
mod websocket; mod websocket;
use crate::api::rpc::RpcHandler; use crate::api::rpc::RpcHandler;
@@ -50,6 +52,10 @@ pub struct ApiHandler {
/// to the phone's default browser. Lets "open in external browser" apps — /// to the phone's default browser. Lets "open in external browser" apps —
/// which the kiosk can't usefully open itself — launch on the controller. /// which the kiosk can't usefully open itself — launch on the controller.
external_open_tx: broadcast::Sender<String>, external_open_tx: broadcast::Sender<String>,
/// Bridge that dispatches companion input into the local kiosk Chromium
/// as trusted CDP events (reaches inside cross-origin app iframes).
/// Inert (never connects) on nodes without a kiosk.
cdp_bridge: cdp::CdpBridge,
/// Content-addressed blob store for attachments shared over mesh/federation. /// Content-addressed blob store for attachments shared over mesh/federation.
blob_store: Arc<BlobStore>, blob_store: Arc<BlobStore>,
/// Our own node pubkey (hex) — used to self-sign debug/test capabilities. /// Our own node pubkey (hex) — used to self-sign debug/test capabilities.
@@ -78,6 +84,7 @@ impl ApiHandler {
); );
let (input_relay_tx, _) = broadcast::channel(64); let (input_relay_tx, _) = broadcast::channel(64);
let (external_open_tx, _) = broadcast::channel(16); let (external_open_tx, _) = broadcast::channel(16);
let cdp_bridge = cdp::CdpBridge::spawn();
// Derive a blob-store capability key from the node's Ed25519 signing // Derive a blob-store capability key from the node's Ed25519 signing
// key. SHA-256 domain-separated so rotating the identity rotates // key. SHA-256 domain-separated so rotating the identity rotates
@@ -108,6 +115,7 @@ impl ApiHandler {
session_store, session_store,
input_relay_tx, input_relay_tx,
external_open_tx, external_open_tx,
cdp_bridge,
blob_store, blob_store,
self_pubkey_hex, self_pubkey_hex,
}) })
@@ -401,6 +409,7 @@ impl ApiHandler {
req, req,
self.input_relay_tx.clone(), self.input_relay_tx.clone(),
self.external_open_tx.subscribe(), self.external_open_tx.subscribe(),
self.cdp_bridge.clone(),
) )
.await; .await;
} }
@@ -415,6 +424,7 @@ impl ApiHandler {
req, req,
self.input_relay_tx.subscribe(), self.input_relay_tx.subscribe(),
self.external_open_tx.clone(), self.external_open_tx.clone(),
self.cdp_bridge.clone(),
) )
.await; .await;
} }
@@ -449,6 +459,14 @@ impl ApiHandler {
self.handle_model_proxy(req_with_bytes, p).await self.handle_model_proxy(req_with_bytes, p).await
} }
// AIUI Routstr proxy — the explicit, user-selected Routstr
// provider (model catalog + Cashu-paid completions), same
// session-gate discipline as the model proxy above. D-05: paid
// requests are refused unless the operator has armed a budget.
(_, p) if p.starts_with("/aiui/api/routstr/") => {
self.handle_routstr_proxy(req_with_bytes, p).await
}
// Health — unauthenticated, returns JSON with service status // Health — unauthenticated, returns JSON with service status
(Method::GET, "/health") => { (Method::GET, "/health") => {
let recovery_complete = crate::crash_recovery::is_recovery_complete(); let recovery_complete = crate::crash_recovery::is_recovery_complete();
@@ -84,14 +84,14 @@ async fn route_model_proxy(
/// call back into `ApiHandler::is_authenticated` — keeping this small and /// call back into `ApiHandler::is_authenticated` — keeping this small and
/// dependency-free is what makes the 401 behaviour unit-testable without /// dependency-free is what makes the 401 behaviour unit-testable without
/// paying for a full `ApiHandler` in every test. /// paying for a full `ApiHandler` in every test.
async fn is_authenticated(session_store: &SessionStore, headers: &HeaderMap) -> bool { pub(super) async fn is_authenticated(session_store: &SessionStore, headers: &HeaderMap) -> bool {
match session::extract_session_cookie(headers) { match session::extract_session_cookie(headers) {
Some(token) => session_store.validate(&token).await, Some(token) => session_store.validate(&token).await,
None => false, None => false,
} }
} }
fn unauthorized() -> Response<Body> { pub(super) fn unauthorized() -> Response<Body> {
let body = serde_json::json!({ "error": "Unauthorized" }); let body = serde_json::json!({ "error": "Unauthorized" });
Response::builder() Response::builder()
.status(StatusCode::UNAUTHORIZED) .status(StatusCode::UNAUTHORIZED)
@@ -119,7 +119,7 @@ fn key_not_configured() -> Response<Body> {
/// backends' egress screen never sees the forwarder path — the standalone /// backends' egress screen never sees the forwarder path — the standalone
/// frontend posts FULL history and images straight here — so the forwarder /// frontend posts FULL history and images straight here — so the forwarder
/// screens for itself. 400, plain-language, never naming what matched. /// screens for itself. 400, plain-language, never naming what matched.
fn blocked_secret_shaped() -> Response<Body> { pub(super) fn blocked_secret_shaped() -> Response<Body> {
let body = serde_json::json!({ let body = serde_json::json!({
"error": "Blocked: this request contained secret-shaped content (e.g. a seed phrase, key, or token). It was not sent anywhere." "error": "Blocked: this request contained secret-shaped content (e.g. a seed phrase, key, or token). It was not sent anywhere."
}); });
@@ -134,12 +134,12 @@ fn blocked_secret_shaped() -> Response<Body> {
/// the assistant's secret-shape rules (G-B1) with this node's own secrets /// the assistant's secret-shape rules (G-B1) with this node's own secrets
/// as the deny corpus. Returns Some(kind) — kind only, never the value — /// as the deny corpus. Returns Some(kind) — kind only, never the value —
/// when the content must not leave. /// when the content must not leave.
async fn forward_screen(text: &str, data_dir: &Path) -> Option<&'static str> { pub(super) async fn forward_screen(text: &str, data_dir: &Path) -> Option<&'static str> {
let secrets = crate::assistant::egress::load_known_secrets(&data_dir.join("secrets")).await; let secrets = crate::assistant::egress::load_known_secrets(&data_dir.join("secrets")).await;
crate::assistant::egress::scan_secret_shapes(text, &secrets) crate::assistant::egress::scan_secret_shapes(text, &secrets)
} }
fn bad_gateway(msg: &str) -> Response<Body> { pub(super) fn bad_gateway(msg: &str) -> Response<Body> {
let body = serde_json::json!({ "error": msg }); let body = serde_json::json!({ "error": msg });
Response::builder() Response::builder()
.status(StatusCode::BAD_GATEWAY) .status(StatusCode::BAD_GATEWAY)
@@ -331,7 +331,7 @@ async fn forward(
/// same shape as `proxy.rs`'s peer-content Range streamer — so a /// same shape as `proxy.rs`'s peer-content Range streamer — so a
/// token-by-token reply doesn't wait for the full response before the first /// token-by-token reply doesn't wait for the full response before the first
/// byte reaches the browser. /// byte reaches the browser.
fn stream_response(resp: reqwest::Response) -> Result<Response<Body>> { pub(super) fn stream_response(resp: reqwest::Response) -> Result<Response<Body>> {
let status = resp.status().as_u16(); let status = resp.status().as_u16();
let headers = resp.headers().clone(); let headers = resp.headers().clone();
let mut builder = Response::builder().status(status); let mut builder = Response::builder().status(status);
@@ -212,6 +212,7 @@ impl ApiHandler {
req: Request<hyper::Body>, req: Request<hyper::Body>,
relay_tx: broadcast::Sender<String>, relay_tx: broadcast::Sender<String>,
mut external_open_rx: broadcast::Receiver<String>, mut external_open_rx: broadcast::Receiver<String>,
cdp_bridge: super::cdp::CdpBridge,
) -> Result<Response<hyper::Body>> { ) -> Result<Response<hyper::Body>> {
// Extract optional player ID from query string: /ws/remote-input?p=1 // Extract optional player ID from query string: /ws/remote-input?p=1
let player_id: Option<u8> = req let player_id: Option<u8> = req
@@ -317,9 +318,20 @@ impl ApiHandler {
} else { } else {
text.clone() text.clone()
}; };
let _ = relay_tx.send(relay_text); let validation = handle_input(&text).await;
let _ = relay_tx.send(relay_text.clone());
// Trusted-input path: while the kiosk CDP
// bridge is live, also dispatch validated
// input into the kiosk Chromium so it
// lands inside cross-origin app iframes
// (the web relay above can't cross that
// boundary; the kiosk subscriber mutes its
// own DOM synthesis — remote_relay.rs).
if matches!(validation, Ok(None)) && cdp_bridge.is_active() {
cdp_bridge.send(&relay_text);
}
match handle_input(&text).await { match validation {
Ok(Some(reply)) => { Ok(Some(reply)) => {
let _ = tx.send(Message::Text(reply)).await; let _ = tx.send(Message::Text(reply)).await;
} }
@@ -21,7 +21,16 @@ impl ApiHandler {
req: Request<hyper::Body>, req: Request<hyper::Body>,
mut relay_rx: broadcast::Receiver<String>, mut relay_rx: broadcast::Receiver<String>,
external_open_tx: broadcast::Sender<String>, external_open_tx: broadcast::Sender<String>,
cdp_bridge: super::cdp::CdpBridge,
) -> Result<Response<hyper::Body>> { ) -> Result<Response<hyper::Body>> {
// The kiosk browser self-identifies with ?kiosk=1 so we can suppress
// its DOM-synthesis path while the CDP bridge delivers trusted input
// (otherwise every key/click/scroll would apply twice). A remote
// browser claiming kiosk=1 only mutes its own input — harmless.
let is_kiosk = req
.uri()
.query()
.is_some_and(|q| q.split('&').any(|s| s == "kiosk=1"));
let (response, ws_fut_opt) = hyper_ws_listener::create_ws(req) let (response, ws_fut_opt) = hyper_ws_listener::create_ws(req)
.map_err(|e| anyhow::anyhow!("WebSocket upgrade failed: {}", e))?; .map_err(|e| anyhow::anyhow!("WebSocket upgrade failed: {}", e))?;
@@ -60,6 +69,19 @@ impl ApiHandler {
msg = relay_rx.recv() => { msg = relay_rx.recv() => {
match msg { match msg {
Ok(text) => { Ok(text) => {
// Kiosk + live CDP bridge: keys/clicks/
// scrolls arrive as trusted browser input
// via CDP; forward only cursor moves (the
// on-screen cursor is drawn by the page)
// so nothing applies twice.
if is_kiosk && cdp_bridge.is_active() {
let tag = serde_json::from_str::<serde_json::Value>(&text)
.ok()
.and_then(|v| v.get("t").and_then(|t| t.as_str().map(str::to_string)));
if !matches!(tag.as_deref(), Some("m") | Some("o") | Some("p")) {
continue;
}
}
if tx.send(Message::Text(text)).await.is_err() { if tx.send(Message::Text(text)).await.is_err() {
break; break;
} }
@@ -0,0 +1,535 @@
//! Session-gated forwarder for `/aiui/api/routstr/*` — the explicit,
//! user-selected Routstr path (as opposed to `assistant/backends/routstr.rs`,
//! which is the D-04 fallback leg the operator never chooses directly).
//!
//! AIUI's model picker lists Routstr as a first-class provider; selecting one
//! of its models routes chat completions through here. Same discipline as
//! `model_proxy.rs`: auth is re-derived from the request's own session cookie
//! (never trusted to nginx), inbound `authorization`/`cookie` headers are
//! never forwarded, and every outbound body is egress-screened (S3) before it
//! leaves the node.
//!
//! Payment is Cashu, D-05-gated end to end: a request is refused unless the
//! operator has set a non-zero Routstr allowance (Settings → System), the
//! quoted price fits the remaining allowance, and `auto_pay_token` (the ONE
//! budget-capped payment primitive, T-13-89) agrees to build the token. The
//! provider's change (`X-Cashu` / `X-Cashu-Refund` response headers, per
//! docs.routstr.com) is redeemed back into the node wallet and only the net
//! is recorded against the allowance.
//!
//! Upstream is the public Routstr aggregator instance routstr.com itself
//! ships against (verified live 2026-08-14: `/v1/models` serves the full
//! catalog with `sats_pricing`; the canonical `api.routstr.com` host 404s).
//! Making the instance operator-configurable — or sourcing it from the Nostr
//! provider announcements once those carry real endpoint/pricing content —
//! is the planned follow-up, not this file's job.
use super::ApiHandler;
use crate::session::SessionStore;
use anyhow::Result;
use hyper::{Body, Method, Request, Response, StatusCode};
use serde_json::{json, Value};
use std::path::Path;
use std::sync::Mutex as StdMutex;
use std::sync::OnceLock;
use std::time::{Duration, Instant};
use super::model_proxy::{
bad_gateway, blocked_secret_shaped, forward_screen, is_authenticated, unauthorized,
};
/// The live public Routstr aggregator (the same instance routstr.com's own
/// frontend queries for `/v1/providers` and `/v1/models`).
const ROUTSTR_INSTANCE: &str = "https://routstr.otrta.me";
/// Generation cap forced onto every forwarded completion — never unbounded
/// (T-13-88), and the completion half of the price quote is arithmetic over
/// exactly this figure.
const MAX_COMPLETION_TOKENS: u64 = 1024;
/// Same round-trip ceiling as `model_proxy.rs`'s Claude/Ollama forwarders.
const FORWARD_TIMEOUT_SECS: u64 = 180;
/// Models-catalog cache TTL — mirrors `backends/routstr.rs`'s provider
/// discovery TTL. The catalog prices every chat request, so it cannot be
/// fetched per-message without doubling latency.
const MODELS_CACHE_TTL: Duration = Duration::from_secs(300);
/// One model's sats-denominated pricing, parsed from the aggregator's
/// `/v1/models` entries (`sats_pricing`). Rates are sats PER TOKEN (fractional
/// floats); `request` is a flat per-request fee in sats. Untrusted input — a
/// missing/garbled field parses as 0.0 and simply prices low, which the
/// remaining-allowance ceiling still caps.
#[derive(Debug, Clone, Default, serde::Deserialize)]
struct SatsPricing {
#[serde(default)]
prompt: f64,
#[serde(default)]
completion: f64,
#[serde(default)]
request: f64,
}
/// Quote a price in whole sats for one completion call: flat request fee +
/// prompt rate × (payload chars / 4, the usual chars-per-token rule of thumb)
/// + completion rate × the forced `MAX_COMPLETION_TOKENS` cap, +20% margin,
/// rounded up, never below 1. Deliberately a pure function so the arithmetic
/// is unit-testable; deliberately conservative because the provider's change
/// comes back as a Cashu refund and is redeemed — overquoting costs nothing
/// but float, underquoting gets the request rejected upstream.
fn estimate_price_sats(pricing: &SatsPricing, prompt_chars: usize, completion_tokens: u64) -> u64 {
let prompt_tokens = (prompt_chars as f64) / 4.0;
let raw = pricing.request
+ pricing.prompt * prompt_tokens
+ pricing.completion * (completion_tokens as f64);
let with_margin = raw * 1.2;
(with_margin.ceil() as u64).max(1)
}
/// Process-lifetime cache of the aggregator's models catalog (same pattern as
/// `backends/routstr.rs`'s `PROVIDER_CACHE`).
static MODELS_CACHE: OnceLock<StdMutex<Option<(Instant, Value)>>> = OnceLock::new();
fn cached_models() -> Option<Value> {
let cache = MODELS_CACHE.get_or_init(|| StdMutex::new(None));
let guard = cache.lock().expect("routstr models cache poisoned");
guard.as_ref().and_then(|(at, models)| {
if at.elapsed() < MODELS_CACHE_TTL {
Some(models.clone())
} else {
None
}
})
}
fn set_cached_models(models: Value) {
let cache = MODELS_CACHE.get_or_init(|| StdMutex::new(None));
*cache.lock().expect("routstr models cache poisoned") = Some((Instant::now(), models));
}
/// Fetch (or serve cached) the aggregator's `/v1/models` catalog.
async fn fetch_models() -> Result<Value> {
if let Some(cached) = cached_models() {
return Ok(cached);
}
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(20))
.build()?;
let url = format!("{ROUTSTR_INSTANCE}/v1/models");
let resp = client.get(&url).send().await?;
if !resp.status().is_success() {
anyhow::bail!("routstr models upstream returned HTTP {}", resp.status());
}
let models: Value = resp.json().await?;
set_cached_models(models.clone());
Ok(models)
}
/// Find one model's `sats_pricing` in the catalog by exact id.
fn pricing_for_model(models: &Value, model_id: &str) -> Option<SatsPricing> {
models
.get("data")?
.as_array()?
.iter()
.find(|m| m.get("id").and_then(|v| v.as_str()) == Some(model_id))
.and_then(|m| m.get("sats_pricing"))
.and_then(|sp| serde_json::from_value(sp.clone()).ok())
}
fn json_response(status: StatusCode, body: Value) -> Response<Body> {
Response::builder()
.status(status)
.header("Content-Type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap_or_default()))
.unwrap_or_else(|_| Response::new(Body::from("{}")))
}
/// Plain-language refusal naming the UI path that fixes it — never a bare
/// status (RULE: every action needs a UI path).
fn budget_refusal(msg: String) -> Response<Body> {
json_response(
StatusCode::SERVICE_UNAVAILABLE,
json!({ "error": { "message": msg } }),
)
}
impl ApiHandler {
/// Entry point wired into the `/aiui/api/routstr/` arm in `mod.rs` —
/// thin, like `handle_model_proxy`, so the routing/budget logic below is
/// testable without a full `ApiHandler`.
pub(super) async fn handle_routstr_proxy(
&self,
req: Request<Body>,
path: &str,
) -> Result<Response<Body>> {
route_routstr_proxy(&self.session_store, &self.config.data_dir, req, path).await
}
}
async fn route_routstr_proxy(
session_store: &SessionStore,
data_dir: &Path,
req: Request<Body>,
path: &str,
) -> Result<Response<Body>> {
if !is_authenticated(session_store, req.headers()).await {
tracing::warn!("401 routstr proxy {} — session invalid or missing", path);
return Ok(unauthorized());
}
match path.strip_prefix("/aiui/api/routstr/") {
Some("models") if req.method() == Method::GET => forward_models().await,
Some("chat/completions") if req.method() == Method::POST => {
forward_chat(req, data_dir).await
}
_ => Ok(unauthorized()),
}
}
/// GET /aiui/api/routstr/models — the full catalog, passed through so AIUI
/// can render ids/names and show sats pricing. Read-only and unpaid.
async fn forward_models() -> Result<Response<Body>> {
match fetch_models().await {
Ok(models) => Ok(json_response(StatusCode::OK, models)),
Err(e) => {
tracing::warn!("routstr proxy: models upstream failed: {}", e);
Ok(bad_gateway("Routstr model catalog is unreachable"))
}
}
}
/// POST /aiui/api/routstr/chat/completions — one paid, non-streaming,
/// OpenAI-shaped completion. Order matters: screen (S3) → budget gate (D-05,
/// offline) → price quote → pay → forward → redeem change → record net.
async fn forward_chat(req: Request<Body>, data_dir: &Path) -> Result<Response<Body>> {
let payload = hyper::body::to_bytes(req.into_body())
.await
.map_err(|e| anyhow::anyhow!("read request payload: {e}"))?;
let payload_str = String::from_utf8_lossy(&payload).to_string();
// S3: the standalone frontend posts full history straight here with no
// assistant loop (and no egress screen) behind it.
if let Some(kind) = forward_screen(&payload_str, data_dir).await {
tracing::error!(
kind,
"routstr proxy: blocked chat forward — secret-shaped content"
);
return Ok(blocked_secret_shaped());
}
let mut body: Value = match serde_json::from_str(&payload_str) {
Ok(v) => v,
Err(_) => {
return Ok(json_response(
StatusCode::BAD_REQUEST,
json!({ "error": { "message": "request body is not valid JSON" } }),
));
}
};
let Some(model_id) = body.get("model").and_then(|v| v.as_str()).map(String::from) else {
return Ok(json_response(
StatusCode::BAD_REQUEST,
json!({ "error": { "message": "request is missing a model id" } }),
));
};
// D-05 gate, checked before any network I/O: a zero allowance means
// Routstr is refused outright, with the UI path that arms it.
let mut budget = crate::assistant::AssistantBudget::load(data_dir).await;
if budget.allowance_sats == 0 {
return Ok(budget_refusal(
"Routstr is disabled on this node — set a sats budget in Settings → System → \
Routstr AI budget to enable it."
.to_string(),
));
}
let remaining = budget.remaining_sats();
if remaining == 0 {
return Ok(budget_refusal(format!(
"This period's Routstr budget is spent ({} of {} sats). Raise the allowance in \
Settings → System → Routstr AI budget to continue.",
budget.spent_sats, budget.allowance_sats
)));
}
// Price the request from the catalog. An unknown model is a caller bug
// (the dropdown only offers catalog models), not a reason to guess a
// price.
let models = match fetch_models().await {
Ok(m) => m,
Err(e) => {
tracing::warn!("routstr proxy: cannot price request, models fetch failed: {e}");
return Ok(bad_gateway(
"Routstr model catalog is unreachable — cannot price this request",
));
}
};
let Some(pricing) = pricing_for_model(&models, &model_id) else {
return Ok(json_response(
StatusCode::BAD_REQUEST,
json!({ "error": { "message": format!("unknown Routstr model: {model_id}") } }),
));
};
// Force the shape this forwarder actually supports: non-streaming, with
// an explicit, capped generation limit (T-13-88).
let max_tokens = body
.get("max_tokens")
.and_then(|v| v.as_u64())
.unwrap_or(MAX_COMPLETION_TOKENS)
.min(MAX_COMPLETION_TOKENS);
body["stream"] = json!(false);
body["max_tokens"] = json!(max_tokens);
let price_sats = estimate_price_sats(&pricing, payload_str.len(), max_tokens);
if price_sats > remaining {
return Ok(budget_refusal(format!(
"This request quotes ~{price_sats} sats but only {remaining} sats remain in this \
period's Routstr budget (Settings → System → Routstr AI budget)."
)));
}
// Pay via the ONE budget-capped primitive (T-13-89) — same call, same
// mint list as the fallback leg in backends/routstr.rs.
let accepted_mints = crate::wallet::ecash::load_accepted_mints(data_dir)
.await
.map(|m| m.mints)
.unwrap_or_default();
let token = match crate::swarm::payment::auto_pay_token(
data_dir,
&budget.payment_policy(),
&accepted_mints,
price_sats,
)
.await?
{
Some(t) => t,
None => {
return Ok(budget_refusal(format!(
"The node wallet could not fund this request (~{price_sats} sats) — check the \
ecash balance and accepted mints in Settings → Wallet."
)));
}
};
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(FORWARD_TIMEOUT_SECS))
.build()?;
let url = format!("{ROUTSTR_INSTANCE}/v1/chat/completions");
let resp = match client
.post(&url)
.header("Authorization", format!("Bearer {token}"))
.header("Content-Type", "application/json")
.json(&body)
.send()
.await
{
Ok(r) => r,
Err(e) => {
// The token never reached the provider — reclaim it into our own
// wallet so the sats aren't stranded, and record nothing.
match crate::wallet::ecash::receive_token(data_dir, &token).await {
Ok(_) => tracing::info!(
"routstr proxy: upstream send failed ({e}); unsent payment token reclaimed"
),
Err(re) => tracing::warn!(
"routstr proxy: upstream send failed ({e}) AND reclaiming the unsent token \
failed ({re}) — {price_sats} sats may be stranded in the token"
),
}
return Ok(bad_gateway("Routstr provider is unreachable"));
}
};
let status = resp.status();
// Change comes back as a Cashu token header (docs.routstr.com names both
// spellings across versions); redeem it so only the net leaves the
// allowance.
let refund_token = ["x-cashu-refund", "x-cashu"]
.iter()
.find_map(|h| resp.headers().get(*h))
.and_then(|v| v.to_str().ok())
.map(String::from);
let resp_body = resp.bytes().await.unwrap_or_default();
let mut reclaimed = 0u64;
if let Some(refund) = refund_token {
match crate::wallet::ecash::receive_token(data_dir, &refund).await {
Ok(sats) => reclaimed = sats,
Err(e) => tracing::warn!("routstr proxy: redeeming the change token failed: {e}"),
}
} else if !status.is_success() {
// The provider refused the request (e.g. "mint unreachable") and
// sent no change — if it never actually redeemed our token, the
// proofs are still ours to take back. If it DID redeem and then
// failed, this reclaim fails harmlessly and the spend stands.
match crate::wallet::ecash::receive_token(data_dir, &token).await {
Ok(sats) => {
reclaimed = sats;
tracing::info!(
"routstr proxy: upstream refused (HTTP {status}); unredeemed payment token \
reclaimed ({sats} sats)"
);
}
Err(e) => tracing::warn!(
"routstr proxy: upstream refused (HTTP {status}) and the payment token could \
not be reclaimed ({e}) — treating the {price_sats} sats as spent"
),
}
}
let net_sats = price_sats.saturating_sub(reclaimed);
if net_sats > 0 {
if let Err(e) = budget.record_spend(data_dir, net_sats).await {
tracing::warn!(
error = %e,
"routstr proxy: failed to persist the budget spend (the payment itself already happened)"
);
}
}
tracing::info!(
model = %model_id,
quoted = price_sats,
reclaimed,
net = net_sats,
status = %status,
"routstr proxy: forwarded paid chat completion"
);
Ok(Response::builder()
.status(status.as_u16())
.header("Content-Type", "application/json")
.body(Body::from(resp_body))
.unwrap_or_else(|_| Response::new(Body::from("{}"))))
}
#[cfg(test)]
mod tests {
use super::*;
async fn test_store() -> SessionStore {
let path = std::env::temp_dir().join(format!(
"archy-routstr-proxy-test-sessions-{}.json",
rand::RngCore::next_u64(&mut rand::rngs::OsRng)
));
SessionStore::new_for_tests(path)
}
fn req(method: &str, path: &str, cookie: Option<&str>, body: &'static str) -> Request<Body> {
let mut builder = Request::builder().method(method).uri(path);
if let Some(c) = cookie {
builder = builder.header("cookie", format!("session={c}"));
}
builder.body(Body::from(body)).unwrap()
}
#[tokio::test]
async fn models_without_session_is_401() {
let store = test_store().await;
let data_dir = tempfile::tempdir().unwrap();
let r = req("GET", "/aiui/api/routstr/models", None, "");
let resp = route_routstr_proxy(&store, data_dir.path(), r, "/aiui/api/routstr/models")
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn chat_without_session_is_401() {
let store = test_store().await;
let data_dir = tempfile::tempdir().unwrap();
let r = req("POST", "/aiui/api/routstr/chat/completions", None, "{}");
let resp = route_routstr_proxy(
&store,
data_dir.path(),
r,
"/aiui/api/routstr/chat/completions",
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}
/// D-05: a fresh node (no budget file → zero allowance) refuses the paid
/// path BEFORE any pricing/network I/O — this test runs fully offline.
#[tokio::test]
async fn chat_with_zero_allowance_is_refused_offline() {
let store = test_store().await;
let token = store.create().await;
let data_dir = tempfile::tempdir().unwrap();
let r = req(
"POST",
"/aiui/api/routstr/chat/completions",
Some(&token),
r#"{"model":"some-model","messages":[{"role":"user","content":"hi"}]}"#,
);
let resp = route_routstr_proxy(
&store,
data_dir.path(),
r,
"/aiui/api/routstr/chat/completions",
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
let body = hyper::body::to_bytes(resp.into_body()).await.unwrap();
let v: Value = serde_json::from_slice(&body).unwrap();
let msg = v["error"]["message"].as_str().unwrap();
assert!(msg.contains("Settings"), "refusal must name the UI path");
}
#[tokio::test]
async fn chat_body_carrying_bip39_is_blocked() {
let store = test_store().await;
let token = store.create().await;
let data_dir = tempfile::tempdir().unwrap();
std::fs::create_dir_all(data_dir.path().join("secrets")).unwrap();
let r = req(
"POST",
"/aiui/api/routstr/chat/completions",
Some(&token),
r#"{"model":"m","messages":[{"role":"user","content":"abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"}]}"#,
);
let resp = route_routstr_proxy(
&store,
data_dir.path(),
r,
"/aiui/api/routstr/chat/completions",
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[test]
fn price_estimate_is_conservative_and_never_zero() {
// A free/garbled pricing entry still quotes at least 1 sat.
assert_eq!(estimate_price_sats(&SatsPricing::default(), 100, 1024), 1);
// Live-catalog-shaped numbers (deepseek-v4-flash, 2026-08-14):
// request 0.001, prompt ~0.000178/tok, completion ~0.000267/tok.
let p = SatsPricing {
prompt: 0.000178,
completion: 0.000267,
request: 0.001,
};
let quote = estimate_price_sats(&p, 4000, 1024);
// ~0.18 + ~0.27 + flat, with margin → rounds up to 1 sat.
assert_eq!(quote, 1);
// A pricier model scales with the prompt.
let expensive = SatsPricing {
prompt: 0.05,
completion: 0.1,
request: 1.0,
};
let quote = estimate_price_sats(&expensive, 40_000, 1024);
assert!(quote >= 600, "quote {quote} should reflect real rates");
}
#[test]
fn pricing_lookup_finds_exact_model_id() {
let models = json!({ "data": [
{ "id": "a-model", "sats_pricing": { "prompt": 0.1, "completion": 0.2, "request": 1.0 } },
{ "id": "other", "sats_pricing": { "prompt": 0.3 } }
]});
let p = pricing_for_model(&models, "a-model").unwrap();
assert_eq!(p.request, 1.0);
assert!(pricing_for_model(&models, "missing").is_none());
}
}
+62
View File
@@ -42,6 +42,13 @@ impl RpcHandler {
"port": g.port, "port": g.port,
"app_id": g.app_id, "app_id": g.app_id,
"app_name": g.app_name, "app_name": g.app_name,
// Is the login challenge active on this port right now
// (manifest default + operator override, resolved)?
"gate_enabled": g.auth_enabled,
// Whether an operator override is recorded, and what the
// manifest would do without it — the UI needs all three
// to render a meaningful toggle.
"override": crate::container::app_gate_config::gate_override(&g.app_id),
}) })
}) })
.collect(); .collect();
@@ -56,4 +63,59 @@ impl RpcHandler {
"exempt": exempt, "exempt": exempt,
})) }))
} }
/// `security.set-app-gate` — the operator's per-app gate toggle.
///
/// Params: `{ id: "<app_id>", enabled: true | false | null }`.
/// `enabled: null` clears the override so the manifest default applies
/// again. Takes effect on the next request (the gate resolves per-request
/// policy from the live port map) — no rebind, no restart.
pub(in crate::api::rpc) async fn handle_set_app_gate(
&self,
params: Option<serde_json::Value>,
) -> Result<serde_json::Value> {
let params = params.ok_or_else(|| anyhow::anyhow!("Missing params"))?;
let app_id = params
.get("id")
.and_then(|v| v.as_str())
.ok_or_else(|| anyhow::anyhow!("Missing id"))?
.to_string();
let enabled = match params.get("enabled") {
None | Some(serde_json::Value::Null) => None,
Some(serde_json::Value::Bool(b)) => Some(*b),
Some(other) => anyhow::bail!("enabled must be true, false or null, got {other}"),
};
// Only apps the gate actually fronts have a challenge to toggle.
// Writing an override for anything else would sit silently in the
// config doing nothing — reject instead so a typo'd id is loud.
let port_map = self.app_gate.port_map().await;
if !port_map.gated_ports().any(|g| g.app_id == app_id) {
anyhow::bail!(
"'{app_id}' has no gate-fronted ports — nothing to toggle \
(auth: none/local ports are manifest-declared, not runtime-toggled)"
);
}
crate::container::app_gate_config::write_gate_override(&app_id, enabled)
.map_err(|e| anyhow::anyhow!("Failed to persist gate override: {e}"))?;
// Rebuild the port map now so the change is live on the next request
// instead of after the next 60s sweep.
self.app_gate.refresh().await;
let effective: Vec<serde_json::Value> = self
.app_gate
.port_map()
.await
.gated_ports()
.filter(|g| g.app_id == app_id)
.map(|g| serde_json::json!({ "port": g.port, "gate_enabled": g.auth_enabled }))
.collect();
tracing::info!(
app = %app_id,
override_ = ?enabled,
"app gate override updated by operator"
);
Ok(serde_json::json!({ "id": app_id, "override": enabled, "ports": effective }))
}
} }
@@ -344,6 +344,7 @@ impl RpcHandler {
"content.indeehub-projects" => self.handle_content_indeehub_projects().await, "content.indeehub-projects" => self.handle_content_indeehub_projects().await,
"system.settings.get" => self.handle_system_settings_get(params).await, "system.settings.get" => self.handle_system_settings_get(params).await,
"system.settings.set" => self.handle_system_settings_set(params).await, "system.settings.set" => self.handle_system_settings_set(params).await,
"system.node-ca.generate" => self.handle_system_node_ca_generate().await,
"system.kiosk-display.get" => self.handle_system_kiosk_display_get().await, "system.kiosk-display.get" => self.handle_system_kiosk_display_get().await,
"system.kiosk-display.set" => self.handle_system_kiosk_display_set(params).await, "system.kiosk-display.set" => self.handle_system_kiosk_display_set(params).await,
"bitcoin.relay-update-settings" => { "bitcoin.relay-update-settings" => {

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