Compare commits

...
46 Commits
Author SHA1 Message Date
naturallaw777 043981a34b chore(release): prepare v1.1.3 2026-08-27 09:24:31 -05:00
naturallaw777 5529fccab2 Sparrow update 2026-08-27 09:12:03 -05:00
naturallaw777 5f84154dca nixpkgs update with bisq, bisq2, and sparrow update 2026-08-27 09:10:45 -05:00
Arena Agent 60b55f715e fix(hub): evaluate local vendored package versions directly
Fix the version metadata generation in sovran-hub.nix for Alby Hub, RTL, and Mempool. Previously, the build would incorrectly fall back to older upstream nixpkgs versions because the package names exist upstream, despite the OS deploying custom vendored forks locally. This replaces the fragile checks with direct evaluations of the local packages.

Also updates the development fallback versions.json to reflect the current vendored Alby Hub version (1.24.0).
2026-08-27 09:05:20 -05:00
naturallaw777 01037cd55c albyhub: re-harvest hashes for fixed sovran tag 2026-08-27 02:09:35 -05:00
naturallaw777 7980833fc2 albyhub: re-harvest hashes for fixed sovran tag 2026-08-27 02:08:13 -05:00
naturallaw777 837fffc8f9 albyhub: re-harvest hashes for fixed sovran tag 2026-08-27 02:05:35 -05:00
naturallaw777 cb4585ecf8 albyhub default.nix hash update 2026-08-27 01:13:48 -05:00
naturallaw777 1de1bf95ad albyhub default.nix hash update 2026-08-27 01:01:56 -05:00
naturallaw777 e9d6edca56 albyhub default.nix hash update 2026-08-27 01:00:17 -05:00
naturallaw777 a7bfc9aa0d albyhub default.nix fix 2026-08-27 00:58:17 -05:00
naturallaw777 ed2e4059c1 albyhub: build from sovran fork tag (LND-only, no frontend) 2026-08-27 00:50:35 -05:00
naturallaw777 f057e43ca0 fix(albyhub): use proxyVendor to preserve secp256k1-zkp cgo headers 2026-08-25 19:28:18 -05:00
naturallaw777 d600198049 feat(albyhub): vendor v1.24.0 LND-only, no-frontend build
Replace the nixpkgs albyhub overrideAttrs patch-chain with a fully
vendored package at packages/albyhub for v1.24.0.

- modules/core/sovran-hub.nix: bump fallback version 1.8.0 -> 1.24.0
- modules/nwc-wallets.nix: build via pkgs.callPackage ../packages/albyhub
- packages/albyhub:
  - drop 0002-isolated-invoice-app-id.patch (fixed upstream)
  - add 0004-lnd-only.patch: strip LDK/Bark/Cashu/CLN/Phoenix backends
    from service/start.go, leaving only the LND case
  - add 0005-no-frontend.patch: remove //go:embed dist and the
    frontend handler registration
  - add default.nix: buildGoModule for v1.24.0 with no nodejs/yarn/
    bark-ffi-go/ldk-node deps (only stdenv.cc.cc), subPackages cmd/http

Keeps 0001-private-route-hints and 0003-loopback-bind-host. Does not
touch flake.nix, VERSION, or CHANGELOG.
2026-08-25 19:11:25 -05:00
naturallaw777 14db4282b7 ux: simplify domain and router setup guidance 2026-08-22 09:10:05 -05:00
naturallaw777 d31887cae6 chore(release): prepare v1.1.2 2026-08-21 09:47:43 -05:00
naturallaw777 669181c75b nixpkgs update with Bisq update 2026-08-20 17:04:36 -05:00
naturallaw777 47e9bb99b0 fix(public-ip): move system.activationScripts under the config attribute
The module mixed the `options` keyword attribute with a bare top-level
`system.*` setting. Once a module declares `options` (or `config`), every
other top-level attribute must be a reserved module keyword — the nixpkgs
unifyModuleSyntax check rejects anything else, so every nixos-rebuild
aborted at evaluation time with:

  error: Module '.../modules/core/public-ip.nix' has an unsupported
  attribute `system'. ... move all of them (namely: system) into the
  `config' attribute.

Prefix the activation script with `config.` (equivalent to wrapping it in
`config = { ... };`) so the module evaluates again. The detector script
itself is unchanged.

Fixes: ac6c498615 (-feat(public-ip): unify public-IP detection into one privacy-first script-)
2026-08-20 17:00:23 -05:00
naturallaw777 ac6c498615 feat(public-ip): unify public-IP detection into one privacy-first script
The public IP was previously detected independently in three places,
each contacting a different third party: the Hub (HTTPS echo via
api.ipify.org / ifconfig.me / icanhazip.com on every API call and
background tick), DDNS (myip.opendns.com via OpenDNS), and LiveKit
(embedded STUN). Consolidate into a single detector with one shared
cache so every consumer reads the same value with minimal exposure.

- add modules/core/public-ip.nix: installs /var/lib/sovran/public-ip.py
  (pure Python stdlib, no new deps) writing /var/lib/secrets/external-ip
- detection chain (first success wins): explicit pin, fresh cache
  (default TTL 300s), STUN binding request over UDP (one packet, no
  metadata), DNS myip.opendns.com query, then OPT-IN HTTPS echo
  (publicIP.httpsEcho, empty by default — never contacted unless listed)
- privacy: while the cache is fresh zero third parties are contacted;
  at most one party learns the IP per refresh interval, via the least
  exposing mechanism available
- hub (server.py): _get_external_ip() now reads the shared detector /
  cache instead of calling ipify/ifconfig/icanhazip directly
- ddns (njalla.nix): use the shared detector instead of a separate
  OpenDNS dig; allow the hardened service to write /var/lib/secrets
- element-calling: livekit-turn-setup falls back to the shared
  detector on cold boot; add LiveKit webhooks to lk-jwt-service
  (sfu_webhook) so abrupt disconnects are cleaned up immediately;
  set LIVEKIT_SANITY_CHECK_INTERVAL_SECONDS=60 as a missed-webhook
  guard; drop the dead services.livekit.settings block and set
  openFirewall=false (Caddy fronts the SFU; no public 7880/tcp)
- new options: sovran_systemsOS.publicIP.{stunServer,stunPort,
  dnsResolver,httpsEcho,cacheTTL}
2026-08-20 16:40:00 -05:00
naturallaw777 224ea99ce4 fix(element-calling): reuse Hub external IP for LiveKit, drop egress service calls 2026-08-20 16:12:00 -05:00
naturallaw777 c54dbfe2a5 feat(element-calling): fix Element X discovery and harden federated calling
The element-calling feature only advertised the LiveKit focus via the
well-known org.matrix.msc4143.rtc_foci file, and relied on STUN
auto-detection for the public IP. Element X queries the MatrixRTC
transports registry endpoint and fails with MISSING_MATRIX_RTC_TRANSPORT
when it is absent, and blocked STUN egress silently left LiveKit
advertising a private IP (call connects but no video across servers).

- synapse: enable msc4143_enabled and advertise matrix_rtc.transports
  (MSC4519) with the site's element-calling URL, so Element X can
  discover the LiveKit focus instead of erroring out
- livekit: determine the public IP to advertise at runtime —
  explicit pin, then HTTPS egress detection (api.ipify.org /
  checkip.amazonaws.com / ifconfig.me), then STUN fallback with a
  warning; reject non-routable results (private/loopback/CGNAT)
- lk-jwt-service: append optional extra homeservers to
  LIVEKIT_FULL_ACCESS_HOMESERVERS via the new
  sovran_systemsOS.elementCalling.fullAccessHomeservers option
- add sovran_systemsOS.elementCalling.externalIP option to pin the
  advertised public IP for multi-WAN/VPN setups
- add element-calling-public-check.service: boot-time diagnostics for
  public DNS (via 1.1.1.1, bypassing local loopback overrides), JWT
  healthz through Caddy and via the public IP, and the transports
  endpoint — turns the silent -no media- failure into a visible error
- add restartTriggers so livekit/lk-jwt-service pick up regenerated
  runtime configs on rebuild
2026-08-20 14:07:06 -05:00
naturallaw777 a1fa40cacf fix(hub): derive Restart required from boot default vs running system
NixOS already knows whether a reboot is pending: /nix/var/nix/profiles/
system vs /run/current-system. Marker files only the Hub's own updater
wrote desynced for terminal-updated machines (and markers from older
updaters could never clear), pinning the badge on forever. Reconcile
REBOOT_REQUIRED against live state on every read; the stale marker
self-heals to IDLE. The .generation marker write is now informational.
2026-08-19 11:31:29 -05:00
naturallaw77 48dacbeef3 refactor(lnd): use pkgs.lndinit, drop local packages/lndinit
The local packages/lndinit/default.nix is a verbatim copy of the
upstream Nixpkgs expression, frozen at v0.1.3-beta (the version that
was vendored in from nix-bitcoin before the Aug 10 2026 refactor in
commit 1fbeafd). It carries no Sovran-specific patches, no local
overrides, and no behavioral modifications - it is byte-for-byte
identical to what Nixpkgs ships, except ~19 minor versions older
(Nixpkgs currently ships 0.1.22-beta; the developer upstream
lightninglabs/lndinit is at v0.1.36-beta as of June 10 2026).

Why this matters
----------------

The Aug 10 2026 refactor (1fbeafd, "refactor: move vendor/nix-bitcoin
to modules/bitcoin, remove overlays") stated the new convention:

    No more random vendor/ or pkgs/ dirs - follows Sovran convention:
    modules/ for NixOS modules, packages/ for packages

That refactor successfully removed:
  * pkgs/sovran-overlay.nix
  * pkgs/nbxplorer.nix
  * pkgs/README.md
  * modules/vendor/ (entire directory)
  * overlay-sovran from flake.nix

It moved the lndinit expression into packages/lndinit/default.nix as
an intermediate step, but the file is still a verbatim upstream copy
and therefore still incurs the maintenance burden the refactor was
meant to eliminate: manual version bumps, manual hash refreshes, and
no upstream security or bug-fix flow. Removing it completes the
intent of 1fbeafd.

The change
----------

modules/bitcoin/lnd.nix (line 153):

    -  lndinit = "${(pkgs.callPackage ../../packages/lndinit {})}/bin/lndinit";
    +  lndinit = "${pkgs.lndinit}/bin/lndinit";

The two later uses of `lndinit` in the same file (lines 243 and 247,
inside the systemd.services.lnd.preStart block that calls
`lndinit gen-seed` and `lndinit init-wallet`) are unchanged because
they reference the let-bound `lndinit` value, not the callPackage
expression. They continue to work with the new pkgs.lndinit binary
path transparently.

Removed:
  * packages/lndinit/default.nix
  * packages/lndinit/ (now empty directory)

No other files in the repository reference packages/lndinit. Verified
by:
  * Git tree search for "packages/lndinit" -> only the file and its
    parent directory match
  * Content grep of flake.nix, configuration.nix,
    modules/bitcoin/default.nix, modules/bitcoin/common.nix, and
    iso/common.nix -> zero matches

Why this is safe
----------------

1. CLI compatibility. The preStart script only invokes two
   lndinit subcommands:
     * `lndinit gen-seed`
     * `lndinit -v init-wallet --file.seed=... --file.wallet-password=... --init-file.output-wallet-dir=...`
   Both subcommands and all four flags have been stable since the
   0.1.x line. The Nixpkgs 0.1.22-beta binary produces a wallet.db
   and admin.macaroon in the same on-disk format that 0.1.3-beta did
   for the same LND version (LND is pinned separately by pkgs.lnd
   from Nixpkgs and is unaffected by this change).

2. No coupled Go modules or shared vendor tree. The local
   packages/lndinit/default.nix is a self-contained buildGoModule
   derivation; it has no shared state with any other Sovran package.

3. Nixpkgs pin is current. flake.nix pins
   github:NixOS/nixpkgs/nixos-unstable, which has shipped pkgs.lndinit
   since 2022 and is currently at 0.1.22-beta. There is no
   "missing attribute" risk.

4. Wallet data is forward-compatible. The wallet.db format is owned
   by LND, not lndinit. lndinit is only used at first boot to create
   the seed and initialize the wallet; subsequent LND restarts do
   not invoke lndinit. So even if a user already initialized a
   wallet with 0.1.3-beta, the binary being upgraded to 0.1.22-beta
   is irrelevant - LND owns the wallet from that point on.

5. Single call site. Only modules/bitcoin/lnd.nix references
   lndinit. No other modules, scripts, or tests need to change.

Operational notes
-----------------

* After this commit, lndinit updates flow through the normal
  `nix flake update` workflow (or whatever automated dependency
  tooling is already in use, e.g. for the recent "chore(deps):
  update RTL to 0.15.10" commits). No Sovran-side action is needed
  to pick up future lndinit versions.

* If a future LND version requires a specific lndinit version, the
  pin can be done in flake.nix via a one-line overlay:

      nixpkgs.overlays = [ (final: prev: {
        lndinit = prev.lndinit.overrideAttrs (o: {
          version = "X.Y.Z-beta";
          src = prev.fetchFromGitHub { ... };
          vendorHash = "...";
        });
      }) ];

  This keeps the upgrade path explicit without bringing the entire
  expression back into the Sovran tree.

* This drops ~20 lines of frozen derivation code, eliminates one
  source of upstream drift, and reduces the surface area of what
  Sovran needs to keep current.
2026-08-18 12:30:59 -05:00
naturallaw777 b6e6adbe31 chore(deps): update RTL to 0.15.10
Refresh the RTL source and Node dependency hashes, and align Hub version metadata with the vendored package.
2026-08-18 11:19:23 -05:00
naturallaw777 64624002bb fix(hub): reconcile completed updates after polling stalls
The full-system updater runs as a detached systemd service and can finish
successfully even when the browser loses its status connection. In that
case the update log and status file correctly report REBOOT_REQUIRED, but
the Hub modal can remain on "Updating..." with its controls disabled.

There were four independent ways for the frontend to get stuck:

* update status fetches had no deadline, so a request that stayed pending
  never rejected and never advanced the existing failure counter;
* setInterval started async polls without waiting for the previous poll,
  allowing slow requests to overlap and responses to arrive out of order;
* each log chunk used textContent +=, replacing the complete and growing
  Nix build log every two seconds, which could stall browser rendering and
  was especially visible over RDP; and
* page reload, tab resume, and RDP reconnect did not reattach the modal to
  the update status persisted by the backend.

This produced a dangerous UX mismatch: the machine had a fully staged
NixOS generation and was ready to reboot, while the Hub continued telling
the user that the update was still running.

Bound status requests with AbortController, prevent overlapping polls, and
replace the endless spinner after sustained failures with an explicit
"Update status unavailable" state and Retry Status action. Reconcile state
immediately on focus, visibility, online, page startup, and before starting
a new update. Use no-store requests and render verbose logs incrementally
with a bounded visible tail while retaining the complete report in memory.
Apply the same timeout and single-flight protection to rebuild polling.

Record the exact generation produced by `nixos-rebuild boot`. The Hub now
keeps REBOOT_REQUIRED visible until that generation matches
/run/current-system, then clears the marker after reboot. For an update
started by an older updater that did not write the marker, recover the
staged generation from the final nixos-rebuild log line. The dashboard
sidebar also distinguishes update-in-progress and restart-required states.

Regression coverage verifies generation marker/log recovery, pre- versus
post-reboot detection, request timeout wiring, single-flight polling,
connection-loss UX, RDP/tab resume reconciliation, bounded log rendering,
page-reload recovery, and JavaScript syntax.

Validation:
* python3 -m unittest discover -s tests -p 'test_*.py' -v (170 passed)
* node --check app/sovran_systemsos_web/static/js/*.js
* python3 -m py_compile for changed Python modules
* git diff --check

A Nix evaluation was not available in the development sandbox; the NixOS
module should still be evaluated and built in CI or on a test machine before
release.
2026-08-18 10:31:28 -05:00
naturallaw777 1ccce429a5 fix(bitcoin): migrate i2pd SAM settings for nixpkgs 26.11
nixpkgs commit c8f9654 refactored the services.i2pd module to use
an RFC42-style settings attribute set and removed services.i2pd.proto.
After updating the root nixpkgs input from f13ff45 to ec2d622, the
vendored bitcoind module failed evaluation on the obsolete
services.i2pd.proto.sam.enable definition.

The error occurred even with services.bitcoind.i2p at its false default:
bitcoind was enabled, so NixOS still validated the obsolete option path
inside the conditional i2pd integration.

Read the SAM endpoint from services.i2pd.settings.sam and configure its
new upstream-style fields explicitly. Keep 127.0.0.1:7656, matching the
old typed option defaults that bitcoind uses to generate its i2psam
setting.

This preserves optional I2P support without activating it by default.
i2pd remains disabled until services.bitcoind.i2p is set to true or
"only-outgoing".

Nixpkgs migration: https://github.com/NixOS/nixpkgs/commit/c8f965411e812060a9377fa4c2d7d0f84e8b10e0
2026-08-18 09:19:15 -05:00
naturallaw777 f832efb0d1 nixpkgs update 2026-08-18 08:59:35 -05:00
Sovran Systems 67ae53ad3f Add tor-browser to the package list 2026-08-17 19:10:19 -05:00
naturallaw777 db5b9f6b60 fix(livekit): order turn-setup after network-online to fix boot-time red dot
livekit-turn-setup.service detects the primary interface from the IPv4
default route, but had no ordering against network-online.target. With
NetworkManager+DHCP the default route is applied late at boot, so the
oneshot could run before it existed, exit 1, and — being a hard
dependency of livekit.service — take livekit down with it. The Hub then
showed a 'failed' red dot until livekit was restarted manually.

Order both livekit.service and livekit-turn-setup.service after
network-online.target. Also add a bounded retry when copying Caddy's ACME
cert so we never write an empty turn.crt/turn.key on a fresh boot.
2026-08-17 19:07:54 -05:00
Sovran Systems 2ea1427766 fix: restore a Zeus-scannable LND REST connect QR
The LND-only rewrite of lndconnect.nix shipped a wrapper Zeus cannot
use: unknown flags (--cert/--macaroon), a non-existent onion path
(free/lnd.onion), and a REST hidden service that collided with LND's
P2P onion. Restore the nix-bitcoin contract — dedicated lnd-rest
onion on port 8080, --nocert over Tor, admin macaroon in the URI —
and only persist a valid lndconnect:// URI for the Hub QR.
2026-08-17 18:22:36 -05:00
Sovran Systems b35b327a07 Merge pull request #435 from naturallaw777/security/lnd-macaroon-argv
security: prevent LND admin macaroon exposure in curl argv
2026-08-15 23:03:44 -05:00
naturallaw777 a9ff168fd6 security: prevent LND admin macaroon exposure in curl argv 2026-08-15 23:00:59 -05:00
naturallaw777 b436dbed95 docs: update desktop and Sovran Hub screenshots 2026-08-15 18:53:15 -05:00
naturallaw777 1cf611d44c chore(release): prepare v1.1.1 2026-08-15 17:49:55 -05:00
Sovran Systems 1e3dd2dd76 Update release-stable.sh 2026-08-15 17:48:45 -05:00
Sovran Systems 45322db41a Enhance release script with preflight checks and metadata
Refactor release script to improve preflight checks and metadata preparation. Update release steps for GitHub and Gitea.
2026-08-15 17:43:03 -05:00
naturallaw777 2a1d73af25 Migrate dock/folder/mime entries from brave to brave-origin on upgrade 2026-08-15 17:31:25 -05:00
Sovran Systems e83c7fdb18 Merge pull request #434 from naturallaw777/fix/hub-logout-persistence
fix(hub): persistent browser profile so logout survives window reopen
2026-08-15 17:24:14 -05:00
naturallaw777 587c19c2a5 fix(hub): persistent browser profile so logout survives window reopen
The Hub launcher used an ephemeral /tmp profile deleted on exit, which
wiped the hub_manual_logout marker cookie. On reopen, /auto-login minted a
new session and logged the user straight back in without a password.

Use a persistent per-user profile under XDG_STATE_HOME and drop the
deletion trap so the logout marker survives close/reopen. Keep
--skip-origin-startup-dialog. Adds regression tests.
2026-08-15 17:22:58 -05:00
naturallaw777 c862ed5806 Skip Brave Origin startup dialog in Hub launcher 2026-08-15 17:15:12 -05:00
Sovran Systems 1d79acb083 Merge pull request #433 from naturallaw777/brave-origin-default
Switch default browser to Brave Origin (brave-origin)
2026-08-15 17:00:24 -05:00
naturallaw777 5edf594eac Switch default browser to Brave Origin (brave-origin) 2026-08-15 16:58:33 -05:00
Sovran Systems 94dba571c1 Merge pull request #432 from naturallaw777/fix/hub-session-auth-recovery
fix(hub): recover from expired sessions and preserve logout
2026-08-15 16:45:24 -05:00
naturallaw777 de32699539 fix(hub): recover from expired sessions and preserve logout 2026-08-15 16:43:37 -05:00
Sovran Systems 892397589f Merge pull request #431 from naturallaw777/feat/bitcoin-tor-ibd-gossip
feat: add Bitcoin Core Tor IBD gossip control
2026-08-15 14:47:21 -05:00
naturallaw777 30b753ec40 feat: add Bitcoin Core Tor IBD gossip control 2026-08-15 14:44:13 -05:00
52 changed files with 2653 additions and 755 deletions

No files matched your search

+121 -1
View File
@@ -7,9 +7,112 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
--- ---
## [Unreleased] ## [1.1.3] - 2026-08-27
### Added
- Sparrow update
- Nixpkgs update with bisq and bisq2
- Albyhub: re-harvest hashes for fixed sovran tag
- Albyhub default.nix hash update
- Albyhub default.nix fix
- Albyhub: build from sovran fork tag (LND-only, no frontend)
- Vendor v1.24.0 LND-only, no-frontend build
- Ux: simplify domain and router setup guidance
### Fixed ### Fixed
- Evaluate local vendored package versions directly
- Use proxyVendor to preserve secp256k1-zkp cgo headers
[1.1.3]: https://git.sovransystems.com/Sovran_Systems/Sovran_SystemsOS/releases/tag/v1.1.3
## [1.1.2] - 2026-08-21
### Added
- Nixpkgs update with Bisq update
- Unify public-IP detection into one privacy-first script
- Fix Element X discovery and harden federated calling
- Nixpkgs update
- Add tor-browser to the package list
### Changed
- Use pkgs.lndinit, drop local packages/lndinit
- Update RTL to 0.15.10
### Fixed
- Move system.activationScripts under the config attribute
- Reuse Hub external IP for LiveKit, drop egress service calls
- Derive Restart required from boot default vs running system
- Reconcile completed updates after polling stalls
- Migrate i2pd SAM settings for nixpkgs 26.11
- Order turn-setup after network-online to fix boot-time red dot
- Restore a Zeus-scannable LND REST connect QR
### Security
- Prevent LND admin macaroon exposure in curl argv
### Documentation
- Update desktop and Sovran Hub screenshots
[1.1.2]: https://git.sovransystems.com/Sovran_Systems/Sovran_SystemsOS/releases/tag/v1.1.2
## [1.1.1] - 2026-08-15
### Added
- Update release-stable.sh
- Enhance release script with preflight checks and metadata
- Migrate dock/folder/mime entries from brave to brave-origin on upgrade
- Skip Brave Origin startup dialog in Hub launcher
- Switch default browser to Brave Origin (brave-origin)
- Add Bitcoin Core Tor IBD gossip control
- Replace Bitcoin Knots with Bitcoin Core
### Fixed
- Persistent browser profile so logout survives window reopen
- Recover from expired sessions and preserve logout
- Prevent Bitcoin Core switch from hanging the Hub UI
### Documentation
- Update README ISO download links to v1.1.0
[1.1.1]: https://git.sovransystems.com/Sovran_Systems/Sovran_SystemsOS/releases/tag/v1.1.1
## [Unreleased]
### Changed
- Replaced Brave Browser with Brave Origin (the new `brave-origin` nixpkgs
package) as the desktop's default browser: installed package, dock
favorite, Browsers app-folder entry, `xdg.mime.defaultApplications`, and
the `$BROWSER` session variable now all point at Brave Origin, and the
Sovran Hub launcher runs it.
- On installs upgrading from the old Brave package, the desktop theme init
now migrates `brave-browser.desktop` → `brave-origin.desktop` in the dock
favorites, the Browsers app folder, and the user's `mimeapps.list`, so
the dock icon and default-browser handler survive the switch without a
manual re-pin.
### Fixed
- Zeus Connect QR in the Hub was invalid: the LND-only `lndconnect`
wrapper used flags Zeus/`lndconnect` do not understand (`--cert`,
`--macaroon`), read a non-existent onion path (`free/lnd.onion`),
and collided with LND's P2P hidden service. The wrapper now matches
the nix-bitcoin contract — dedicated `lnd-rest` onion on port 8080,
`--nocert` over Tor, admin macaroon in the URI — so scanning the Hub
QR in Zeus works again.
- The Hub launcher now uses a persistent per-user browser profile
(`$XDG_STATE_HOME/sovran-hub-browser`) instead of a throwaway `/tmp`
profile that was deleted on exit. The throwaway profile wiped the
`hub_manual_logout` marker cookie on every close, so `/auto-login`
silently logged the user straight back in after they signed out and
reopened the Hub window. The persistent profile makes explicit logout
stick (until the next password login) while still skipping Brave Origin's
one-time startup dialog.
- The Hub now redirects to the login page when an API request finds an
expired browser session, instead of leaving the dashboard tile grid in a
loading state while `/api/services` continues returning 401 every five
seconds.
- Explicitly logging out now suppresses the desktop launcher's local
auto-login after the Hub window is closed and reopened. A successful
password login clears that preference.
- Sessions are now persisted to `/var/lib/secrets/hub-sessions.json` so the - Sessions are now persisted to `/var/lib/secrets/hub-sessions.json` so the
browser login survives the Hub service restart that `nixos-rebuild switch` browser login survives the Hub service restart that `nixos-rebuild switch`
performs during activation. Previously the in-memory session store was performs during activation. Previously the in-memory session store was
@@ -20,6 +123,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
polling failures instead of hanging indefinitely. polling failures instead of hanging indefinitely.
- Rebuild/update scripts stream `nixos-rebuild` output into the live log - Rebuild/update scripts stream `nixos-rebuild` output into the live log
(it was buffered until completion, making long rebuilds look frozen). (it was buffered until completion, making long rebuilds look frozen).
- The update modal now reconciles persisted update state after a page/RDP
reconnect, bounds every status request with a timeout, prevents overlapping
async polls, and reports an explicit "status unavailable" state with a
Retry Status action instead of spinning forever. Verbose Nix logs are
rendered incrementally and bounded so they cannot stall the browser UI.
- Successful staged updates now record the exact NixOS generation. The Hub
keeps showing "Restart required" until that generation is active, then
clears the marker after reboot (with log-based recovery for older updates).
- Pending-reboot state is now derived from NixOS itself — the boot default
(`/nix/var/nix/profiles/system`) versus the running `/run/current-system`
— instead of from Hub-written marker files. Updates performed from a
terminal or support session (which never touch the Hub's status files)
previously left a stale `REBOOT_REQUIRED` marker the Hub could never
clear, pinning the "Restart required" badge forever even after many
reboots. The marker self-heals to `IDLE` on the next status read whenever
boot default and running system agree, and recording the informational
`.generation` marker can no longer fail an otherwise successful update.
--- ---
+18 -14
View File
@@ -21,12 +21,12 @@ Lightning infrastructure, private cloud, and communications platform when you
are ready. are ready.
[Visit the Website](https://sovransystems.com) · [Visit the Website](https://sovransystems.com) ·
[Download the ISO](https://downloads.sovransystems.com/Sovran_SystemsOS-1.1.0.iso) · [Download the ISO](https://downloads.sovransystems.com/Sovran_SystemsOS-1.1.3.iso) ·
[Try it safely in a VM](#try-it-first-in-a-virtual-machine) · [Try it safely in a VM](#try-it-first-in-a-virtual-machine) ·
[Verify the Download](https://downloads.sovransystems.com/Sovran_SystemsOS-1.1.0.iso.sha256) · [Verify the Download](https://downloads.sovransystems.com/Sovran_SystemsOS-1.1.3.iso.sha256) ·
[Build from Source](#build-from-source) [Build from Source](#build-from-source)
<img src="assets/desktop-screenshot.png" alt="Sovran_SystemsOS private Bitcoin desktop" width="800" /> <img src="assets/desktop-screenshot.webp" alt="Sovran_SystemsOS private Bitcoin desktop" width="800" />
*Bitcoin sovereignty from the first boot.* *Bitcoin sovereignty from the first boot.*
@@ -185,7 +185,7 @@ hardware you control.
### Your desktop ### Your desktop
- [GNOME](https://www.gnome.org) desktop - [GNOME](https://www.gnome.org) desktop
- [Brave](https://brave.com) and - [Brave Origin](https://brave.com/origin/) and
[Firefox](https://www.mozilla.org/firefox) browsers [Firefox](https://www.mozilla.org/firefox) browsers
- File management, email, calendar, and office applications - File management, email, calendar, and office applications
- System monitoring and administration tools - System monitoring and administration tools
@@ -281,6 +281,10 @@ From one place, the Hub helps you:
- Reach your Bitcoin tools, private cloud, and communications - Reach your Bitcoin tools, private cloud, and communications
- Perform supported system operations without everyday terminal commands - Perform supported system operations without everyday terminal commands
<img src="assets/sovran-hub-screenshot.webp" alt="The Sovran Hub dashboard" width="800" />
*The Sovran Hub: manage your private infrastructure from one place.*
### Example home setup ### Example home setup
```text ```text
@@ -341,8 +345,8 @@ with an imaging application such as [Balena Etcher](https://etcher.balena.io).
### 1. Download the ISO and checksum ### 1. Download the ISO and checksum
- [Download Sovran_SystemsOS-1.1.0.iso](https://downloads.sovransystems.com/Sovran_SystemsOS-1.1.0.iso) - [Download Sovran_SystemsOS-1.1.3.iso](https://downloads.sovransystems.com/Sovran_SystemsOS-1.1.3.iso)
- [Download Sovran_SystemsOS-1.1.0.iso.sha256](https://downloads.sovransystems.com/Sovran_SystemsOS-1.1.0.iso.sha256) - [Download Sovran_SystemsOS-1.1.3.iso.sha256](https://downloads.sovransystems.com/Sovran_SystemsOS-1.1.3.iso.sha256)
The download may take some time. Do not rename or modify the ISO before The download may take some time. Do not rename or modify the ISO before
verifying it, and keep both files in the same folder. verifying it, and keep both files in the same folder.
@@ -360,16 +364,16 @@ checksum exactly.
Open a terminal in the download folder and run: Open a terminal in the download folder and run:
```bash ```bash
sha256sum --check Sovran_SystemsOS-1.1.0.iso.sha256 sha256sum --check Sovran_SystemsOS-1.1.3.iso.sha256
``` ```
A successful comparison reports: A successful comparison reports:
```text ```text
Sovran_SystemsOS-1.1.0.iso: OK Sovran_SystemsOS-1.1.3.iso: OK
``` ```
You can also run `sha256sum Sovran_SystemsOS-1.1.0.iso` and compare the output You can also run `sha256sum Sovran_SystemsOS-1.1.3.iso` and compare the output
against the checksum file manually. against the checksum file manually.
</details> </details>
@@ -380,11 +384,11 @@ against the checksum file manually.
Open Terminal in the download folder and run: Open Terminal in the download folder and run:
```bash ```bash
shasum -a 256 Sovran_SystemsOS-1.1.0.iso shasum -a 256 Sovran_SystemsOS-1.1.3.iso
``` ```
Compare the value shown in Terminal with the value inside Compare the value shown in Terminal with the value inside
`Sovran_SystemsOS-1.1.0.iso.sha256`. `Sovran_SystemsOS-1.1.3.iso.sha256`.
</details> </details>
@@ -394,7 +398,7 @@ Compare the value shown in Terminal with the value inside
Open PowerShell in the download folder and run: Open PowerShell in the download folder and run:
```powershell ```powershell
Get-FileHash .\Sovran_SystemsOS-1.1.0.iso -Algorithm SHA256 Get-FileHash .\Sovran_SystemsOS-1.1.3.iso -Algorithm SHA256
``` ```
Compare the value under `Hash` with the published checksum. Compare the value under `Hash` with the published checksum.
@@ -409,7 +413,7 @@ match exactly.
1. Download and install [Balena Etcher](https://etcher.balena.io), then 1. Download and install [Balena Etcher](https://etcher.balena.io), then
connect the USB drive. connect the USB drive.
2. Choose **Flash from file** and select `Sovran_SystemsOS-1.1.0.iso`. 2. Choose **Flash from file** and select `Sovran_SystemsOS-1.1.3.iso`.
3. Choose **Select target**, select the USB drive, and review your selection 3. Choose **Select target**, select the USB drive, and review your selection
carefully. carefully.
4. Choose **Flash** and wait for the writing and verification process to 4. Choose **Flash** and wait for the writing and verification process to
@@ -852,7 +856,7 @@ primary location for collaboration. Please read our
## Privacy. Sovereignty. Bitcoin. ## Privacy. Sovereignty. Bitcoin.
[Visit Sovran Systems](https://sovransystems.com) · [Visit Sovran Systems](https://sovransystems.com) ·
[Download Sovran_SystemsOS](https://downloads.sovransystems.com/Sovran_SystemsOS-1.1.0.iso) · [Download Sovran_SystemsOS](https://downloads.sovransystems.com/Sovran_SystemsOS-1.1.3.iso) ·
[View the License](LICENSE) [View the License](LICENSE)
</div> </div>
+1 -1
View File
@@ -1 +1 @@
1.1.0 1.1.3
@@ -491,6 +491,8 @@ if [[ -d /home ]]; then
--exclude='.config/chromium/*/Code Cache/' \ --exclude='.config/chromium/*/Code Cache/' \
--exclude='.config/BraveSoftware/Brave-Browser/*/Cache/' \ --exclude='.config/BraveSoftware/Brave-Browser/*/Cache/' \
--exclude='.config/BraveSoftware/Brave-Browser/*/Code Cache/' \ --exclude='.config/BraveSoftware/Brave-Browser/*/Code Cache/' \
--exclude='.config/BraveSoftware/Brave-Origin/*/Cache/' \
--exclude='.config/BraveSoftware/Brave-Origin/*/Code Cache/' \
--exclude='.local/share/baloo/' \ --exclude='.local/share/baloo/' \
--exclude='.thumbnails/' \ --exclude='.thumbnails/' \
--exclude='.xsession-errors' \ --exclude='.xsession-errors' \
+243 -66
View File
@@ -21,6 +21,7 @@ import subprocess
import tempfile import tempfile
import threading import threading
import time import time
import sys
import urllib.error import urllib.error
import urllib.parse import urllib.parse
import urllib.request import urllib.request
@@ -55,6 +56,7 @@ from .security_helpers import (
load_session_store, load_session_store,
save_session_store, save_session_store,
) )
from .update_state import effective_update_status
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -64,9 +66,10 @@ FLAKE_LOCK_PATH = "/etc/nixos/flake.lock"
FLAKE_INPUT_NAME = "Sovran_Systems" FLAKE_INPUT_NAME = "Sovran_Systems"
GITEA_API_BASE = "https://git.sovransystems.com/api/v1/repos/Sovran_Systems/Sovran_SystemsOS/commits" GITEA_API_BASE = "https://git.sovransystems.com/api/v1/repos/Sovran_Systems/Sovran_SystemsOS/commits"
UPDATE_LOG = "/var/log/sovran-hub-update.log" UPDATE_LOG = "/var/log/sovran-hub-update.log"
UPDATE_STATUS = "/var/log/sovran-hub-update.status" UPDATE_STATUS = "/var/log/sovran-hub-update.status"
UPDATE_UNIT = "sovran-hub-update.service" UPDATE_GENERATION = "/var/log/sovran-hub-update.generation"
UPDATE_UNIT = "sovran-hub-update.service"
REBUILD_LOG = "/var/log/sovran-hub-rebuild.log" REBUILD_LOG = "/var/log/sovran-hub-rebuild.log"
REBUILD_STATUS = "/var/log/sovran-hub-rebuild.status" REBUILD_STATUS = "/var/log/sovran-hub-rebuild.status"
@@ -132,6 +135,7 @@ _SERVICE_DOMAIN_KEYS = frozenset([
]) ])
INTERNAL_IP_FILE = "/var/lib/secrets/internal-ip" INTERNAL_IP_FILE = "/var/lib/secrets/internal-ip"
EXTERNAL_IP_FILE = "/var/lib/secrets/external-ip"
ZEUS_CONNECT_FILE = "/var/lib/secrets/zeus-connect-url" ZEUS_CONNECT_FILE = "/var/lib/secrets/zeus-connect-url"
ONBOARDING_FLAG = "/var/lib/sovran/onboarding-complete" ONBOARDING_FLAG = "/var/lib/sovran/onboarding-complete"
@@ -142,9 +146,13 @@ AUTOLAUNCH_DISABLE_FLAG = "/var/lib/sovran/hub-autolaunch-disabled"
FREE_PASSWORD_FILE = "/var/lib/secrets/free-password" FREE_PASSWORD_FILE = "/var/lib/secrets/free-password"
FREE_PASSWORD_FILE_WEB = "/var/lib/secrets/free-password-web" FREE_PASSWORD_FILE_WEB = "/var/lib/secrets/free-password-web"
MIGRATION_NEWPASS_FILE = "/var/lib/secrets/free-password-migration-newpass" MIGRATION_NEWPASS_FILE = "/var/lib/secrets/free-password-migration-newpass"
HUB_SESSION_SECRET_FILE = "/var/lib/secrets/hub-session-secret" HUB_SESSION_SECRET_FILE = "/var/lib/secrets/hub-session-secret"
SESSION_COOKIE_NAME = "hub_session" SESSION_COOKIE_NAME = "hub_session"
SESSION_MAX_AGE = 86400 # 24 hours MANUAL_LOGOUT_COOKIE_NAME = "hub_manual_logout"
SESSION_MAX_AGE = 86400 # 24 hours
# Chromium limits persistent cookies to roughly 400 days. This marker only
# suppresses desktop auto-login until the next successful password login.
MANUAL_LOGOUT_MAX_AGE = 400 * 86400
# Sessions are persisted here so logins survive a restart of the Hub service. # Sessions are persisted here so logins survive a restart of the Hub service.
# nixos-rebuild switch restarts sovran-hub-web.service during activation (its # nixos-rebuild switch restarts sovran-hub-web.service during activation (its
@@ -238,8 +246,8 @@ CATEGORY_ORDER = [
FEATURE_REGISTRY = [ FEATURE_REGISTRY = [
{ {
"id": "rdp", "id": "rdp",
"name": "Remote Desktop (RDP)", "name": "Remote Desktop",
"description": "Access your desktop remotely via RDP client", "description": "Access your desktop from a device on your home network — no router setup needed",
"category": "infrastructure", "category": "infrastructure",
"needs_domain": False, "needs_domain": False,
"domain_name": None, "domain_name": None,
@@ -317,6 +325,27 @@ FEATURE_REGISTRY = [
"conflicts_with": [], "conflicts_with": [],
"port_requirements": [], "port_requirements": [],
}, },
{
"id": "bitcoin-tor-gossip",
"name": "Advertise Tor IBD Node",
"description": "Advertise this Bitcoin Core node's onion address through Bitcoin peer gossip so more Tor-capable nodes can discover it and request blocks.",
"details": [
"Your Tor IBD listener remains available whether or not advertising is enabled.",
"Enabling this announces only the node's .onion P2P address; it does not publish your home IP address.",
"Other Tor nodes can discover your node and request historical blocks while performing Initial Block Download (IBD).",
"No clearnet port or router port forwarding is opened.",
"Serving additional IBD peers can use significant upload bandwidth.",
],
"category": "bitcoin",
"modal_only": True,
"needs_domain": False,
"domain_name": None,
"needs_ddns": False,
"extra_fields": [],
"conflicts_with": [],
"requires": ["bitcoin-service"],
"port_requirements": [],
},
{ {
"id": "sshd", "id": "sshd",
"name": "SSH Remote Access", "name": "SSH Remote Access",
@@ -333,8 +362,8 @@ FEATURE_REGISTRY = [
}, },
{ {
"id": "btcpay-web", "id": "btcpay-web",
"name": "BTCPay Server Web Access", "name": "Put BTCPay Server Online",
"description": "Expose BTCPay Server to the internet via your domain. When disabled, BTCPay Server still runs locally but is not accessible from the web.", "description": "Let people donate Bitcoin, pay you, or visit your online store. BTCPay Server stays private when this is turned off.",
"category": "bitcoin", "category": "bitcoin",
"needs_domain": True, "needs_domain": True,
"domain_name": "btcpayserver", "domain_name": "btcpayserver",
@@ -358,6 +387,7 @@ FEATURE_SERVICE_MAP = {
"haven": "haven-relay.service", "haven": "haven-relay.service",
"element-calling": "livekit.service", "element-calling": "livekit.service",
"mempool": "mempool.service", "mempool": "mempool.service",
"bitcoin-tor-gossip": None,
"btcpay-web": "btcpayserver.service", "btcpay-web": "btcpayserver.service",
"nwc-wallets": "albyhub.service", "nwc-wallets": "albyhub.service",
"sshd": "sshd.service", "sshd": "sshd.service",
@@ -431,7 +461,7 @@ ROLE_CATEGORIES: dict[str, set[str] | None] = {
ROLE_FEATURES: dict[str, set[str] | None] = { ROLE_FEATURES: dict[str, set[str] | None] = {
"server_plus_desktop": None, "server_plus_desktop": None,
"desktop": {"rdp", "sshd"}, "desktop": {"rdp", "sshd"},
"node": {"rdp", "mempool", "btcpay-web", "nwc-wallets", "sshd"}, "node": {"rdp", "bitcoin-tor-gossip", "mempool", "btcpay-web", "nwc-wallets", "sshd"},
} }
SERVICE_DESCRIPTIONS: dict[str, str] = { SERVICE_DESCRIPTIONS: dict[str, str] = {
@@ -461,9 +491,9 @@ SERVICE_DESCRIPTIONS: dict[str, str] = {
"Sovran_SystemsOS makes running a production-grade payment gateway as simple as flipping a switch." "Sovran_SystemsOS makes running a production-grade payment gateway as simple as flipping a switch."
), ),
"zeus-connect-setup.service": ( "zeus-connect-setup.service": (
"Connect the Zeus mobile wallet to your Lightning node via LND REST. Send and receive " "Connect the Zeus mobile wallet to your Lightning node via LND REST over Tor. Send and receive "
"Lightning payments from your phone using a direct node connection. " "Lightning payments from your phone using a direct node connection. "
"Scan the QR code to add your node to Zeus — this gives full node admin access." "Scan the QR code to add your node to Zeus, then enable Use Tor — this gives full node admin access."
), ),
"mempool.service": ( "mempool.service": (
"Your own blockchain explorer and mempool visualizer. Monitor transactions, " "Your own blockchain explorer and mempool visualizer. Monitor transactions, "
@@ -515,9 +545,9 @@ SERVICE_DESCRIPTIONS: dict[str, str] = {
"Addresses on your Sovran_SystemsOS node." "Addresses on your Sovran_SystemsOS node."
), ),
"gnome-remote-desktop.service": ( "gnome-remote-desktop.service": (
"Access your server's full desktop environment from anywhere using any RDP client. " "Access your desktop from a device on your home network — no router setup needed. "
"Manage your system visually without being physically present. " "Sovran_SystemsOS creates the address, username, and password for you: "
"Sovran_SystemsOS sets up secure remote access with generated credentials — connect and go." "just open an RDP app and connect."
), ),
"sshd.service": ( "sshd.service": (
"Secure Shell (SSH) remote access. When enabled, authorized users can connect " "Secure Shell (SSH) remote access. When enabled, authorized users can connect "
@@ -924,21 +954,43 @@ def _save_internal_ip(ip: str):
pass pass
def _get_external_ip() -> str: def _save_external_ip(ip: str):
MAX_IP_LENGTH = 46 """Write the external IP to a file so other services (e.g. LiveKit) can
for url in [ reference it without running their own detection."""
"https://api.ipify.org", if ip and ip != "unavailable":
"https://ifconfig.me/ip",
"https://icanhazip.com",
]:
try: try:
req = urllib.request.Request(url, method="GET") os.makedirs(os.path.dirname(EXTERNAL_IP_FILE), exist_ok=True)
with urllib.request.urlopen(req, timeout=8) as resp: with open(EXTERNAL_IP_FILE, "w") as f:
ip = resp.read().decode().strip() f.write(ip)
if ip and len(ip) < MAX_IP_LENGTH: except OSError:
return ip pass
except Exception:
continue
def _get_external_ip() -> str:
"""Public IP via the shared detector (/var/lib/sovran/public-ip.py).
The detector owns discovery (STUN -> DNS -> opt-in HTTPS echo), caches the
result in /var/lib/secrets/external-ip, and contacts at most one third
party per refresh interval. This function only reads the cache and asks
the detector to refresh when it is missing or stale — it performs no
per-call external queries of its own.
"""
try:
r = subprocess.run(
[sys.executable, "/var/lib/sovran/public-ip.py", "check"],
capture_output=True, text=True, timeout=20,
)
if r.returncode == 0 and r.stdout.strip():
return r.stdout.strip().splitlines()[0]
except Exception:
pass
try:
with open(EXTERNAL_IP_FILE) as f:
ip = f.read().strip()
if ip:
return ip
except OSError:
pass
return "unavailable" return "unavailable"
@@ -1506,31 +1558,38 @@ def _evaluate_domain_checklist(
def _generate_qr_png_bytes(data: str, scale: int = 6, margin: int = 2) -> bytes | None: def _generate_qr_png_bytes(data: str, scale: int = 6, margin: int = 2) -> bytes | None:
"""Generate a QR code PNG and return the raw bytes. """Generate a QR code PNG and return the raw bytes.
Uses qrencode CLI (available on the system via credentials.nix).""" Uses qrencode CLI (available on the system via credentials.nix).
try:
result = subprocess.run( High error-correction (H) is preferred for short payloads. Long
["qrencode", "-o", "-", "-t", "PNG", "-s", str(scale), "-m", str(margin), "-l", "H", data], lndconnect URIs can exceed version-40 capacity at H, so fall back to
capture_output=True, timeout=10, quartile then low ECC — otherwise the Hub shows an empty Zeus QR.
) """
if result.returncode == 0 and result.stdout: for ecc in ("H", "Q", "L"):
return result.stdout try:
except Exception: result = subprocess.run(
pass ["qrencode", "-o", "-", "-t", "PNG", "-s", str(scale), "-m", str(margin), "-l", ecc, data],
capture_output=True, timeout=10,
)
if result.returncode == 0 and result.stdout:
return result.stdout
except Exception:
pass
return None return None
def _generate_qr_svg(data: str, scale: int = 10, margin: int = 4) -> str | None: def _generate_qr_svg(data: str, scale: int = 10, margin: int = 4) -> str | None:
"""Generate a QR code SVG document (resolution-independent, ideal if the """Generate a QR code SVG document (resolution-independent, ideal if the
user wants to embed the QR in a website or print it at any size).""" user wants to embed the QR in a website or print it at any size)."""
try: for ecc in ("H", "Q", "L"):
result = subprocess.run( try:
["qrencode", "-o", "-", "-t", "SVG", "-s", str(scale), "-m", str(margin), "-l", "H", data], result = subprocess.run(
capture_output=True, timeout=10, ["qrencode", "-o", "-", "-t", "SVG", "-s", str(scale), "-m", str(margin), "-l", ecc, data],
) capture_output=True, timeout=10,
if result.returncode == 0 and result.stdout: )
return result.stdout.decode("utf-8", errors="replace") if result.returncode == 0 and result.stdout:
except Exception: return result.stdout.decode("utf-8", errors="replace")
pass except Exception:
pass
return None return None
@@ -1601,15 +1660,6 @@ def _nwc_lnurl_bech32(alias: str, domain: str) -> str:
# ── Update helpers (file-based, no systemctl) ──────────────────── # ── Update helpers (file-based, no systemctl) ────────────────────
def _read_update_status() -> str:
"""Read the status file. Returns RUNNING, SUCCESS, REBOOT_REQUIRED, FAILED, or IDLE."""
try:
with open(UPDATE_STATUS, "r") as f:
return f.read().strip()
except FileNotFoundError:
return "IDLE"
def _write_update_status(status: str): def _write_update_status(status: str):
"""Write to the status file.""" """Write to the status file."""
try: try:
@@ -1619,6 +1669,36 @@ def _write_update_status(status: str):
pass pass
def _read_update_status() -> str:
"""Read and reconcile the persistent update status.
``REBOOT_REQUIRED`` survives Hub/browser restarts before the reboot, but
it is a CLAIM about live NixOS state, not the source of truth: the boot
default (``/nix/var/nix/profiles/system``) versus the running
``/run/current-system``. Re-validating on every read keeps the Hub
correct when the system was updated from a terminal or support session
(which never writes Hub markers), and lets an old marker that predates
the reconciliation feature self-heal instead of demanding reboots
forever. The stale marker file is removed once cleared.
"""
try:
with open(UPDATE_STATUS, "r") as f:
status = f.read().strip()
except FileNotFoundError:
return "IDLE"
effective = effective_update_status(status)
if effective != status:
_write_update_status(effective)
try:
os.remove(UPDATE_GENERATION)
except OSError:
pass
return effective
return status
def _read_log(offset: int = 0) -> tuple[str, int]: def _read_log(offset: int = 0) -> tuple[str, int]:
"""Read the update log file from the given byte offset. """Read the update log file from the given byte offset.
Returns (new_text, new_offset).""" Returns (new_text, new_offset)."""
@@ -1654,6 +1734,9 @@ def _resolve_credential(cred: dict) -> dict | None:
qr_data = _generate_qr_base64(result["value"]) qr_data = _generate_qr_base64(result["value"])
if qr_data: if qr_data:
result["qrcode"] = qr_data result["qrcode"] = qr_data
else:
# Don't hide the URI if we could not render a scannable QR.
qronly = False
if qronly: if qronly:
result["qronly"] = True result["qronly"] = True
return result return result
@@ -1688,6 +1771,9 @@ def _resolve_credential(cred: dict) -> dict | None:
qr_data = _generate_qr_base64(value) qr_data = _generate_qr_base64(value)
if qr_data: if qr_data:
result["qrcode"] = qr_data result["qrcode"] = qr_data
else:
# Don't hide the URI if we could not render a scannable QR.
qronly = False
if qronly: if qronly:
result["qronly"] = True result["qronly"] = True
@@ -2058,14 +2144,24 @@ def _migrate_strip_deprecated_features() -> None:
# ── Feature status helpers ───────────────────────────────────────── # ── Feature status helpers ─────────────────────────────────────────
def _is_feature_enabled_in_config(feature_id: str) -> bool | None: def _is_feature_enabled_in_config(feature_id: str) -> bool | None:
"""Check if a feature's service appears as enabled in the running config.json. """Check whether a feature is enabled in the evaluated Hub configuration.
Returns True/False if found, None if the feature has no mapped service."""
Most features map directly to a systemd service. Modal-only settings are
represented separately in ``config.json``. Returns ``None`` only when no
evaluated state is available.
"""
if feature_id == "btcpay-web": if feature_id == "btcpay-web":
return False # Default off in Node role; only on via explicit hub toggle return False # Default off in Node role; only on via explicit hub toggle
cfg = load_config()
if feature_id == "bitcoin-tor-gossip":
state = cfg.get("feature_states", {}).get(feature_id)
return bool(state) if state is not None else None
unit = FEATURE_SERVICE_MAP.get(feature_id) unit = FEATURE_SERVICE_MAP.get(feature_id)
if unit is None: if unit is None:
return None return None
cfg = load_config()
for svc in cfg.get("services", []): for svc in cfg.get("services", []):
if svc.get("unit") == unit: if svc.get("unit") == unit:
return svc.get("enabled", False) return svc.get("enabled", False)
@@ -2485,6 +2581,10 @@ async def auto_login_redirect(request: Request):
client_ip = request.client.host if request.client else "unknown" client_ip = request.client.host if request.client else "unknown"
if client_ip not in ("127.0.0.1", "::1"): if client_ip not in ("127.0.0.1", "::1"):
raise HTTPException(status_code=403, detail="Forbidden") raise HTTPException(status_code=403, detail="Forbidden")
# An explicit logout must take precedence over the desktop launcher's
# localhost auto-login, including after the Hub window is closed/reopened.
if request.cookies.get(MANUAL_LOGOUT_COOKIE_NAME) == "1":
return RedirectResponse(url="/login", status_code=303)
token = _create_session() token = _create_session()
response = RedirectResponse(url="/", status_code=303) response = RedirectResponse(url="/", status_code=303)
response.set_cookie( response.set_cookie(
@@ -2521,17 +2621,27 @@ async def api_login(req: LoginRequest, request: Request):
samesite="lax", samesite="lax",
secure=False, # LAN-only appliance; no TLS on the Hub port secure=False, # LAN-only appliance; no TLS on the Hub port
) )
# A successful password login explicitly reverses a prior manual logout.
response.delete_cookie(key=MANUAL_LOGOUT_COOKIE_NAME)
return response return response
@app.post("/api/logout") @app.post("/api/logout")
async def api_logout(request: Request): async def api_logout(request: Request):
"""Clear the session cookie and destroy the server-side session.""" """Destroy the session and prevent desktop auto-login until password login."""
token = request.cookies.get(SESSION_COOKIE_NAME) token = request.cookies.get(SESSION_COOKIE_NAME)
if token: if token:
_destroy_session(token) _destroy_session(token)
response = JSONResponse({"ok": True}) response = JSONResponse({"ok": True})
response.delete_cookie(key=SESSION_COOKIE_NAME) response.delete_cookie(key=SESSION_COOKIE_NAME)
response.set_cookie(
key=MANUAL_LOGOUT_COOKIE_NAME,
value="1",
max_age=MANUAL_LOGOUT_MAX_AGE,
httponly=True,
samesite="lax",
secure=False, # LAN-only appliance; no TLS on the Hub port
)
return response return response
@@ -3546,6 +3656,37 @@ async def api_service_detail(unit: str, icon: str | None = None):
"port_requirements": feat_meta.get("port_requirements", []), "port_requirements": feat_meta.get("port_requirements", []),
} }
# Modal-only settings related to this service. These are intentionally not
# rendered as standalone feature cards: the user encounters them in the
# context where their consequences are easiest to understand.
related_features: list[dict] = []
if icon == "bitcoin-core":
related_id = "bitcoin-tor-gossip"
related_meta = next((f for f in FEATURE_REGISTRY if f["id"] == related_id), None)
if related_meta is not None:
if related_id in overrides:
related_enabled = bool(overrides[related_id])
else:
config_state = _is_feature_enabled_in_config(related_id)
related_enabled = bool(config_state) if config_state is not None else False
related_features.append({
"id": related_id,
"name": related_meta["name"],
"description": related_meta["description"],
"details": related_meta.get("details", []),
"category": related_meta["category"],
"enabled": related_enabled,
"available": bool(enabled),
"needs_domain": False,
"domain_configured": True,
"domain_name": None,
"needs_ddns": False,
"extra_fields": [],
"conflicts_with": related_meta.get("conflicts_with", []),
"requires": related_meta.get("requires", []),
"port_requirements": [],
})
service_detail: dict = { service_detail: dict = {
"name": entry.get("name", ""), "name": entry.get("name", ""),
"unit": unit, "unit": unit,
@@ -3568,6 +3709,7 @@ async def api_service_detail(unit: str, icon: str | None = None):
"external_ip": external_ip, "external_ip": external_ip,
"internal_ip": internal_ip, "internal_ip": internal_ip,
"feature": feature_entry, "feature": feature_entry,
"related_features": related_features,
} }
if sync_ibd is not None: if sync_ibd is not None:
service_detail["sync_ibd"] = sync_ibd service_detail["sync_ibd"] = sync_ibd
@@ -3600,6 +3742,9 @@ async def api_network():
# Keep the internal-ip file in sync for credential lookups # Keep the internal-ip file in sync for credential lookups
_save_internal_ip(internal) _save_internal_ip(internal)
_cached_external_ip = external _cached_external_ip = external
# Persist the external IP so other services (e.g. LiveKit) can reuse the
# Hub's detection instead of running their own.
_save_external_ip(external)
return {"internal_ip": internal, "external_ip": external} return {"internal_ip": internal, "external_ip": external}
@@ -3737,9 +3882,15 @@ async def api_ports_health():
@app.get("/api/updates/check") @app.get("/api/updates/check")
async def api_updates_check(): async def api_updates_check():
loop = asyncio.get_event_loop() loop = asyncio.get_event_loop()
status = await loop.run_in_executor(None, _read_update_status)
if status in {"RUNNING", "REBOOT_REQUIRED"}:
# Avoid a slow remote update check when there is already an operation
# the dashboard needs to surface.
return {"available": True, "status": status.lower()}
available = await loop.run_in_executor(None, check_for_updates) available = await loop.run_in_executor(None, check_for_updates)
# None means inconclusive (check failed) — report as available so the UI doesn't block # None means inconclusive (check failed) — report as available so the UI doesn't block
return {"available": available is not False} return {"available": available is not False, "status": status.lower()}
@app.get("/api/ping") @app.get("/api/ping")
@@ -4190,8 +4341,10 @@ async def api_features():
role = load_config().get("role", "server_plus_desktop") role = load_config().get("role", "server_plus_desktop")
allowed_features = ROLE_FEATURES.get(role) allowed_features = ROLE_FEATURES.get(role)
registry = FEATURE_REGISTRY if allowed_features is None else [ registry = [
f for f in FEATURE_REGISTRY if f["id"] in allowed_features f for f in FEATURE_REGISTRY
if not f.get("modal_only")
and (allowed_features is None or f["id"] in allowed_features)
] ]
features = [] features = []
@@ -4265,6 +4418,22 @@ async def api_features_toggle(req: FeatureToggleRequest):
features, nostr_npub, cur_tz, cur_locale = await loop.run_in_executor(None, _read_hub_overrides) features, nostr_npub, cur_tz, cur_locale = await loop.run_in_executor(None, _read_hub_overrides)
if req.enabled: if req.enabled:
# Onion-address advertising is only meaningful while the Bitcoin Core
# service is enabled. The control is shown in that service's modal, but
# enforce the dependency server-side as well.
if req.feature == "bitcoin-tor-gossip":
bitcoin_core_enabled = any(
svc.get("unit") == "bitcoind.service"
and svc.get("icon") == "bitcoin-core"
and bool(svc.get("enabled", False))
for svc in load_config().get("services", [])
)
if not bitcoin_core_enabled:
raise HTTPException(
status_code=400,
detail="Enable the Bitcoin service before advertising its Tor IBD service.",
)
# Element-calling requires matrix domain # Element-calling requires matrix domain
if req.feature == "element-calling": if req.feature == "element-calling":
if not os.path.exists(os.path.join(DOMAINS_DIR, "matrix")): if not os.path.exists(os.path.join(DOMAINS_DIR, "matrix")):
@@ -6068,10 +6237,19 @@ async def _startup_migrate_deprecated_features():
async def _background_domain_reachability_checker(): async def _background_domain_reachability_checker():
"""Periodically curl configured domains and cache reachability results.""" """Periodically curl configured domains and cache reachability results."""
global _cached_external_ip
await asyncio.sleep(_DOMAIN_REACHABILITY_STARTUP_DELAY) await asyncio.sleep(_DOMAIN_REACHABILITY_STARTUP_DELAY)
consecutive_failures = 0 consecutive_failures = 0
while True: while True:
try: try:
# Keep the persisted external IP fresh (dynamic WAN IPs), so
# services like LiveKit can read /var/lib/secrets/external-ip.
loop = asyncio.get_event_loop()
external = await loop.run_in_executor(None, _get_external_ip)
if external != "unavailable":
_cached_external_ip = external
_save_external_ip(external)
cfg = load_config() cfg = load_config()
services = cfg.get("services", []) services = cfg.get("services", [])
@@ -6081,7 +6259,6 @@ async def _background_domain_reachability_checker():
if unit is not None if unit is not None
} }
loop = asyncio.get_event_loop()
overrides, *_ = await loop.run_in_executor(None, _read_hub_overrides) overrides, *_ = await loop.run_in_executor(None, _read_hub_overrides)
domains_to_check: list[str] = [] domains_to_check: list[str] = []
@@ -365,6 +365,45 @@
color: var(--text-dim); color: var(--text-dim);
} }
.svc-detail-option-card {
padding: 16px;
background: rgba(94, 173, 138, 0.06);
border: 1px solid rgba(94, 173, 138, 0.24);
border-radius: 10px;
}
.svc-detail-option-list {
margin: 10px 0 0;
padding-left: 20px;
color: var(--text-secondary);
font-size: 0.84rem;
line-height: 1.55;
}
.svc-detail-option-list li {
margin-bottom: 5px;
}
.svc-detail-option-privacy {
margin-top: 12px;
padding: 10px 12px;
border-left: 3px solid var(--accent-color);
background: rgba(94, 173, 138, 0.08);
border-radius: 6px;
color: var(--text-secondary);
font-size: 0.82rem;
line-height: 1.5;
}
.svc-detail-option-privacy strong {
color: var(--accent-color);
}
.svc-detail-related-feature-btn:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.feature-conflict-warning { .feature-conflict-warning {
margin-top: 8px; margin-top: 8px;
margin-bottom: 8px; margin-bottom: 8px;
@@ -4,11 +4,17 @@
const POLL_INTERVAL_SERVICES = 5000; const POLL_INTERVAL_SERVICES = 5000;
const POLL_INTERVAL_UPDATES = 1800000; const POLL_INTERVAL_UPDATES = 1800000;
const UPDATE_POLL_INTERVAL = 2000; const UPDATE_POLL_INTERVAL = 2000;
// Max consecutive failed rebuild/update status polls before the page gives up // A pending fetch never rejects by itself. Bound every status request so a
// waiting and reloads to re-sync (2s interval → ~2 minutes of failures). // wedged browser connection cannot leave the modal spinning forever.
// A brief Hub restart during activation only causes a handful of failures. const STATUS_POLL_FETCH_TIMEOUT = 15000;
const STATUS_POLL_MAX_FAILURES = 60; // Eight timed-out requests plus the poll interval is a little over two minutes.
// A brief Hub restart or a heavily loaded Nix build remains well inside this.
const STATUS_POLL_MAX_FAILURES = 8;
// Keep verbose Nix output from making textContent updates quadratic and
// freezing the Hub renderer (especially noticeable over RDP).
const UPDATE_VISIBLE_LOG_MAX_CHARS = 250000;
const UPDATE_VISIBLE_LOG_TRIM_CHARS = 200000;
const REBOOT_CHECK_INTERVAL = 5000; const REBOOT_CHECK_INTERVAL = 5000;
const REBOOT_FETCH_TIMEOUT = 12000; const REBOOT_FETCH_TIMEOUT = 12000;
const REBOOT_REQUEST_TIMEOUT = 4000; const REBOOT_REQUEST_TIMEOUT = 4000;
@@ -1,22 +1,14 @@
/* Sovran_SystemsOS Hub — Shared domain-prerequisite instructions. /* Sovran_SystemsOS Hub — Shared domain and router instructions.
SINGLE SOURCE OF TRUTH for the "you need a Njal.la domain + router port This is the single source of truth for the simple setup guidance shown in:
forwarding" guidance that must read identically everywhere it appears:
• First-boot onboarding wizard (Server + Desktop role) • First-boot onboarding for Server + Desktop
— onboarding.js step 3 • Feature setup in the Hub
• Feature-enable domain modal (Node role, and any role) • Domain reconfiguration and troubleshooting
— features.js openDomainSetupModal()
(Lightning Wallet Connections / NWC, BTCPay Server, Haven, …)
• Domain reconfigure / troubleshooting modal
— features.js openDomainReconfigureModal()
Keep these three surfaces word-for-word consistent: always edit this Keep the wording consistent by editing it here. */
file, never fork the wording inline. Plain classic script (no modules) —
both templates load it with a plain <script> tag. */
"use strict"; "use strict";
/* Escape helper local to this file so it is self-contained on both pages. */
function dpEsc(str) { function dpEsc(str) {
return String(str) return String(str)
.replace(/&/g, "&amp;") .replace(/&/g, "&amp;")
@@ -26,105 +18,71 @@ function dpEsc(str) {
.replace(/'/g, "&#39;"); .replace(/'/g, "&#39;");
} }
/* ── "What you'll need" intro ────────────────────────────────────── /* Explain only what the user needs for the step in front of them. */
opts.serviceName — e.g. "Lightning Wallet Connections", or null for
the multi-service (onboarding) wording.
opts.hostExample — e.g. "lightning" → lightning.yourdomain.com */
function renderDomainNeedsHtml(opts) { function renderDomainNeedsHtml(opts) {
opts = opts || {};
var serviceName = opts.serviceName || null; var serviceName = opts.serviceName || null;
var hostExample = dpEsc(opts.hostExample || "myservice"); var purpose = opts.purpose || "";
var html = ""; var html = "";
if (serviceName) { if (purpose === "btcpay") {
html += "<p>To enable <strong>" + dpEsc(serviceName) + "</strong>, you'll need two things first:</p>"; html += "<p><strong>Put your BTCPay Server online</strong></p>";
html += '<ol style="margin:8px 0 0 16px;padding:0;line-height:1.7;">'; html += "<p>Let people donate Bitcoin, pay you, or visit your online store.</p>";
html += "<li><strong>A domain of your own from <a href=\"https://njal.la\" target=\"_blank\" rel=\"noopener noreferrer\" style=\"color:var(--accent-color);\">Njal.la</a></strong> " html += "<p>BTCPay Server needs a domain so people can reach it. "
+ "— privacy-friendly, no personal details required, accepts Bitcoin. " + "Sovran_SystemsOS walks you through getting your domain from "
+ dpEsc(serviceName) + " gets its own hostname: a subdomain (e.g. <code>" + hostExample + ".yourdomain.com</code>) " + '<a href="https://njal.la" target="_blank" rel="noopener noreferrer" style="color:var(--accent-color);">Njal.la</a>'
+ "or a separate domain — your choice. Subdomains are free, and one domain can have many.</li>"; + " and connecting it. Just follow the steps below.</p>";
html += "<li><strong>Access to your router</strong> — you'll forward ports <strong>80</strong> and <strong>443</strong> (TCP) " } else if (serviceName) {
+ "to this computer once. All domain-based services share these two ports; " html += "<p>To make <strong>" + dpEsc(serviceName) + "</strong> available outside your home, it needs a domain.</p>";
+ "they're required for HTTPS and SSL certificates.</li>"; html += "<p>Sovran_SystemsOS walks you through getting your domain from "
html += "</ol>"; + '<a href="https://njal.la" target="_blank" rel="noopener noreferrer" style="color:var(--accent-color);">Njal.la</a>'
+ " and connecting it. Just follow the steps below.</p>";
} else { } else {
html += "<p><strong>Each service below needs two things set up:</strong></p>"; html += "<p>Your domain is the address people use to reach your services on the internet.</p>";
html += '<ol style="margin:8px 0 0 16px;padding:0;line-height:1.7;">'; html += "<p>Sovran_SystemsOS walks you through getting your domain from "
html += "<li><strong>A domain of your own from <a href=\"https://njal.la\" target=\"_blank\" rel=\"noopener noreferrer\" style=\"color:var(--accent-color);\">Njal.la</a></strong> " + '<a href="https://njal.la" target="_blank" rel="noopener noreferrer" style="color:var(--accent-color);">Njal.la</a>'
+ "— privacy-friendly, no personal details required, accepts Bitcoin. " + " and connecting your services. Just follow the steps below.</p>";
+ "Each service gets its own hostname: its own subdomain (e.g. <code>" + hostExample + ".yourdomain.com</code>) "
+ "or a separate domain — your choice. Subdomains are free, and one domain can have many, "
+ "so a single domain can serve every service.</li>";
html += "<li><strong>Access to your router</strong> — you'll forward ports <strong>80</strong> and <strong>443</strong> (TCP) "
+ "to this computer once. All domain-based services share these two ports; "
+ "they're required for HTTPS and SSL certificates.</li>";
html += "</ol>";
} }
return html; return html;
} }
/* ── "How to set it up at Njal.la" steps ─────────────────────────── /* The shortest Njal.la steps that still tell the user exactly what to do. */
opts.hostExample — host part used in the examples (default "call").
opts.pasteHint — where the curl command goes:
"below" (single service) or "next to its service below"
(onboarding, many services). */
function renderNjallaStepsHtml(opts) { function renderNjallaStepsHtml(opts) {
var hostExample = dpEsc((opts && opts.hostExample) || "call"); var hostExample = dpEsc((opts && opts.hostExample) || "call");
var pasteHint = (opts && opts.pasteHint) || "below"; var pasteHint = (opts && opts.pasteHint) || "below";
var html = ""; var html = "";
html += "<p style=\"margin-top:12px;\"><strong>How to set it up at Njal.la:</strong></p>"; html += '<p style="margin-top:12px;"><strong>Get and connect your domain:</strong></p>';
html += '<ol style="margin:8px 0 0 16px;padding:0;line-height:1.7;">'; html += '<ol style="margin:8px 0 0 16px;padding:0;line-height:1.7;">';
html += "<li>Create an account at <a href=\"https://njal.la\" target=\"_blank\" rel=\"noopener noreferrer\" style=\"color:var(--accent-color);\">https://njal.la</a> and buy a domain.</li>"; html += '<li>Open <a href="https://njal.la" target="_blank" rel="noopener noreferrer" style="color:var(--accent-color);">Njal.la</a>, create an account, and get a domain.</li>';
html += "<li>Add a <strong>Dynamic</strong> record for the hostname:" html += "<li>Open your domain and add a <strong>Dynamic</strong> record for this service. "
+ '<ul style="margin:4px 0 0 16px;padding:0;line-height:1.7;">' + "In the <strong>Name</strong> box, enter only the first part of the address. "
+ "<li>In the Njal.la <strong>Name</strong> field, type ONLY the host part — the word before your domain.<br>" + "For <code>" + hostExample + ".yourdomain.com</code>, enter <code>" + hostExample + "</code>. "
+ "(For &quot;" + hostExample + ".yourdomain.com&quot; you&apos;d type just: <code>" + hostExample + "</code>.)<br>" + "If you are using the whole domain, leave the box blank or enter <code>@</code>.</li>";
+ "&#9888; Do NOT type the full domain here — Njal.la adds it automatically.</li>" html += "<li>Copy the update command Njal.la gives you and paste it " + pasteHint + ".</li>";
+ "<li>Dedicating a whole separate domain to this service? Leave the Name field blank or use <code>@</code>.</li>"
+ "</ul>"
+ "</li>";
html += "<li>A Dynamic record has <strong>NO IP field</strong> — you don&apos;t enter an IP anywhere. "
+ "It auto-fills once Sovran_SystemsOS runs the update command (on save, and again after every reboot).</li>";
html += "<li>Njal.la gives you a curl command, e.g.:<br>"
+ '<code style="font-size:0.8em;">curl &quot;https://njal.la/update/?h=' + hostExample + '.yourdomain.com&amp;k=abc123&amp;auto&quot;</code><br>'
+ "Copy it and paste it " + pasteHint + ".</li>";
html += "</ol>"; html += "</ol>";
return html; return html;
} }
/* ── "One router task" port-forwarding box ───────────────────────── /* One router task shared by all normal domain-based services. */
opts.internalIp — LAN IP string, or empty/null for generic wording.
opts.plural — true for multi-service (onboarding) wording.
opts.includeSsh — also mention port 22 for SSH (onboarding).
opts.extraNote — extra sentence appended at the end (optional). */
function renderRouterPortsHtml(opts) { function renderRouterPortsHtml(opts) {
opts = opts || {}; opts = opts || {};
var ipPart = opts.internalIp var ipPart = opts.internalIp
? " to this computer&rsquo;s internal IP <strong>" + dpEsc(opts.internalIp) + "</strong>" ? " to this computer at <strong>" + dpEsc(opts.internalIp) + "</strong>"
: " to this computer&rsquo;s internal IP"; : " to this computer";
var serviceWord = opts.plural ? "services" : "service";
var html = ""; var html = "";
html += "🔌 <strong>One router task:</strong> in your router&rsquo;s <strong>port forwarding</strong> settings, " html += "🔌 <strong>One router task:</strong> in your router&rsquo;s <strong>Port Forwarding</strong> settings, "
+ "forward port <strong>80 (TCP)</strong> and port <strong>443 (TCP)</strong>" + "forward <strong>80 (TCP)</strong> and <strong>443 (TCP)</strong>"
+ ipPart + ". Use the <strong>same number for the internal and external port</strong>. " + ipPart + ". If your router asks for outside and inside port numbers, use the same number for both. "
+ "This only needs to be done once — all domain services share these ports — " + "You only need to do this once. All your services share these two ports.";
+ "but HTTPS and SSL certificates won&rsquo;t work without them, so your " + serviceWord + " "
+ "can&rsquo;t be reached from outside your home network. "
+ "You&rsquo;ll need normal access to your router&rsquo;s settings with working port forwarding — "
+ "if your ISP blocks it (e.g. CGNAT), domain-based services can&rsquo;t be reached from the internet. ";
if (opts.includeSsh) {
html += "Add port <strong>22 (TCP)</strong> as well if you want remote SSH access. ";
}
if (opts.extraNote) { if (opts.extraNote) {
html += dpEsc(opts.extraNote); html += " " + dpEsc(opts.extraNote);
} }
return html; return html;
} }
/* ── Async helper: fill a router-box container with the internal IP ── /* Show generic wording immediately, then add the computer's address when found. */
Renders generic text immediately, then upgrades to the concrete LAN IP
if /api/network provides one. Best-effort — never blocks the UI. */
function renderRouterPortsBox(elId, opts) { function renderRouterPortsBox(elId, opts) {
var el = document.getElementById(elId); var el = document.getElementById(elId);
if (!el) return; if (!el) return;
@@ -142,5 +100,5 @@ function renderRouterPortsBox(elId, opts) {
target.innerHTML = renderRouterPortsHtml(next); target.innerHTML = renderRouterPortsHtml(next);
} }
}) })
.catch(function() { /* generic wording already shown — fine */ }); .catch(function() { /* Generic wording is already shown. */ });
} }
@@ -6,6 +6,16 @@
if ($btnCloseModal) $btnCloseModal.addEventListener("click", closeUpdateModal); if ($btnCloseModal) $btnCloseModal.addEventListener("click", closeUpdateModal);
if ($btnReboot) $btnReboot.addEventListener("click", doReboot); if ($btnReboot) $btnReboot.addEventListener("click", doReboot);
if ($btnSave) $btnSave.addEventListener("click", saveErrorReport); if ($btnSave) $btnSave.addEventListener("click", saveErrorReport);
if ($btnRetryUpdate) $btnRetryUpdate.addEventListener("click", retryUpdateStatus);
// Browser timers and requests may be suspended while an RDP session/tab is in
// the background. Reconcile immediately when the user returns instead of
// waiting for the next interval.
window.addEventListener("focus", resumeUpdateStatusAfterInterruption);
window.addEventListener("online", resumeUpdateStatusAfterInterruption);
document.addEventListener("visibilitychange", function() {
if (document.visibilityState === "visible") resumeUpdateStatusAfterInterruption();
});
if ($credsCloseBtn) $credsCloseBtn.addEventListener("click", closeCredsModal); if ($credsCloseBtn) $credsCloseBtn.addEventListener("click", closeCredsModal);
if ($supportCloseBtn) $supportCloseBtn.addEventListener("click", closeSupportModal); if ($supportCloseBtn) $supportCloseBtn.addEventListener("click", closeSupportModal);
@@ -248,6 +258,11 @@ async function init() {
setInterval(checkUpdates, POLL_INTERVAL_UPDATES); setInterval(checkUpdates, POLL_INTERVAL_UPDATES);
loadAutolaunchToggle(); loadAutolaunchToggle();
} }
// If the page was reloaded or the RDP/browser session resumed during an
// update, reopen the modal from the persisted backend state. This also
// surfaces a completed update that is waiting for its activation reboot.
await restoreUpdateModalIfNeeded();
} }
document.addEventListener("DOMContentLoaded", init); document.addEventListener("DOMContentLoaded", init);
+21 -15
View File
@@ -60,6 +60,7 @@ function openDomainSetupModal(feat, onSaved) {
if ($domainSetupTitle) $domainSetupTitle.textContent = "🌐 Domain Setup — " + feat.name; if ($domainSetupTitle) $domainSetupTitle.textContent = "🌐 Domain Setup — " + feat.name;
var isWalletConnections = (feat.id === "nwc-wallets" || feat.domain_name === "lightning"); var isWalletConnections = (feat.id === "nwc-wallets" || feat.domain_name === "lightning");
var isBtcpay = feat.id === "btcpay-web";
var npubField = ""; var npubField = "";
if (feat.id === "haven") { if (feat.id === "haven") {
@@ -77,30 +78,30 @@ function openDomainSetupModal(feat, onSaved) {
var nwcWarning = isWalletConnections var nwcWarning = isWalletConnections
? '<div class="domain-nwc-warning">' + ? '<div class="domain-nwc-warning">' +
'<strong>⚠ Lightning Wallet Connections requires its own unique hostname.</strong> ' + '<strong>Lightning Wallet Connections needs its own address.</strong> ' +
'Use a new subdomain such as <code>lightning.yourdomain.com</code>, or a separate domain. ' + 'Use a new address such as <code>lightning.yourdomain.com</code>. Do not use an address already connected to another service.' +
'Do not reuse a domain already assigned to Matrix, Nextcloud, WordPress, BTCPay Server, Vaultwarden, Haven, or another Caddy site.' +
'</div>' '</div>'
: ''; : '';
var domainPlaceholder = isWalletConnections ? "lightning.yourdomain.com" : "myservice.example.com"; var domainPlaceholder = isWalletConnections ? "lightning.yourdomain.com" : (isBtcpay ? "btcpay.yourdomain.com" : "myservice.example.com");
var domainLabelExample = isWalletConnections ? "lightning.yourdomain.com" : "call.yourdomain.com"; var domainLabelExample = isWalletConnections ? "lightning.yourdomain.com" : (isBtcpay ? "btcpay.yourdomain.com" : "call.yourdomain.com");
// Shared instructions (single source of truth: static/js/domain-prereqs.js) — // Shared instructions (single source of truth: static/js/domain-prereqs.js) —
// identical wording to the Server + Desktop onboarding wizard and every other // identical wording to the Server + Desktop onboarding wizard and every other
// domain-based feature, regardless of role (Node / Desktop / Server+Desktop). // domain-based feature, regardless of role (Node / Desktop / Server+Desktop).
var hostExample = isWalletConnections ? "lightning" : "call"; var hostExample = isWalletConnections ? "lightning" : (isBtcpay ? "btcpay" : "call");
var purpose = isBtcpay ? "btcpay" : "";
$domainSetupBody.innerHTML = $domainSetupBody.innerHTML =
'<div class="domain-setup-intro">' + '<div class="domain-setup-intro">' +
nwcWarning + nwcWarning +
renderDomainNeedsHtml({ serviceName: feat.name, hostExample: hostExample }) + renderDomainNeedsHtml({ serviceName: feat.name, hostExample: hostExample, purpose: purpose }) +
renderNjallaStepsHtml({ hostExample: hostExample, pasteHint: "below" }) + renderNjallaStepsHtml({ hostExample: hostExample, pasteHint: "below" }) +
'<div class="onboarding-port-warn" id="domain-router-box" style="margin-top:12px;"></div>' + '<div class="onboarding-port-warn" id="domain-router-box" style="margin-top:12px;"></div>' +
'<p style="margin-top:10px;">Below, enter the full domain for this service — a subdomain (e.g. ' + domainLabelExample + ') or a separate domain — and paste its curl command.</p>' + '<p style="margin-top:10px;">Enter the address for this service and paste the update command from Njal.la.</p>' +
'</div>' + '</div>' +
'<div class="domain-field-group"><label class="domain-field-label" for="domain-subdomain-input">Service domain (e.g. ' + domainLabelExample + '):</label><input class="domain-field-input" type="text" id="domain-subdomain-input" placeholder="' + domainPlaceholder + '" /></div>' + '<div class="domain-field-group"><label class="domain-field-label" for="domain-subdomain-input">Service address (e.g. ' + domainLabelExample + '):</label><input class="domain-field-input" type="text" id="domain-subdomain-input" placeholder="' + domainPlaceholder + '" /></div>' +
'<div class="domain-field-group"><label class="domain-field-label" for="domain-ddns-input">Njal.la Dynamic DNS Update Command:</label><input class="domain-field-input" type="text" id="domain-ddns-input" placeholder="curl &quot;https://njal.la/update/?h=' + domainPlaceholder + '&amp;k=abc123&amp;auto&quot;" /><p class="domain-field-hint">ℹ Paste the full curl command from your Njal.la dashboard\'s Dynamic record</p></div>' + '<div class="domain-field-group"><label class="domain-field-label" for="domain-ddns-input">Njal.la Update Command:</label><input class="domain-field-input" type="text" id="domain-ddns-input" placeholder="curl &quot;https://njal.la/update/?h=' + domainPlaceholder + '&amp;k=abc123&amp;auto&quot;" /><p class="domain-field-hint">Paste the update command from Njal.la</p></div>' +
npubField + npubField +
'<div class="domain-field-actions"><button class="btn btn-close-modal" id="domain-setup-cancel-btn">Cancel</button><button class="btn btn-primary" id="domain-setup-save-btn">Save &amp; Enable</button></div>'; '<div class="domain-field-actions"><button class="btn btn-close-modal" id="domain-setup-cancel-btn">Cancel</button><button class="btn btn-primary" id="domain-setup-save-btn">Save &amp; Enable</button></div>';
@@ -169,9 +170,8 @@ function openDomainReconfigureModal(feat, existingDomain, onSaved) {
var nwcWarning = isWalletConnections var nwcWarning = isWalletConnections
? '<div class="domain-nwc-warning">' + ? '<div class="domain-nwc-warning">' +
'<strong>⚠ Lightning Wallet Connections requires its own unique hostname.</strong> ' + '<strong>Lightning Wallet Connections needs its own address.</strong> ' +
'Use a new subdomain such as <code>lightning.yourdomain.com</code>, or a separate domain. ' + 'Use a new address such as <code>lightning.yourdomain.com</code>. Do not use an address already connected to another service.' +
'Do not reuse a domain already assigned to Matrix, Nextcloud, WordPress, BTCPay Server, Vaultwarden, Haven, or another Caddy site.' +
'</div>' '</div>'
: ''; : '';
@@ -342,8 +342,11 @@ async function performFeatureToggle(featId, enabled, extra) {
function handleFeatureToggle(feat, newEnabled) { function handleFeatureToggle(feat, newEnabled) {
if (!newEnabled) { if (!newEnabled) {
// Disable: ask confirmation // Disable: ask confirmation
var disableMessage = (feat.id === "bitcoin-tor-gossip")
? "This will stop advertising your Bitcoin Core onion address to other peers. Nodes that already know the address can still connect through Tor, and no clearnet port will be opened. The system will rebuild. Continue?"
: "This will disable " + feat.name + ". The system will rebuild. Continue?";
openFeatureConfirm( openFeatureConfirm(
"This will disable " + feat.name + ". The system will rebuild. Continue?", disableMessage,
function() { performFeatureToggle(feat.id, false, {}); } function() { performFeatureToggle(feat.id, false, {}); }
); );
return; return;
@@ -403,7 +406,10 @@ function handleFeatureToggle(feat, newEnabled) {
openPortRequirementsModal(feat.name, ports, proceedAfterPortCheck); openPortRequirementsModal(feat.name, ports, proceedAfterPortCheck);
} }
if (conflictNames.length > 0) { if (feat.id === "bitcoin-tor-gossip") {
var torGossipConfirmMsg = "This will advertise your Bitcoin Core .onion P2P address through Bitcoin peer gossip. More Tor-capable nodes may discover your node and request historical blocks during IBD, which can use significant upload bandwidth. Your home IP remains hidden and no clearnet port or router forwarding is opened. Continue?";
openFeatureConfirm(torGossipConfirmMsg, proceedAfterConflictCheck);
} else if (conflictNames.length > 0) {
openFeatureConfirm("This will disable " + conflictNames.join(", ") + ". Continue?", proceedAfterConflictCheck); openFeatureConfirm("This will disable " + conflictNames.join(", ") + ". Continue?", proceedAfterConflictCheck);
} else { } else {
proceedAfterConflictCheck(); proceedAfterConflictCheck();
@@ -111,8 +111,19 @@ function formatDuration(seconds) {
// ── Fetch wrappers ──────────────────────────────────────────────── // ── Fetch wrappers ────────────────────────────────────────────────
// Avoid issuing multiple redirects when several startup requests discover an
// expired session at the same time.
let _authRedirectInProgress = false;
async function apiFetch(path, options) { async function apiFetch(path, options) {
const res = await fetch(path, options || {}); const res = await fetch(path, options || {});
if (res.status === 401) {
if (!_authRedirectInProgress) {
_authRedirectInProgress = true;
window.location.replace("/login");
}
throw new Error("Unauthenticated");
}
if (!res.ok) { if (!res.ok) {
let detail = res.status + " " + res.statusText; let detail = res.status + " " + res.statusText;
try { try {
@@ -133,3 +144,22 @@ async function apiFetch(path, options) {
} }
return res.json(); return res.json();
} }
async function apiFetchWithTimeout(path, options, timeoutMs) {
var controller = new AbortController();
var fetchOptions = Object.assign({}, options || {});
fetchOptions.signal = controller.signal;
var timer = setTimeout(function() { controller.abort(); }, timeoutMs);
try {
return await apiFetch(path, fetchOptions);
} catch (err) {
if (controller.signal.aborted) {
var timeoutError = new Error("Request timed out");
timeoutError.name = "TimeoutError";
throw timeoutError;
}
throw err;
} finally {
clearTimeout(timer);
}
}
+13 -6
View File
@@ -8,6 +8,7 @@ function openRebuildModal() {
_rebuildLogOffset = 0; _rebuildLogOffset = 0;
_rebuildServerDown = false; _rebuildServerDown = false;
_rebuildFinished = false; _rebuildFinished = false;
_rebuildPollInFlight = false;
_rebuildPollFailures = 0; _rebuildPollFailures = 0;
if ($rebuildLog) { $rebuildLog.textContent = ""; $rebuildLog.style.display = "none"; } if ($rebuildLog) { $rebuildLog.textContent = ""; $rebuildLog.style.display = "none"; }
var action = _rebuildIsEnabling ? "Enabling" : "Disabling"; var action = _rebuildIsEnabling ? "Enabling" : "Disabling";
@@ -34,6 +35,7 @@ function appendRebuildLog(text) {
} }
function startRebuildPoll() { function startRebuildPoll() {
if (_rebuildPollTimer) clearInterval(_rebuildPollTimer);
pollRebuildStatus(); pollRebuildStatus();
_rebuildPollTimer = setInterval(pollRebuildStatus, UPDATE_POLL_INTERVAL); _rebuildPollTimer = setInterval(pollRebuildStatus, UPDATE_POLL_INTERVAL);
} }
@@ -43,9 +45,14 @@ function stopRebuildPoll() {
} }
async function pollRebuildStatus() { async function pollRebuildStatus() {
if (_rebuildFinished) return; if (_rebuildFinished || _rebuildPollInFlight) return;
_rebuildPollInFlight = true;
try { try {
var data = await apiFetch("/api/rebuild/status?offset=" + _rebuildLogOffset); var data = await apiFetchWithTimeout(
"/api/rebuild/status?offset=" + _rebuildLogOffset,
{ cache: "no-store" },
STATUS_POLL_FETCH_TIMEOUT
);
_rebuildPollFailures = 0; _rebuildPollFailures = 0;
if (_rebuildServerDown) { _rebuildServerDown = false; } if (_rebuildServerDown) { _rebuildServerDown = false; }
if (data.log) appendRebuildLog(data.log); if (data.log) appendRebuildLog(data.log);
@@ -61,10 +68,8 @@ async function pollRebuildStatus() {
} catch (err) { } catch (err) {
_rebuildPollFailures += 1; _rebuildPollFailures += 1;
// The Hub restarts itself during activation, which briefly drops this poll. // The Hub restarts itself during activation, which briefly drops this poll.
// If polling stays broken long past a normal restart, the page's session // If polling stays broken long past a normal restart, reload to
// almost certainly no longer matches the server (e.g. the Hub restarted // re-authenticate and show the resulting feature state.
// and sessions were not recovered). Reload to re-authenticate and show
// the real feature state instead of spinning forever.
if (_rebuildPollFailures >= STATUS_POLL_MAX_FAILURES) { if (_rebuildPollFailures >= STATUS_POLL_MAX_FAILURES) {
_rebuildFinished = true; _rebuildFinished = true;
stopRebuildPoll(); stopRebuildPoll();
@@ -72,6 +77,8 @@ async function pollRebuildStatus() {
return; return;
} }
if (!_rebuildServerDown) { _rebuildServerDown = true; if ($rebuildStatus) $rebuildStatus.textContent = "Applying changes…"; } if (!_rebuildServerDown) { _rebuildServerDown = true; if ($rebuildStatus) $rebuildStatus.textContent = "Applying changes…"; }
} finally {
_rebuildPollInFlight = false;
} }
} }
@@ -11,9 +11,9 @@ function _getZeusConnectGuideHtml() {
'<div class="nwc-connect-step"><div class="nwc-step-num">2</div><div>Open Zeus and open the <strong>Wallets</strong> screen.</div></div>' + '<div class="nwc-connect-step"><div class="nwc-step-num">2</div><div>Open Zeus and open the <strong>Wallets</strong> screen.</div></div>' +
'<div class="nwc-connect-step"><div class="nwc-step-num">3</div><div>Tap the <strong>+ (Add Wallet)</strong> button in the top-right corner.</div></div>' + '<div class="nwc-connect-step"><div class="nwc-step-num">3</div><div>Tap the <strong>+ (Add Wallet)</strong> button in the top-right corner.</div></div>' +
'<div class="nwc-connect-step"><div class="nwc-step-num">4</div><div>On <strong>Wallet Configuration</strong>, tap the <strong>scan icon</strong> in the top-right corner, then scan the QR code above.</div></div>' + '<div class="nwc-connect-step"><div class="nwc-step-num">4</div><div>On <strong>Wallet Configuration</strong>, tap the <strong>scan icon</strong> in the top-right corner, then scan the QR code above.</div></div>' +
'<div class="nwc-connect-step"><div class="nwc-step-num">5</div><div>Zeus detects the LND REST QR and fills in the connection details. Review them, then tap <strong>Save Wallet Config</strong>.</div></div>' + '<div class="nwc-connect-step"><div class="nwc-step-num">5</div><div>Zeus detects the LND REST QR and fills in the connection details. Turn <strong>Use Tor</strong> on (the host is a .onion address), then tap <strong>Save Wallet Config</strong>.</div></div>' +
'</div>' + '</div>' +
'<div class="nwc-connect-note"><strong>💡 Note:</strong> This is <em>not</em> the same as the NWC pairing QR shown in Lightning Wallet Connections — that gives your wallet sandboxed, limited access for everyday spending. LND REST connects Zeus directly to your node for full admin control.</div>' + '<div class="nwc-connect-note"><strong>💡 Note:</strong> This is <em>not</em> the same as the NWC pairing QR shown in Lightning Wallet Connections — that gives your wallet sandboxed, limited access for everyday spending. LND REST connects Zeus directly to your node for full admin control. The QR uses your dedicated LND REST Tor address (no TLS cert) so Zeus can scan and connect over Tor.</div>' +
'</div>'; '</div>';
} }
@@ -918,6 +918,54 @@ async function openServiceDetailModal(unit, name, icon) {
'</div>'); '</div>');
} }
// Section G: Contextual feature options. The Tor IBD advertising control is
// deliberately shown only inside the Bitcoin Core modal so its bandwidth
// and privacy implications are explained before the user enables it.
var relatedFeatures = Array.isArray(data.related_features) ? data.related_features : [];
relatedFeatures.forEach(function(optionFeat) {
// Keep the shared feature state current for the standard rebuild flow.
if (!_featuresData) {
_featuresData = { features: [optionFeat], ssl_email_configured: false };
} else {
var optionIndex = _featuresData.features.findIndex(function(f) { return f.id === optionFeat.id; });
if (optionIndex >= 0) _featuresData.features[optionIndex] = optionFeat;
else _featuresData.features.push(optionFeat);
}
var detailsHtml = "";
if (Array.isArray(optionFeat.details) && optionFeat.details.length > 0) {
detailsHtml = '<ul class="svc-detail-option-list">' +
optionFeat.details.map(function(detail) {
return '<li>' + escHtml(detail) + '</li>';
}).join("") +
'</ul>';
}
var optionAvailable = optionFeat.available !== false;
var optionStatusLabel = optionFeat.enabled ? "Advertising enabled \u2713" : "Not advertised";
var optionStatusCls = optionFeat.enabled ? "addon-status--on" : "addon-status--off";
var optionButtonLabel = optionFeat.enabled ? "Stop Advertising" : "Advertise Onion Address";
var optionButtonCls = optionFeat.enabled ? "btn btn-close-modal" : "btn btn-primary";
if (!optionAvailable) {
optionStatusLabel = "Bitcoin Core is not enabled";
optionButtonLabel = "Enable Bitcoin Core First";
optionButtonCls = "btn btn-close-modal";
}
addSetup('<div class="svc-detail-section svc-detail-option-card">' +
'<div class="svc-detail-section-title">Tor IBD Service Advertising</div>' +
'<p class="svc-detail-desc">' + escHtml(optionFeat.description || "") + '</p>' +
detailsHtml +
'<div class="svc-detail-option-privacy">' +
'<strong>Tor-only:</strong> This setting advertises the onion service. It does not open a clearnet port, expose your home IP address, or require router port forwarding.' +
'</div>' +
'<div class="svc-detail-addon-row">' +
'<span class="svc-detail-addon-status ' + optionStatusCls + '">' + escHtml(optionStatusLabel) + '</span>' +
'<button class="' + optionButtonCls + ' svc-detail-related-feature-btn" data-feature-id="' + escHtml(optionFeat.id) + '"' + (!optionAvailable ? ' disabled' : '') + '>' + escHtml(optionButtonLabel) + '</button>' +
'</div>' +
'</div>');
});
if ((effectiveEnabled || data.enabled) && unit !== "phpfpm-nextcloud.service" && unit !== "phpfpm-wordpress.service") { if ((effectiveEnabled || data.enabled) && unit !== "phpfpm-nextcloud.service" && unit !== "phpfpm-wordpress.service") {
addSetup('<div class="svc-detail-section svc-detail-restart-section">' + addSetup('<div class="svc-detail-section svc-detail-restart-section">' +
'<div class="svc-detail-section-title">Troubleshooting</div>' + '<div class="svc-detail-section-title">Troubleshooting</div>' +
@@ -978,6 +1026,18 @@ async function openServiceDetailModal(unit, name, icon) {
} }
} }
var relatedFeatureButtons = $credsBody.querySelectorAll(".svc-detail-related-feature-btn");
relatedFeatureButtons.forEach(function(button) {
button.addEventListener("click", function() {
if (button.disabled) return;
var featureId = button.getAttribute("data-feature-id");
var relatedFeat = relatedFeatures.find(function(f) { return f.id === featureId; });
if (!relatedFeat) return;
closeCredsModal();
handleFeatureToggle(relatedFeat, !relatedFeat.enabled);
});
});
var restartBtn = document.getElementById("svc-detail-restart-btn"); var restartBtn = document.getElementById("svc-detail-restart-btn");
var restartResult = document.getElementById("svc-detail-restart-result"); var restartResult = document.getElementById("svc-detail-restart-result");
if (restartBtn && restartResult) { if (restartBtn && restartResult) {
@@ -6,9 +6,12 @@ let _servicesCache = [];
let _categoryLabels = {}; let _categoryLabels = {};
let _updateLog = ""; let _updateLog = "";
let _updatePollTimer = null; let _updatePollTimer = null;
let _updatePollInFlight = false;
let _updateLogOffset = 0; let _updateLogOffset = 0;
let _updateVisibleLogChars = 0;
let _serverWasDown = false; let _serverWasDown = false;
let _updateFinished = false; let _updateFinished = false;
let _updateStatusUnavailable = false;
let _updatePollFailures = 0; // consecutive failed update-status polls let _updatePollFailures = 0; // consecutive failed update-status polls
let _supportTimerInt = null; let _supportTimerInt = null;
let _supportEnabledAt = null; let _supportEnabledAt = null;
@@ -24,6 +27,7 @@ let _featuresData = null;
let _rebuildLog = ""; let _rebuildLog = "";
let _rebuildLogOffset = 0; let _rebuildLogOffset = 0;
let _rebuildPollTimer = null; let _rebuildPollTimer = null;
let _rebuildPollInFlight = false;
let _rebuildFinished = false; let _rebuildFinished = false;
let _rebuildServerDown = false; let _rebuildServerDown = false;
let _rebuildPollFailures = 0; // consecutive failed rebuild-status polls let _rebuildPollFailures = 0; // consecutive failed rebuild-status polls
@@ -48,6 +52,7 @@ const $modalStatus = document.getElementById("modal-status");
const $modalLog = document.getElementById("modal-log"); const $modalLog = document.getElementById("modal-log");
const $btnReboot = document.getElementById("btn-reboot"); const $btnReboot = document.getElementById("btn-reboot");
const $btnSave = document.getElementById("btn-save-report"); const $btnSave = document.getElementById("btn-save-report");
const $btnRetryUpdate = document.getElementById("btn-retry-update-status");
const $btnCloseModal = document.getElementById("btn-close-modal"); const $btnCloseModal = document.getElementById("btn-close-modal");
const $rebootOverlay = document.getElementById("reboot-overlay"); const $rebootOverlay = document.getElementById("reboot-overlay");
+10 -1
View File
@@ -271,10 +271,19 @@ async function checkUpdates() {
try { try {
var data = await apiFetch("/api/updates/check"); var data = await apiFetch("/api/updates/check");
var hasUpdates = !!data.available; var hasUpdates = !!data.available;
var updateStatus = data.status || "idle";
var sidebarUpdateBtn = document.getElementById("sidebar-btn-update"); var sidebarUpdateBtn = document.getElementById("sidebar-btn-update");
var sidebarUpdateHint = document.getElementById("sidebar-update-hint"); var sidebarUpdateHint = document.getElementById("sidebar-update-hint");
if (sidebarUpdateBtn) { if (sidebarUpdateBtn) {
if (hasUpdates) { if (updateStatus === "reboot_required") {
sidebarUpdateBtn.style.borderColor = "#e5a50a";
sidebarUpdateBtn.style.backgroundColor = "rgba(229, 165, 10, 0.10)";
if (sidebarUpdateHint) sidebarUpdateHint.textContent = "Restart required";
} else if (updateStatus === "running") {
sidebarUpdateBtn.style.borderColor = "#3584e4";
sidebarUpdateBtn.style.backgroundColor = "rgba(53, 132, 228, 0.10)";
if (sidebarUpdateHint) sidebarUpdateHint.textContent = "Update in progress…";
} else if (hasUpdates) {
sidebarUpdateBtn.style.borderColor = "#2ec27e"; sidebarUpdateBtn.style.borderColor = "#2ec27e";
sidebarUpdateBtn.style.backgroundColor = "rgba(46, 194, 126, 0.08)"; sidebarUpdateBtn.style.backgroundColor = "rgba(46, 194, 126, 0.08)";
if (sidebarUpdateHint) sidebarUpdateHint.textContent = "Updates available!"; if (sidebarUpdateHint) sidebarUpdateHint.textContent = "Updates available!";
+163 -27
View File
@@ -2,20 +2,45 @@
// ── Update modal ────────────────────────────────────────────────── // ── Update modal ──────────────────────────────────────────────────
function openUpdateModal() { async function openUpdateModal() {
if (!$modal) return; if (!$modal) return;
apiFetch("/api/updates/check")
// Reattach before checking for new updates. This makes a browser reload,
// RDP reconnect, or suspended tab recover the authoritative systemd-backed
// state instead of starting over or claiming the system is merely up to date.
try {
var current = await apiFetchWithTimeout(
"/api/updates/status?offset=0",
{ cache: "no-store" },
STATUS_POLL_FETCH_TIMEOUT
);
if (current.running || current.result === "reboot_required") {
showExistingUpdate(current);
return;
}
} catch (_) {
// The normal start path below has its own visible error handling.
}
apiFetchWithTimeout(
"/api/updates/check",
{ cache: "no-store" },
STATUS_POLL_FETCH_TIMEOUT
)
.then(function(data) { .then(function(data) {
if (!data.available) { if (!data.available) {
stopUpdatePoll(); stopUpdatePoll();
_updateLog = ""; _updateLog = "";
_updateLogOffset = 0; _updateLogOffset = 0;
_updateVisibleLogChars = 0;
_updateFinished = true; _updateFinished = true;
_updateStatusUnavailable = false;
if ($modalLog) $modalLog.textContent = ""; if ($modalLog) $modalLog.textContent = "";
if ($modalStatus) $modalStatus.textContent = "✓ System is already up to date"; if ($modalStatus) $modalStatus.textContent = "✓ System is already up to date";
if ($modalSpinner) $modalSpinner.classList.remove("spinning"); if ($modalSpinner) $modalSpinner.classList.remove("spinning");
if ($btnReboot) $btnReboot.style.display = "none"; if ($btnReboot) $btnReboot.style.display = "none";
if ($btnSave) $btnSave.style.display = "none"; if ($btnSave) $btnSave.style.display = "none";
if ($btnRetryUpdate) $btnRetryUpdate.style.display = "none";
if ($btnCloseModal) $btnCloseModal.disabled = false; if ($btnCloseModal) $btnCloseModal.disabled = false;
$modal.classList.add("open"); $modal.classList.add("open");
return; return;
@@ -27,23 +52,69 @@ function openUpdateModal() {
}); });
} }
function _doOpenUpdateModal() { function prepareUpdateModal() {
if (!$modal) return; if (!$modal) return;
stopUpdatePoll();
_updateLog = ""; _updateLog = "";
_updateLogOffset = 0; _updateLogOffset = 0;
_updateVisibleLogChars = 0;
_updatePollInFlight = false;
_serverWasDown = false; _serverWasDown = false;
_updateFinished = false; _updateFinished = false;
_updateStatusUnavailable = false;
_updatePollFailures = 0; _updatePollFailures = 0;
if ($modalLog) $modalLog.textContent = ""; if ($modalLog) $modalLog.textContent = "";
if ($modalStatus) $modalStatus.textContent = "Starting update…"; if ($modalStatus) $modalStatus.textContent = "Starting update…";
if ($modalSpinner) $modalSpinner.classList.add("spinning"); if ($modalSpinner) $modalSpinner.classList.add("spinning");
if ($btnReboot) $btnReboot.style.display = "none"; if ($btnReboot) $btnReboot.style.display = "none";
if ($btnSave) $btnSave.style.display = "none"; if ($btnSave) $btnSave.style.display = "none";
if ($btnRetryUpdate) $btnRetryUpdate.style.display = "none";
if ($btnCloseModal) $btnCloseModal.disabled = true; if ($btnCloseModal) $btnCloseModal.disabled = true;
$modal.classList.add("open"); $modal.classList.add("open");
}
function _doOpenUpdateModal() {
prepareUpdateModal();
startUpdate(); startUpdate();
} }
function showExistingUpdate(data) {
prepareUpdateModal();
if (data.log) appendLog(data.log);
_updateLogOffset = Number(data.offset) || 0;
if (data.running) {
if ($modalStatus) $modalStatus.textContent = "Updating…";
startUpdatePoll();
return;
}
_updateFinished = true;
if (data.result === "reboot_required") {
onUpdateDone("reboot_required");
} else if (data.result === "success") {
onUpdateDone(true);
} else {
onUpdateDone(false);
}
}
async function restoreUpdateModalIfNeeded() {
if (!$modal || $modal.classList.contains("open")) return;
try {
var data = await apiFetchWithTimeout(
"/api/updates/status?offset=0",
{ cache: "no-store" },
STATUS_POLL_FETCH_TIMEOUT
);
if (data.running || data.result === "reboot_required") {
showExistingUpdate(data);
}
} catch (_) {
// Dashboard startup must remain usable when status cannot be reached.
}
}
function closeUpdateModal() { function closeUpdateModal() {
if (!$modal) return; if (!$modal) return;
$modal.classList.remove("open"); $modal.classList.remove("open");
@@ -53,21 +124,36 @@ function closeUpdateModal() {
function appendLog(text) { function appendLog(text) {
if (!text) return; if (!text) return;
_updateLog += text; _updateLog += text;
if ($modalLog) { $modalLog.textContent += text; $modalLog.scrollTop = $modalLog.scrollHeight; } if ($modalLog) {
// Appending a text node avoids reparsing/replacing the complete log on
// every two-second poll. Trim only occasionally once the visible log is
// large; the complete _updateLog remains available for error reports.
if (_updateVisibleLogChars + text.length > UPDATE_VISIBLE_LOG_MAX_CHARS) {
var tail = _updateLog.slice(-UPDATE_VISIBLE_LOG_TRIM_CHARS);
var notice = "[Earlier update output hidden from this view; it remains in the saved report.]\n\n";
$modalLog.textContent = notice + tail;
_updateVisibleLogChars = notice.length + tail.length;
} else {
$modalLog.appendChild(document.createTextNode(text));
_updateVisibleLogChars += text.length;
}
$modalLog.scrollTop = $modalLog.scrollHeight;
}
} }
function startUpdate() { function startUpdate() {
fetch("/api/updates/run", { method: "POST" }) apiFetchWithTimeout(
.then(function(response) { "/api/updates/run",
if (!response.ok) return response.text().then(function(t) { throw new Error(t); }); { method: "POST" },
return response.json(); STATUS_POLL_FETCH_TIMEOUT * 2
}) )
.then(function(data) { .then(function(data) {
if (data.status === "no_updates") { if (data.status === "no_updates") {
if ($modalStatus) $modalStatus.textContent = "✓ System is already up to date"; if ($modalStatus) $modalStatus.textContent = "✓ System is already up to date";
if ($modalSpinner) $modalSpinner.classList.remove("spinning"); if ($modalSpinner) $modalSpinner.classList.remove("spinning");
if ($btnReboot) $btnReboot.style.display = "none"; if ($btnReboot) $btnReboot.style.display = "none";
if ($btnSave) $btnSave.style.display = "none"; if ($btnSave) $btnSave.style.display = "none";
if ($btnRetryUpdate) $btnRetryUpdate.style.display = "none";
if ($btnCloseModal) $btnCloseModal.disabled = false; if ($btnCloseModal) $btnCloseModal.disabled = false;
_updateFinished = true; _updateFinished = true;
return; return;
@@ -83,6 +169,7 @@ function startUpdate() {
} }
function startUpdatePoll() { function startUpdatePoll() {
if (_updatePollTimer) clearInterval(_updatePollTimer);
pollUpdateStatus(); pollUpdateStatus();
_updatePollTimer = setInterval(pollUpdateStatus, UPDATE_POLL_INTERVAL); _updatePollTimer = setInterval(pollUpdateStatus, UPDATE_POLL_INTERVAL);
} }
@@ -92,33 +179,45 @@ function stopUpdatePoll() {
} }
async function pollUpdateStatus() { async function pollUpdateStatus() {
if (_updateFinished) return; // setInterval does not wait for an async callback. The guard prevents a slow
// request from creating overlapping, out-of-order status polls.
if (_updateFinished || _updatePollInFlight) return;
_updatePollInFlight = true;
try { try {
var data = await apiFetch("/api/updates/status?offset=" + _updateLogOffset); var data = await apiFetchWithTimeout(
"/api/updates/status?offset=" + _updateLogOffset,
{ cache: "no-store" },
STATUS_POLL_FETCH_TIMEOUT
);
_updatePollFailures = 0; _updatePollFailures = 0;
if (_serverWasDown) { if (_serverWasDown) {
_serverWasDown = false; _serverWasDown = false;
if (!data.running) { if (!data.running) {
// The update finished while the server was restarting. Reset to // The update finished while the server or browser connection was away.
// offset 0 and re-fetch so the complete log is shown from the top. // Re-fetch from offset 0 so the final result and complete tail agree.
_updateLog = ""; _updateLog = "";
_updateLogOffset = 0; _updateLogOffset = 0;
_updateVisibleLogChars = 0;
if ($modalLog) $modalLog.textContent = ""; if ($modalLog) $modalLog.textContent = "";
try { try {
var fullData = await apiFetch("/api/updates/status?offset=0"); var fullData = await apiFetchWithTimeout(
"/api/updates/status?offset=0",
{ cache: "no-store" },
STATUS_POLL_FETCH_TIMEOUT
);
if (fullData.log) appendLog(fullData.log); if (fullData.log) appendLog(fullData.log);
_updateLogOffset = fullData.offset; _updateLogOffset = fullData.offset;
} catch (e) { data = fullData;
// If the re-fetch fails, fall through with whatever we have. } catch (_) {
if (data.log) appendLog(data.log); if (data.log) appendLog(data.log);
_updateLogOffset = data.offset; _updateLogOffset = data.offset;
} }
if (data.result === "reboot_required") { if (data.result === "reboot_required") {
appendLog("[Server restarted — update completed, reboot required.]\n"); appendLog("[Reconnected — update completed, reboot required.]\n");
} else if (data.result === "success") { } else if (data.result === "success") {
appendLog("[Server restarted — update completed successfully.]\n"); appendLog("[Reconnected — update completed successfully.]\n");
} else { } else {
appendLog("[Server restarted — update encountered an error.]\n"); appendLog("[Reconnected — update encountered an error.]\n");
} }
_updateFinished = true; _updateFinished = true;
stopUpdatePoll(); stopUpdatePoll();
@@ -129,7 +228,7 @@ async function pollUpdateStatus() {
} }
return; return;
} }
appendLog("[Server reconnected]\n"); appendLog("[Update status reconnected]\n");
if ($modalStatus) $modalStatus.textContent = "Updating…"; if ($modalStatus) $modalStatus.textContent = "Updating…";
} }
if (data.log) appendLog(data.log); if (data.log) appendLog(data.log);
@@ -146,21 +245,57 @@ async function pollUpdateStatus() {
} }
} catch (err) { } catch (err) {
_updatePollFailures += 1; _updatePollFailures += 1;
// Same guard as the rebuild modal: if polling stays broken long past a
// normal Hub restart, reload to re-authenticate and show the real state
// instead of spinning forever.
if (_updatePollFailures >= STATUS_POLL_MAX_FAILURES) { if (_updatePollFailures >= STATUS_POLL_MAX_FAILURES) {
_updateFinished = true; showUpdateStatusUnavailable();
stopUpdatePoll();
window.location.reload();
return; return;
} }
if (!_serverWasDown) { _serverWasDown = true; appendLog("\n[Server restarting — waiting for it to come back…]\n"); if ($modalStatus) $modalStatus.textContent = "Server restarting…"; } if (!_serverWasDown) {
_serverWasDown = true;
appendLog("\n[Update status connection interrupted — retrying…]\n");
if ($modalStatus) $modalStatus.textContent = "Reconnecting to update…";
}
} finally {
_updatePollInFlight = false;
}
}
function showUpdateStatusUnavailable() {
_updateFinished = true;
_updateStatusUnavailable = true;
stopUpdatePoll();
if ($modalSpinner) $modalSpinner.classList.remove("spinning");
if ($modalStatus) $modalStatus.textContent = "Update status unavailable — update may still be running";
appendLog("\n[The Hub could not confirm update status. The background update was not stopped. Select Retry Status after reconnecting.]\n");
if ($btnRetryUpdate) $btnRetryUpdate.style.display = "inline-flex";
if ($btnCloseModal) $btnCloseModal.disabled = false;
}
function retryUpdateStatus() {
if (!$modal) return;
_updateFinished = false;
_updateStatusUnavailable = false;
_updatePollFailures = 0;
_serverWasDown = true;
if ($modalSpinner) $modalSpinner.classList.add("spinning");
if ($modalStatus) $modalStatus.textContent = "Reconnecting to update…";
if ($btnRetryUpdate) $btnRetryUpdate.style.display = "none";
if ($btnCloseModal) $btnCloseModal.disabled = true;
startUpdatePoll();
}
function resumeUpdateStatusAfterInterruption() {
if (!$modal || !$modal.classList.contains("open")) return;
if (_updateStatusUnavailable) {
retryUpdateStatus();
} else if (!_updateFinished) {
pollUpdateStatus();
} }
} }
function onUpdateDone(result) { function onUpdateDone(result) {
_updateStatusUnavailable = false;
if ($modalSpinner) $modalSpinner.classList.remove("spinning"); if ($modalSpinner) $modalSpinner.classList.remove("spinning");
if ($btnRetryUpdate) $btnRetryUpdate.style.display = "none";
if ($btnCloseModal) $btnCloseModal.disabled = false; if ($btnCloseModal) $btnCloseModal.disabled = false;
if (result === true) { if (result === true) {
if ($modalStatus) $modalStatus.textContent = "✓ Update complete"; if ($modalStatus) $modalStatus.textContent = "✓ Update complete";
@@ -187,6 +322,7 @@ function saveErrorReport() {
URL.revokeObjectURL(url); URL.revokeObjectURL(url);
} }
// ── Reboot ──────────────────────────────────────────────────────── // ── Reboot ────────────────────────────────────────────────────────
var _rebootStartTime = 0; var _rebootStartTime = 0;
+7 -12
View File
@@ -364,17 +364,12 @@ async function loadStep3() {
+ renderDomainNeedsHtml({ serviceName: null, hostExample: "call" }) + renderDomainNeedsHtml({ serviceName: null, hostExample: "call" })
+ renderNjallaStepsHtml({ hostExample: "call", pasteHint: "next to its service below" }) + renderNjallaStepsHtml({ hostExample: "call", pasteHint: "next to its service below" })
+ '</div>'; + '</div>';
html += '<p class="onboarding-hint">Enter each service\'s full domain — a subdomain (e.g. <code>call.yourdomain.com</code>) or a separate domain (e.g. <code>call.com</code>) — and its Njal.la DDNS curl command.</p>'; html += '<p class="onboarding-hint">Enter the address for each service and paste its update command from Njal.la.</p>';
// Router note (the same wording is shown again, per-service, whenever a // Router note (the same wording is shown again, per-service, whenever a
// domain-based feature is enabled, and lives on each service tile afterwards) // domain-based feature is enabled, and lives on each service tile afterwards)
html += '<div class="onboarding-port-warn" style="margin-bottom:16px;">' html += '<div class="onboarding-port-warn" style="margin-bottom:16px;">'
+ renderRouterPortsHtml({ + renderRouterPortsHtml({ internalIp: internalIp })
internalIp: internalIp,
plural: true,
includeSsh: true,
extraNote: "Element Call needs a few extra ports (some UDP), and you’ll be shown exactly which when you enable it.",
})
+ '</div>'; + '</div>';
relevantDomains.forEach(function(d) { relevantDomains.forEach(function(d) {
@@ -382,20 +377,20 @@ async function loadStep3() {
html += '<div class="onboarding-domain-group">'; html += '<div class="onboarding-domain-group">';
html += '<label class="onboarding-domain-label">' + escHtml(d.label) + '</label>'; html += '<label class="onboarding-domain-label">' + escHtml(d.label) + '</label>';
html += '<input class="onboarding-domain-input domain-field-input" type="text" id="domain-input-' + escHtml(d.name) + '" data-domain="' + escHtml(d.name) + '" placeholder="e.g. ' + escHtml(d.name) + '.yourdomain.com" value="' + escHtml(currentVal) + '" />'; html += '<input class="onboarding-domain-input domain-field-input" type="text" id="domain-input-' + escHtml(d.name) + '" data-domain="' + escHtml(d.name) + '" placeholder="e.g. ' + escHtml(d.name) + '.yourdomain.com" value="' + escHtml(currentVal) + '" />';
html += '<label class="onboarding-domain-label onboarding-domain-label--sub">Njal.la DDNS Curl Command</label>'; html += '<label class="onboarding-domain-label onboarding-domain-label--sub">Njal.la Update Command</label>';
html += '<input class="onboarding-domain-input domain-field-input" type="text" id="ddns-input-' + escHtml(d.name) + '" data-ddns="' + escHtml(d.name) + '" placeholder="curl &quot;https://njal.la/update/?h=...&amp;k=...&amp;auto&quot;" />'; html += '<input class="onboarding-domain-input domain-field-input" type="text" id="ddns-input-' + escHtml(d.name) + '" data-ddns="' + escHtml(d.name) + '" placeholder="curl &quot;https://njal.la/update/?h=...&amp;k=...&amp;auto&quot;" />';
html += '<p class="onboarding-hint" style="margin-top:4px;">ℹ Paste the curl URL from your Njal.la dashboard\'s Dynamic record</p>'; html += '<p class="onboarding-hint" style="margin-top:4px;">Paste the update command from Njal.la</p>';
html += '<button type="button" class="btn btn-primary onboarding-domain-save-btn" data-save-domain="' + escHtml(d.name) + '" style="align-self:flex-start;margin-top:8px;font-size:0.82rem;padding:6px 16px;">Save</button>'; html += '<button type="button" class="btn btn-primary onboarding-domain-save-btn" data-save-domain="' + escHtml(d.name) + '" style="align-self:flex-start;margin-top:8px;font-size:0.82rem;padding:6px 16px;">Save</button>';
html += '<span class="onboarding-domain-save-status" id="domain-save-status-' + escHtml(d.name) + '" style="font-size:0.82rem;min-height:1.2em;"></span>'; html += '<span class="onboarding-domain-save-status" id="domain-save-status-' + escHtml(d.name) + '" style="font-size:0.82rem;min-height:1.2em;"></span>';
html += '</div>'; html += '</div>';
}); });
} }
// SSL email section // Contact email section
var emailVal = domainValues["sslemail"] || ""; var emailVal = domainValues["sslemail"] || "";
html += '<div class="onboarding-domain-group onboarding-domain-group--email">'; html += '<div class="onboarding-domain-group onboarding-domain-group--email">';
html += '<label class="onboarding-domain-label">📧 SSL Certificate Email</label>'; html += '<label class="onboarding-domain-label">📧 Email Address</label>';
html += '<p class="onboarding-hint onboarding-hint--inline">Let\'s Encrypt uses this for certificate expiry notifications.</p>'; html += '<p class="onboarding-hint onboarding-hint--inline">Used to send important notices about your services.</p>';
html += '<input class="onboarding-domain-input domain-field-input" type="email" id="ssl-email-input" placeholder="you@example.com" value="' + escHtml(emailVal) + '" />'; html += '<input class="onboarding-domain-input domain-field-input" type="email" id="ssl-email-input" placeholder="you@example.com" value="' + escHtml(emailVal) + '" />';
html += '<button type="button" class="btn btn-primary onboarding-domain-save-btn" data-save-email="true" style="align-self:flex-start;margin-top:8px;font-size:0.82rem;padding:6px 16px;">Save</button>'; html += '<button type="button" class="btn btn-primary onboarding-domain-save-btn" data-save-email="true" style="align-self:flex-start;margin-top:8px;font-size:0.82rem;padding:6px 16px;">Save</button>';
html += '<span class="onboarding-domain-save-status" id="domain-save-status-email" style="font-size:0.82rem;min-height:1.2em;"></span>'; html += '<span class="onboarding-domain-save-status" id="domain-save-status-email" style="font-size:0.82rem;min-height:1.2em;"></span>';
+5 -12
View File
@@ -74,6 +74,7 @@
<div class="modal-log" id="modal-log" aria-live="polite"></div> <div class="modal-log" id="modal-log" aria-live="polite"></div>
<div class="modal-footer"> <div class="modal-footer">
<button class="btn btn-save" id="btn-save-report" style="display:none">Save Error Report</button> <button class="btn btn-save" id="btn-save-report" style="display:none">Save Error Report</button>
<button class="btn btn-save" id="btn-retry-update-status" style="display:none">Retry Status</button>
<button class="btn btn-reboot" id="btn-reboot" style="display:none">Restart Entire System</button> <button class="btn btn-reboot" id="btn-reboot" style="display:none">Restart Entire System</button>
<button class="btn btn-close-modal" id="btn-close-modal" disabled>Close</button> <button class="btn btn-close-modal" id="btn-close-modal" disabled>Close</button>
</div> </div>
@@ -196,22 +197,14 @@
encrypted messaging, password management, cloud storage, website hosting, and more. encrypted messaging, password management, cloud storage, website hosting, and more.
</p> </p>
<div class="upgrade-info-box"> <div class="upgrade-info-box">
<p class="upgrade-info-title">⚠ What you should know:</p> <p class="upgrade-info-title">Simple, guided setup:</p>
<ul class="upgrade-info-list"> <ul class="upgrade-info-list">
<li>You will need to purchase domains for your services — <a href="https://njal.la" target="_blank" rel="noopener noreferrer">Njal.la</a> is the only supported domain provider</li> <li>Sovran_SystemsOS walks you through getting your domain from <a href="https://njal.la" target="_blank" rel="noopener noreferrer">Njal.la</a> and connecting your services</li>
<li>Some services require ports to be opened on your router</li> <li>To make your services available outside your home, complete one router task: forward ports <strong>80 and 443</strong> to this computer</li>
</ul>
</div>
<div class="upgrade-info-box">
<p class="upgrade-info-title">ℹ️ Good to know:</p>
<ul class="upgrade-info-list">
<li>Your services will be accessible via your home internet connection. Your approximate geographic area may be visible through DNS records — this is normal for all self-hosted services</li>
<li>Your Bitcoin node remains fully private over Tor</li>
</ul> </ul>
</div> </div>
<p class="support-desc"> <p class="support-desc">
<strong>Don't worry</strong> — the Hub will walk you through every step after the upgrade. The Hub guides you through every step.
Domain setup, port forwarding, and configuration are all guided.
</p> </p>
<p class="support-desc upgrade-rebuild-note"> <p class="support-desc upgrade-rebuild-note">
The system will rebuild after upgrading. This may take several minutes. The system will rebuild after upgrading. This may take several minutes.
@@ -123,10 +123,10 @@
<div class="onboarding-panel" id="step-3" style="display:none"> <div class="onboarding-panel" id="step-3" style="display:none">
<div class="onboarding-step-header"> <div class="onboarding-step-header">
<span class="onboarding-step-icon">🌐</span> <span class="onboarding-step-icon">🌐</span>
<h2 class="onboarding-step-title">Domain Configuration</h2> <h2 class="onboarding-step-title">Connect Your Services</h2>
<p class="onboarding-step-desc"> <p class="onboarding-step-desc">
Sovran_SystemsOS uses <strong><a href="https://njal.la" target="_blank" style="color: var(--accent-color);">Njal.la</a></strong> for domains and Dynamic DNS, and your router needs ports <strong>80</strong> and <strong>443</strong> (TCP) forwarded to this computer. Sovran_SystemsOS walks you through getting your domain from <strong><a href="https://njal.la" target="_blank" style="color: var(--accent-color);">Njal.la</a></strong> and connecting your services.
Everything you need — Njal.la account, Dynamic records, and the one router task — is laid out step by step below. To make your services available outside your home, you’ll complete one router task: forward ports <strong>80</strong> and <strong>443</strong> to this computer.
</p> </p>
</div> </div>
<div class="onboarding-card" id="step-3-body"> <div class="onboarding-card" id="step-3-body">
+88
View File
@@ -0,0 +1,88 @@
"""Update-state helpers for the Sovran Hub.
The full-system updater stages a NixOS generation with ``nixos-rebuild boot``.
That generation is not active until the machine reboots — and the same is true
for updates started from a terminal or an SSH support session, which never go
near the Hub's status files.
The ONLY reliable indicator that a reboot is pending is NixOS itself: the
system profile (``/nix/var/nix/profiles/system``), which ``nixos-rebuild``
points at the newest generation on every ``boot`` AND every ``switch``, versus
``/run/current-system``, the generation actually running since the last boot.
When the two differ, a staged generation has not been booted yet.
Earlier revisions reconstructed this from a marker file and log tails written
by the Hub's own updater. Any system updated by other means — or whose
``REBOOT_REQUIRED`` status was written by an updater older than the marker
feature — left the Hub showing "Restart required" forever: the recorded
generation could never equal the (since advanced) running one, so the marker
could never be cleared.
This module has no FastAPI or systemd dependencies so the policy can be tested
without importing the Hub server.
"""
from __future__ import annotations
import os
# The NixOS system profile. ``nixos-rebuild boot`` and ``nixos-rebuild
# switch`` both add a generation here; ``boot`` additionally makes it the
# bootloader default. The path is a symlink chain (``system`` ->
# ``system-N-link`` -> ``/nix/store/...-nixos-system-...``).
BOOT_PROFILE_PATH = "/nix/var/nix/profiles/system"
CURRENT_SYSTEM_PATH = "/run/current-system"
def reboot_is_pending(
boot_profile_path: str = BOOT_PROFILE_PATH,
current_system_path: str = CURRENT_SYSTEM_PATH,
) -> bool:
"""Return whether a staged NixOS generation has not been booted yet.
This is deliberately independent of how the update was started — Hub
"Update System", terminal ``nixos-rebuild boot``, or a support session all
move the system profile the same way:
* after ``nixos-rebuild boot``: profile -> new, current -> old → pending
* after rebooting: both -> new → cleared
* after ``nixos-rebuild switch``: both move together → no reboot
ever needed (switch activates immediately)
* after a rollback: both point at the rollback target → cleared
Unreadable or missing paths are treated as "not pending": the Hub must
never demand a reboot it cannot substantiate.
"""
try:
boot_default = os.path.realpath(boot_profile_path)
current = os.path.realpath(current_system_path)
except OSError:
return False
if not os.path.exists(boot_default) or not os.path.exists(current):
return False
return boot_default != current
def effective_update_status(
status: str,
boot_profile_path: str = BOOT_PROFILE_PATH,
current_system_path: str = CURRENT_SYSTEM_PATH,
) -> str:
"""Map a persisted Hub status to the one that reflects live NixOS state.
Only ``REBOOT_REQUIRED`` is re-validated: it means "the update staged a
generation the machine has not booted into", a claim that must stay true
no matter which tool performed the last update. When the boot default IS
the running system the claim is stale — the staged generation booted, was
superseded by a newer update, or the marker was written by an updater that
could never clear it — so the effective status is ``IDLE``.
All other statuses (``RUNNING``, ``FAILED``, ``SUCCESS``, ``IDLE``) pass
through unchanged; RUNNING staleness is handled separately against the
systemd unit itself.
"""
if status == "REBOOT_REQUIRED" and not reboot_is_pending(
boot_profile_path, current_system_path
):
return "IDLE"
return status
+2 -2
View File
@@ -5,9 +5,9 @@
"bitcoind.service": "27.1.0", "bitcoind.service": "27.1.0",
"electrs.service": "0.10.6", "electrs.service": "0.10.6",
"lnd.service": "0.18.0", "lnd.service": "0.18.0",
"rtl.service": "0.15.8", "rtl.service": "0.15.10",
"btcpayserver.service": "2.4.2", "btcpayserver.service": "2.4.2",
"albyhub.service": "1.8.0", "albyhub.service": "1.24.0",
"mempool.service": "3.2.1", "mempool.service": "3.2.1",
"matrix-synapse.service": "1.115.0", "matrix-synapse.service": "1.115.0",
"livekit.service": "1.5.2", "livekit.service": "1.5.2",
Binary file not shown.

Before

Width:  |  Height:  |  Size: 442 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 217 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 392 KiB

+2 -1
View File
@@ -145,12 +145,13 @@
ranger fastfetch gedit openssl pwgen ranger fastfetch gedit openssl pwgen
aspell aspellDicts.en lm_sensors aspell aspellDicts.en lm_sensors
hunspell hunspellDicts.en_US hunspell hunspellDicts.en_US
synadm brave dua synadm brave-origin dua
gparted pv unzip parted screen zenity gparted pv unzip parted screen zenity
libargon2 gnome-terminal libreoffice-fresh libargon2 gnome-terminal libreoffice-fresh
dig firefox wp-cli axel dig firefox wp-cli axel
lk-jwt-service livekit-libwebrtc livekit lk-jwt-service livekit-libwebrtc livekit
matrix-synapse age onlyoffice-desktopeditors matrix-synapse age onlyoffice-desktopeditors
tor-browser
]; ];
# ── Shell ────────────────────────────────────────────────── # ── Shell ──────────────────────────────────────────────────
Generated
+19 -18
View File
@@ -5,11 +5,11 @@
"nixpkgs": "nixpkgs" "nixpkgs": "nixpkgs"
}, },
"locked": { "locked": {
"lastModified": 1785778881, "lastModified": 1787839684,
"narHash": "sha256-yHJJTm3o7ZhiVp68G+hh+dz1GKV+ACOT6mQj+eYvJLQ=", "narHash": "sha256-xTafqsVs2/zyGsaCel41QT5Lpbs/rG56Kp+YsmLXL8I=",
"owner": "emmanuelrosa", "owner": "emmanuelrosa",
"repo": "btc-clients-nix", "repo": "btc-clients-nix",
"rev": "fc1aca94d839f82e7501fe0d01279d5c1fba6e63", "rev": "ef81159876930802ef9861aa5c039cec6886a30f",
"type": "github" "type": "github"
}, },
"original": { "original": {
@@ -26,11 +26,11 @@
] ]
}, },
"locked": { "locked": {
"lastModified": 1782949081, "lastModified": 1785627969,
"narHash": "sha256-vp6Y/Grm98ESt6ceOkWiHWyZRDV3J1RID4w+6NWK9yA=", "narHash": "sha256-4dtXQk/NMePegK/nWp5NSeuZKLATItOq61lpEvmXqGw=",
"owner": "hercules-ci", "owner": "hercules-ci",
"repo": "flake-parts", "repo": "flake-parts",
"rev": "17c9d6cdfc60c64f4ee8d306f9bc0b4ccb51481e", "rev": "427bf4bd9435fdf21321c8cc628c24efc14c0f7a",
"type": "github" "type": "github"
}, },
"original": { "original": {
@@ -56,11 +56,11 @@
}, },
"nixpkgs-stable": { "nixpkgs-stable": {
"locked": { "locked": {
"lastModified": 1786201459, "lastModified": 1787753485,
"narHash": "sha256-CiOTEjmwAmG2AWnaIno9YaCJJmpca2FXPhMAsnrolCg=", "narHash": "sha256-BZWCi9ZRJiARTuKTbbtvFTj7t1TK4G3UEckT3HyNfRg=",
"owner": "nixos", "owner": "nixos",
"repo": "nixpkgs", "repo": "nixpkgs",
"rev": "8b8c811c7c2541c30382c5de7ed26be055569c60", "rev": "062346a6d85bc4b49dfaa61c986e9c5be21217d1",
"type": "github" "type": "github"
}, },
"original": { "original": {
@@ -72,11 +72,11 @@
}, },
"nixpkgs_2": { "nixpkgs_2": {
"locked": { "locked": {
"lastModified": 1786106723, "lastModified": 1787498568,
"narHash": "sha256-zDSUbpoeo/9ZmD2+wXnzxoo1+uhL8vxc0b8yuYMKYq0=", "narHash": "sha256-9i/VTdusq/+NM/tz+J1Re+ojkMB8MBf0QshnYfzHz30=",
"owner": "NixOS", "owner": "NixOS",
"repo": "nixpkgs", "repo": "nixpkgs",
"rev": "f13ff45afd1bb73e640eaa08a7066dbed07e3238", "rev": "56c02bc00adcf003215cc4bd996d6efaf4cff188",
"type": "github" "type": "github"
}, },
"original": { "original": {
@@ -88,11 +88,11 @@
}, },
"nixpkgs_3": { "nixpkgs_3": {
"locked": { "locked": {
"lastModified": 1784555310, "lastModified": 1787364730,
"narHash": "sha256-/FCliTPgiuV1owejZFNx3Ch9irdvkOfOFl+HHZ+DrtM=", "narHash": "sha256-NcYt9QJfpJiF1lAyN8BDPB4EeScbPU+EwQqPiBElrpU=",
"owner": "NixOS", "owner": "NixOS",
"repo": "nixpkgs", "repo": "nixpkgs",
"rev": "421eebfd0ec7bccd4abe826ce62d7e6e83129493", "rev": "a831408e6378bc02ebf8cc09b52c96ca86f6bab4",
"type": "github" "type": "github"
}, },
"original": { "original": {
@@ -109,11 +109,11 @@
"systems": "systems" "systems": "systems"
}, },
"locked": { "locked": {
"lastModified": 1785763201, "lastModified": 1787691219,
"narHash": "sha256-wA373y/B9orM3HatLu9oS+Ke5lmdZyBl/bdjd2gLMq4=", "narHash": "sha256-CjeJTOjrluiDuL0W/YBFkSBOQjBYmdKwj7hWAJ4PIh0=",
"owner": "nix-community", "owner": "nix-community",
"repo": "nixvim", "repo": "nixvim",
"rev": "c7be49306b23a952c0151cf4bbeacd944ed82f2a", "rev": "ebec1ae277a50b16e7d6682edd009ef585d68261",
"type": "github" "type": "github"
}, },
"original": { "original": {
@@ -131,6 +131,7 @@
} }
}, },
"systems": { "systems": {
"flake": false,
"locked": { "locked": {
"lastModified": 1774449309, "lastModified": 1774449309,
"narHash": "sha256-brhZ8DmuGtzkCYHJg4HEd602amKm89Y9ytsFZ5uWD1w=", "narHash": "sha256-brhZ8DmuGtzkCYHJg4HEd602amKm89Y9ytsFZ5uWD1w=",
+1 -35
View File
@@ -423,40 +423,6 @@ class InstallerWindow(Adw.ApplicationWindow):
sep.set_margin_end(40) sep.set_margin_end(40)
outer.append(sep) outer.append(sep)
notice_frame = Gtk.Frame()
notice_frame.add_css_class("card")
notice_frame.set_margin_start(40)
notice_frame.set_margin_end(40)
notice_frame.set_margin_top(20)
notice_frame.set_margin_bottom(4)
notice_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=12)
notice_box.set_margin_top(12)
notice_box.set_margin_bottom(12)
notice_box.set_margin_start(16)
notice_box.set_margin_end(16)
notice_icon = symbolic_icon("dialog-information-symbolic")
notice_icon.set_valign(Gtk.Align.START)
notice_box.append(notice_icon)
notice_lbl = Gtk.Label()
notice_lbl.set_use_markup(True)
notice_lbl.set_wrap(True)
notice_lbl.set_xalign(0)
notice_lbl.set_halign(Gtk.Align.FILL)
notice_lbl.set_markup(
"<span weight='bold'>Heads up — Server + Desktop prerequisites</span>\n"
"• A domain or subdomain from <span weight='bold'>https://njal.la</span>\n"
"• The ability to open / forward ports on your router\n\n"
"Don't worry — after install, the onboarding wizard walks you through every step.\n"
"<span size='small'>Desktop Only and Node Only do not require a domain or port forwarding.</span>"
)
notice_box.append(notice_lbl)
notice_frame.set_child(notice_box)
outer.append(notice_frame)
if self.virtualization: if self.virtualization:
vm_frame = Gtk.Frame() vm_frame = Gtk.Frame()
vm_frame.add_css_class("card") vm_frame.add_css_class("card")
@@ -505,7 +471,7 @@ class InstallerWindow(Adw.ApplicationWindow):
# Role cards # Role cards
roles = [ roles = [
("Server + Desktop", ("Server + Desktop",
"Full sovereign experience: beautiful desktop, your own cloud, secure messaging, Bitcoin node, and more.", "Full sovereignty: host your own websites, cloud, chat, passwords, and Bitcoin services instead of relying on Big Tech. Sovran_SystemsOS walks you through getting your domain from Njal.la and connecting everything. One router task is required: forward ports 80 and 443 to this computer.",
"Server+Desktop"), "Server+Desktop"),
("Desktop Only", ("Desktop Only",
"A beautiful, easy-to-use desktop without the background server applications.", "A beautiful, easy-to-use desktop without the background server applications.",
+8 -2
View File
@@ -284,7 +284,9 @@ let
nbLib = config.nix-bitcoin.lib; nbLib = config.nix-bitcoin.lib;
secretsDir = config.nix-bitcoin.secretsDir; secretsDir = config.nix-bitcoin.secretsDir;
i2pSAM = config.services.i2pd.proto.sam; # nixpkgs 26.11 moved i2pd's protocol configuration from
# `services.i2pd.proto` to the RFC42-style `services.i2pd.settings`.
i2pSAM = config.services.i2pd.settings.sam;
configFile = builtins.toFile "bitcoin.conf" '' configFile = builtins.toFile "bitcoin.conf" ''
# We're already logging via journald # We're already logging via journald
@@ -374,7 +376,11 @@ in {
services.i2pd = mkIf (cfg.i2p != false) { services.i2pd = mkIf (cfg.i2p != false) {
enable = true; enable = true;
proto.sam.enable = true; settings.sam = {
enabled = true;
address = "127.0.0.1";
port = 7656;
};
}; };
systemd.tmpfiles.rules = [ systemd.tmpfiles.rules = [
+5 -2
View File
@@ -150,7 +150,7 @@ let
nbLib = config.nix-bitcoin.lib; nbLib = config.nix-bitcoin.lib;
secretsDir = config.nix-bitcoin.secretsDir; secretsDir = config.nix-bitcoin.secretsDir;
runAsUser = config.nix-bitcoin.runAsUserCmd; runAsUser = config.nix-bitcoin.runAsUserCmd;
lndinit = "${(pkgs.callPackage ../../packages/lndinit {})}/bin/lndinit"; lndinit = "${pkgs.lndinit}/bin/lndinit";
bitcoind = config.services.bitcoind; bitcoind = config.services.bitcoind;
@@ -264,13 +264,16 @@ in {
curl = "${pkgs.curl}/bin/curl -fsS --cacert ${cfg.certPath}"; curl = "${pkgs.curl}/bin/curl -fsS --cacert ${cfg.certPath}";
restUrl = "https://${nbLib.addressWithPort cfg.restAddress cfg.restPort}/v1"; restUrl = "https://${nbLib.addressWithPort cfg.restAddress cfg.restPort}/v1";
# Setting macaroon permissions for other users needs root permissions # Setting macaroon permissions for other users needs root permissions
# The admin macaroon is passed to curl via a fd because argv is
# world-readable through /proc/<pid>/cmdline
script = nbLib.rootScript "lnd-create-macaroons" '' script = nbLib.rootScript "lnd-create-macaroons" ''
umask ug=r,o= umask ug=r,o=
${lib.concatMapStrings (macaroon: '' ${lib.concatMapStrings (macaroon: ''
echo "Create custom macaroon ${macaroon}" echo "Create custom macaroon ${macaroon}"
macaroonPath="$RUNTIME_DIRECTORY/${macaroon}.macaroon" macaroonPath="$RUNTIME_DIRECTORY/${macaroon}.macaroon"
adminMacaroonHex=$(${pkgs.xxd}/bin/xxd -ps -u -c 99999 '${networkDir}/admin.macaroon')
${curl} \ ${curl} \
-H "Grpc-Metadata-macaroon: $(${pkgs.xxd}/bin/xxd -ps -u -c 99999 '${networkDir}/admin.macaroon')" \ -H @<(printf 'Grpc-Metadata-macaroon: %s\n' "$adminMacaroonHex") \
-X POST \ -X POST \
-d '{"permissions":[${cfg.macaroons.${macaroon}.permissions}]}' \ -d '{"permissions":[${cfg.macaroons.${macaroon}.permissions}]}' \
${restUrl}/macaroon |\ ${restUrl}/macaroon |\
+86 -34
View File
@@ -1,63 +1,115 @@
{ config, lib, pkgs, ... }: { config, lib, pkgs, ... }:
# LND-only lndconnect wrapper. Restored to the fort-nix/nix-bitcoin contract
# after the LND-only rewrite shipped a Zeus QR that Zeus cannot use:
# - unknown flags (--cert / --macaroon instead of --tlscertpath / --adminmacaroonpath)
# - onion hostname read from /var/lib/tor/onion/free/lnd/hostname (does not exist)
# - REST hidden service named "lnd", colliding with the LND P2P onion
# - TLS cert embedded in the URI (localhost CN + QR too dense to scan)
#
# Zeus needs: lndconnect://<lnd-rest-onion>:8080?macaroon=<admin> (no cert over Tor)
with lib; with lib;
let let
cfg = config.services.lnd; cfg = config.services.lnd;
operatorName = config.nix-bitcoin.operator.name; operatorName = config.nix-bitcoin.operator.name;
nbLib = config.nix-bitcoin.lib; nbLib = config.nix-bitcoin.lib;
runAsUser = config.nix-bitcoin.runAsUserCmd;
mkLndconnect = { name, isClightning ? false, enableOnion, onionService, port, certPath, authSecretPath }: mkLndconnect = {
let name,
lnd = config.services.lnd; shebang ? "#!${pkgs.stdenv.shell} -e",
getOnionAddress = "cat ${config.nix-bitcoin.secretsDir}/onion-address-${onionService} 2>/dev/null || echo ${onionService}.onion"; port,
in pkgs.writeScriptBin name '' authSecretPath,
#!${pkgs.bash}/bin/bash enableOnion,
set -e onionService ? null,
certPath="${certPath}" certPath ? null
authSecretPath="${authSecretPath}" }:
if [ "${toString enableOnion}" = "1" ]; then # lndconnect requires a --configfile argument, although it's unused
host=$(cat /var/lib/tor/onion/${onionService}/hostname 2>/dev/null || echo "${onionService}.onion") # https://github.com/LN-Zap/lndconnect/issues/25
port="${toString port}" lib.hiPrio (pkgs.writeScriptBin name ''
else ${shebang}
host="${nbLib.address lnd.restAddress}" url=$(
port="${toString lnd.restPort}" ${getExe pkgs.lndconnect} --url \
fi ${optionalString enableOnion "--host=$(cat ${config.nix-bitcoin.onionAddresses.dataDir}/${onionService})"} \
# lndconnect is provided by pkgs.lndconnect --port=${toString port} \
${getExe pkgs.lndconnect} --host="$host" --port="$port" --cert="$certPath" --macaroon="$authSecretPath" "$@" ${if enableOnion || certPath == null then "--nocert" else "--tlscertpath='${certPath}'"} \
''; --adminmacaroonpath='${authSecretPath}' \
--configfile=/dev/null "$@"
)
# If --url is in args
if [[ " $* " =~ " --url " ]]; then
echo "$url"
else
# UTF-8 QR is smaller than lndconnect's native output
echo -n "$url" | ${getExe pkgs.qrencode} -t UTF8 -o -
fi
'');
in { in {
options.services.lnd.lndconnect = { options.services.lnd.lndconnect = {
enable = mkOption { enable = mkOption {
type = types.bool; type = types.bool;
default = false; default = false;
description = "Enable lndconnect for LND"; description = ''
Add a `lndconnect` binary to the system environment which prints
connection info for lnd clients (Zeus).
See: https://github.com/LN-Zap/lndconnect
Usage:
```bash
# Print QR code
lndconnect
# Print URL
lndconnect --url
```
'';
}; };
onion = mkOption { onion = mkOption {
type = types.bool; type = types.bool;
default = false; default = false;
description = "Expose lndconnect via Tor onion service"; description = ''
Create an onion service for the lnd REST server,
which is used by lndconnect / Zeus.
'';
}; };
}; };
config = mkIf cfg.enable (mkMerge [ config = mkIf (cfg.enable && cfg.lndconnect.enable) (mkMerge [
(mkIf cfg.lndconnect.enable { {
environment.systemPackages = [ environment.systemPackages = [(
(mkLndconnect { mkLndconnect {
name = "lndconnect"; name = "lndconnect";
# Run as lnd user because the macaroon and cert are not group-readable
shebang = "#!/usr/bin/env -S ${runAsUser} ${cfg.user} ${pkgs.bash}/bin/bash";
enableOnion = cfg.lndconnect.onion; enableOnion = cfg.lndconnect.onion;
onionService = "${operatorName}/lnd"; onionService = "${cfg.user}/lnd-rest";
port = cfg.restPort; port = cfg.restPort;
certPath = cfg.certPath; certPath = cfg.certPath;
authSecretPath = "${cfg.networkDir}/admin.macaroon"; authSecretPath = "${cfg.networkDir}/admin.macaroon";
}) }
]; )];
})
(mkIf (cfg.lndconnect.enable && cfg.lndconnect.onion) { # LAN / clearnet Zeus needs REST on all interfaces. Tor-only stays on
services.tor.relay.onionServices.lnd = nbLib.mkOnionService { # the existing restAddress (loopback) and is reached via lnd-rest.
port = cfg.restPort; services.lnd.restAddress = mkIf (!cfg.lndconnect.onion) "0.0.0.0";
target = { addr = nbLib.address cfg.restAddress; port = cfg.restPort; }; }
(mkIf cfg.lndconnect.onion {
services.tor = {
enable = true;
# Dedicated name — must not reuse onionServices.lnd (that's P2P :9735).
relay.onionServices.lnd-rest = nbLib.mkOnionService {
target.addr = nbLib.address cfg.restAddress;
target.port = cfg.restPort;
port = cfg.restPort;
};
};
nix-bitcoin.onionAddresses.access = {
${cfg.user} = [ "lnd-rest" ];
${operatorName} = [ "lnd-rest" ];
}; };
nix-bitcoin.onionAddresses.access.${operatorName} = [ "lnd" ];
}) })
]); ]);
} }
+12 -1
View File
@@ -4,6 +4,11 @@ lib.mkIf config.sovran_systemsOS.services.bitcoin {
services.bitcoind = { services.bitcoind = {
enable = true; enable = true;
# Keep the normal loopback P2P socket available for local clients such as
# Bisq. Because `address` defaults to 127.0.0.1 this does not expose a
# clearnet or LAN listener. When the existing bitcoind onion service is
# enabled, this also creates its Tor-tagged loopback target on port 8334.
listen = true;
package = pkgs.bitcoind; package = pkgs.bitcoind;
dataDir = "/run/media/Second_Drive/BTCEcoandBackup/Bitcoin_Node"; dataDir = "/run/media/Second_Drive/BTCEcoandBackup/Bitcoin_Node";
txindex = true; txindex = true;
@@ -16,7 +21,13 @@ lib.mkIf config.sovran_systemsOS.services.bitcoin {
''; '';
}; };
nix-bitcoin.onionServices.bitcoind.enable = true; nix-bitcoin.onionServices.bitcoind = {
enable = true;
# This is a locally vendored option namespace, not an upstream dependency.
# The onion listener remains available to peers that already know it;
# advertising its address through Bitcoin peer gossip is opt-in in the Hub.
public = config.sovran_systemsOS.features.bitcoin-tor-gossip;
};
nix-bitcoin.onionServices.electrs.enable = true; nix-bitcoin.onionServices.electrs.enable = true;
nix-bitcoin.onionServices.rtl.enable = true; nix-bitcoin.onionServices.rtl.enable = true;
+17 -4
View File
@@ -33,7 +33,7 @@
# /var/lib/njalla/ddns_urls.json. # /var/lib/njalla/ddns_urls.json.
NoNewPrivileges = true; NoNewPrivileges = true;
ProtectSystem = "strict"; ProtectSystem = "strict";
ReadWritePaths = [ "/var/lib/njalla" ]; ReadWritePaths = [ "/var/lib/njalla" "/var/lib/secrets" ];
ReadOnlyPaths = [ "/etc/sovran" ]; ReadOnlyPaths = [ "/etc/sovran" ];
ProtectHome = true; ProtectHome = true;
PrivateTmp = true; PrivateTmp = true;
@@ -88,12 +88,15 @@ try:
except Exception: except Exception:
sys.exit(0) # no URLs configured — nothing to do sys.exit(0) # no URLs configured — nothing to do
# Resolve current public IP once # Resolve current public IP via the shared detector — one script, one cache
# (STUN -> DNS -> opt-in HTTPS echo; see /var/lib/sovran/public-ip.py).
# The detector refreshes /var/lib/secrets/external-ip, which the Hub and
# LiveKit read as well, so the whole system shares a single detected value.
public_ip = "" public_ip = ""
try: try:
r = subprocess.run( r = subprocess.run(
["dig", "@resolver4.opendns.com", "myip.opendns.com", "+short", "-4"], [sys.executable, "/var/lib/sovran/public-ip.py", "check"],
capture_output=True, text=True, timeout=10, capture_output=True, text=True, timeout=20,
) )
raw = r.stdout.strip().splitlines()[0] if r.stdout.strip() else "" raw = r.stdout.strip().splitlines()[0] if r.stdout.strip() else ""
ipaddress.ip_address(raw) # validates — raises if not a real IP ipaddress.ip_address(raw) # validates — raises if not a real IP
@@ -101,6 +104,16 @@ try:
except Exception: except Exception:
pass pass
if not public_ip:
# Last resort: the shared cache file, if the detector is unavailable.
try:
with open("/var/lib/secrets/external-ip") as f:
raw = f.read().strip()
ipaddress.ip_address(raw)
public_ip = raw
except Exception:
pass
if not public_ip: if not public_ip:
sys.exit(0) # no IP resolved — skip to avoid sending bare ''${IP} sys.exit(0) # no IP resolved — skip to avoid sending bare ''${IP}
+323
View File
@@ -0,0 +1,323 @@
# ── Unified public-IP detection (privacy-first) ─────────────────────────────
#
# One script, one cache file, every consumer on the system reads the same
# value. Previously the public IP was detected independently in three places,
# each phoning home to a different third party:
# * the Hub (server.py _get_external_ip) → api.ipify.org / ifconfig.me /
# icanhazip.com over HTTPS on every /api/network call and every
# background-loop tick
# * DDNS (ddns-update.py) → myip.opendns.com via OpenDNS
# * LiveKit → STUN (its own embedded detection)
#
# This module replaces all of that with a single script
# (/var/lib/sovran/public-ip.py) that detects the IP once per TTL using the
# least-exposing mechanism available, and caches it in
# /var/lib/secrets/external-ip. Consumers (Hub, DDNS, LiveKit) read the cache
# and only invoke the script when it is missing or stale.
#
# Detection chain (first success wins, stops immediately):
# 1. pin — sovran_systemsOS.elementCalling.externalIP (baked in)
# 2. cache — /var/lib/secrets/external-ip if newer than cacheTTL
# 3. STUN — UDP binding request (one packet, no application data,
# no HTTP metadata; the same protocol every WebRTC client
# uses). Server configurable via publicIP.stunServer.
# 4. DNS — "myip.opendns.com" A query via publicIP.dnsResolver
# (single DNS query, no HTTP headers)
# 5. HTTPS echo — ONLY endpoints listed in publicIP.httpsEcho (empty by
# default → never contacted)
#
# Privacy property: while the cache is fresh, zero third parties are
# contacted. When detection runs, at most ONE party learns the IP per
# refresh interval (default 5 minutes), and the STUN/DNS mechanisms expose
# nothing beyond the bare address.
{
config,
pkgs,
lib,
...
}:
let
stunServer = config.sovran_systemsOS.publicIP.stunServer;
stunPort = config.sovran_systemsOS.publicIP.stunPort;
dnsResolver = config.sovran_systemsOS.publicIP.dnsResolver;
httpsEcho = config.sovran_systemsOS.publicIP.httpsEcho;
cacheTTL = config.sovran_systemsOS.publicIP.cacheTTL;
# Optional pin shared with element-calling (baked in at build time).
pin = if config.sovran_systemsOS.elementCalling.externalIP != null then config.sovran_systemsOS.elementCalling.externalIP else "";
echoList = lib.concatStringsSep "," (map (u: "'${u}'") httpsEcho);
in
{
options.sovran_systemsOS.publicIP = {
stunServer = lib.mkOption {
type = lib.types.str;
default = "stun.l.google.com";
description = ''
STUN server used to discover the public IP over UDP. STUN is the most
privacy-preserving detection mechanism: a single stateless packet,
no HTTP metadata. Only used when the cache is stale.
'';
};
stunPort = lib.mkOption {
type = lib.types.port;
default = 19302;
};
dnsResolver = lib.mkOption {
type = lib.types.str;
default = "resolver4.opendns.com";
description = ''
DNS resolver used as fallback (myip.opendns.com trick) when STUN is
unavailable (e.g. ISP blocks UDP egress). A single DNS query, no
HTTP headers.
'';
};
httpsEcho = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
example = [ "https://api.ipify.org" ];
description = ''
OPT-IN HTTPS endpoints that return the caller's public IP as a bare
IPv4 literal. Each listed endpoint observes this server's public IP
and HTTP metadata every time detection runs. Empty by default — no
HTTPS echo service is ever contacted unless you add one here. This is
the last-resort fallback after STUN and DNS.
'';
};
cacheTTL = lib.mkOption {
type = lib.types.int;
default = 300;
description = "Seconds the detected public IP is cached before re-detection.";
};
};
# ── Install the unified detector ──────────────────────────────────────────
# This module declares `options` above, so ALL configuration must go under
# the `config` attribute: NixOS forbids mixing bare top-level settings
# (like `system.*`) with the `options`/`config` keyword attributes in the
# same module. (Fixes: "Module ... has an unsupported attribute `system'".)
config.system.activationScripts.sovranPublicIpInstall = lib.stringAfter [ "users" ] ''
install -d -m 0755 /var/lib/sovran
cat > /var/lib/sovran/public-ip.py <<'PYEOF'
#!/usr/bin/env python3
"""sovran-public-ip — one detector, one cache, every consumer reads the same IP.
Privacy-first detection chain (first success wins):
1. pin — baked in from sovran_systemsOS.elementCalling.externalIP
2. cache — /var/lib/secrets/external-ip if newer than CACHE_TTL seconds
3. STUN — UDP binding request (one packet, no application data)
4. DNS — myip.opendns.com A query via the configured resolver
5. HTTPS — ONLY endpoints baked in from publicIP.httpsEcho (opt-in)
Usage:
public-ip.py check print current public IP (cache first; refresh if stale)
public-ip.py refresh force re-detection, update the cache file, print IP
Exit status: 0 with the IP on stdout on success; 1 if no IP is available
(cached value, if any, is still printed to stdout with a warning on stderr).
"""
import ipaddress
import os
import random
import socket
import struct
import sys
import time
import urllib.request
CACHE_FILE = "/var/lib/secrets/external-ip"
PIN = "${pin}"
STUN_SERVER = "${stunServer}"
STUN_PORT = ${toString stunPort}
DNS_RESOLVER = "${dnsResolver}"
DNS_HOST = "myip.opendns.com"
ECHO_URLS = [ ${echoList} ]
CACHE_TTL = ${toString cacheTTL}
TIMEOUT = 3.0
# ---------------------------------------------------------------------------
# Detection primitives
# ---------------------------------------------------------------------------
def is_usable_ip(text: str) -> bool:
"""True if text is a globally routable IPv4 that LiveKit may advertise."""
try:
ip = ipaddress.ip_address(text)
except ValueError:
return False
if ip.version != 4:
return False
if (ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_multicast
or ip.is_reserved or ip.is_unspecified or not ip.is_global):
return False
# RFC 6598 shared (CGNAT) space — not reachable from the internet.
if ip in ipaddress.ip_network("100.64.0.0/10"):
return False
return True
def stun_public_ip() -> str | None:
"""RFC 5389 Binding request over UDP; returns the mapped (public) IPv4."""
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.settimeout(TIMEOUT)
try:
txid = random.randbytes(12)
req = struct.pack("!HHI", 0x0001, 0, 0) + txid # Binding request
sock.sendto(req, (STUN_SERVER, STUN_PORT))
data, _ = sock.recvfrom(2048)
except OSError:
return None
finally:
sock.close()
if len(data) < 20:
return None
mtype, _mlen = struct.unpack("!HH", data[:4])
if mtype != 0x0101: # Binding success response
return None
cookie = data[4:8]
i = 20
while i + 4 <= len(data):
atype, alen = struct.unpack("!HH", data[i : i + 4])
aval = data[i + 4 : i + 4 + alen]
if atype in (0x0001, 0x0020) and len(aval) >= 8: # MAPPED / XOR-MAPPED
family = aval[1]
if family == 0x01: # IPv4
raw = aval[4:8]
if atype == 0x0020: # XOR with magic cookie + txid prefix
raw = bytes(b ^ c for b, c in zip(raw, cookie + txid[:4]))
return socket.inet_ntop(socket.AF_INET, raw)
i += 4 + ((alen + 3) // 4) * 4
return None
def dns_public_ip() -> str | None:
"""Minimal DNS A query for myip.opendns.com against the given resolver."""
qid = random.randint(0, 0xFFFF)
qname = b"".join(bytes([len(p)]) + p.encode() for p in DNS_HOST.split(".")) + b"\x00"
query = struct.pack("!HHHHHH", qid, 0x0100, 1, 0, 0, 0) + qname + struct.pack("!HH", 1, 1)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.settimeout(TIMEOUT)
try:
sock.sendto(query, (DNS_RESOLVER, 53))
data, _ = sock.recvfrom(4096)
except OSError:
return None
finally:
sock.close()
try:
if len(data) < 12:
return None
rid, _flags, _qd, an, _ns, _ar = struct.unpack("!HHHHHH", data[:12])
if rid != qid or an == 0:
return None
i = 12
for _ in range(_qd): # skip question
while data[i] != 0:
i += 1 + data[i]
i += 5
for _ in range(an):
if data[i] & 0xC0 == 0xC0:
i += 2
else:
while data[i] != 0:
i += 1 + data[i]
i += 1
rtype, _rclass, _ttl, rdlen = struct.unpack("!HHIH", data[i : i + 10])
i += 10
if rtype == 1 and rdlen == 4:
return socket.inet_ntop(socket.AF_INET, data[i : i + 4])
i += rdlen
except (IndexError, struct.error):
return None
return None
def echo_public_ip() -> str | None:
"""Opt-in HTTPS echo endpoints (baked in at build time; empty by default)."""
for url in ECHO_URLS:
try:
req = urllib.request.Request(url, headers={"User-Agent": "sovran-public-ip"})
with urllib.request.urlopen(req, timeout=TIMEOUT) as resp:
text = resp.read().decode().strip()
if is_usable_ip(text):
return text
except Exception:
continue
return None
# ---------------------------------------------------------------------------
# Cache handling
# ---------------------------------------------------------------------------
def read_cache() -> str:
try:
with open(CACHE_FILE) as f:
return f.read().strip()
except OSError:
return ""
def write_cache(ip: str) -> None:
try:
os.makedirs(os.path.dirname(CACHE_FILE), exist_ok=True)
tmp = f"{CACHE_FILE}.tmp"
with open(tmp, "w") as f:
f.write(ip + "\n")
os.replace(tmp, CACHE_FILE)
except OSError:
pass
def cache_fresh() -> bool:
try:
return time.time() - os.path.getmtime(CACHE_FILE) < CACHE_TTL
except OSError:
return False
def detect() -> str:
"""Run the chain; returns usable IP or an empty string."""
if PIN and is_usable_ip(PIN):
return PIN
for fn in (stun_public_ip, dns_public_ip, echo_public_ip):
try:
cand = fn()
except Exception:
continue
if cand and is_usable_ip(cand):
return cand
return ""
def main() -> int:
force = len(sys.argv) > 1 and sys.argv[1] == "refresh"
ip = ""
if not force and cache_fresh():
ip = read_cache()
if not ip:
ip = detect()
if ip:
write_cache(ip)
else:
stale = read_cache()
if stale:
print(stale)
print("WARNING: detection failed; using last known public IP", file=sys.stderr)
return 0
print("ERROR: could not determine a public IP (STUN/DNS unreachable)", file=sys.stderr)
return 1
print(ip)
return 0
if __name__ == "__main__":
sys.exit(main())
PYEOF
chmod 0555 /var/lib/sovran/public-ip.py
'';
}
+1
View File
@@ -33,6 +33,7 @@
haven = lib.mkForce false; haven = lib.mkForce false;
mempool = lib.mkForce false; mempool = lib.mkForce false;
element-calling = lib.mkForce false; element-calling = lib.mkForce false;
bitcoin-tor-gossip = lib.mkForce false;
"nwc-wallets" = lib.mkForce false; "nwc-wallets" = lib.mkForce false;
}; };
+36
View File
@@ -45,6 +45,7 @@
haven = lib.mkEnableOption "Haven NOSTR relay"; haven = lib.mkEnableOption "Haven NOSTR relay";
mempool = lib.mkEnableOption "Bitcoin Mempool Explorer"; mempool = lib.mkEnableOption "Bitcoin Mempool Explorer";
element-calling = lib.mkEnableOption "Element Video and Audio Calling"; element-calling = lib.mkEnableOption "Element Video and Audio Calling";
bitcoin-tor-gossip = lib.mkEnableOption "Advertise the Bitcoin Core onion service through Bitcoin peer gossip";
# Compatibility shim for Hub-managed settings from releases where Core # Compatibility shim for Hub-managed settings from releases where Core
# was an optional replacement for the default node. Core is now always # was an optional replacement for the default node. Core is now always
# selected when the Bitcoin service is enabled. # selected when the Bitcoin service is enabled.
@@ -78,6 +79,41 @@
}; };
}; };
# ── Element Calling (video/audio) tuning ──────────────────
elementCalling = {
fullAccessHomeservers = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
example = [ "matrix.peer.example.com" ];
description = ''
Additional Matrix server_names (beyond this server itself) that may
trigger LiveKit room creation on this server's SFU via lk-jwt-service.
Not needed for the common federated setup: each participant's client
always obtains its token from its own homeserver's JWT service and
publishes to its own SFU, and the participant who starts a call
creates the room on their own SFU — the remote user merely joins
(joining does not require full access).
Only set this for asymmetric cases: e.g. a peer homeserver that has
no focus of its own, or calls whose first participant lands on this
server's SFU but belongs to the peer.
'';
};
externalIP = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
example = "203.0.113.10";
description = ''
Optional pin: force LiveKit to advertise this public IPv4 in its
host/TURN ICE candidates. Not required in normal operation — the
module auto-detects the public IP at runtime (HTTPS egress
detection, falling back to STUN). Set it only to override a
mis-detected address (e.g. multi-WAN/VPN setups).
'';
};
};
# ── Domain setup registry ───────────────────────────────── # ── Domain setup registry ─────────────────────────────────
domainRequirements = lib.mkOption { domainRequirements = lib.mkOption {
type = lib.types.listOf (lib.types.submodule { type = lib.types.listOf (lib.types.submodule {
+38 -17
View File
@@ -40,7 +40,7 @@ let
# ── Bitcoin Base ──────────────────────────────────────────── # ── Bitcoin Base ────────────────────────────────────────────
++ lib.optionals cfg.services.bitcoin [ ++ lib.optionals cfg.services.bitcoin [
{ name = "Bitcoin Core"; unit = "bitcoind.service"; type = "system"; icon = "bitcoin-core"; enabled = cfg.services.bitcoin; category = "bitcoin-base"; credentials = [ { name = "Bitcoin Core"; unit = "bitcoind.service"; type = "system"; icon = "bitcoin-core"; enabled = cfg.services.bitcoin; category = "bitcoin-base"; credentials = [
{ label = "Tor Address — Access from anywhere via Tor Browser"; file = "/var/lib/tor/onion/bitcoind/hostname"; prefix = "http://"; } { label = "Tor Bitcoin P2P Address — Reachable only through Tor"; file = "/var/lib/tor/onion/bitcoind/hostname"; suffix = ":8333"; }
]; } ]; }
] ]
# ── Bitcoin Apps (services on top of the node) ───────────── # ── Bitcoin Apps (services on top of the node) ─────────────
@@ -122,6 +122,9 @@ let
role = activeRole; role = activeRole;
services = monitoredServices; services = monitoredServices;
feature_manager = true; feature_manager = true;
feature_states = {
bitcoin-tor-gossip = cfg.features.bitcoin-tor-gossip;
};
sovran_version = sovranVersion; sovran_version = sovranVersion;
}); });
@@ -132,16 +135,12 @@ let
"bitcoind.service" = if pkgs ? bitcoind then pkgs.bitcoind.version else "27.1.0"; "bitcoind.service" = if pkgs ? bitcoind then pkgs.bitcoind.version else "27.1.0";
"electrs.service" = if pkgs ? electrs then pkgs.electrs.version else "0.10.6"; "electrs.service" = if pkgs ? electrs then pkgs.electrs.version else "0.10.6";
"lnd.service" = if pkgs ? lnd then pkgs.lnd.version else "0.18.0"; "lnd.service" = if pkgs ? lnd then pkgs.lnd.version else "0.18.0";
# Keep the fallbacks aligned with the vendored packages used by the # Evaluate locally vendored packages directly so we don't accidentally
# service modules (RTL 0.15.8 and Mempool 3.2.1). The nixpkgs attrs are # pick up older/different versions from upstream nixpkgs.
# optional because these packages are built locally in this repository. "rtl.service" = (pkgs.callPackage ../../packages/rtl { fetchNodeModules = pkgs.callPackage ../../packages/build-support/fetch-node-modules.nix {}; }).version;
"rtl.service" = if pkgs ? clightning-rtl then pkgs.clightning-rtl.version else (if pkgs ? rtl then pkgs.rtl.version else "0.15.8");
# BTCPay Server is intentionally sourced from pkgs.stable by the service
# module. Read the configured package here rather than pkgs.btcpayserver
# (unstable), otherwise the Hub can advertise a version that is not running.
"btcpayserver.service" = lib.getVersion config.services.btcpayserver.package; "btcpayserver.service" = lib.getVersion config.services.btcpayserver.package;
"albyhub.service" = if pkgs ? albyhub then pkgs.albyhub.version else "1.8.0"; "albyhub.service" = (pkgs.callPackage ../../packages/albyhub {}).version;
"mempool.service" = if pkgs ? mempool then pkgs.mempool.version else "3.2.1"; "mempool.service" = (pkgs.callPackage ../../packages/mempool { fetchNodeModules = pkgs.callPackage ../../packages/build-support/fetch-node-modules.nix {}; }).version;
"matrix-synapse.service" = if pkgs ? matrix-synapse then pkgs.matrix-synapse.version else "1.115.0"; "matrix-synapse.service" = if pkgs ? matrix-synapse then pkgs.matrix-synapse.version else "1.115.0";
"livekit.service" = if pkgs ? livekit then pkgs.livekit.version else "1.5.2"; "livekit.service" = if pkgs ? livekit then pkgs.livekit.version else "1.5.2";
"vaultwarden.service" = if pkgs ? vaultwarden then pkgs.vaultwarden.version else "1.32.0"; "vaultwarden.service" = if pkgs ? vaultwarden then pkgs.vaultwarden.version else "1.32.0";
@@ -157,8 +156,10 @@ let
LOG="/var/log/sovran-hub-update.log" LOG="/var/log/sovran-hub-update.log"
STATUS="/var/log/sovran-hub-update.status" STATUS="/var/log/sovran-hub-update.status"
GENERATION="/var/log/sovran-hub-update.generation"
echo "RUNNING" > "$STATUS" echo "RUNNING" > "$STATUS"
rm -f "$GENERATION"
: > "$LOG" : > "$LOG"
exec > >(tee -a "$LOG") 2>&1 exec > >(tee -a "$LOG") 2>&1
@@ -193,6 +194,12 @@ let
if [ "$BOOT_RC" -ne 0 ]; then if [ "$BOOT_RC" -ne 0 ]; then
echo "[ERROR] nixos-rebuild boot failed" echo "[ERROR] nixos-rebuild boot failed"
RC=1 RC=1
elif ! readlink -f /nix/var/nix/profiles/system > "$GENERATION"; then
# The marker is informational only. The Hub derives pending-reboot
# state from the NixOS system profile itself, so failing to record
# the marker must not fail an otherwise successful update.
echo "[WARNING] update succeeded but its staged generation could not be recorded"
rm -f "$GENERATION"
fi fi
echo "" echo ""
fi fi
@@ -279,17 +286,31 @@ let
fi fi
''; '';
# ── Brave launcher wrapper: stable profile dir so Wayland app_id is # ── Brave Origin launcher wrapper: a *persistent* per-user profile dir.
# deterministic and GNOME Shell can match the window to the .desktop # It must NOT be wiped on exit: the Hub's logout marker cookie
# entry (fixes generic gear icon appearing in the dock). # (hub_manual_logout) and the session cookie live in this profile.
# Launching from a fresh/ephemeral profile every time throws away the
# marker, so /auto-login would mint a new session and silently log the
# user straight back in after they signed out and reopened the window.
# A stable directory also keeps the Wayland app_id deterministic so
# GNOME Shell can match the window to the .desktop entry (dock icon).
hub-brave-wrapper = pkgs.writeShellScript "sovran-hub-brave.sh" '' hub-brave-wrapper = pkgs.writeShellScript "sovran-hub-brave.sh" ''
export PATH="${lib.makeBinPath [ pkgs.brave pkgs.coreutils ]}:$PATH" export PATH="${lib.makeBinPath [ pkgs.brave-origin pkgs.coreutils ]}:$PATH"
HUB_DATA="/tmp/sovran-hub-brave-$(id -u)" # Per-user, persistent browser state. $XDG_STATE_HOME keeps it out of the
# way of backups and survives reboots and window close/reopen.
if [ -n "$XDG_STATE_HOME" ]; then
HUB_DATA="$XDG_STATE_HOME/sovran-hub-browser"
else
HUB_DATA="$HOME/.local/state/sovran-hub-browser"
fi
mkdir -p "$HUB_DATA" mkdir -p "$HUB_DATA"
trap '[ -n "$HUB_DATA" ] && rm -rf "$HUB_DATA"' EXIT INT TERM
export BAMF_DESKTOP_FILE_HINT="/run/current-system/sw/share/applications/sovran-hub.desktop" export BAMF_DESKTOP_FILE_HINT="/run/current-system/sw/share/applications/sovran-hub.desktop"
export GIO_LAUNCHED_DESKTOP_FILE="/run/current-system/sw/share/applications/sovran-hub.desktop" export GIO_LAUNCHED_DESKTOP_FILE="/run/current-system/sw/share/applications/sovran-hub.desktop"
brave --app=http://localhost:8937/auto-login \ # With a persistent profile Brave Origin's one-time "Proceed with Origin
# for free on Linux" onboarding dialog only appears once; keep skipping it
# anyway so it can never block auto-login (Linux-only switch).
brave-origin --app=http://localhost:8937/auto-login \
--skip-origin-startup-dialog \
--class=sovran-hub \ --class=sovran-hub \
--user-data-dir="$HUB_DATA" \ --user-data-dir="$HUB_DATA" \
--password-store=basic \ --password-store=basic \
+44 -15
View File
@@ -44,6 +44,35 @@ let
fi fi
fi fi
# ── Brave Origin migration (existing installs upgrading from `brave`) ──
# The old package's brave-browser.desktop no longer exists, so GNOME drops
# it from the dock and the Browsers folder. Swap the id in place, but only
# when the stale value is still present (never touch user customizations).
if [ -f "$USER_DB" ]; then
FAVS="$(${pkgs.dconf}/bin/dconf read /org/gnome/shell/favorite-apps 2>/dev/null || true)"
if [ -n "$FAVS" ]; then
NEW_FAVS="''${FAVS//brave-browser.desktop/brave-origin.desktop}"
if [ "$NEW_FAVS" != "$FAVS" ]; then
${pkgs.dconf}/bin/dconf write /org/gnome/shell/favorite-apps "$NEW_FAVS"
fi
fi
BROWSER_APPS="$(${pkgs.dconf}/bin/dconf read /org/gnome/desktop/app-folders/folders/Browsers/apps 2>/dev/null || true)"
if [ -n "$BROWSER_APPS" ]; then
NEW_BROWSER_APPS="''${BROWSER_APPS//brave-browser.desktop/brave-origin.desktop}"
if [ "$NEW_BROWSER_APPS" != "$BROWSER_APPS" ]; then
${pkgs.dconf}/bin/dconf write /org/gnome/desktop/app-folders/folders/Browsers/apps "$NEW_BROWSER_APPS"
fi
fi
fi
# A previous fresh install wrote the user's mimeapps.list with the old id;
# XDG gives it precedence over the new system-wide default, so rewrite it.
MIME_LIST="$HOME/.config/mimeapps.list"
if [ -f "$MIME_LIST" ] && ${pkgs.gnugrep}/bin/grep -q 'brave-browser\.desktop' "$MIME_LIST"; then
${pkgs.gnused}/bin/sed -i 's/brave-browser\.desktop/brave-origin.desktop/g' "$MIME_LIST"
fi
# Already applied — skip # Already applied — skip
if [ -f "$STAMP" ]; then if [ -f "$STAMP" ]; then
exit 0 exit 0
@@ -61,11 +90,11 @@ let
mkdir -p "$HOME/.config" mkdir -p "$HOME/.config"
cat > "$HOME/.config/mimeapps.list" << EOF cat > "$HOME/.config/mimeapps.list" << EOF
[Default Applications] [Default Applications]
text/html=brave-browser.desktop text/html=brave-origin.desktop
x-scheme-handler/http=brave-browser.desktop x-scheme-handler/http=brave-origin.desktop
x-scheme-handler/https=brave-browser.desktop x-scheme-handler/https=brave-origin.desktop
x-scheme-handler/about=brave-browser.desktop x-scheme-handler/about=brave-origin.desktop
x-scheme-handler/unknown=brave-browser.desktop x-scheme-handler/unknown=brave-origin.desktop
EOF EOF
${pkgs.dconf}/bin/dconf load / << EOF ${pkgs.dconf}/bin/dconf load / << EOF
@@ -104,7 +133,7 @@ search-filter-time-type='last_modified'
[org/gnome/shell] [org/gnome/shell]
disabled-extensions=['just-perfection-desktop@just-perfection'] disabled-extensions=['just-perfection-desktop@just-perfection']
enabled-extensions=['appindicatorsupport@rgcjonas.gmail.com', 'dash-to-dock-cosmic-@halfmexicanhalfamazing@gmail.com', 'Vitals@CoreCoding.com', 'dash-to-dock@micxgx.gmail.com', 'pop-shell@system76.com', 'date-menu-formatter@marcinjakubowski.github.com', 'light-style@gnome-shell-extensions.gcampax.github.com'] enabled-extensions=['appindicatorsupport@rgcjonas.gmail.com', 'dash-to-dock-cosmic-@halfmexicanhalfamazing@gmail.com', 'Vitals@CoreCoding.com', 'dash-to-dock@micxgx.gmail.com', 'pop-shell@system76.com', 'date-menu-formatter@marcinjakubowski.github.com', 'light-style@gnome-shell-extensions.gcampax.github.com']
favorite-apps=['brave-browser.desktop', 'org.gnome.Settings.desktop', 'org.gnome.Nautilus.desktop', 'sovran-hub.desktop', 'org.gnome.Software.desktop', 'org.gnome.Geary.desktop', 'org.gnome.Contacts.desktop', 'org.gnome.Calendar.desktop', 'sparrow.desktop', 'Bisq.desktop', 'bisq2.desktop'] favorite-apps=['brave-origin.desktop', 'org.gnome.Settings.desktop', 'org.gnome.Nautilus.desktop', 'sovran-hub.desktop', 'org.gnome.Software.desktop', 'org.gnome.Geary.desktop', 'org.gnome.Contacts.desktop', 'org.gnome.Calendar.desktop', 'sparrow.desktop', 'Bisq.desktop', 'bisq2.desktop']
welcome-dialog-last-shown-version='48.4' welcome-dialog-last-shown-version='48.4'
[org/gnome/desktop/app-folders] [org/gnome/desktop/app-folders]
@@ -112,7 +141,7 @@ folder-children=['Browsers', 'Office', 'Terminal', 'Chat', 'Bitcoin', 'Media', '
[org/gnome/desktop/app-folders/folders/Browsers] [org/gnome/desktop/app-folders/folders/Browsers]
name='Browsers' name='Browsers'
apps=['brave-browser.desktop', 'firefox.desktop', 'org.gnome.Epiphany.desktop'] apps=['brave-origin.desktop', 'firefox.desktop', 'org.gnome.Epiphany.desktop']
[org/gnome/desktop/app-folders/folders/Office] [org/gnome/desktop/app-folders/folders/Office]
name='Office' name='Office'
@@ -269,7 +298,7 @@ in
]; ];
favorite-apps = [ favorite-apps = [
"brave-browser.desktop" "brave-origin.desktop"
"org.gnome.Settings.desktop" "org.gnome.Settings.desktop"
"org.gnome.Nautilus.desktop" "org.gnome.Nautilus.desktop"
"sovran-hub.desktop" "sovran-hub.desktop"
@@ -292,7 +321,7 @@ in
"org/gnome/desktop/app-folders/folders/Browsers" = { "org/gnome/desktop/app-folders/folders/Browsers" = {
name = "Browsers"; name = "Browsers";
apps = [ apps = [
"brave-browser.desktop" "brave-origin.desktop"
"firefox.desktop" "firefox.desktop"
"org.gnome.Epiphany.desktop" "org.gnome.Epiphany.desktop"
]; ];
@@ -433,13 +462,13 @@ in
]; ];
xdg.mime.defaultApplications = { xdg.mime.defaultApplications = {
"text/html" = "brave-browser.desktop"; "text/html" = "brave-origin.desktop";
"x-scheme-handler/http" = "brave-browser.desktop"; "x-scheme-handler/http" = "brave-origin.desktop";
"x-scheme-handler/https" = "brave-browser.desktop"; "x-scheme-handler/https" = "brave-origin.desktop";
"x-scheme-handler/about" = "brave-browser.desktop"; "x-scheme-handler/about" = "brave-origin.desktop";
"x-scheme-handler/unknown" = "brave-browser.desktop"; "x-scheme-handler/unknown" = "brave-origin.desktop";
}; };
environment.sessionVariables.BROWSER = "brave-browser"; environment.sessionVariables.BROWSER = "brave-origin";
} }
+267 -27
View File
@@ -33,9 +33,15 @@ lib.mkIf config.sovran_systemsOS.features.element-calling {
''; '';
}; };
####### ENSURE SERVICES START AFTER KEY EXISTS ####### ####### ENSURE SERVICES START AFTER KEY & NETWORK EXIST #######
systemd.services.livekit.after = [ "livekit-key-setup.service" "livekit-turn-setup.service" ]; # Ordering against network-online.target matters: livekit-turn-setup detects
systemd.services.livekit.wants = [ "livekit-key-setup.service" "livekit-turn-setup.service" ]; # the primary interface from the IPv4 default route. If it runs before the
# network is up (no default route yet) it exits 1 and, being a hard
# dependency of livekit.service, takes livekit down with it — the Hub then
# shows a "failed" red dot until livekit is restarted manually. See the
# livekit-turn-setup block for the matching network-online ordering.
systemd.services.livekit.after = [ "network-online.target" "livekit-key-setup.service" "livekit-turn-setup.service" ];
systemd.services.livekit.wants = [ "network-online.target" "livekit-key-setup.service" "livekit-turn-setup.service" ];
systemd.services.lk-jwt-service.after = [ "livekit-key-setup.service" ]; systemd.services.lk-jwt-service.after = [ "livekit-key-setup.service" ];
systemd.services.lk-jwt-service.wants = [ "livekit-key-setup.service" ]; systemd.services.lk-jwt-service.wants = [ "livekit-key-setup.service" ];
@@ -114,7 +120,12 @@ EOF
# substituted) that the overridden ExecStart loads. # substituted) that the overridden ExecStart loads.
systemd.services.livekit-turn-setup = { systemd.services.livekit-turn-setup = {
description = "Stage TURN cert and generate LiveKit runtime config from domain files"; description = "Stage TURN cert and generate LiveKit runtime config from domain files";
after = [ "caddy.service" "livekit-key-setup.service" ]; # Wait for a default IPv4 route before detecting the interface, and for
# Caddy to have started (cert generation is async, so also see the retry
# loop below). Otherwise on a cold boot this unit can fail / produce empty
# certs, which breaks livekit.service (requiredBy) and shows a red dot.
after = [ "network-online.target" "caddy.service" "livekit-key-setup.service" ];
wants = [ "network-online.target" ];
before = [ "livekit.service" ]; before = [ "livekit.service" ];
requiredBy = [ "livekit.service" ]; requiredBy = [ "livekit.service" ];
wantedBy = [ "multi-user.target" ]; wantedBy = [ "multi-user.target" ];
@@ -125,19 +136,39 @@ EOF
unitConfig = { unitConfig = {
ConditionPathExists = "/var/lib/domains/element-calling"; ConditionPathExists = "/var/lib/domains/element-calling";
}; };
path = [ pkgs.coreutils pkgs.findutils pkgs.iproute2 pkgs.gawk ]; path = [ pkgs.coreutils pkgs.findutils pkgs.iproute2 pkgs.gawk pkgs.python3 ];
script = '' script = ''
MATRIX=$(cat /var/lib/domains/matrix) MATRIX=$(cat /var/lib/domains/matrix)
ELEMENT_CALLING=$(cat /var/lib/domains/element-calling)
mkdir -p /run/livekit mkdir -p /run/livekit
# Copy Caddy's already-issued matrix cert/key into LiveKit's state dir. # Copy Caddy's already-issued matrix cert/key into LiveKit's state dir.
# The ACME CA hostname directory can vary, so glob for the domain dir. # The ACME CA hostname directory can vary, so glob for the domain dir.
CRT=$(find /var/lib/caddy -path "*/$MATRIX/$MATRIX.crt" | head -n1) # Caddy issues ACME certs asynchronously, so on a fresh boot the cert may
KEY=$(find /var/lib/caddy -path "*/$MATRIX/$MATRIX.key" | head -n1) # not exist yet. Retry (bounded) so we never write an empty turn.crt/key;
cp "$CRT" /var/lib/livekit/turn.crt # otherwise embedded TURN silently breaks until the next livekit restart.
cp "$KEY" /var/lib/livekit/turn.key CRT=""
chmod 640 /var/lib/livekit/turn.crt /var/lib/livekit/turn.key KEY=""
for _ in $(seq 1 30); do
CRT=$(find /var/lib/caddy -path "*/$MATRIX/$MATRIX.crt" | head -n1)
KEY=$(find /var/lib/caddy -path "*/$MATRIX/$MATRIX.key" | head -n1)
if [ -n "$CRT" ] && [ -n "$KEY" ] \
&& [ -s "$CRT" ] && [ -s "$KEY" ]; then
break
fi
CRT=""
KEY=""
echo "Waiting for Caddy to issue the $MATRIX ACME certificate..."
sleep 2
done
if [ -z "$CRT" ] || [ -z "$KEY" ]; then
echo "ERROR: Caddy ACME certificate for $MATRIX not available after retries; TURN will not be enabled for LiveKit." >&2
else
cp "$CRT" /var/lib/livekit/turn.crt
cp "$KEY" /var/lib/livekit/turn.key
chmod 640 /var/lib/livekit/turn.crt /var/lib/livekit/turn.key
fi
# Detect the primary network interface from the IPv4 default route. # Detect the primary network interface from the IPv4 default route.
# Restricting LiveKit to this single interface prevents it from # Restricting LiveKit to this single interface prevents it from
@@ -158,7 +189,57 @@ EOF
# rtc.interfaces.includes are only known at runtime, so they are # rtc.interfaces.includes are only known at runtime, so they are
# substituted here. The cert/key paths point at the LoadCredential-staged # substituted here. The cert/key paths point at the LoadCredential-staged
# copies under /run/credentials. # copies under /run/credentials.
cat > /run/livekit/livekit.yaml <<EOF #
# Determine the public IPv4 to advertise in LiveKit ICE candidates.
# Remote peers must be able to reach this address, so it must be the
# server's public IP — or the router's WAN IP when the server is behind
# NAT with port-forwarding. It does not need to be assigned to this box,
# and it may be dynamic.
#
# Reuse the shared detector (/var/lib/sovran/public-ip.py — see
# modules/core/public-ip.nix) instead of running our own: one script,
# one cache, privacy-first (STUN -> DNS -> opt-in HTTPS echo). Priority:
# 1. sovran_systemsOS.elementCalling.externalIP (explicit pin, if set)
# 2. /var/lib/secrets/external-ip (the shared cache)
# 3. run the detector now (it refreshes the cache)
# 4. STUN auto-detection (use_external_ip) as the fallback, with a
# warning — this is where broken installs used to silently end up
# advertising a private IP, causing "call connects but no video".
EXTERNAL_IP='${if config.sovran_systemsOS.elementCalling.externalIP != null then config.sovran_systemsOS.elementCalling.externalIP else ""}'
PUBLIC_IP="$EXTERNAL_IP"
if [ -z "$PUBLIC_IP" ] && [ -f /var/lib/secrets/external-ip ]; then
PUBLIC_IP=$(tr -d '[:space:]' < /var/lib/secrets/external-ip 2>/dev/null)
fi
if [ -z "$PUBLIC_IP" ] && [ -x /var/lib/sovran/public-ip.py ]; then
PUBLIC_IP=$(python3 /var/lib/sovran/public-ip.py check 2>/dev/null | head -n1)
fi
# Reject non-routable addresses (loopback, private, link-local, CGNAT).
# A detected/pinned address like this must never be advertised.
if [ -n "$PUBLIC_IP" ] && printf '%s' "$PUBLIC_IP" | grep -qE \
'^(0\.|127\.|10\.|100\.64\.|169\.254\.|172\.(1[6-9]|2[0-9]|3[01])\.|192\.168\.)'; then
echo "WARNING: external IP '$PUBLIC_IP' is not routable; falling back to STUN auto-detection." >&2
PUBLIC_IP=""
fi
if [ -n "$PUBLIC_IP" ]; then
cat > /run/livekit/livekit.yaml <<EOF
port: 7880
rtc:
use_external_ip: false
node_ip: $PUBLIC_IP
tcp_port: 7881
udp_port: 7882
port_range_start: 30000
port_range_end: 40000
interfaces:
includes:
- $IFACE
EOF
echo "LiveKit will advertise public IP: $PUBLIC_IP"
else
cat > /run/livekit/livekit.yaml <<EOF
port: 7880 port: 7880
rtc: rtc:
use_external_ip: true use_external_ip: true
@@ -170,6 +251,20 @@ rtc:
interfaces: interfaces:
includes: includes:
- $IFACE - $IFACE
EOF
echo "WARNING: could not determine a public IP for LiveKit; using STUN auto-detection. If calls connect without media, check STUN egress or set sovran_systemsOS.elementCalling.externalIP." >&2
fi
# Webhooks → lk-jwt-service. The JWT service validates the HMAC
# signature against the same key file it issues tokens with, and uses
# the events (participant_left / room_finished) to detect abruptly
# disconnected participants instead of waiting for the delayed-event
# timeout. The URL hits local Caddy via the /etc/hosts loopback
# override and is routed to the JWT service by the element-calling
# vhost (/livekit/jwt/sfu_webhook → 8073).
LK_KEY=$(cut -d: -f1 < ${livekitKeyFile} | tr -d '[:space:]')
cat >> /run/livekit/livekit.yaml <<EOF
room: room:
auto_create: false auto_create: false
turn: turn:
@@ -179,6 +274,10 @@ turn:
udp_port: 3478 udp_port: 3478
cert_file: /run/credentials/livekit.service/turn-cert cert_file: /run/credentials/livekit.service/turn-cert
key_file: /run/credentials/livekit.service/turn-key key_file: /run/credentials/livekit.service/turn-key
webhook:
api_key: $LK_KEY
urls:
- https://$ELEMENT_CALLING/livekit/jwt/sfu_webhook
EOF EOF
chmod 644 /run/livekit/livekit.yaml chmod 644 /run/livekit/livekit.yaml
@@ -186,24 +285,17 @@ EOF
}; };
####### LIVEKIT SERVICE ####### ####### LIVEKIT SERVICE #######
# NOTE: the runtime config (rtc ports, TURN, webhook, node_ip) is generated
# by livekit-turn-setup and delivered via LoadCredential; the upstream
# module's `settings` block is therefore intentionally NOT used (it would
# be dead config that silently diverges from what LiveKit actually loads).
# The firewall ports are opened explicitly below; openFirewall is left off
# so the upstream module does not also open 7880/tcp publicly (Caddy fronts
# the SFU on this host).
services.livekit = { services.livekit = {
enable = true; enable = true;
openFirewall = true; openFirewall = false;
keyFile = livekitKeyFile; keyFile = livekitKeyFile;
settings = {
rtc.use_external_ip = true;
rtc.skip_external_ip_validation = true;
rtc.tcp_port = 7881;
rtc.udp_port = 7882;
rtc.port_range_start = 30000;
rtc.port_range_end = 40000;
room.auto_create = false;
turn = {
enabled = true;
tls_port = 5349;
udp_port = 3478;
};
};
}; };
# Override ExecStart to load the runtime-generated config (which carries the # Override ExecStart to load the runtime-generated config (which carries the
@@ -247,12 +339,26 @@ EOF
script = '' script = ''
ELEMENT_CALLING=$(cat /var/lib/domains/element-calling) ELEMENT_CALLING=$(cat /var/lib/domains/element-calling)
MATRIX=$(cat /var/lib/domains/matrix) MATRIX=$(cat /var/lib/domains/matrix)
FULL_ACCESS_HOMESERVERS="$MATRIX"
# Federated peers may also be granted LiveKit room-creation (full access)
# on this SFU via sovran_systemsOS.elementCalling.fullAccessHomeservers.
# Without this, remote users can join existing calls but cannot be the
# first to start one on your SFU.
EXTRA_HS='${lib.concatStringsSep "," config.sovran_systemsOS.elementCalling.fullAccessHomeservers}'
if [ -n "$EXTRA_HS" ]; then
FULL_ACCESS_HOMESERVERS="$FULL_ACCESS_HOMESERVERS,$EXTRA_HS"
fi
mkdir -p /run/lk-jwt-service mkdir -p /run/lk-jwt-service
cat > /run/lk-jwt-service/env <<EOF cat > /run/lk-jwt-service/env <<EOF
LIVEKIT_URL=wss://$ELEMENT_CALLING LIVEKIT_URL=wss://$ELEMENT_CALLING
LIVEKIT_FULL_ACCESS_HOMESERVERS=$MATRIX LIVEKIT_FULL_ACCESS_HOMESERVERS=$FULL_ACCESS_HOMESERVERS
# Re-check, every 60s, that connected participants are still on the SFU;
# guards against missed SFU webhooks (e.g. an SFU restart) leaving stale
# call members in Matrix rooms.
LIVEKIT_SANITY_CHECK_INTERVAL_SECONDS=60
EOF EOF
chmod 640 /run/lk-jwt-service/env chmod 640 /run/lk-jwt-service/env
@@ -264,6 +370,9 @@ EOF
enable = true; enable = true;
port = 8073; port = 8073;
keyFile = livekitKeyFile; keyFile = livekitKeyFile;
# Required by the upstream module's option type, but overridden at runtime
# by EnvironmentFile (/run/lk-jwt-service/env, generated above from the
# element-calling domain). Kept as a harmless placeholder.
livekitUrl = "wss://placeholder.local"; livekitUrl = "wss://placeholder.local";
}; };
@@ -271,6 +380,126 @@ EOF
"/run/lk-jwt-service/env" "/run/lk-jwt-service/env"
]; ];
# Restart LiveKit / lk-jwt-service when a rebuild regenerates their runtime
# configs (new domains, externalIP, full-access list), mirroring the domain
# change flow.
# Re-run the config generator and restart LiveKit when a rebuild regenerates
# the runtime config, or when the Hub persists a new external IP (dynamic
# WAN IPs), so the advertised ICE candidate stays current without a manual
# restart. The trigger chain: external-ip change → livekit-turn-setup
# re-runs → rewrites livekit.yaml → livekit restarts with the new config.
systemd.services.livekit-turn-setup.restartTriggers = [ "/var/lib/secrets/external-ip" ];
systemd.services.livekit.restartTriggers = [ "/run/livekit/livekit.yaml" ];
systemd.services.lk-jwt-service.restartTriggers = [ "/run/lk-jwt-service/env" ];
####### PUBLIC REACHABILITY SELF-CHECK #######
# Diagnostic only — never a hard dependency of livekit/caddy. Catches the
# classic "call connects but no media" setup errors at boot instead of at
# call time:
# * the element-calling domain having no public records (or resolving to
# loopback/link-local/CGNAT for remote peers),
# * the lk-jwt-service being unreachable through Caddy,
# * the MatrixRTC transports endpoint being absent (Element X cannot
# discover calling and shows MISSING_MATRIX_RTC_TRANSPORT).
# The check queries only the operator's own DNS provider (the domain's
# authoritative nameservers, resolved via the local resolver) plus the
# server's own Caddy and public IP — no third-party resolver or service is
# contacted. dig queries resolvers directly, so the /etc/hosts loopback
# overrides (modules/core/local-domain-loopback.nix) do not influence the
# result.
systemd.services.element-calling-public-check = {
description = "Verify Element Calling domain, JWT service and MatrixRTC transports endpoint are publicly reachable";
after = [ "network-online.target" "caddy.service" "livekit.service" "lk-jwt-service.service" ];
wants = [ "network-online.target" ];
wantedBy = [ "multi-user.target" ];
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
};
unitConfig = {
ConditionPathExists = "/var/lib/domains/element-calling";
};
path = [ pkgs.coreutils pkgs.gawk pkgs.dnsutils pkgs.curl ];
script = ''
ELEMENT_CALLING=$(cat /var/lib/domains/element-calling)
MATRIX=$(cat /var/lib/domains/matrix)
FAIL=0
echo "── Element Calling public reachability self-check ──"
# 1) Authoritative DNS view (bypassing the /etc/hosts loopback
# overrides). Resolve the domain's own nameservers via the local
# resolver, then query those nameservers directly — the only party
# that sees the query is the DNS provider the operator already uses
# for the domain.
NS_LIST=$(dig +short NS "$ELEMENT_CALLING" 2>/dev/null | tr '\n' ' ')
if [ -n "$NS_LIST" ]; then
IPS=""
for NSRV in $NS_LIST; do
IPS=$( { dig +short A "$ELEMENT_CALLING" "@$NSRV" 2>/dev/null; dig +short AAAA "$ELEMENT_CALLING" "@$NSRV" 2>/dev/null; } | tr '\n' ' ' )
[ -n "$IPS" ] && break
done
echo "Authoritative nameservers for $ELEMENT_CALLING: $NS_LIST"
else
echo "WARNING: could not resolve nameservers for $ELEMENT_CALLING via the local resolver; using the local resolver's answer instead." >&2
IPS=$( { dig +short A "$ELEMENT_CALLING" 2>/dev/null; dig +short AAAA "$ELEMENT_CALLING" 2>/dev/null; } | tr '\n' ' ' )
fi
if [ -z "$IPS" ]; then
echo "ERROR: no A/AAAA records for $ELEMENT_CALLING at its authoritative nameservers. Remote peers cannot reach this LiveKit; calls will connect without media." >&2
FAIL=1
else
echo "Public DNS for $ELEMENT_CALLING: $IPS"
for IP in $IPS; do
case "$IP" in
0.*|127.*|169.254.*|100.64.*|::1|fe80:*|fc*:*|fd*:*)
echo "ERROR: $ELEMENT_CALLING resolves to $IP (loopback/link-local/CGNAT). Remote peers cannot reach it." >&2
FAIL=1 ;;
esac
done
fi
# 2) lk-jwt-service healthz through Caddy (validates the proxy chain).
if curl -fsS --max-time 10 "https://$ELEMENT_CALLING/livekit/jwt/healthz" >/dev/null 2>&1; then
echo "OK: https://$ELEMENT_CALLING/livekit/jwt/healthz responds"
else
echo "ERROR: https://$ELEMENT_CALLING/livekit/jwt/healthz not reachable through Caddy." >&2
FAIL=1
fi
# 3) Same healthz via the first public IP (tests the full NAT path).
# NOTE: if this box is behind the same NAT you are testing through,
# routers without hairpin NAT will fail this step — the warning is
# then expected and harmless; verify from an external device instead.
if [ -n "$IPS" ]; then
PUBIP=$(echo "$IPS" | awk '{print $1}')
if curl -fsS --max-time 15 --resolve "$ELEMENT_CALLING:443:$PUBIP" "https://$ELEMENT_CALLING/livekit/jwt/healthz" >/dev/null 2>&1; then
echo "OK: healthz reachable via public IP $PUBIP (NAT path works)"
else
echo "WARNING: healthz NOT reachable via public IP $PUBIP — check router port-forwarding (443/TCP) and NAT hairpin. Expected if the router lacks hairpin NAT; verify from an external device." >&2
fi
fi
# 4) MatrixRTC transports registry (MSC4519) — required by Element X.
CODE=$(curl -s -o /dev/null -w "%{http_code}" --max-time 10 "https://$MATRIX/_matrix/client/unstable/org.matrix.msc4143/rtc/transports")
case "$CODE" in
401|200)
echo "OK: MatrixRTC transports endpoint present (HTTP $CODE; auth required is expected)" ;;
404)
echo "ERROR: /_matrix/client/unstable/org.matrix.msc4143/rtc/transports missing (HTTP 404) — Element X cannot discover calling. Enable msc4143_enabled and matrix_rtc.transports in Synapse." >&2
FAIL=1 ;;
*)
echo "WARNING: transports endpoint returned HTTP $CODE" >&2 ;;
esac
if [ "$FAIL" -eq 1 ]; then
echo "── Element Calling self-check FAILED — see errors above ──" >&2
exit 1
fi
echo "── Element Calling self-check passed ──"
'';
};
####### SYNAPSE RUNTIME CONFIG (element-calling additions) ####### ####### SYNAPSE RUNTIME CONFIG (element-calling additions) #######
systemd.services.element-calling-synapse-config = { systemd.services.element-calling-synapse-config = {
description = "Generate Synapse runtime config for Element Calling"; description = "Generate Synapse runtime config for Element Calling";
@@ -287,6 +516,7 @@ EOF
path = [ pkgs.coreutils ]; path = [ pkgs.coreutils ];
script = '' script = ''
MATRIX=$(cat /var/lib/domains/matrix) MATRIX=$(cat /var/lib/domains/matrix)
ELEMENT_CALLING=$(cat /var/lib/domains/element-calling)
mkdir -p /run/matrix-synapse mkdir -p /run/matrix-synapse
@@ -296,7 +526,17 @@ public_baseurl: "https://$MATRIX"
serve_server_wellknown: true serve_server_wellknown: true
experimental_features: experimental_features:
msc3266_enabled: true msc3266_enabled: true
# MSC4143: enables the MatrixRTC transports registry endpoint
# (/_matrix/client/unstable/org.matrix.msc4143/rtc/transports, MSC4519).
# Element X requires this endpoint to discover the LiveKit focus; without it
# mobile clients fail with MISSING_MATRIX_RTC_TRANSPORT / cannot start calls.
msc4143_enabled: true
msc4222_enabled: true msc4222_enabled: true
# MSC4519: advertise this site's LiveKit focus via the transports registry.
matrix_rtc:
transports:
- type: livekit
livekit_service_url: "https://$ELEMENT_CALLING/livekit/jwt"
max_event_delay_duration: "24h" max_event_delay_duration: "24h"
rc_message: rc_message:
per_second: 0.5 per_second: 0.5
+1
View File
@@ -17,6 +17,7 @@
./core/no-sleep.nix ./core/no-sleep.nix
./core/cpu-performance.nix ./core/cpu-performance.nix
./core/local-domain-loopback.nix ./core/local-domain-loopback.nix
./core/public-ip.nix
# ── Always on (no flag) ─────────────────────────────────── # ── Always on (no flag) ───────────────────────────────────
./php.nix ./php.nix
+2 -7
View File
@@ -3,13 +3,8 @@
let let
albyHubPort = 18080; albyHubPort = 18080;
albyHubApiBase = "http://127.0.0.1:${toString albyHubPort}"; albyHubApiBase = "http://127.0.0.1:${toString albyHubPort}";
patchedAlbyHub = pkgs.albyhub.overrideAttrs (old: { vendoredAlbyHub = pkgs.callPackage ../packages/albyhub {};
patches = (old.patches or []) ++ [ patchedAlbyHub = vendoredAlbyHub;
../packages/albyhub/0001-private-route-hints.patch
../packages/albyhub/0002-isolated-invoice-app-id.patch
../packages/albyhub/0003-loopback-bind-host.patch
];
});
lndRpcAddress = lib.attrByPath [ "services" "lnd" "rpcAddress" ] "127.0.0.1" config; lndRpcAddress = lib.attrByPath [ "services" "lnd" "rpcAddress" ] "127.0.0.1" config;
lndRpcPort = toString (lib.attrByPath [ "services" "lnd" "rpcPort" ] 10009 config); lndRpcPort = toString (lib.attrByPath [ "services" "lnd" "rpcPort" ] 10009 config);
+24 -9
View File
@@ -47,29 +47,44 @@ EOF
systemd.services.zeus-connect-setup = { systemd.services.zeus-connect-setup = {
description = "Save Zeus lndconnect URL"; description = "Save Zeus lndconnect URL";
wantedBy = [ "multi-user.target" ]; wantedBy = [ "multi-user.target" ];
after = [ "lnd.service" ]; after = [ "lnd.service" "onion-addresses.service" ];
wants = [ "lnd.service" "onion-addresses.service" ];
serviceConfig = { serviceConfig = {
Type = "oneshot"; Type = "oneshot";
RemainAfterExit = true; RemainAfterExit = true;
}; };
path = [ pkgs.coreutils "/run/current-system/sw" ]; # sudo is required: the lndconnect wrapper re-execs as the lnd user so it
# can read admin.macaroon (not group-readable).
path = [ pkgs.coreutils pkgs.gnugrep pkgs.sudo "/run/current-system/sw" ];
script = '' script = ''
SECRET_FILE="/var/lib/secrets/zeus-connect-url" SECRET_FILE="/var/lib/secrets/zeus-connect-url"
mkdir -p /var/lib/secrets mkdir -p /var/lib/secrets
# LND may still be creating the wallet / macaroon, and the dedicated
# lnd-rest onion hostname is published by onion-addresses.service.
URL="" URL=""
if command -v lndconnect >/dev/null 2>&1; then ATTEMPTS=0
URL=$(lndconnect --url 2>/dev/null || true) while [ "$ATTEMPTS" -lt 60 ]; do
elif command -v lnconnect-clnrest >/dev/null 2>&1; then if command -v lndconnect >/dev/null 2>&1; then
URL=$(lnconnect-clnrest --url 2>/dev/null || true) URL=$(lndconnect --url 2>/dev/null | tr -d '\r' | tail -n 1 || true)
fi fi
# Zeus LND REST over Tor: lndconnect://<v3-onion>:8080?macaroon=...
if echo "$URL" | grep -q '^lndconnect://' \
&& echo "$URL" | grep -q '\.onion' \
&& echo "$URL" | grep -q 'macaroon='; then
break
fi
URL=""
ATTEMPTS=$((ATTEMPTS + 1))
sleep 2
done
if [ -n "$URL" ]; then if [ -n "$URL" ]; then
echo "$URL" > "$SECRET_FILE" printf '%s\n' "$URL" > "$SECRET_FILE"
chmod 600 "$SECRET_FILE" chmod 600 "$SECRET_FILE"
echo "Zeus connect URL saved." echo "Zeus connect URL saved."
else else
echo "No lndconnect URL available yet." echo "No valid lndconnect URL available yet."
fi fi
''; '';
}; };
@@ -1,13 +0,0 @@
diff --git a/lnclient/lnd/lnd.go b/lnclient/lnd/lnd.go
index bad532f..ba35b7b 100644
--- a/lnclient/lnd/lnd.go
+++ b/lnclient/lnd/lnd.go
@@ -708,7 +708,7 @@ func (svc *LNDService) MakeInvoice(ctx context.Context, amountMsat int64, descri
DescriptionHash: descriptionHashBytes,
Expiry: expiry,
RouteHints: hints,
- Private: !hasPublicChannels, // use private channel hints in the invoice
+ Private: true, // always include private channel hints in the invoice
}
resp, err := svc.client.AddInvoice(ctx, addInvoiceRequest)
@@ -1,71 +0,0 @@
diff --git a/api/models.go b/api/models.go
index 28bd117..dceb79a 100644
--- a/api/models.go
+++ b/api/models.go
@@ -46,7 +46,7 @@ type API interface {
ListTransactions(ctx context.Context, appId *uint, limit uint64, offset uint64) (*ListTransactionsResponse, error)
ListOnchainTransactions(ctx context.Context) ([]OnchainTransaction, error)
SendPayment(ctx context.Context, invoice string, amountMsat *uint64, metadata map[string]interface{}, fromAppId *uint) (*SendPaymentResponse, error)
- CreateInvoice(ctx context.Context, amountMsat uint64, description string) (*MakeInvoiceResponse, error)
+ CreateInvoice(ctx context.Context, amountMsat uint64, description string, appId *uint) (*MakeInvoiceResponse, error)
LookupInvoice(ctx context.Context, paymentHash string) (*LookupInvoiceResponse, error)
SetTransactionUserLabels(ctx context.Context, id uint, labels map[string]string) error
RequestMempoolApi(ctx context.Context, endpoint string) (interface{}, error)
@@ -586,6 +586,7 @@ type MakeInvoiceRequest struct {
AmountSat *uint64 `json:"amountSat"`
AmountMsat *uint64 `json:"amountMsat"`
Description string `json:"description"`
+ AppId *uint `json:"appId"`
}
type ResetRouterRequest struct {
diff --git a/api/transactions.go b/api/transactions.go
index aaf9380..3f9850a 100644
--- a/api/transactions.go
+++ b/api/transactions.go
@@ -12,12 +12,12 @@ import (
"github.com/sirupsen/logrus"
)
-func (api *api) CreateInvoice(ctx context.Context, amountMsat uint64, description string) (*MakeInvoiceResponse, error) {
+func (api *api) CreateInvoice(ctx context.Context, amountMsat uint64, description string, appId *uint) (*MakeInvoiceResponse, error) {
lnClient := api.svc.GetLNClient()
if lnClient == nil {
return nil, ErrLNClientNotStarted
}
- transaction, err := api.svc.GetTransactionsService().MakeInvoice(ctx, amountMsat, description, "", 0, nil, lnClient, nil, nil, nil)
+ transaction, err := api.svc.GetTransactionsService().MakeInvoice(ctx, amountMsat, description, "", 0, nil, lnClient, appId, nil, nil)
if err != nil {
return nil, err
}
diff --git a/http/http_service.go b/http/http_service.go
index bf650b9..cf61250 100644
--- a/http/http_service.go
+++ b/http/http_service.go
@@ -687,7 +687,12 @@ func (httpSvc *HttpService) makeInvoiceHandler(c echo.Context) error {
amountMsat = *resolvedAmountMsat
}
- invoice, err := httpSvc.api.CreateInvoice(c.Request().Context(), amountMsat, makeInvoiceRequest.Description)
+ invoice, err := httpSvc.api.CreateInvoice(
+ c.Request().Context(),
+ amountMsat,
+ makeInvoiceRequest.Description,
+ makeInvoiceRequest.AppId,
+ )
if err != nil {
return c.JSON(http.StatusInternalServerError, ErrorResponse{
diff --git a/wails/wails_handlers.go b/wails/wails_handlers.go
index d25259b..c9fe4e8 100644
--- a/wails/wails_handlers.go
+++ b/wails/wails_handlers.go
@@ -600,7 +600,7 @@ func (app *WailsApp) WailsRequestRouter(route string, method string, body string
if resolvedAmountMsat != nil {
amountMsat = *resolvedAmountMsat
}
- invoice, err := app.api.CreateInvoice(ctx, amountMsat, makeInvoiceRequest.Description)
+ invoice, err := app.api.CreateInvoice(ctx, amountMsat, makeInvoiceRequest.Description, nil)
if err != nil {
return WailsRequestRouterResponse{Body: nil, Error: err.Error()}
}
@@ -1,37 +0,0 @@
diff --git a/cmd/http/main.go b/cmd/http/main.go
index ed31f96..4d31212 100644
--- a/cmd/http/main.go
+++ b/cmd/http/main.go
@@ -2,8 +2,8 @@ package main
import (
"context"
- "fmt"
nethttp "net/http"
+ "net"
"os"
"os/signal"
"syscall"
@@ -51,8 +51,9 @@ func main() {
httpSvc := http.NewHttpService(svc, svc.GetEventPublisher())
httpSvc.RegisterSharedRoutes(e)
//start Echo server
+ bindAddress := net.JoinHostPort(svc.GetConfig().GetEnv().Host, svc.GetConfig().GetEnv().Port)
go func() {
- if err := e.Start(fmt.Sprintf(":%v", svc.GetConfig().GetEnv().Port)); err != nil && err != nethttp.ErrServerClosed {
+ if err := e.Start(bindAddress); err != nil && err != nethttp.ErrServerClosed {
logger.Logger.WithError(err).Error("echo server failed to start")
cancel()
}
diff --git a/config/models.go b/config/models.go
index 0fb8870..dc11afd 100644
--- a/config/models.go
+++ b/config/models.go
@@ -24,6 +24,7 @@ type AppConfig struct {
LNDAddress string `envconfig:"LND_ADDRESS"`
LNDCertFile string `envconfig:"LND_CERT_FILE"`
LNDMacaroonFile string `envconfig:"LND_MACAROON_FILE"`
+ Host string `envconfig:"HOST" default:"127.0.0.1"`
Workdir string `envconfig:"WORK_DIR"`
Port string `envconfig:"PORT" default:"8080"`
DatabaseUri string `envconfig:"DATABASE_URI" default:"nwc.db"`
+78
View File
@@ -0,0 +1,78 @@
{ lib
, buildGoModule
, fetchFromGitHub
, stdenv
}:
buildGoModule rec {
pname = "albyhub";
version = "1.24.0";
# sovran fork = upstream v1.24.0 + LND-only, no frontend, HOST bind,
# always-private route hints (the customization lives in the fork's commits)
src = fetchFromGitHub {
owner = "naturallaw777";
repo = "hub";
tag = "sovran-1.24.0";
# round 1: copy the "got: sha256-..." from the build error
hash = "sha256-9l7xK7iA1p9qQRClgNV+eYg/vYJxbwBiRObeLRpyfDo=";
};
# `go mod vendor` strips the secp256k1-zkp cgo headers (include/), so use
# the full module cache. Round 2: copy the "got: sha256-..." from the error
proxyVendor = true;
vendorHash = "sha256-U0NLVV0gH2IERqaGsJwE2f+iZQ35D+czH8mUKXSM4Wc=";
subPackages = [ "cmd/http" ];
# LND client needs cgo (secp256k1-zkp)
buildInputs = [ (lib.getLib stdenv.cc.cc) ];
# pin module downloads to a hermetic proxy and the local toolchain
# (otherwise GOPROXY/GOTOOLCHAIN can leak into the builder env and the
# cache comes back incomplete — the original failure)
overrideModAttrs = (finalAttrs: previousAttrs: {
modBuildPhase = ''
runHook preBuild
export GIT_SSL_CAINFO=$NIX_SSL_CERT_FILE
export GOPROXY=https://proxy.golang.org,direct
export GOSUMDB=sum.golang.org
export GOTOOLCHAIN=local
mkdir -p "$GOPATH/pkg/mod/cache/download"
go mod download all
export GOPROXY="file://$GOPATH/pkg/mod/cache/download"
go list ./cmd/http
mkdir -p vendor
runHook postBuild
'';
});
ldflags = [
"-X github.com/getAlby/hub/version.Tag=${version}"
"-s"
"-w"
];
postInstall = ''
mv $out/bin/http $out/bin/albyhub
'';
preFixup = ''
# Go's external linker bakes the sandbox build dir into the RPATH;
# rewrite it to the real store paths before the fixup audit
patchelf --set-rpath ${
lib.makeLibraryPath [
(lib.getLib stdenv.cc.cc)
(lib.getLib stdenv.cc.libc)
]
} $out/bin/albyhub
'';
meta.mainProgram = "albyhub";
}
-19
View File
@@ -1,19 +0,0 @@
{ lib, buildGoModule, fetchFromGitHub }:
buildGoModule rec {
pname = "lndinit";
version = "0.1.3-beta";
src = fetchFromGitHub {
owner = "lightninglabs";
repo = pname;
rev = "v${version}";
sha256 = "sha256-sO1DpbppCurxr9g9nUl9Vx82FJK1mTcUw3rY1Fm1wEU=";
};
vendorHash = "sha256-El44BS5Bu0K/klMxkajciU/R6uqiXBMOiLN536QztbE=";
subPackages = [ "." ];
meta = with lib; {
description = "Wallet initializer for lnd (from nix-bitcoin)";
homepage = "https://github.com/lightninglabs/lndinit";
license = licenses.mit;
};
}
+3 -3
View File
@@ -10,11 +10,11 @@
}: }:
let self = stdenvNoCC.mkDerivation { let self = stdenvNoCC.mkDerivation {
pname = "rtl"; pname = "rtl";
version = "0.15.8"; version = "0.15.10";
src = fetchurl { src = fetchurl {
url = "https://github.com/Ride-The-Lightning/RTL/archive/refs/tags/v${self.version}.tar.gz"; url = "https://github.com/Ride-The-Lightning/RTL/archive/refs/tags/v${self.version}.tar.gz";
hash = "sha256-8XdGyORxB2dkZRB/Yl7zh+Quqo4L/Y0VmC6Brbr/hqU="; hash = "sha256-r5riYV2FN0OKi0mwj9I1jBeeU1LOv2HVB6CEovPlUuY=";
}; };
passthru = { passthru = {
@@ -26,7 +26,7 @@ let self = stdenvNoCC.mkDerivation {
# TODO-EXTERNAL: Remove `npmFlags` when no longer required # TODO-EXTERNAL: Remove `npmFlags` when no longer required
# See: https://github.com/Ride-The-Lightning/RTL/issues/1182 # See: https://github.com/Ride-The-Lightning/RTL/issues/1182
npmFlags = "--legacy-peer-deps"; npmFlags = "--legacy-peer-deps";
hash = "sha256-oMqd6nLzS6iQ9w4z2yzpR2unA5qhOq5YdvfoS8IgYLY="; hash = "sha256-NKiWcjqYcHBVIB+vbF3aKXLe2fJRmh/quu8obztP3TA=";
}; };
}; };
+272 -188
View File
@@ -20,6 +20,11 @@
set -euo pipefail set -euo pipefail
# Always operate from the repository root, regardless of the caller's cwd.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
cd "$REPO_ROOT"
# Colors # Colors
RED='\033[0;31m' RED='\033[0;31m'
GREEN='\033[0;32m' GREEN='\033[0;32m'
@@ -62,13 +67,28 @@ echo
# ───────────────────────────────────────────────────────────────────────────── # ─────────────────────────────────────────────────────────────────────────────
# Helper: Get latest tag # Helper: Get latest tag
# ───────────────────────────────────────────────────────────────────────────── # ─────────────────────────────────────────────────────────────────────────────
# GitHub release tags are fetched into a private namespace instead of
# refs/tags/. GitHub and Gitea contain some same-named historical tags that
# point to different objects; sharing refs/tags/ would make either fetch fail
# with "would clobber existing tag".
GITHUB_TAG_NAMESPACE="refs/release-tags/github"
get_latest_tag() { get_latest_tag() {
local exclude="${1:-}" local exclude="${1:-}"
if [[ -n "$exclude" ]]; then local tag
git tag --list 'v*' --sort=-version:refname | grep -v -x -E "v?${exclude#v}|${exclude}" | head -1 || echo ""
else while IFS= read -r tag; do
git tag --list 'v*' --sort=-version:refname | head -1 || echo "" if [[ -n "$exclude" && "$tag" == "v${exclude#v}" ]]; then
fi continue
fi
printf '%s\n' "$tag"
return 0
done < <(git for-each-ref \
--sort=-version:refname \
--format='%(refname:strip=3)' \
"${GITHUB_TAG_NAMESPACE}/v*")
return 0
} }
# ───────────────────────────────────────────────────────────────────────────── # ─────────────────────────────────────────────────────────────────────────────
@@ -90,10 +110,84 @@ suggest_next_version() {
} }
# ───────────────────────────────────────────────────────────────────────────── # ─────────────────────────────────────────────────────────────────────────────
# Step 0: Fetch everything # Step 0: Preflight and fetch everything
# ───────────────────────────────────────────────────────────────────────────── # ─────────────────────────────────────────────────────────────────────────────
echo -e "${BLUE}Step 0: Fetching latest from all remotes...${NC}" echo -e "${BLUE}Step 0: Running release preflight...${NC}"
git fetch --all --tags 2>/dev/null || true
# A release must start from an exact, committed, reproducible tree. This also
# prevents release metadata generated below from being mixed with local work.
if [[ -n "$(git status --porcelain)" ]]; then
echo -e "${RED}Error: the working tree is not clean. Commit, stash, or remove local changes first.${NC}" >&2
git status --short >&2
exit 1
fi
for remote in "$GITHUB_REMOTE" "$GITEA_REMOTE"; do
if ! git remote | grep -q -x "$remote"; then
echo -e "${RED}Error: required remote '$remote' is not configured.${NC}" >&2
exit 1
fi
done
for command_name in gh curl; do
if ! command -v "$command_name" >/dev/null 2>&1; then
echo -e "${RED}Error: required command '$command_name' is not installed.${NC}" >&2
exit 1
fi
done
if ! gh auth status >/dev/null 2>&1; then
echo -e "${RED}Error: GitHub CLI is not authenticated. Run 'gh auth login' first.${NC}" >&2
exit 1
fi
if [[ -z "${GITEA_TOKEN:-}" ]]; then
echo
read -rsp "Enter your Gitea API token (input hidden): " GITEA_TOKEN
echo
fi
if [[ -z "${GITEA_TOKEN:-}" ]]; then
echo -e "${RED}Error: a GITEA_TOKEN with write:repository scope is required.${NC}" >&2
exit 1
fi
echo -e " Fetching GitHub (${GITHUB_REMOTE}) and Gitea (${GITEA_REMOTE})..."
# Never fetch either host's tags into refs/tags/. Historical tags with the same
# name differ between the hosts, and Git correctly refuses to clobber them.
git fetch "$GITHUB_REMOTE" --prune --no-tags
git fetch "$GITEA_REMOTE" --prune --no-tags
git fetch "$GITHUB_REMOTE" --prune --no-tags \
"+refs/tags/*:${GITHUB_TAG_NAMESPACE}/*"
GITHUB_MAIN_REF="refs/remotes/${GITHUB_REMOTE}/main"
GITEA_STAGING_REF="refs/remotes/${GITEA_REMOTE}/staging-dev"
if ! git rev-parse --verify "$GITHUB_MAIN_REF" >/dev/null 2>&1; then
echo -e "${RED}Error: cannot resolve GitHub main at ${GITHUB_MAIN_REF}.${NC}" >&2
exit 1
fi
if ! git rev-parse --verify "$GITEA_STAGING_REF" >/dev/null 2>&1; then
echo -e "${RED}Error: cannot resolve Gitea staging-dev at ${GITEA_STAGING_REF}.${NC}" >&2
exit 1
fi
HEAD_COMMIT=$(git rev-parse HEAD)
GITHUB_MAIN_COMMIT=$(git rev-parse "$GITHUB_MAIN_REF")
GITEA_STAGING_COMMIT=$(git rev-parse "$GITEA_STAGING_REF")
if [[ "$GITHUB_MAIN_COMMIT" != "$GITEA_STAGING_COMMIT" ]]; then
echo -e "${RED}Error: GitHub main and Gitea staging-dev are not synchronized.${NC}" >&2
echo " GitHub main : $GITHUB_MAIN_COMMIT" >&2
echo " Gitea staging-dev : $GITEA_STAGING_COMMIT" >&2
exit 1
fi
if [[ "$HEAD_COMMIT" != "$GITHUB_MAIN_COMMIT" ]]; then
echo -e "${RED}Error: local HEAD is not the synchronized release candidate.${NC}" >&2
echo " Local HEAD : $HEAD_COMMIT" >&2
echo " Remote HEAD : $GITHUB_MAIN_COMMIT" >&2
echo "Update/check out the synchronized commit, then run the script again." >&2
exit 1
fi
echo -e " ${GREEN}✓${NC} Clean tree; GitHub main and Gitea staging-dev match local HEAD"
LATEST_TAG=$(get_latest_tag) LATEST_TAG=$(get_latest_tag)
NEXT_VERSION=$(suggest_next_version "$LATEST_TAG") NEXT_VERSION=$(suggest_next_version "$LATEST_TAG")
@@ -117,6 +211,23 @@ fi
VERSION="${VERSION#v}" VERSION="${VERSION#v}"
TAG="v${VERSION}" TAG="v${VERSION}"
if [[ ! "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo -e "${RED}Error: version must use MAJOR.MINOR.PATCH format (for example, 1.1.1).${NC}" >&2
exit 1
fi
remote_has_tag() {
local remote="$1"
[[ -n "$(git ls-remote --tags "$remote" "refs/tags/${TAG}" "refs/tags/${TAG}^{}")" ]]
}
if git show-ref --verify --quiet "refs/tags/${TAG}" || \
git show-ref --verify --quiet "${GITHUB_TAG_NAMESPACE}/${TAG}" || \
remote_has_tag "$GITHUB_REMOTE" || remote_has_tag "$GITEA_REMOTE"; then
echo -e "${RED}Error: tag ${TAG} already exists locally or on a remote.${NC}" >&2
echo "Refusing to move or overwrite an existing release tag." >&2
exit 1
fi
# ───────────────────────────────────────────────────────────────────────────── # ─────────────────────────────────────────────────────────────────────────────
# Get release message # Get release message
# ───────────────────────────────────────────────────────────────────────────── # ─────────────────────────────────────────────────────────────────────────────
@@ -193,20 +304,26 @@ generate_release_notes() {
printf '%s' "$notes" printf '%s' "$notes"
} }
# Build the notes from commits since the previous tag (exclude the target tag if already present) # Build notes from the previous canonical GitHub tag. Use its private ref so a
# conflicting local or Gitea tag with the same name cannot select the wrong
# commit.
PREV_TAG=$(get_latest_tag "$TAG") PREV_TAG=$(get_latest_tag "$TAG")
if [[ -n "$PREV_TAG" ]] && git rev-parse -q --verify "$PREV_TAG" >/dev/null; then PREV_TAG_REF="${GITHUB_TAG_NAMESPACE}/${PREV_TAG}"
COMMIT_RANGE="${PREV_TAG}..HEAD" if [[ -n "$PREV_TAG" ]] && git rev-parse -q --verify "$PREV_TAG_REF" >/dev/null; then
COMMIT_RANGE="${PREV_TAG_REF}..HEAD"
COMMIT_RANGE_DISPLAY="${PREV_TAG}..HEAD"
else else
COMMIT_RANGE="HEAD" COMMIT_RANGE="HEAD"
COMMIT_RANGE_DISPLAY="HEAD"
fi fi
echo echo
echo -e "${BLUE}Generating draft release notes from ${COMMIT_RANGE}...${NC}" echo -e "${BLUE}Generating draft release notes from ${COMMIT_RANGE_DISPLAY}...${NC}"
RELEASE_NOTES="$(generate_release_notes "$COMMIT_RANGE")" RELEASE_NOTES="$(generate_release_notes "$COMMIT_RANGE")"
# Let the user review/edit the generated notes before publishing # Let the user review/edit the generated notes before publishing
NOTES_FILE="$(mktemp "/tmp/release-notes-${TAG}.XXXXXX.md")" NOTES_FILE="$(mktemp "/tmp/release-notes-${TAG}.XXXXXX.md")"
trap 'rm -f "$NOTES_FILE"' EXIT
{ {
echo "## Sovran_SystemsOS ${TAG}" echo "## Sovran_SystemsOS ${TAG}"
echo echo
@@ -246,214 +363,182 @@ if [[ ! "$confirm" =~ ^[Yy]$ ]]; then
fi fi
# ───────────────────────────────────────────────────────────────────────────── # ─────────────────────────────────────────────────────────────────────────────
# Step 1: Push tested code to Gitea (stable & staging-dev) # Step 1: Prepare and commit all release metadata
# ───────────────────────────────────────────────────────────────────────────── # ─────────────────────────────────────────────────────────────────────────────
echo echo
echo -e "${BLUE}Step 1: Pushing tested code to Gitea (stable & staging-dev)...${NC}" echo -e "${BLUE}Step 1: Preparing release metadata for ${TAG}...${NC}"
if git remote | grep -q -x "${GITEA_REMOTE}"; then
git push "${GITEA_REMOTE}" HEAD:stable --force-with-lease || echo -e " ${YELLOW}⚠ Push to ${GITEA_REMOTE} (stable) failed.${NC}"
git push "${GITEA_REMOTE}" HEAD:staging-dev --force-with-lease || echo -e " ${YELLOW}⚠ Push to ${GITEA_REMOTE} (staging-dev) failed.${NC}"
else
echo -e " ${YELLOW}⚠ Remote '${GITEA_REMOTE}' not found in git — skipping Gitea push.${NC}"
fi
# ───────────────────────────────────────────────────────────────────────────── # VERSION drives ISO naming.
# Step 2: Create annotated tag
# ─────────────────────────────────────────────────────────────────────────────
echo
echo -e "${BLUE}Step 2: Creating annotated tag ${TAG}...${NC}"
git tag -f -a "${TAG}" -m "${RELEASE_MESSAGE}
- Stable release of Sovran_SystemsOS
- See CHANGELOG.md for full details" || true
if git remote | grep -q -x "${GITEA_REMOTE}"; then
git push "${GITEA_REMOTE}" "${TAG}" || echo -e " ${YELLOW}⚠ Tag push to ${GITEA_REMOTE} failed.${NC}"
else
echo -e " ${YELLOW}⚠ Remote '${GITEA_REMOTE}' not found in git — skipping Gitea tag push.${NC}"
fi
if git remote | grep -q -x "${GITHUB_REMOTE}"; then
git push "${GITHUB_REMOTE}" "${TAG}" || echo -e " ${YELLOW}⚠ Tag push to ${GITHUB_REMOTE} failed.${NC}"
fi
# Update VERSION file for ISO builds
echo "${VERSION}" > VERSION echo "${VERSION}" > VERSION
git add VERSION
git commit -m "chore: bump VERSION to ${TAG} for ISO naming" || true
echo -e " ${GREEN}✓${NC} VERSION file updated to ${VERSION}"
# ─────────────────────────────────────────────────────────────────────────────
# Step 2b: Auto-update README.md ISO download references
# ─────────────────────────────────────────────────────────────────────────────
echo
echo -e "${BLUE}Step 2b: Updating README.md ISO references to ${VERSION}...${NC}"
# Update every versioned ISO filename in README.md.
README_FILE="README.md" README_FILE="README.md"
if [ -f "$README_FILE" ]; then if [[ ! -f "$README_FILE" ]]; then
# Extract the version currently used in the README's ISO filenames, echo -e "${RED}Error: ${README_FILE} not found.${NC}" >&2
# e.g. "Sovran_SystemsOS-1.0.6.iso" -> "1.0.6" exit 1
OLD_ISO_VER=$(grep -oE 'Sovran_SystemsOS-[0-9]+\.[0-9]+\.[0-9]+\.iso' "$README_FILE" | head -1 | sed 's/Sovran_SystemsOS-//; s/\.iso//') fi
OLD_ISO_VER=$(grep -oE 'Sovran_SystemsOS-[0-9]+\.[0-9]+\.[0-9]+\.iso' "$README_FILE" \
if [ -n "$OLD_ISO_VER" ] && [ "$OLD_ISO_VER" != "$VERSION" ]; then | head -1 | sed 's/Sovran_SystemsOS-//; s/\.iso//')
# Portable in-place edit (works with GNU sed and BSD/macOS sed) if [[ -z "$OLD_ISO_VER" ]]; then
sed "s/Sovran_SystemsOS-${OLD_ISO_VER}/Sovran_SystemsOS-${VERSION}/g" \ echo -e "${RED}Error: no versioned ISO reference found in ${README_FILE}.${NC}" >&2
"$README_FILE" > "$README_FILE.tmp" && mv "$README_FILE.tmp" "$README_FILE" exit 1
fi
UPDATED=$(grep -c "Sovran_SystemsOS-${VERSION}" "$README_FILE") if [[ "$OLD_ISO_VER" != "$VERSION" ]]; then
echo -e " ${GREEN}✓${NC} README.md: ${OLD_ISO_VER} -> ${VERSION} (${UPDATED} references updated)" sed "s/Sovran_SystemsOS-${OLD_ISO_VER}/Sovran_SystemsOS-${VERSION}/g" \
"$README_FILE" > "$README_FILE.tmp"
git add "$README_FILE" mv "$README_FILE.tmp" "$README_FILE"
git commit -m "docs: update README ISO download links to ${TAG}" || true
echo -e " ${GREEN}✓${NC} Committed README update"
else
echo -e " ${YELLOW}⚠${NC} README.md already references ${VERSION} or no versioned ISO links found — skipping"
fi
else
echo -e " ${YELLOW}⚠${NC} README.md not found — skipping"
fi fi
# ───────────────────────────────────────────────────────────────────────────── # Add the changelog entry before tagging so the tag and stable branch contain it.
# Step 3: Auto-update CHANGELOG.md
# ─────────────────────────────────────────────────────────────────────────────
echo
echo -e "${BLUE}Step 3: Updating ${CHANGELOG_FILE}...${NC}"
TODAY=$(date +%Y-%m-%d) TODAY=$(date +%Y-%m-%d)
# Create new changelog entry from the generated notes (no placeholders)
NEW_ENTRY="## [${VERSION}] - ${TODAY} NEW_ENTRY="## [${VERSION}] - ${TODAY}
${RELEASE_NOTES} ${RELEASE_NOTES}
[${VERSION}]: https://git.sovransystems.com/Sovran_Systems/Sovran_SystemsOS/releases/tag/${TAG} [${VERSION}]: https://git.sovransystems.com/Sovran_Systems/Sovran_SystemsOS/releases/tag/${TAG}
" "
# Prepend to changelog (after the header) if [[ ! -f "$CHANGELOG_FILE" ]]; then
if [ -f "$CHANGELOG_FILE" ]; then echo -e "${RED}Error: ${CHANGELOG_FILE} not found.${NC}" >&2
# Backup exit 1
cp "$CHANGELOG_FILE" "${CHANGELOG_FILE}.bak"
# Insert new section after the first --- line
awk -v new_entry="$NEW_ENTRY" '
BEGIN { printed=0 }
/^---$/ && !printed {
print
print ""
print new_entry
printed=1
next
}
{ print }
' "$CHANGELOG_FILE" > "${CHANGELOG_FILE}.tmp" && mv "${CHANGELOG_FILE}.tmp" "$CHANGELOG_FILE"
rm -f "${CHANGELOG_FILE}.bak"
echo -e " ${GREEN}✓${NC} CHANGELOG.md updated with new section for ${TAG}"
else
echo -e " ${YELLOW}⚠${NC} CHANGELOG.md not found — skipping"
fi fi
awk -v new_entry="$NEW_ENTRY" '
BEGIN { printed=0 }
/^---$/ && !printed {
print
print ""
print new_entry
printed=1
next
}
{ print }
END { if (!printed) exit 2 }
' "$CHANGELOG_FILE" > "${CHANGELOG_FILE}.tmp" || {
rm -f "${CHANGELOG_FILE}.tmp"
echo -e "${RED}Error: could not find the changelog insertion marker.${NC}" >&2
exit 1
}
mv "${CHANGELOG_FILE}.tmp" "$CHANGELOG_FILE"
# Commit the changelog update git add VERSION "$README_FILE" "$CHANGELOG_FILE"
git add "$CHANGELOG_FILE"
if git diff --cached --quiet; then if git diff --cached --quiet; then
echo " (No changes to commit in changelog)" echo -e "${RED}Error: release preparation produced no changes.${NC}" >&2
else exit 1
git commit -m "docs: update CHANGELOG.md for ${TAG}"
echo -e " ${GREEN}✓${NC} Committed changelog update"
# Ask if user wants to push
echo
read -rp "Push the changelog commit to GitHub (main) and Gitea (staging-dev) now? (y/N): " push_confirm
if [[ "$push_confirm" =~ ^[Yy]$ ]]; then
if git remote | grep -q -x "${GITHUB_REMOTE}"; then
echo -e "${BLUE}Pushing changelog commit to GitHub main...${NC}"
if git push "${GITHUB_REMOTE}" HEAD:main; then
echo -e " ${GREEN}✓${NC} Changelog pushed to GitHub main (${GITHUB_REMOTE})"
else
echo -e " ${YELLOW}⚠ Push to GitHub main failed — verify credentials or remote name.${NC}"
fi
fi
if git remote | grep -q -x "${GITEA_REMOTE}"; then
echo -e "${BLUE}Pushing changelog commit to Gitea staging-dev...${NC}"
if git push "${GITEA_REMOTE}" HEAD:staging-dev; then
echo -e " ${GREEN}✓${NC} Changelog pushed to Gitea staging-dev (${GITEA_REMOTE})"
else
echo -e " ${YELLOW}⚠ Push to Gitea staging-dev failed.${NC}"
fi
fi
else
echo " (Changelog commit left local — remember to push later)"
fi
fi fi
git commit -m "chore(release): prepare ${TAG}"
RELEASE_COMMIT=$(git rev-parse HEAD)
echo -e " ${GREEN}✓${NC} VERSION, README, and CHANGELOG committed"
echo -e " Release commit: ${CYAN}${RELEASE_COMMIT}${NC}"
# ───────────────────────────────────────────────────────────────────────────── # ─────────────────────────────────────────────────────────────────────────────
# Step 4: Create GitHub Release via gh CLI # Step 2: Publish the final release commit to every release branch
# ───────────────────────────────────────────────────────────────────────────── # ─────────────────────────────────────────────────────────────────────────────
echo echo
echo -e "${BLUE}Step 4: Creating GitHub Release...${NC}" echo -e "${BLUE}Step 2: Publishing the final release commit...${NC}"
if command -v gh &>/dev/null; then # GitHub main and Gitea staging-dev were verified equal during preflight, so
title_suffix="${RELEASE_MESSAGE#Sovran_SystemsOS v* — }" # these are normal fast-forward pushes. Stable is an intentional promotion and
title_suffix="${title_suffix#Sovran_SystemsOS * — }" # uses a lease to prevent overwriting a branch changed since the fetch.
if gh release create "${TAG}" \ git push "$GITHUB_REMOTE" HEAD:main
--repo naturallaw777/Sovran_SystemsOS \ git push "$GITEA_REMOTE" HEAD:staging-dev
--title "${TAG} — ${title_suffix}" \ git push "$GITEA_REMOTE" HEAD:stable --force-with-lease
--notes-file "${NOTES_FILE}"; then
echo -e " ${GREEN}✓${NC} GitHub release created successfully" # Verify all three branch tips before creating an immutable release tag.
else remote_branch_commit() {
echo -e " ${YELLOW}⚠${NC} GitHub release creation failed (check 'gh auth status' or create via web GUI)" local remote="$1"
fi local branch="$2"
else git ls-remote "$remote" "refs/heads/${branch}" | awk 'NR == 1 { print $1 }'
echo -e " ${YELLOW}⚠${NC} gh CLI not found — skipping GitHub release (create via GitHub web GUI)" }
PUBLISHED_GITHUB=$(remote_branch_commit "$GITHUB_REMOTE" main)
PUBLISHED_STAGING=$(remote_branch_commit "$GITEA_REMOTE" staging-dev)
PUBLISHED_STABLE=$(remote_branch_commit "$GITEA_REMOTE" stable)
if [[ "$PUBLISHED_GITHUB" != "$RELEASE_COMMIT" || \
"$PUBLISHED_STAGING" != "$RELEASE_COMMIT" || \
"$PUBLISHED_STABLE" != "$RELEASE_COMMIT" ]]; then
echo -e "${RED}Error: post-push verification failed; no release tag was created.${NC}" >&2
echo " Expected : $RELEASE_COMMIT" >&2
echo " GitHub main : ${PUBLISHED_GITHUB:-missing}" >&2
echo " Gitea staging-dev : ${PUBLISHED_STAGING:-missing}" >&2
echo " Gitea stable : ${PUBLISHED_STABLE:-missing}" >&2
exit 1
fi fi
echo -e " ${GREEN}✓${NC} GitHub main, Gitea staging-dev, and Gitea stable all match"
# ───────────────────────────────────────────────────────────────────────────── # ─────────────────────────────────────────────────────────────────────────────
# Step 5: Create Gitea Release via API # Step 3: Tag the final release commit and publish the tag
# ───────────────────────────────────────────────────────────────────────────── # ─────────────────────────────────────────────────────────────────────────────
echo echo
echo -e "${BLUE}Step 5: Creating Gitea Release via API...${NC}" echo -e "${BLUE}Step 3: Creating annotated tag ${TAG} on ${RELEASE_COMMIT}...${NC}"
git tag -a "$TAG" -m "${RELEASE_MESSAGE}
# ── Gitea Token Handling ───────────────────────────────────────────────────── - Stable release of Sovran_SystemsOS
if [[ -z "${GITEA_TOKEN:-}" ]]; then - See CHANGELOG.md for full details" "$RELEASE_COMMIT"
echo
echo -e "${YELLOW}GITEA_TOKEN is not set.${NC}" git push "$GITHUB_REMOTE" "$TAG"
read -rsp "Enter your Gitea API token (input will be hidden): " GITEA_TOKEN git push "$GITEA_REMOTE" "$TAG"
echo
if [[ -z "$GITEA_TOKEN" ]]; then # For an annotated tag, ^{} resolves the commit referenced by the tag object.
echo -e " ${YELLOW}⚠${NC} No token provided — skipping Gitea release" remote_tag_commit() {
GITEA_TOKEN="" local remote="$1"
fi git ls-remote "$remote" "refs/tags/${TAG}^{}" | awk 'NR == 1 { print $1 }'
}
GITHUB_TAG_COMMIT=$(remote_tag_commit "$GITHUB_REMOTE")
GITEA_TAG_COMMIT=$(remote_tag_commit "$GITEA_REMOTE")
if [[ "$GITHUB_TAG_COMMIT" != "$RELEASE_COMMIT" || "$GITEA_TAG_COMMIT" != "$RELEASE_COMMIT" ]]; then
echo -e "${RED}Error: published tag verification failed.${NC}" >&2
exit 1
fi
echo -e " ${GREEN}✓${NC} ${TAG} points to the final release commit on GitHub and Gitea"
# ─────────────────────────────────────────────────────────────────────────────
# Step 4: Create GitHub release via gh CLI
# ─────────────────────────────────────────────────────────────────────────────
echo
echo -e "${BLUE}Step 4: Creating GitHub release...${NC}"
title_suffix="${RELEASE_MESSAGE#Sovran_SystemsOS v* — }"
title_suffix="${title_suffix#Sovran_SystemsOS * — }"
gh release create "$TAG" \
--repo naturallaw777/Sovran_SystemsOS \
--title "${TAG} — ${title_suffix}" \
--notes-file "$NOTES_FILE"
echo -e " ${GREEN}✓${NC} GitHub release created successfully"
# ─────────────────────────────────────────────────────────────────────────────
# Step 5: Create Gitea release via API
# ─────────────────────────────────────────────────────────────────────────────
echo
echo -e "${BLUE}Step 5: Creating Gitea release via API...${NC}"
GITEA_REPO="Sovran_Systems/Sovran_SystemsOS"
# Build JSON safely because release notes may contain quotes and newlines.
if command -v jq >/dev/null 2>&1; then
PAYLOAD=$(jq -n \
--arg tag "$TAG" \
--arg name "$TAG — Stable Release" \
--arg body "$RELEASE_BODY" \
'{tag_name: $tag, name: $name, body: $body, draft: false, prerelease: false}')
else
PAYLOAD=$(python3 -c "import json,sys; print(json.dumps({'tag_name': sys.argv[1], 'name': sys.argv[1] + ' — Stable Release', 'body': open(sys.argv[2]).read(), 'draft': False, 'prerelease': False}))" "$TAG" "$NOTES_FILE")
fi fi
if [[ -n "${GITEA_TOKEN:-}" ]]; then RESPONSE_FILE=$(mktemp "/tmp/gitea-release-${TAG}.XXXXXX.json")
GITEA_REPO="Sovran_Systems/Sovran_SystemsOS" HTTP_STATUS=$(curl -sS -o "$RESPONSE_FILE" -w '%{http_code}' -X POST \
-H "Authorization: token ${GITEA_TOKEN}" \
-H "Content-Type: application/json" \
-d "$PAYLOAD" \
"${GITEA_API_URL}/repos/${GITEA_REPO}/releases")
# Build JSON payload safely (release body may contain quotes/newlines) if [[ "$HTTP_STATUS" != "201" ]]; then
if command -v jq &>/dev/null; then echo -e "${RED}Error: Gitea release creation failed (HTTP ${HTTP_STATUS}).${NC}" >&2
PAYLOAD=$(jq -n \ cat "$RESPONSE_FILE" >&2
--arg tag "${TAG}" \ rm -f "$RESPONSE_FILE"
--arg name "${TAG} — Stable Release" \ exit 1
--arg body "${RELEASE_BODY}" \
'{tag_name: $tag, name: $name, body: $body, draft: false, prerelease: false}')
else
PAYLOAD=$(python3 -c "import json,sys; print(json.dumps({'tag_name': sys.argv[1], 'name': sys.argv[1] + ' — Stable Release', 'body': open(sys.argv[2]).read(), 'draft': False, 'prerelease': False}))" "${TAG}" "${NOTES_FILE}")
fi
RESPONSE=$(curl -s -X POST \
-H "Authorization: token ${GITEA_TOKEN}" \
-H "Content-Type: application/json" \
-d "${PAYLOAD}" \
"${GITEA_API_URL}/repos/${GITEA_REPO}/releases" 2>/dev/null || echo "")
if echo "$RESPONSE" | grep -q '"id"'; then
echo -e " ${GREEN}✓${NC} Gitea release created successfully"
elif echo "$RESPONSE" | grep -q "write:repository"; then
echo -e " ${YELLOW}⚠${NC} Gitea token scope issue: your token requires the 'write:repository' scope (currently has write:package)."
echo " To fix: In Gitea, navigate to Settings → Applications → Manage Access Tokens and generate a token with 'write:repository'."
else
echo -e " ${YELLOW}⚠${NC} Gitea release creation failed or already exists"
echo " Response: $RESPONSE"
fi
fi fi
rm -f "$RESPONSE_FILE"
echo -e " ${GREEN}✓${NC} Gitea release created successfully"
# ───────────────────────────────────────────────────────────────────────────── # ─────────────────────────────────────────────────────────────────────────────
# Final Summary # Final Summary
@@ -468,8 +553,7 @@ echo " • Build the installer ISO:"
echo " nix build .#nixosConfigurations.sovran_systemsos-iso.config.system.build.isoImage" echo " nix build .#nixosConfigurations.sovran_systemsos-iso.config.system.build.isoImage"
echo " • Package, verify, and upload ISO to CDN:" echo " • Package, verify, and upload ISO to CDN:"
echo " ./scripts/upload-cdn.sh --upload" echo " ./scripts/upload-cdn.sh --upload"
echo " • Review and enhance the new section in CHANGELOG.md" echo " • Verify the ISO download and checksum from the public CDN"
echo " • Push changes: git push ${GITHUB_REMOTE} HEAD:main && git push ${GITEA_REMOTE} HEAD:staging-dev"
echo " • Verify releases on both GitHub and Gitea" echo " • Verify releases on both GitHub and Gitea"
echo echo
echo -e "${CYAN}Tag created: ${TAG}${NC}" echo -e "${CYAN}Tag created: ${TAG}${NC}"
+78
View File
@@ -0,0 +1,78 @@
"""Regression tests for the Bitcoin Core Tor IBD gossip Hub option.
These tests intentionally avoid importing the FastAPI application so they can run
in the repository's lightweight test environment without NixOS service access.
"""
import ast
import os
import unittest
_REPO_ROOT = os.path.normpath(os.path.join(os.path.dirname(__file__), ".."))
def _read(*parts: str) -> str:
with open(os.path.join(_REPO_ROOT, *parts), encoding="utf-8") as source:
return source.read()
def _literal_assignment(source: str, name: str):
tree = ast.parse(source)
for node in tree.body:
if isinstance(node, ast.Assign):
if any(isinstance(target, ast.Name) and target.id == name for target in node.targets):
return ast.literal_eval(node.value)
raise AssertionError(f"Assignment {name} was not found")
class TestBitcoinTorGossipNixWiring(unittest.TestCase):
def test_bitcoind_loopback_listener_is_always_enabled(self):
ecosystem = _read("modules", "bitcoinecosystem.nix")
self.assertIn("listen = true;", ecosystem)
self.assertIn("peerbloomfilters=1", ecosystem)
def test_gossip_is_opt_in(self):
ecosystem = _read("modules", "bitcoinecosystem.nix")
self.assertIn(
"public = config.sovran_systemsOS.features.bitcoin-tor-gossip;",
ecosystem,
)
def test_hub_option_and_evaluated_state_are_declared(self):
roles = _read("modules", "core", "roles.nix")
hub = _read("modules", "core", "sovran-hub.nix")
self.assertIn("bitcoin-tor-gossip = lib.mkEnableOption", roles)
self.assertIn("bitcoin-tor-gossip = cfg.features.bitcoin-tor-gossip;", hub)
class TestBitcoinTorGossipHubWiring(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.server_source = _read("app", "sovran_systemsos_web", "server.py")
cls.registry = _literal_assignment(cls.server_source, "FEATURE_REGISTRY")
def test_feature_is_modal_only_and_explains_risk(self):
feature = next(item for item in self.registry if item["id"] == "bitcoin-tor-gossip")
self.assertTrue(feature["modal_only"])
self.assertIn("bitcoin-service", feature["requires"])
self.assertTrue(any("clearnet" in detail for detail in feature["details"]))
self.assertTrue(any("bandwidth" in detail for detail in feature["details"]))
def test_backend_rejects_gossip_without_bitcoin_service(self):
self.assertIn(
"Enable the Bitcoin service before advertising its Tor IBD service.",
self.server_source,
)
def test_core_modal_renders_and_controls_the_option(self):
frontend = _read(
"app", "sovran_systemsos_web", "static", "js", "service-detail.js"
)
self.assertIn("Tor IBD Service Advertising", frontend)
self.assertIn("svc-detail-related-feature-btn", frontend)
self.assertIn("handleFeatureToggle(relatedFeat", frontend)
if __name__ == "__main__":
unittest.main()
+121
View File
@@ -333,6 +333,33 @@ class TestSshPubkeyValidation(unittest.TestCase):
_validate_ssh_pubkey("ssh-ed25519") _validate_ssh_pubkey("ssh-ed25519")
# ---------------------------------------------------------------------------
# LND macaroon command-line safety
# ---------------------------------------------------------------------------
class TestLndMacaroonCommandLineSafety(unittest.TestCase):
"""The LND admin macaroon must never be exposed in curl's argv."""
@classmethod
def setUpClass(cls):
path = os.path.join(_REPO_ROOT, "modules", "bitcoin", "lnd.nix")
with open(path, encoding="utf-8") as f:
cls.lnd_module = f.read()
def test_admin_macaroon_not_interpolated_into_header_argument(self):
self.assertNotIn(
'-H "Grpc-Metadata-macaroon: $(',
self.lnd_module,
)
def test_admin_macaroon_header_is_passed_via_file_descriptor(self):
self.assertIn("adminMacaroonHex=$(", self.lnd_module)
self.assertIn(
"""-H @<(printf 'Grpc-Metadata-macaroon: %s\\n' "$adminMacaroonHex")""",
self.lnd_module,
)
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# Auth-exempt paths # Auth-exempt paths
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
@@ -365,6 +392,100 @@ class TestAuthExemptPaths(unittest.TestCase):
self.assertIn("/api/ping", self._get_exempt_paths()) self.assertIn("/api/ping", self._get_exempt_paths())
class TestFrontendAuthRecovery(unittest.TestCase):
"""Expired browser sessions must not leave the Hub polling forever."""
@classmethod
def setUpClass(cls):
path = os.path.join(
_REPO_ROOT, "app", "sovran_systemsos_web", "static", "js", "helpers.js"
)
with open(path, encoding="utf-8") as f:
cls.helpers = f.read()
def test_api_fetch_redirects_unauthorized_response_to_login(self):
self.assertRegex(self.helpers, r"res\.status\s*===\s*401")
self.assertIn('window.location.replace("/login")', self.helpers)
def test_unauthorized_response_does_not_use_local_auto_login(self):
# Remote clients must still authenticate with the Hub password.
self.assertNotIn('window.location.replace("/auto-login")', self.helpers)
class TestManualLogoutPersistence(unittest.TestCase):
"""Explicit logout must take precedence over desktop auto-login."""
@classmethod
def setUpClass(cls):
path = os.path.join(_REPO_ROOT, "app", "sovran_systemsos_web", "server.py")
with open(path, encoding="utf-8") as f:
cls.server = f.read()
def _between(self, start, end):
return self.server.split(start, 1)[1].split(end, 1)[0]
def test_auto_login_honors_manual_logout_cookie(self):
route = self._between(
'@app.get("/auto-login")',
"class LoginRequest",
)
self.assertIn("request.cookies.get(MANUAL_LOGOUT_COOKIE_NAME)", route)
self.assertIn('RedirectResponse(url="/login"', route)
def test_logout_sets_persistent_manual_logout_cookie(self):
route = self._between(
'@app.post("/api/logout")',
"def _get_sovran_version",
)
self.assertIn("key=MANUAL_LOGOUT_COOKIE_NAME", route)
self.assertIn("max_age=MANUAL_LOGOUT_MAX_AGE", route)
self.assertIn("httponly=True", route)
def test_password_login_clears_manual_logout_cookie(self):
route = self._between(
'@app.post("/api/login")',
'@app.post("/api/logout")',
)
self.assertIn(
"response.delete_cookie(key=MANUAL_LOGOUT_COOKIE_NAME)", route
)
class TestHubBrowserProfilePersistence(unittest.TestCase):
"""The desktop launcher must keep a persistent browser profile.
The hub_manual_logout marker (and the session cookie) are stored in this
profile. If the launcher used an ephemeral /tmp profile that it deleted on
exit, closing and reopening the Hub window would wipe the marker and
/auto-login would silently log the user back in without a password.
"""
@classmethod
def setUpClass(cls):
path = os.path.join(
_REPO_ROOT, "modules", "core", "sovran-hub.nix"
)
with open(path, encoding="utf-8") as f:
cls.wrapper = f.read()
def test_profile_is_not_under_tmp(self):
# The profile must live in a persistent per-user location, not /tmp.
self.assertNotIn("/tmp/sovran-hub-brave", self.wrapper)
def test_profile_is_not_deleted_on_exit(self):
# There must be no trap that removes the user-data-dir on exit.
self.assertNotRegex(self.wrapper, r"rm\s+-rf\s+.*HUB_DATA")
self.assertNotIn("trap '", self.wrapper)
def test_profile_is_persistent_per_user_location(self):
self.assertIn("sovran-hub-browser", self.wrapper)
# It should honour XDG_STATE_HOME (standard, persistent per-user dir).
self.assertIn("XDG_STATE_HOME", self.wrapper)
def test_launcher_still_uses_user_data_dir(self):
self.assertIn("--user-data-dir=", self.wrapper)
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# Persistent session store # Persistent session store
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
+222
View File
@@ -0,0 +1,222 @@
"""Regression tests for Hub update completion and polling recovery."""
from __future__ import annotations
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
_REPO_ROOT = Path(__file__).resolve().parents[1]
_APP_PARENT = _REPO_ROOT / "app"
if str(_APP_PARENT) not in sys.path:
sys.path.insert(0, str(_APP_PARENT))
from sovran_systemsos_web.update_state import ( # noqa: E402
effective_update_status,
reboot_is_pending,
)
# Real store paths observed on the incident machine that prompted this rework.
RUNNING_GENERATION = (
"84rsiqi66nc68jbikd26ms50ap831xf8-nixos-system-nixos-26.11.20260817.ec2d622"
)
PREVIOUS_GENERATION = (
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-nixos-system-nixos-26.11.20260816.old"
)
# What the stale Hub log still claimed was staged: a two-week-old update cycle.
HUB_LOG_GENERATION = (
"yis0saq6p8fhqcaii0h2yzqf0blhdwns-nixos-system-nixos-26.11.20260804.e72e4f2"
)
class TestRebootPendingState(unittest.TestCase):
"""Reboot-pending state is derived from NixOS, not from Hub marker files.
The system profile (what boots next) is compared against
/run/current-system (what is running). This stays correct no matter
which tool performed the update: Hub "Update System", a terminal
``nixos-rebuild``, or an SSH support session.
"""
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
root = Path(self.tmp.name)
self.store = root / "store"
self.store.mkdir()
# /nix/var/nix/profiles/system is a two-hop chain: the diagnostics on
# the incident box showed ``system`` -> ``system-148-link`` -> store.
self.profile = root / "system"
self.profile_entry = root / "system-148-link"
# /run/current-system links straight to the running store path.
self.current = root / "current-system"
def _store_dir(self, name: str) -> str:
path = self.store / name
path.mkdir(exist_ok=True)
return str(path)
def _stage(self, booted: str, running: str) -> None:
"""Stage ``booted`` as the boot default with ``running`` live."""
os.symlink(self._store_dir(booted), self.profile_entry)
os.symlink(self.profile_entry, self.profile)
os.symlink(self._store_dir(running), self.current)
def test_hub_update_staged_and_not_yet_rebooted_is_pending(self):
self._stage(booted=RUNNING_GENERATION, running=PREVIOUS_GENERATION)
self.assertTrue(
reboot_is_pending(str(self.profile), str(self.current))
)
def test_staged_generation_booted_is_no_longer_pending(self):
self._stage(booted=RUNNING_GENERATION, running=RUNNING_GENERATION)
self.assertFalse(
reboot_is_pending(str(self.profile), str(self.current))
)
def test_terminal_switch_needs_no_reboot(self):
# nixos-rebuild switch moves the profile AND current-system together.
self._stage(booted=RUNNING_GENERATION, running=RUNNING_GENERATION)
self.assertFalse(
reboot_is_pending(str(self.profile), str(self.current))
)
def test_rollback_leaves_nothing_pending(self):
# nixos-rebuild switch --rollback points both at the rollback target.
self._stage(booted=PREVIOUS_GENERATION, running=PREVIOUS_GENERATION)
self.assertFalse(
reboot_is_pending(str(self.profile), str(self.current))
)
def test_unverifiable_state_is_never_a_reboot_demand(self):
# No profile and no running system readable: the Hub must not nag
# about a reboot it cannot substantiate.
self.assertFalse(
reboot_is_pending(str(self.profile), str(self.current))
)
def test_stale_hub_marker_clears_after_terminal_updates(self):
"""The exact incident: terminal-updated machine, frozen Hub marker.
The user's last Hub update (old updater, weeks prior) left
REBOOT_REQUIRED behind. Every update since ran in a terminal and
never touched the Hub's files, so the log still records a staged
generation from 2026-08-04 while the machine runs a 2026-08-17
build. With the profile and the running system in agreement, the
stale claim must reconcile to IDLE regardless of anything the old
marker/log files say.
"""
root = Path(self.tmp.name)
log = root / "sovran-hub-update.log"
log.write_text(
"Done. The new configuration is "
f"/nix/store/{HUB_LOG_GENERATION}\n"
"✓ Update staged successfully\n",
encoding="utf-8",
)
# Deliberately no sovran-hub-update.generation marker: the updater
# that produced this state predates the marker feature.
self.assertFalse(
(root / "sovran-hub-update.generation").exists()
)
self._stage(booted=RUNNING_GENERATION, running=RUNNING_GENERATION)
self.assertEqual(
effective_update_status(
"REBOOT_REQUIRED", str(self.profile), str(self.current)
),
"IDLE",
)
def test_genuine_pending_reboot_claim_survives(self):
# A staged generation that has NOT been booted yet: the claim is
# true and must keep surfacing until the reboot really happens.
self._stage(booted=RUNNING_GENERATION, running=PREVIOUS_GENERATION)
self.assertEqual(
effective_update_status(
"REBOOT_REQUIRED", str(self.profile), str(self.current)
),
"REBOOT_REQUIRED",
)
def test_other_statuses_pass_through_unchanged(self):
self._stage(booted=RUNNING_GENERATION, running=RUNNING_GENERATION)
for status in ("RUNNING", "FAILED", "SUCCESS", "IDLE"):
self.assertEqual(
effective_update_status(
status, str(self.profile), str(self.current)
),
status,
)
class TestUpdatePollingWiring(unittest.TestCase):
"""Guard the browser failure modes that caused a permanent spinner."""
@classmethod
def setUpClass(cls):
js_dir = _REPO_ROOT / "app" / "sovran_systemsos_web" / "static" / "js"
cls.update_js = (js_dir / "update.js").read_text(encoding="utf-8")
cls.rebuild_js = (js_dir / "rebuild.js").read_text(encoding="utf-8")
cls.helpers_js = (js_dir / "helpers.js").read_text(encoding="utf-8")
cls.events_js = (js_dir / "events.js").read_text(encoding="utf-8")
cls.template = (
_REPO_ROOT / "app" / "sovran_systemsos_web" / "templates" / "index.html"
).read_text(encoding="utf-8")
def test_status_fetches_have_an_abort_timeout(self):
self.assertIn("function apiFetchWithTimeout", self.helpers_js)
self.assertIn("new AbortController()", self.helpers_js)
self.assertIn("controller.abort()", self.helpers_js)
self.assertIn("apiFetchWithTimeout(", self.update_js)
self.assertIn("STATUS_POLL_FETCH_TIMEOUT", self.update_js)
def test_async_update_polls_cannot_overlap(self):
self.assertIn("_updatePollInFlight", self.update_js)
self.assertIn(
"if (_updateFinished || _updatePollInFlight) return;", self.update_js
)
self.assertIn("finally", self.update_js)
def test_connection_failure_has_explicit_non_running_ui(self):
self.assertIn("showUpdateStatusUnavailable", self.update_js)
self.assertIn("Update status unavailable", self.update_js)
self.assertIn("Retry Status", self.template)
self.assertIn("retryUpdateStatus", self.events_js)
def test_rdp_or_tab_resume_forces_reconciliation(self):
self.assertIn("resumeUpdateStatusAfterInterruption", self.events_js)
self.assertIn('window.addEventListener("focus"', self.events_js)
self.assertIn('document.addEventListener("visibilitychange"', self.events_js)
def test_verbose_log_rendering_is_bounded(self):
self.assertIn("UPDATE_VISIBLE_LOG_MAX_CHARS", self.update_js)
self.assertIn("document.createTextNode(text)", self.update_js)
self.assertNotIn("$modalLog.textContent += text", self.update_js)
def test_page_reload_restores_running_or_completed_update(self):
self.assertIn("restoreUpdateModalIfNeeded", self.update_js)
self.assertIn("await restoreUpdateModalIfNeeded();", self.events_js)
self.assertIn('current.result === "reboot_required"', self.update_js)
def test_all_javascript_remains_syntax_valid(self):
node = shutil.which("node")
if not node:
self.skipTest("node is not available in this test environment")
for script in (
_REPO_ROOT / "app" / "sovran_systemsos_web" / "static" / "js"
).glob("*.js"):
result = subprocess.run(
[node, "--check", str(script)], capture_output=True, text=True
)
self.assertEqual(result.returncode, 0, result.stderr)
if __name__ == "__main__":
unittest.main()
+91
View File
@@ -0,0 +1,91 @@
"""Regression tests for the Hub Zeus Connect QR.
The LND-only rewrite of modules/bitcoin/lndconnect.nix shipped a wrapper
that Zeus cannot use. These tests lock the contract the Hub QR depends on
without needing lnd / tor / qrencode at test time.
"""
import os
import re
import unittest
_REPO_ROOT = os.path.normpath(os.path.join(os.path.dirname(__file__), ".."))
def _read(relpath: str) -> str:
with open(os.path.join(_REPO_ROOT, relpath), encoding="utf-8") as fh:
return fh.read()
class TestLndconnectWrapper(unittest.TestCase):
"""The system `lndconnect` wrapper must emit a Zeus-scannable URI."""
@classmethod
def setUpClass(cls):
cls.src = _read("modules/bitcoin/lndconnect.nix")
def test_uses_official_lndconnect_flags(self):
self.assertIn("--adminmacaroonpath=", self.src)
self.assertIn("--configfile=/dev/null", self.src)
self.assertIn("--nocert", self.src)
self.assertIn("--tlscertpath=", self.src)
def test_does_not_pass_unknown_short_flags(self):
# The broken rewrite called `lndconnect --cert … --macaroon …`.
# Those flags do not exist; Zeus then never got a valid URI.
self.assertIsNone(re.search(r"--cert=", self.src))
self.assertIsNone(re.search(r"--macaroon=", self.src))
def test_uses_dedicated_lnd_rest_onion(self):
self.assertIn("lnd-rest", self.src)
self.assertIn('onionServices.lnd-rest', self.src)
# Must not collide with the LND P2P onion named `lnd`.
self.assertNotIn("onionServices.lnd =", self.src)
self.assertNotIn('onionService = "${operatorName}/lnd"', self.src)
def test_reads_onion_from_onion_addresses_dir(self):
self.assertIn("onionAddresses.dataDir", self.src)
self.assertNotIn("/var/lib/tor/onion/${onionService}/hostname", self.src)
def test_omits_tls_cert_over_tor(self):
# Onion host + embedded localhost cert = Zeus rejects the QR.
self.assertIn('then "--nocert"', self.src)
class TestZeusConnectSetup(unittest.TestCase):
"""zeus-connect-setup must wait for the REST onion and validate the URI."""
@classmethod
def setUpClass(cls):
cls.src = _read("modules/wallet-autoconnect.nix")
def test_waits_for_onion_addresses(self):
self.assertIn("onion-addresses.service", self.src)
def test_rejects_non_lndconnect_output(self):
self.assertIn("^lndconnect://", self.src)
self.assertIn("\\.onion", self.src)
self.assertIn("macaroon=", self.src)
def test_no_clightning_fallback(self):
self.assertNotIn("lnconnect-clnrest", self.src)
class TestHubQrFallback(unittest.TestCase):
"""Hub QR encoding must not die on a payload that is too large for ECC H."""
def test_qrencode_falls_back_to_lower_ecc(self):
src = _read("app/sovran_systemsos_web/server.py")
self.assertIn('for ecc in ("H", "Q", "L")', src)
def test_qronly_does_not_hide_uri_when_qr_fails(self):
src = _read("app/sovran_systemsos_web/server.py")
self.assertIn("Don't hide the URI if we could not render a scannable QR.", src)
def test_zeus_guide_mentions_use_tor(self):
src = _read("app/sovran_systemsos_web/static/js/service-detail.js")
self.assertIn("Use Tor", src)
if __name__ == "__main__":
unittest.main()