From 10a6af2a60d5d5d7cedf044b726054b5428535bb Mon Sep 17 00:00:00 2001 From: Enrico Rubboli Date: Thu, 12 Nov 2026 21:18:04 +0100 Subject: [PATCH] feat(tailscale): remote access via a Tailscale sidecar Fourth access mode for the installer, alongside localhost/SSH, LAN HTTPS and LAN plain HTTP. The tailscale sidecar joins the host's tailnet and serves the web GUI at https://..ts.net with a real Let's Encrypt certificate - no host ports published, no CA import. - docker-compose.yml: tailscale service (profile: tailscale) with persistent state, healthcheck, /dev/net/tun + NET_ADMIN, and a static serve config (Web -> web-gui:4321 only). RPC ports, Postgres and the indexer stay on the internal network; Funnel is deliberately not wired up. Watchtower does not manage this container: it sits on the trust path (TRUST_PROXY depends on its XFF-overwriting behavior, set via Header.Set in tailscaled's serve), so upgrades are deliberate. - init.sh: access-mode chooser with /dev/net/tun gating (native Linux only; Docker Desktop VMs always provide it), node-name and auth-key prompts (tskey-auth- regex validated - compose would otherwise expand dollar-vars in .env values), post-start join flow that captures the ts.net FQDN and wires WEB_GUI_HOST/PASSKEY_* for WebAuthn, with distinct recovery hints for join-timeout, MagicDNS-disabled and a crash-looping sidecar. TRUST_PROXY=true is written for the shipped proxy modes (caddy gains it too - previously missing, which broke cross-site Origin derivation and per-IP rate limiting behind TLS). - installer hardening found during review: atomic .env rewrite (env_set, O_EXCL temp + fsync + rename), port arithmetic with 10# (leading-zero input used to crash), BITCOIN_CORE_CHAIN follows the Mintlayer network on empty BITCOIN_NETWORK (testnet installs used to get a mainnet Bitcoin node), qrencode/parse fallbacks for older qrencode and macOS hosts (no seq, bash 3.2), password policy shared between RPC and UI secrets (dollar signs, quotes, inline-comment and whitespace hazards rejected before they hit compose dotenv), 1777 seeding window closed via sticky bit, randomized container-side DB name (rename does not follow symlinks) and trap-restore on all signal paths. - tools/test-env-set.sh: regression tests for the .env rewrite helper and the Tailscale status parser. - .env.example + README: Tailscale section, prerequisites, security notes. --- .env.example | 34 +- .gitignore | 29 +- README.md | 64 +++- docker-compose.yml | 87 ++++- init.sh | 678 ++++++++++++++++++++++++++++++++---- tailscale/serve-config.json | 16 + tools/test-env-set.sh | 162 +++++++++ 7 files changed, 984 insertions(+), 86 deletions(-) create mode 100644 tailscale/serve-config.json create mode 100755 tools/test-env-set.sh diff --git a/.env.example b/.env.example index 6c7c039..a3668c9 100644 --- a/.env.example +++ b/.env.example @@ -62,15 +62,35 @@ WEB_GUI_TLS_PORT=443 # Interface the HTTPS port binds to (0.0.0.0 = whole LAN). WEB_GUI_TLS_BIND=0.0.0.0 # CADDY_IMAGE=caddy:2-alpine -# TRUST_PROXY: set true ONLY when requests arrive through the shipped caddy -# gateway (web profile). Caddy overwrites X-Forwarded-For with the real -# client IP (see caddy/Caddyfile), so with TRUST_PROXY=true the app can -# safely use it for per-IP rate limiting AND derive the browser-visible -# https:// Origin - without it, every form POST behind caddy would 403 on -# the cross-site check. Direct/LAN exposure (WEB_GUI_TLS=false, no caddy) -# must keep TRUST_PROXY unset: X-Forwarded-* is attacker-controllable then. +# TRUST_PROXY: set true ONLY when requests arrive through a shipped proxy - +# the caddy gateway (web profile) or the Tailscale sidecar (tailscale +# profile). Both overwrite X-Forwarded-For with the real client IP, so with +# TRUST_PROXY=true the app can safely use it for per-IP rate limiting AND +# derive the browser-visible https:// Origin - without it, form POSTs +# behind them would 403 on the cross-site check. Direct/LAN exposure +# (WEB_GUI_TLS=false, no caddy/tailscale) must keep TRUST_PROXY unset: +# X-Forwarded-* is attacker-controllable then. TRUST_PROXY= +# ── Remote access via Tailscale (optional, profile: tailscale) ───── +# The tailscale sidecar joins your tailnet and serves the web GUI over it at +# https://..ts.net - valid HTTPS (certificate +# provisioned by Tailscale), no host ports published to LAN/internet. +# Start with: docker compose --profile tailscale up -d +# Prerequisites (one-time, Tailscale admin console): MagicDNS + HTTPS +# certificates enabled. Needs /dev/net/tun on the Docker host (Docker +# Desktop VMs provide it; unprivileged LXC / rootless Docker may not). +TAILSCALE_HOSTNAME=nexus +# tskey-auth-... joins headlessly (init.sh stores it here; this file must be +# chmod 600 and gitignored). Empty = interactive login URL printed in the +# sidecar logs on first start: docker compose logs -f tailscale +TS_AUTHKEY= +# Optional 'tailscale up' extras, e.g. --advertise-tags=tag:nexus +# (recommended so a tailnet ACL can scope this device, dst tag:nexus:443). +# NOTE: compose expands $VAR/${VAR} in .env values - escape a literal '$' as '$$'. +TS_EXTRA_ARGS= +# TAILSCALE_IMAGE=tailscale/tailscale:latest + # ── Passkeys (WebAuthn) ─────────────────────────────── # Set by init.sh from WEB_GUI_HOST. Override only if behind a reverse proxy # that rewrites the hostname (e.g. your Node process sees a different URL diff --git a/.gitignore b/.gitignore index 67f82df..6b58b43 100644 --- a/.gitignore +++ b/.gitignore @@ -1,15 +1,20 @@ # documentation -wiki/ -TODO.md - -# Environment +/wiki/ +/TODO.md + +# Environment / credentials - init.sh writes .env, env_set() rewrites via +# temp files (.env.tmp., credentials mid-rewrite) and pre-rewrite +# backups (.env.bak.*). Enumerated (not .env*) so unrelated files like +# direnv's .envrc stay trackable. .env.example is the only tracked env file +# - placeholders only, never real credentials. Note: .gitignore comments +# must start the line; no inline '#'s. .env -.env.dev +.env.* +!.env*.example # Node node_modules/ -app/node_modules/ # Astro build output app/dist/ @@ -19,17 +24,17 @@ app/.astro/ app/coverage/ # Mintlayer data directory (node + wallet files) -mintlayer-data/ +/mintlayer-data/ # Docker volumes -postgres-data/ +/postgres-data/ # OS .DS_Store Thumbs.db -# Tauri -/windows/src-tauri +# Windows/Tauri experiment (reverted in 4903559); re-ignore if it returns +/windows/src-tauri/ # Editor .vscode/ @@ -40,7 +45,7 @@ Thumbs.db *.swo # Bitcoin (optional, profile: bitcoin) -bitcoin-data/ -bitcoin-wallet-data*/ +/bitcoin-data/ +/bitcoin-wallet-data*/ bdk-wallet/target/ .ecc/ diff --git a/README.md b/README.md index 0929d9c..392c412 100644 --- a/README.md +++ b/README.md @@ -135,7 +135,68 @@ After creating your wallet at , the dashboard at plain-HTTP LAN hostname (e.g. `http://192.168.1.50:4321`) will silently fail. > By default the GUI also binds to `127.0.0.1` only - set `WEB_GUI_BIND=0.0.0.0` > in `.env` to expose it, and put a TLS reverse proxy in front for real remote -> access. +> access - or skip port publishing entirely with the +> [Tailscale profile](#remote-access-via-tailscale). + +### Remote access via Tailscale + +Run `./init.sh` and pick **Tailnet (Tailscale)** as the access mode: it joins +the stack to your tailnet, captures the assigned `https://..ts.net` +name, and derives the passkey (WebAuthn) settings from it. Manual setup: + +```bash +# .env - keep comments on their own line (inline '#' handling varies by +# compose version and would corrupt the values) +TAILSCALE_HOSTNAME=nexus +# empty: first start prints a login URL in the logs +TS_AUTHKEY= +# REQUIRED for manual setup: login POSTs 403 behind the sidecar without it +TRUST_PROXY=true +# TS_EXTRA_ARGS=--advertise-tags=tag:nexus + +docker compose --profile tailscale up -d +docker compose logs -f tailscale # login URL on first start (no key set) +``` + +After approving the login URL, wire the assigned name into `.env` (this is +what init.sh automates): + +```bash +docker compose exec tailscale tailscale status --json # Self.DNSName = your ts.net name +``` + +```bash +# .env - WEB_GUI_HOST and PASSKEY_RP_ID take the BARE name (no https://); +# only PASSKEY_ORIGIN carries the scheme. Then restart web-gui: +WEB_GUI_HOST=nexus..ts.net +PASSKEY_RP_ID=nexus..ts.net +PASSKEY_ORIGIN=https://nexus..ts.net +``` + +```bash +docker compose up -d web-gui +``` + +What you get: + +| | | +|---|---| +| URL | `https://nexus..ts.net` - valid Let's Encrypt certificate, no CA import like the Caddy mode | +| Exposure | none on the host - only tailnet devices reach the sidecar; the LAN and the internet see nothing | +| Auth | the app's password + TOTP login still applies (matters on shared tailnets) | +| Scope | web UI only - node RPC (3030), wallet RPC (3034), Postgres and the indexer stay on the internal compose network | + +Prerequisites (one-time, Tailscale admin console): **MagicDNS** and **HTTPS +certificates** enabled. The Docker host needs `/dev/net/tun` (kernel-mode +networking; Docker Desktop VMs provide it, unprivileged LXC and rootless +Docker may not). Local access on the host keeps working at +`http://localhost:4321`. + +Optional hardening: tag the node (`TS_EXTRA_ARGS=--advertise-tags=tag:nexus`) +and add a tailnet ACL rule scoping reachability to it (`dst: tag:nexus:443`). + +> Tailscale **Funnel** (a public internet URL) is deliberately not wired up - +> a wallet GUI must not get a public link. > **Sync time:** balance and transaction history only appear once the node has fully synced. On first run this takes several hours for mainnet. The dashboard shows the current block height so you can track progress. @@ -385,3 +446,4 @@ docker compose restart web-gui - Wallet RPC credentials are never sent to the browser - all calls are proxied server-side by the Astro app. - Only a fixed allowlist of RPC methods is callable through the `/api/rpc` endpoint. - The wallet RPC (3034) and node RPC (3030) ports are not exposed to the host by default. +- The optional Tailscale sidecar (profile: `tailscale`) serves only the web UI over your tailnet - RPC ports stay on the internal compose network, and Funnel (public URLs) is not shipped. diff --git a/docker-compose.yml b/docker-compose.yml index 790b22e..555361c 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -131,10 +131,15 @@ services: HOST: "0.0.0.0" # Settings -> HTTPS section renders only when the gateway is enabled WEB_GUI_TLS: "${WEB_GUI_TLS:-false}" - # Gate for proxy-derived headers (client IP + Origin): set true ONLY when - # traffic arrives through the shipped caddy gateway, which overwrites - # X-Forwarded-For with the real client IP. Direct/LAN exposure must keep - # it unset - X-Forwarded-* is attacker-controllable then. + # Gate for proxy-derived headers (client IP + Origin): set true ONLY + # when traffic arrives through a shipped proxy that overwrites + # X-Forwarded-For with the real client IP: the caddy gateway + # (header_up XFF {client_ip}, see caddy/Caddyfile) or the tailscale + # sidecar (tailscale serve Set()s XFF from the WireGuard peer address - + # addProxyForwardedHeaders in tailscale's ipn/ipnlocal/serve.go, which + # also clears client-supplied Tailscale-* identity headers). Direct/LAN + # exposure must keep it unset - X-Forwarded-* is attacker-controllable + # then. TRUST_PROXY: "${TRUST_PROXY:-}" # WebAuthn: init.sh writes these into .env; without the passthrough # compose never injects them and passkeys silently fail on TLS setups. @@ -435,9 +440,83 @@ services: - web restart: unless-stopped + # ───────────────────────────────────────── + # Remote access via Tailscale (profile: tailscale) + # + # Joins the node to your Tailscale network and serves the web GUI over it: + # https://..ts.net + # valid HTTPS (certificate provisioned by Tailscale, no CA import), with no + # ports published to the host LAN or the internet. Requires MagicDNS + HTTPS + # certificates to be enabled for the tailnet (admin console, one-time). + # + # Threat model: only the web GUI is reachable through the sidecar. Node RPC + # (3030), wallet RPC (3034), Postgres and the indexer stay on the internal + # compose network, and the app's password + TOTP login still applies (it + # matters on shared tailnets). Funnel (public internet exposure) is + # deliberately not wired up - a wallet GUI must not get a public URL. + # + # Kernel-mode networking (/dev/net/tun + NET_ADMIN). Hosts without a TUN + # device (unprivileged LXC, rootless Docker, some NAS) cannot run this + # service; Tailscale's own userspace networking mode is the upstream escape + # hatch (tailscale.com/kb - userspace networking) but is not shipped here. + # + # First start without TS_AUTHKEY prints a login URL in this container's + # logs: docker compose logs -f tailscale + # ───────────────────────────────────────── + tailscale: + image: "${TAILSCALE_IMAGE:-tailscale/tailscale:stable}" + hostname: "${TAILSCALE_HOSTNAME:-nexus}" + # Deliberately NOT watchtower-managed (watchtower runs --label-enable): + # this sidecar sits on the trust path - TRUST_PROXY=true depends on its + # XFF-overwriting behavior - so upgrade it deliberately + # (docker compose pull tailscale). Default tag :stable tracks the + # Tailscale stable channel (not :latest); override via TAILSCALE_IMAGE. + depends_on: + - web-gui + environment: + # State must persist, or the node re-authenticates (new tailnet + # identity) on every restart. + TS_STATE_DIR: "/state" + TS_HOSTNAME: "${TAILSCALE_HOSTNAME:-nexus}" + # Empty = interactive login URL in the logs. A tskey-auth-... here + # joins headlessly (init.sh stores it in .env, 0600 + gitignored). + TS_AUTHKEY: "${TS_AUTHKEY:-}" + # Keep existing state across restarts even when TS_AUTHKEY is rotated. + TS_AUTH_ONCE: "true" + # Never adopt tailnet DNS settings: compose service names (web-gui, + # wallet-rpc-daemon, ...) must keep resolving via Docker's DNS. + TS_ACCEPT_DNS: "false" + TS_USERSPACE: "false" + # Serves the GUI on the tailnet at ${TS_CERT_DOMAIN}:443 - see + # ./tailscale/serve-config.json. + TS_SERVE_CONFIG: "/config/serve-config.json" + # Optional 'tailscale up' extras, e.g. --advertise-tags=tag:nexus + # (recommended so a tailnet ACL can scope this device). + TS_EXTRA_ARGS: "${TS_EXTRA_ARGS:-}" + volumes: + - "tailscale-state:/state" + - "./tailscale:/config:ro" + devices: + - "/dev/net/tun:/dev/net/tun" + cap_add: + - NET_ADMIN + healthcheck: + # --json exits 0 whenever tailscaled answers, including NeedsLogin; + # plain status exits 1 ("Logged out.") and would mark the sidecar + # unhealthy for the whole login-approval window. + test: ["CMD", "tailscale", "status", "--peers=false", "--json"] + interval: "30s" + timeout: "10s" + retries: "5" + start_period: "30s" + profiles: + - tailscale + restart: unless-stopped + volumes: postgres-data: caddy-data: caddy-config: ca-public: feature-requests: + tailscale-state: diff --git a/init.sh b/init.sh index 0cb73e7..d8580ce 100755 --- a/init.sh +++ b/init.sh @@ -1,5 +1,32 @@ #!/usr/bin/env bash set -euo pipefail +SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) || exit 1 +CLEANUP_FILES="" # .env heredoc tmp (registered when created); swept by the traps. + # Unquoted expansion in the traps is safe: the whitespace guard + # rejects checkouts with spaces in their path. +trap 'rm -f "$SCRIPT_DIR/.env.tmp.$$" ${CLEANUP_FILES:-} 2>/dev/null || true; chmod 700 "$SCRIPT_DIR/mintlayer-data/prefs" 2>/dev/null || true' EXIT +trap 'rm -f "$SCRIPT_DIR/.env.tmp.$$" ${CLEANUP_FILES:-} 2>/dev/null || true; chmod 700 "$SCRIPT_DIR/mintlayer-data/prefs" 2>/dev/null || true; exit 130' INT +trap 'rm -f "$SCRIPT_DIR/.env.tmp.$$" ${CLEANUP_FILES:-} 2>/dev/null || true; chmod 700 "$SCRIPT_DIR/mintlayer-data/prefs" 2>/dev/null || true; exit 143' TERM +trap 'rm -f "$SCRIPT_DIR/.env.tmp.$$" ${CLEANUP_FILES:-} 2>/dev/null || true; chmod 700 "$SCRIPT_DIR/mintlayer-data/prefs" 2>/dev/null || true; exit 129' HUP +# Sweep this run's .env temp copy (credentials mid-rewrite) on any exit. +# INT/TERM clean up and then exit - a bare cleanup trap would resume the +# script after Ctrl-C. $$ matches env_set's temp file name below. +# EXIT/INT/TERM also restore 0700 on the prefs dir: the credential-seeding +# step widens it to 0777 for a rootful container, and an interrupted run +# would otherwise leave a world-writable credentials directory behind. +# Log window for the Tailscale login-URL scrape: URLs printed before this +# run started may be consumed/expired from an earlier attempt. +SCRIPT_START_EPOCH=$(date +%s) +# Anchor to the checkout: every path below (.env, bind mounts, compose +# project dir) assumes repo-root CWD, so `bash /path/to/init.sh` from +# elsewhere would otherwise write .env into the wrong directory. +cd -- "$(dirname -- "${BASH_SOURCE[0]}")" || exit 1 +# Best-effort sweep of residue from a SIGKILLed/aborted earlier run (the +# traps only cover this run's pid). Only files idle for over an hour are +# swept: a concurrent live run's temp is recent and must survive (its rename +# depends on it). Runs AFTER the anchor so it sweeps the checkout's +# directory, not the caller's. +find . -maxdepth 1 -name '.env.tmp.*' -mmin +60 -delete 2>/dev/null || true # ───────────────────────────────────────────────────────────────────────────── # Mintlayer Nexus - interactive setup @@ -41,7 +68,7 @@ prompt() { } prompt_secret() { - local var="$1" question="$2" + local var="$1" question="$2" input printf "${CYAN}│${RESET} ${question} " read -rs input printf '\n' @@ -99,6 +126,19 @@ rand_pass() { fi } +# Real shell assignment (the .env heredoc below only writes the TEXT +# 'PROJECT_DIR_HOST=...'), needed by the whitespace guard early in the +# script and by the feature-enabler .env consumers. +PROJECT_DIR_HOST=$(pwd) +case "$PROJECT_DIR_HOST" in + *[[:space:]]*) + err "The repository path contains whitespace: $PROJECT_DIR_HOST" + err "Settings-page feature toggles will not work." + err "Move this checkout to a path without spaces and re-run init.sh." + exit 1 + ;; +esac + # ── Detect OS ───────────────────────────────────────────────────────────────── detect_os() { case "$(uname -s)" in @@ -195,6 +235,13 @@ check_prereqs() { printf " Install Node.js v18+ from https://nodejs.org or via your package manager.\n\n" exit 1 } + # env_set() needs fs.rmSync (>= 14.14) and the Tailscale status parser uses + # optional chaining (>= 14): enforce the advertised floor, not just presence. + node -e 'process.exit(parseInt(process.versions.node, 10) < 18 ? 1 : 0)' || { + err "Node.js v18+ is required." + printf " Install Node.js v18+ from https://nodejs.org or via your package manager.\n\n" + exit 1 + } } # ── Determine compose command ───────────────────────────────────────────────── @@ -206,10 +253,120 @@ compose_cmd() { fi } +# ── Update a single KEY=VALUE line in .env ────────────── +env_set() { + # env_set KEY VALUE - rewrite "KEY=" in .env, appending when absent. + # Uses node (a checked prerequisite) instead of sed -i: BSD and GNU sed + # disagree on how -i takes its backup argument. The temp file name comes + # from bash's $$ so the EXIT trap sweeps crash residue. KEY/VALUE travel + # via the environment, not argv: `ps` shows argv world-readable, and a + # future call site passing a secret must not leak through the process + # table (/proc//environ is owner-only). + OCR_ENV_SET_KEY="$1" OCR_ENV_SET_VALUE="$2" OCR_ENV_SET_TMP=".env.tmp.$$" \ + node -e ' + const fs = require("fs"); + const key = process.env.OCR_ENV_SET_KEY; + const value = process.env.OCR_ENV_SET_VALUE; + const tmp = process.env.OCR_ENV_SET_TMP; + // Validate before touching .env: an embedded newline would corrupt every + // line after the rewritten key. + if (/[\r\n]/.test(key) || /[\r\n]/.test(value)) { + console.error("env_set: key and value must not contain newlines"); + process.exit(1); + } + if (/\$/.test(key) || /\$/.test(value)) { + console.error("env_set: key and value must not contain $ (compose would expand it)"); + process.exit(1); + } + let lines; + try { + lines = fs.readFileSync(".env", "utf8").replace(/\r\n/g, "\n").split("\n"); + } catch (err) { + console.error("env_set: cannot read .env - run init.sh first: " + err.message); + process.exit(1); + } + let found = false; + const rewritten = lines.map((line) => { + // Match indented (compose trims keys) and `export KEY=` lines too, so a + // hand-edited .env is replaced in place instead of duplicated. + const stripped = line.trim().replace(/^export\s+/, ""); + if (stripped.startsWith(key + "=")) { + found = true; + return key + "=" + value; + } + return line; + }); + if (!found) rewritten.push(key + "=" + value); + if (rewritten[rewritten.length - 1] !== "") rewritten.push(""); + // Atomic replace: an interrupted truncate-in-place write would destroy + // the SESSION_SECRET/RPC/DB credentials in .env. mode 0600 applies at + // creation (umask cannot widen it); rm clears pid-reuse staleness and + // the EXIT trap (same bash $$ via the tmp env var) sweeps residue. + // 'wx' = O_CREAT|O_EXCL: a racing local user could swap the predictable + // .env.tmp. path for a symlink in the rm->write window - O_EXCL + // refuses the path instead of following it, aborting the rewrite rather + // than leaking credentials to an attacker-chosen target. + fs.rmSync(tmp, { force: true }); + const fd = fs.openSync(tmp, "wx", 0o600); + fs.writeFileSync(fd, rewritten.join("\n")); + // fsync before rename: without it a power loss can persist the rename + // while the temp file data blocks are still in page cache. + fs.fsyncSync(fd); + fs.closeSync(fd); + fs.renameSync(tmp, ".env"); + ' +} + +# lower STRING - lowercase without bash-4 ${var,,} (macOS ships bash 3.2). +lower() { printf '%s' "$1" | tr '[:upper:]' '[:lower:]'; } + +# password_reject_reason VALUE - print the rejection reason for a user-chosen +# password (empty = acceptable). Rejects $ because compose expands $VAR/ +# ${VAR} in .env values, which would corrupt the credential on write. +password_reject_reason() { + if [[ ${#1} -lt 8 ]]; then + printf "Password must be at least 8 characters" + elif [[ "$1" == *'$'* ]]; then + printf 'Password must not contain $ - compose would expand it in .env' + elif [[ "$1" == *' #'* ]]; then + printf 'Password must not contain " #" - compose treats it as an inline comment' + elif [[ "$1" == '"'* || "$1" == "'"* ]]; then + printf 'Password must not start with a quote - compose strips it from .env' + elif [[ "$1" =~ ^[[:space:]] || "$1" =~ [[:space:]]$ ]]; then + printf "Password must not start or end with whitespace - compose trims it" + fi +} + +# api_port_reject_reason VALUE - conflict/validity message for the indexer +# REST API port (empty = acceptable). Called after the access mode is chosen, +# so the TLS-gateway reservation only applies in that mode. +api_port_reject_reason() { + if ! [[ "$1" =~ ^[0-9]{1,5}$ ]] || (( 10#$1 < 1 || 10#$1 > 65535 )); then + printf "Enter a valid port number (1-65535)" + elif (( 10#$1 == 10#$WEB_GUI_PORT )); then + printf "Port %s is taken by the web GUI - pick another" "$1" + elif [[ "$WEB_GUI_TLS" == "true" && "$1" == "443" ]]; then + printf "Port 443 is reserved for the HTTPS gateway - pick another" + fi +} + +# show_totp_qr - render the TOTP URI as a terminal QR, falling back to the +# plain URI: qrencode -t ANSIUTF8 needs qrencode >= 3.4, and an older build +# used to abort the whole script mid-setup instead of degrading. +show_totp_qr() { + if command -v qrencode &>/dev/null && \ + echo "$TOTP_URI" | qrencode -t ANSIUTF8 2>/dev/null | sed "s/^/${CYAN}│${RESET} /"; then + return 0 + fi + printf "${CYAN}│${RESET} ${GRAY}%s${RESET}\n" "$TOTP_URI" + printf "${CYAN}│${RESET} ${DIM}(Install qrencode >= 3.4 for a scannable QR code in the terminal)${RESET}\n" + return 0 +} + # ───────────────────────────────────────────────────────────────────────────── # Banner # ───────────────────────────────────────────────────────────────────────────── -clear +clear 2>/dev/null || true printf "\n" printf "${CYAN}${BOLD}" printf " ███╗ ███╗██╗███╗ ██╗████████╗██╗ █████╗ ██╗ ██╗███████╗██████╗ \n" @@ -264,17 +421,21 @@ else ask "Node RPC password" hint "Used by node-daemon - not exposed outside Docker" prompt_secret NODE_RPC_PASSWORD "Password:" - while [[ ${#NODE_RPC_PASSWORD} -lt 8 ]]; do - printf "${CYAN}│${RESET} ${RED}Password must be at least 8 characters${RESET}\n" + reason="$(password_reject_reason "$NODE_RPC_PASSWORD")" + while [[ -n "$reason" ]]; do + printf "${CYAN}│${RESET} ${RED}%s${RESET}\n" "$reason" prompt_secret NODE_RPC_PASSWORD "Password:" + reason="$(password_reject_reason "$NODE_RPC_PASSWORD")" done ask "Wallet RPC password" hint "Used by wallet-rpc-daemon - not exposed outside Docker" prompt_secret WALLET_RPC_PASSWORD "Password:" - while [[ ${#WALLET_RPC_PASSWORD} -lt 8 ]]; do - printf "${CYAN}│${RESET} ${RED}Password must be at least 8 characters${RESET}\n" + reason="$(password_reject_reason "$WALLET_RPC_PASSWORD")" + while [[ -n "$reason" ]]; do + printf "${CYAN}│${RESET} ${RED}%s${RESET}\n" "$reason" prompt_secret WALLET_RPC_PASSWORD "Password:" + reason="$(password_reject_reason "$WALLET_RPC_PASSWORD")" done fi @@ -296,17 +457,21 @@ hint "Choose a strong password - this guards access to your wallet." UI_PASSWORD="" UI_PASSWORD_CONFIRM="" prompt_secret UI_PASSWORD "Password:" -while [[ ${#UI_PASSWORD} -lt 8 ]]; do - printf "${CYAN}│${RESET} ${RED}Password must be at least 8 characters${RESET}\n" +reason="$(password_reject_reason "$UI_PASSWORD")" +while [[ -n "$reason" ]]; do + printf "${CYAN}│${RESET} ${RED}%s${RESET}\n" "$reason" prompt_secret UI_PASSWORD "Password:" + reason="$(password_reject_reason "$UI_PASSWORD")" done prompt_secret UI_PASSWORD_CONFIRM "Confirm password:" while [[ "$UI_PASSWORD" != "$UI_PASSWORD_CONFIRM" ]]; do printf "${CYAN}│${RESET} ${RED}Passwords do not match, try again${RESET}\n" prompt_secret UI_PASSWORD "Password:" - while [[ ${#UI_PASSWORD} -lt 8 ]]; do - printf "${CYAN}│${RESET} ${RED}Password must be at least 8 characters${RESET}\n" + reason="$(password_reject_reason "$UI_PASSWORD")" + while [[ -n "$reason" ]]; do + printf "${CYAN}│${RESET} ${RED}%s${RESET}\n" "$reason" prompt_secret UI_PASSWORD "Password:" + reason="$(password_reject_reason "$UI_PASSWORD")" done prompt_secret UI_PASSWORD_CONFIRM "Confirm password:" done @@ -322,6 +487,7 @@ UI_PASSWORD_HASH=$(UI_PASSWORD="$UI_PASSWORD" node -e " process.stdout.write('pbkdf2:sha512:210000:' + salt + ':' + key.toString('hex')); }); ") +[[ -n "$UI_PASSWORD_HASH" ]] || { err "Password hashing produced no output"; exit 1; } ok "Password hashed" # Generate TOTP secret (20 random bytes → base32) @@ -349,19 +515,14 @@ SESSION_SECRET=$(openssl rand -hex 32 2>/dev/null || head -c 32 /dev/urandom | o TOTP_URI="otpauth://totp/Mintlayer%20Nexus?secret=${UI_TOTP_SECRET}&issuer=Mintlayer" printf "${CYAN}│${RESET}\n" +[[ -n "$UI_TOTP_SECRET" ]] || { err "TOTP secret generation failed"; exit 1; } ok "TOTP secret generated" printf "${CYAN}│${RESET}\n" printf "${CYAN}│${RESET} ${BOLD}Scan this with Google Authenticator, Authy, or any TOTP app:${RESET}\n" printf "${CYAN}│${RESET}\n" # Show QR code if qrencode is available, otherwise show the URI -if command -v qrencode &>/dev/null; then - echo "$TOTP_URI" | qrencode -t ANSIUTF8 | sed "s/^/${CYAN}│${RESET} /" -else - printf "${CYAN}│${RESET} ${GRAY}%s${RESET}\n" "$TOTP_URI" - printf "${CYAN}│${RESET}\n" - printf "${CYAN}│${RESET} ${DIM}(Install qrencode for a scannable QR code in the terminal)${RESET}\n" -fi +show_totp_qr printf "${CYAN}│${RESET}\n" hint "Or enter the secret manually: ${BOLD}${UI_TOTP_SECRET}${RESET}" @@ -374,11 +535,7 @@ while [[ "$SCANNED" != "yes" ]]; do printf "${CYAN}│${RESET} ${RED}Please scan the QR code or save the secret before continuing.${RESET}\n" printf "${CYAN}│${RESET}\n" # Re-display the URI in case they need it again - if command -v qrencode &>/dev/null; then - echo "$TOTP_URI" | qrencode -t ANSIUTF8 | sed "s/^/${CYAN}│${RESET} /" - else - printf "${CYAN}│${RESET} ${GRAY}%s${RESET}\n" "$TOTP_URI" - fi + show_totp_qr printf "${CYAN}│${RESET}\n" confirm SCANNED "I have scanned the QR code / saved the TOTP secret" "N" done @@ -396,36 +553,70 @@ hint "The Astro web interface will be available at http://localhost:" prompt WEB_GUI_PORT "Port:" "4321" # Validate it's a number -while ! [[ "$WEB_GUI_PORT" =~ ^[0-9]+$ ]] || (( WEB_GUI_PORT < 1 || WEB_GUI_PORT > 65535 )); do +while ! [[ "$WEB_GUI_PORT" =~ ^[0-9]{1,5}$ ]] || (( 10#$WEB_GUI_PORT < 1 || 10#$WEB_GUI_PORT > 65535 )); do printf "${CYAN}│${RESET} ${RED}Enter a valid port number (1-65535)${RESET}\n" prompt WEB_GUI_PORT "Port:" "4321" done +# The TLS gateway (mode chosen below) publishes host port 443 - a GUI port +# of 443 would collide only after the mode is picked, so reserve it now. +if (( 10#$WEB_GUI_PORT == 443 )); then + warn "Port 443 is reserved for the HTTPS gateway - using 4321 for the GUI." + WEB_GUI_PORT="4321" +fi ask "Expose the web GUI to your network?" -hint "Three access modes:" + +# The Tailscale sidecar runs kernel-mode networking and needs a TUN device +# (Docker Desktop's VM provides one; native Linux almost always does). +# Unprivileged LXC, rootless Docker and some NAS setups don't - offering the +# option there would only crash-loop the sidecar. +TAILSCALE_AVAILABLE="true" +if [[ "$(detect_os)" == "linux" && ! -e /dev/net/tun ]]; then + TAILSCALE_AVAILABLE="false" +fi + +hint "Access modes:" hint " localhost only - the GUI is reachable solely from this machine;" hint " open it through an SSH tunnel. Most secure." hint " LAN over HTTPS - other devices open it at https://; Caddy" hint " terminates TLS with a local Certificate Authority (works without a" hint " public domain). Browsers warn once until you import the CA root," hint " downloadable from Settings -> HTTPS after setup." +hint " Tailnet (Tailscale) - the GUI joins your tailnet; any device logged" +hint " into it opens https://..ts.net with valid HTTPS." +hint " Nothing is published to the LAN or the internet. Needs a (free)" +hint " Tailscale account with MagicDNS + HTTPS certificates enabled." hint " LAN plain HTTP - not recommended: traffic is unencrypted and the" hint " session cookie is refused on non-localhost origins, so sign-in only" hint " works from this machine anyway." +if [[ "$TAILSCALE_AVAILABLE" != "true" ]]; then + hint "Tailnet (Tailscale) is unavailable on this host: /dev/net/tun is" + hint " missing, so the sidecar cannot start." +fi hint "Running your own TLS proxy on a public domain? Pick 'localhost only'" hint "and set WEB_GUI_HOST + PASSKEY_* in .env manually (see .env.example)." + +ACCESS_MODE_OPTIONS=("localhost only (SSH tunnel)" "LAN over HTTPS (Caddy local CA)") +if [[ "$TAILSCALE_AVAILABLE" == "true" ]]; then + ACCESS_MODE_OPTIONS+=("Tailnet (Tailscale - remote access)") +fi +ACCESS_MODE_OPTIONS+=("LAN plain HTTP (not recommended)") + ACCESS_CHOICE="" -choose ACCESS_CHOICE "Access mode:" \ - "localhost only (SSH tunnel)" \ - "LAN over HTTPS (Caddy local CA)" \ - "LAN plain HTTP (not recommended)" +choose ACCESS_CHOICE "Access mode:" "${ACCESS_MODE_OPTIONS[@]}" WEB_GUI_TLS="false" WEB_GUI_BIND="127.0.0.1" WEB_GUI_HOST="localhost" +TRUST_PROXY="" +TAILSCALE_ENABLED="false" +TAILSCALE_HOSTNAME="nexus" +TS_AUTHKEY="" +TS_EXTRA_ARGS="" case "$ACCESS_CHOICE" in *"LAN over HTTPS"*) WEB_GUI_TLS="true" + TRUST_PROXY="true" ask "Hostname for the HTTPS certificate" hint "Must resolve to this machine from your devices, e.g. ml1.local" hint "(mDNS) or an entry in your router's DNS / your device's hosts file." @@ -433,15 +624,64 @@ case "$ACCESS_CHOICE" in # Hostname flows into the Caddyfile (pre-parse textual substitution), # docker-compose env interpolation, and the WebAuthn RP ID - so it must # be a plain lowercase DNS name. Uppercase is normalized; everything - # else invalid is re-asked. - while ! [[ "${WEB_GUI_HOST,,}" =~ ^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)+$ ]]; do - printf "${CYAN}│${RESET} ${RED}Enter a valid hostname (letters, digits, dots, hyphens - no ports, spaces or underscores)${RESET}\n" + # else invalid is re-asked. (lower(), not ${var,,}: macOS ships bash 3.2.) + WEB_GUI_HOST="$(lower "$WEB_GUI_HOST")" + while ! [[ "$WEB_GUI_HOST" =~ ^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)+$ ]]; do + printf "${CYAN}│${RESET} ${RED}Enter a valid hostname (letters, digits, dots, hyphens - uppercase is lowercased automatically; no ports, spaces or underscores)${RESET}\n" prompt WEB_GUI_HOST "Hostname:" "$(hostname -s 2>/dev/null || echo mintlayer-gui).local" + WEB_GUI_HOST="$(lower "$WEB_GUI_HOST")" done - WEB_GUI_HOST="${WEB_GUI_HOST,,}" warn "The GUI stays bound to 127.0.0.1 - only the HTTPS gateway (port 443) is exposed." hint "Always open https://${WEB_GUI_HOST} - plain http:// (port 80) is not published." ;; + *"Tailnet (Tailscale"*) + TAILSCALE_ENABLED="true" + # Traffic arrives through the shipped sidecar, which overwrites + # X-Forwarded-For - the same trust model as the caddy gateway. + TRUST_PROXY="true" + ask "Tailscale node name" + hint "Devices on your tailnet will open https://..ts.net." + prompt TAILSCALE_HOSTNAME "Name:" "nexus" + # Flows into the sidecar hostname, the ts.net certificate name and + # MagicDNS - a plain lowercase DNS label only. + TAILSCALE_HOSTNAME="$(lower "$TAILSCALE_HOSTNAME")" + while ! [[ "$TAILSCALE_HOSTNAME" =~ ^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$ ]]; do + printf "${CYAN}│${RESET} ${RED}Enter a short DNS name (letters, digits, hyphens - uppercase is lowercased automatically)${RESET}\n" + prompt TAILSCALE_HOSTNAME "Name:" "nexus" + TAILSCALE_HOSTNAME="$(lower "$TAILSCALE_HOSTNAME")" + done + + printf "${CYAN}│${RESET}\n" + TS_AUTH_CHOICE="" + choose TS_AUTH_CHOICE "How should the node join your tailnet?" \ + "Login URL - approve once in the browser, nothing secret is stored" \ + "Auth key - paste a key from the Tailscale admin console (headless)" + TS_AUTHKEY="" + if [[ "$TS_AUTH_CHOICE" == *"Auth key"* ]]; then + ask "Tailscale auth key" + hint "Admin console -> Settings -> Keys. The key lands in .env" + hint "(chmod 600, gitignored). Leave blank to use the login URL instead." + prompt_secret TS_AUTHKEY "Auth key:" + # Paste hygiene: strip surrounding whitespace (trailing spaces, CR from Windows clips). + TS_AUTHKEY="$(printf '%s' "$TS_AUTHKEY" | tr -d '[:space:]')" + # Only plain tskey-auth-... tokens: the value lands unquoted in .env, + # where compose expands $VAR/${VAR} references in values - a malformed + # paste would corrupt interpolation or leak other secrets from this + # file into the sidecar environment. + if [[ -n "$TS_AUTHKEY" && ! "$TS_AUTHKEY" =~ ^tskey-auth-[A-Za-z0-9_-]+$ ]]; then + warn "That does not look like a Tailscale auth key (expected tskey-auth-...)." + hint "Falling back to the interactive login-URL flow." + TS_AUTHKEY="" + fi + fi + + warn "The GUI stays bound to 127.0.0.1 on the host - only the Tailscale" + warn "sidecar reaches the stack, and only from inside your tailnet." + hint "Note: some hosts (unprivileged LXC, rootless Docker) accept the" + hint "/dev/net/tun device but deny its configuration - the sidecar then" + hint "restart-loops. If that happens: docker compose logs tailscale, and" + hint "re-run ./init.sh to pick a different access mode." + ;; *"LAN plain HTTP"*) WEB_GUI_BIND="0.0.0.0" warn "GUI will be reachable from other machines (plain HTTP)." @@ -490,9 +730,11 @@ if [[ "$ENABLE_INDEXER" == "yes" ]]; then else ask "PostgreSQL password" prompt_secret POSTGRES_PASSWORD "Password:" - while [[ ${#POSTGRES_PASSWORD} -lt 8 ]]; do - printf "${CYAN}│${RESET} ${RED}Password must be at least 8 characters${RESET}\n" + reason="$(password_reject_reason "$POSTGRES_PASSWORD")" + while [[ -n "$reason" ]]; do + printf "${CYAN}│${RESET} ${RED}%s${RESET}\n" "$reason" prompt_secret POSTGRES_PASSWORD "Password:" + reason="$(password_reject_reason "$POSTGRES_PASSWORD")" done fi @@ -500,9 +742,11 @@ if [[ "$ENABLE_INDEXER" == "yes" ]]; then prompt API_WEB_SERVER_PORT "Port:" "3000" # Same validation as the web GUI port: garbage here breaks the compose # port mapping (127.0.0.1:${API_WEB_SERVER_PORT:-3000}:3000). - while ! [[ "$API_WEB_SERVER_PORT" =~ ^[0-9]+$ ]] || (( API_WEB_SERVER_PORT < 1 || API_WEB_SERVER_PORT > 65535 )); do - printf "${CYAN}│${RESET} ${RED}Enter a valid port number (1-65535)${RESET}\n" + reason="$(api_port_reject_reason "$API_WEB_SERVER_PORT")" + while [[ -n "$reason" ]]; do + printf "${CYAN}│${RESET} ${RED}%s${RESET}\n" "$reason" prompt API_WEB_SERVER_PORT "Port:" "3000" + reason="$(api_port_reject_reason "$API_WEB_SERVER_PORT")" done else # Inert while the indexer profile is off, but pre-filled so a later manual @@ -545,15 +789,19 @@ if [[ "$ENABLE_BITCOIN" == "yes" ]]; then else ask "Bitcoin node RPC password" prompt_secret BITCOIN_RPC_PASSWORD "Password:" - while [[ ${#BITCOIN_RPC_PASSWORD} -lt 8 ]]; do - printf "${CYAN}│${RESET} ${RED}Password must be at least 8 characters${RESET}\n" + reason="$(password_reject_reason "$BITCOIN_RPC_PASSWORD")" + while [[ -n "$reason" ]]; do + printf "${CYAN}│${RESET} ${RED}%s${RESET}\n" "$reason" prompt_secret BITCOIN_RPC_PASSWORD "Password:" + reason="$(password_reject_reason "$BITCOIN_RPC_PASSWORD")" done ask "BTC wallet API password" prompt_secret BITCOIN_WALLET_HTTP_PASSWORD "Password:" - while [[ ${#BITCOIN_WALLET_HTTP_PASSWORD} -lt 8 ]]; do - printf "${CYAN}│${RESET} ${RED}Password must be at least 8 characters${RESET}\n" + reason="$(password_reject_reason "$BITCOIN_WALLET_HTTP_PASSWORD")" + while [[ -n "$reason" ]]; do + printf "${CYAN}│${RESET} ${RED}%s${RESET}\n" "$reason" prompt_secret BITCOIN_WALLET_HTTP_PASSWORD "Password:" + reason="$(password_reject_reason "$BITCOIN_WALLET_HTTP_PASSWORD")" done fi @@ -598,6 +846,12 @@ if [[ "$ENABLE_WATCHTOWER" == "yes" ]]; then hint "Format: telegram://BOT_TOKEN@telegram?channels=CHAT_ID" hint "Leave blank to skip." prompt WATCHTOWER_NOTIFICATION_URL "Notification URL:" "" + # The value lands unquoted in .env: compose expands $VAR/${VAR} in values, + # which would corrupt the URL or pull other secrets from this file. + if [[ "$WATCHTOWER_NOTIFICATION_URL" == *'$'* ]]; then + err "Notification URL must not contain \$ - compose would expand it." + exit 1 + fi fi divider @@ -639,6 +893,12 @@ if [[ "$SETUP_IPFS" == "yes" ]]; then printf "${CYAN}│${RESET} ${RED}API key cannot be empty${RESET}\n" prompt_secret FILEBASE_TOKEN "API key:" done + # The token lands unquoted in .env: compose expands $VAR/${VAR} there, + # which would corrupt the key or pull other secrets from this file. + if [[ "$FILEBASE_TOKEN" == *'$'* ]]; then + err "Filebase API key must not contain \$ - compose would expand it." + exit 1 + fi ok "Filebase API key saved" ;; *"Pinata"*) @@ -649,6 +909,11 @@ if [[ "$SETUP_IPFS" == "yes" ]]; then printf "${CYAN}│${RESET} ${RED}JWT cannot be empty${RESET}\n" prompt_secret PINATA_JWT "JWT:" done + # Same .env interpolation hazard: reject $ early. + if [[ "$PINATA_JWT" == *'$'* ]]; then + err "Pinata JWT must not contain \$ - compose would expand it." + exit 1 + fi ok "Pinata JWT saved" ;; esac @@ -687,6 +952,11 @@ if [[ "$SETUP_TELEGRAM" == "yes" ]]; then printf "${CYAN}│${RESET} ${RED}Chat ID cannot be empty${RESET}\n" prompt TELEGRAM_CHAT_ID "Chat ID:" done + # Same .env interpolation hazard as above: reject $ early. + if [[ "$TELEGRAM_BOT_TOKEN" == *'$'* || "$TELEGRAM_CHAT_ID" == *'$'* ]]; then + err "Telegram token and chat ID must not contain \$ - compose would expand them." + exit 1 + fi ok "Telegram configured" fi @@ -703,6 +973,7 @@ printf "${CYAN}│${RESET} %-22s %s\n" "Passwords:" "${BOLD}$([ "$USE_RANDOM_P printf "${CYAN}│${RESET} %-22s %s\n" "Web UI auth:" "${BOLD}password + TOTP 2FA${RESET}" printf "${CYAN}│${RESET} %-22s %s\n" "Web GUI:" "${BOLD}${PASSKEY_ORIGIN}${RESET}" printf "${CYAN}│${RESET} %-22s %s\n" "LAN HTTPS:" "${BOLD}$([ "$WEB_GUI_TLS" == "true" ] && echo "enabled (${WEB_GUI_HOST}, local CA)" || echo "disabled")${RESET}" +[[ "$TAILSCALE_ENABLED" == "true" ]] && printf "${CYAN}│${RESET} %-22s %s\n" "Remote access:" "${BOLD}Tailscale tailnet (${TAILSCALE_HOSTNAME}..ts.net)${RESET}" printf "${CYAN}│${RESET} %-22s %s\n" "Passkeys:" "${BOLD}$([ "$WEB_GUI_HOST" != "localhost" ] && echo "enabled (${WEB_GUI_HOST})" || echo "localhost only")${RESET}" printf "${CYAN}│${RESET} %-22s %s\n" "Indexer:" "${BOLD}$([ "$ENABLE_INDEXER" == "yes" ] && echo "enabled (port ${API_WEB_SERVER_PORT}) - Token Management + Trading active" || echo "disabled - Token Management + Trading hidden")${RESET}" printf "${CYAN}│${RESET} %-22s %s\n" "Bitcoin:" "${BOLD}$([ "$ENABLE_BITCOIN" == "yes" ] && echo "enabled (node + BTC wallet)" || echo "disabled")${RESET}" @@ -772,9 +1043,19 @@ fi # Bitcoin Core's -chain flag wants "main" for mainnet ("mainnet" is # rejected with CreateBaseChainParams). Other network names pass through. -BITCOIN_CORE_CHAIN="main" -if [[ -n "$BITCOIN_NETWORK" && "$BITCOIN_NETWORK" != "mainnet" ]]; then - BITCOIN_CORE_CHAIN="$BITCOIN_NETWORK" +# An empty BITCOIN_NETWORK follows the Mintlayer network - including on +# testnet installs (the old hardcoded "main" default provisioned a mainnet +# Bitcoin node alongside a testnet Mintlayer node). +if [[ -z "$BITCOIN_NETWORK" ]]; then + BITCOIN_NETWORK="$NETWORK" +fi +BITCOIN_CORE_CHAIN="$BITCOIN_NETWORK" +# Core's -chain wants "main"/"test"/"regtest"/"signet": map the Mintlayer +# names that differ ("mainnet" -> "main", "testnet" -> "test"). +if [[ "$BITCOIN_CORE_CHAIN" == "mainnet" ]]; then + BITCOIN_CORE_CHAIN="main" +elif [[ "$BITCOIN_CORE_CHAIN" == "testnet" ]]; then + BITCOIN_CORE_CHAIN="test" fi # Compose profiles matching the user's choices (mirrored into .env below so @@ -784,6 +1065,7 @@ COMPOSE_PROFILES_LINE="" [[ "$ENABLE_BITCOIN" == "yes" ]] && COMPOSE_PROFILES_LINE="${COMPOSE_PROFILES_LINE:+$COMPOSE_PROFILES_LINE,}bitcoin" [[ "$ENABLE_WATCHTOWER" == "yes" ]] && COMPOSE_PROFILES_LINE="${COMPOSE_PROFILES_LINE:+$COMPOSE_PROFILES_LINE,}watchtower" [[ "$WEB_GUI_TLS" == "true" ]] && COMPOSE_PROFILES_LINE="${COMPOSE_PROFILES_LINE:+$COMPOSE_PROFILES_LINE,}web" +[[ "$TAILSCALE_ENABLED" == "true" ]] && COMPOSE_PROFILES_LINE="${COMPOSE_PROFILES_LINE:+$COMPOSE_PROFILES_LINE,}tailscale" # Build the full wallet-rpc-daemon command (avoids shell expansion tricks in docker-compose) WALLET_RPC_CMD="wallet-rpc-daemon ${NETWORK}" @@ -792,11 +1074,28 @@ WALLET_RPC_CMD="wallet-rpc-daemon ${NETWORK}" # from the start (umask 077), and harden any pre-existing file too. if [[ -f .env ]]; then ENV_BACKUP=".env.bak.$(date +%Y%m%d-%H%M%S)" - cp .env "$ENV_BACKUP" && chmod 600 "$ENV_BACKUP" + # install -m 600: mode applied at creation (no world-readable window), and + # a failed backup aborts the run BEFORE the destructive .env rewrite below + # (a bare `cp && chmod` would swallow the failure inside the && list). + install -m 600 .env "$ENV_BACKUP" + # Keep the 3 most recent backups; each holds a complete old credential set. + # Also tighten modes of retained backups created before install -m 600. + chmod 600 .env.bak.* 2>/dev/null || true + { ls -1t .env.bak.* 2>/dev/null || true; } | tail -n +4 | while IFS= read -r old; do + rm -f "$old" + done warn "Existing .env detected - old credentials saved to $ENV_BACKUP." warn "Re-running setup REGENERATES the password, 2FA secret and RPC credentials; you will be logged out and must re-scan TOTP." fi -( umask 077 && cat > .env < "$ENV_TMP" <..ts.net +TAILSCALE_HOSTNAME=${TAILSCALE_HOSTNAME} +# tskey-auth-... joins headlessly; empty = interactive login URL printed in +# the sidecar logs on first start (docker compose logs -f tailscale) +TS_AUTHKEY=${TS_AUTHKEY} +# Optional 'tailscale up' extras, e.g. --advertise-tags=tag:nexus +# NOTE: compose expands \$VAR/\${VAR} inside .env values - escape a literal +# '\$' as '\$\$', or the sidecar environment gets interpolated/corrupted. +TS_EXTRA_ARGS=${TS_EXTRA_ARGS} + # Passkeys (WebAuthn) - derived from WEB_GUI_HOST above # Override these if running behind a reverse proxy that changes the visible hostname. PASSKEY_RP_ID=${PASSKEY_RP_ID} @@ -881,21 +1196,12 @@ COMPOSE_PROFILES=${COMPOSE_PROFILES_LINE} # 'docker compose --project-directory' - identical paths keep the compose # project name and every relative bind mount resolving to this directory on # the host (a mismatched path would build a phantom duplicate stack). -PROJECT_DIR_HOST=$(pwd) +PROJECT_DIR_HOST=${PROJECT_DIR_HOST} EOF +mv -f "$ENV_TMP" .env ) chmod 600 .env 2>/dev/null || true -# A checkout path with whitespace completes the install but breaks the -# feature-enabler's POSIX-sh compose() helper (unquoted -f args) - every -# Settings toggle would fail while the stack itself works. Fail loudly now. -case "$PROJECT_DIR_HOST" in - *[[:space:]]*) - err "The repository path contains whitespace: $PROJECT_DIR_HOST" - err "Settings-page feature toggles will not work. Move this checkout to a path without spaces and re-run init.sh." - exit 1 - ;; -esac ok ".env written" # ── Write credentials to SQLite via temporary alpine container ─────────────── @@ -907,7 +1213,12 @@ mkdir -p mintlayer-data/prefs mintlayer-data/plugins mintlayer-data/uploads # the seeding window only - the alpine container tightens it to 0700 (and # chowns the DB to this user) a few lines down; do not 'fix' this to 0770, # rootless hosts have no shared group to grant it to. -chmod 0777 mintlayer-data/prefs +# Note on the 1777 window: a local user could pre-plant mintlayer_prefs.sqlite +# for the seeding container to follow. The container writes to an unpredictable +# mktemp name instead and atomically renames over any pre-planted entry +# (rename does not follow symlinks), the EXIT/INT/TERM/HUP traps restore 0700, +# and a pre-planted target fails seeding loudly instead of writing silently. +chmod 1777 mintlayer-data/prefs # sql_json VALUE -> stdout: VALUE as a JSON string literal, safe inside a # single-quoted SQL literal. The app JSON.parse()s every pref value, so the # DB must hold '"value"' - quotes included - or login breaks on a fresh @@ -917,6 +1228,8 @@ sql_json() { printf '%s' "$1" | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g' -e "s/'/''/g" } +SEED_OK="true" +SEED_RC=0 # pref_sql KEY VALUE -> a complete INSERT statement storing VALUE as a # JSON string (quotes included) - getPref() JSON.parses every row. pref_sql() { @@ -934,11 +1247,41 @@ pref_sql() { } | docker run --rm -i \ -v "$(pwd)/mintlayer-data/prefs:/prefs" \ alpine \ - sh -c 'apk add -q --no-progress sqlite >/dev/null 2>&1 && sqlite3 /prefs/mintlayer_prefs.sqlite && chmod 600 /prefs/mintlayer_prefs.sqlite && chmod 700 /prefs' + sh -c 'apk add -q --no-progress sqlite >/dev/null 2>&1 || exit 1 + [ -e /prefs/mintlayer_prefs.sqlite ] && { echo "refusing pre-planted target" >&2; exit 3; } + db=$(mktemp /prefs/db.XXXXXX) || exit 1 + # Sweep the credential-bearing temp on any outcome: after a successful mv + # this is a no-op, on failure it removes the residue. + trap "rm -f \$db" EXIT + sqlite3 "$db" && chmod 600 "$db" && mv -f "$db" /prefs/mintlayer_prefs.sqlite || exit 1 + chmod 700 /prefs || true + exit 0' \ + || { SEED_RC=$?; SEED_OK="false"; } +if [[ "$SEED_OK" != "true" ]]; then + # Close the 1777 seeding window the host-side chmod opened earlier. + chmod 700 mintlayer-data/prefs 2>/dev/null || true + if [[ "${SEED_RC:-0}" == "3" ]]; then + err "Refusing a pre-planted mintlayer_prefs.sqlite in the prefs directory." + hint "Remove that file and re-run ./init.sh." + else + err "Credential seeding failed (this step needs network: 'apk add sqlite')." + hint ".env holds the new credentials; the prefs DB was NOT updated." + hint "Re-run ./init.sh once the network is available - it regenerates the" + hint "credentials and reseeds (you will need to re-scan the TOTP QR code)." + fi + exit 1 +fi # The seeding container runs as root; tighten ownership of the prefs DB to the # invoking user so the app (and only it) can read the TOTP secret/hash. -docker run --rm -v "$(pwd)/mintlayer-data/prefs:/prefs" alpine \ - chown -R "${ML_USER_ID}:${ML_GROUP_ID}" /prefs 2>/dev/null || true +if ! docker run --rm -v "$(pwd)/mintlayer-data/prefs:/prefs" alpine \ + chown -R "${ML_USER_ID}:${ML_GROUP_ID}" /prefs >/dev/null 2>&1; then + warn "Could not hand the credentials DB to uid ${ML_USER_ID}:${ML_GROUP_ID}." + hint "If the web GUI cannot read its credentials, run:" + hint " sudo chown -R ${ML_USER_ID}:${ML_GROUP_ID} mintlayer-data/prefs" +fi +# Seeding is done: close the 1777 window immediately instead of leaving it +# open for the rest of the script (the EXIT trap would only catch it at exit). +chmod 700 mintlayer-data/prefs 2>/dev/null || true ok "Credentials written to mintlayer-data/prefs/mintlayer_prefs.sqlite" # ── Create data directories ────────────────────────────────────────────────── @@ -979,6 +1322,9 @@ if [[ "$START" == "yes" ]]; then if [[ "$WEB_GUI_TLS" == "true" ]]; then PROFILES="$PROFILES --profile web" fi + if [[ "$TAILSCALE_ENABLED" == "true" ]]; then + PROFILES="$PROFILES --profile tailscale" + fi # Pull the CI-built multi-arch images (amd64+arm64) from ghcr.io and start. # Local rebuilds stay available: docker compose build (see README). @@ -990,6 +1336,188 @@ if [[ "$START" == "yes" ]]; then $COMPOSE $PROFILES up -d ok "Services started" + + # ── Tailscale: join the tailnet, capture the ts.net name, wire passkeys ── + # The ts.net FQDN only exists after the node joins, so the WEB_GUI_HOST / + # PASSKEY_* placeholders written to .env above get their real values here. + if [[ "$TAILSCALE_ENABLED" == "true" ]]; then + printf "${CYAN}│${RESET}\n" + hint "Waiting for the Tailscale sidecar to join your tailnet..." + + # ts_status - one line per call: " " (fqdn empty + # unless Running with MagicDNS). "Unknown" state when the sidecar is down. + ts_status() { + $COMPOSE exec -T tailscale tailscale status --json 2>/dev/null | node -e ' + let raw = ""; + process.stdin.on("data", (chunk) => { raw += chunk; }); + process.stdin.on("end", () => { + try { + const s = JSON.parse(raw); + const dns = s.BackendState === "Running" ? (s.Self?.DNSName || "").replace(/\.$/, "") : ""; + process.stdout.write((s.BackendState || "Unknown") + " " + dns); + } catch { process.stdout.write("Unknown "); } + }); + ' 2>/dev/null || true + } + + TS_STATUS=$(ts_status) + TS_STATE="${TS_STATUS%% *}" # empty input -> "" (exec failed) + + if [[ -z "$TS_AUTHKEY" && "$TS_STATE" != "Running" ]]; then + # Node still needs login: surface the approval URL. On a re-run with + # persisted state the node already joined - old URLs are dead. + # --since is Compose v2-only; docker-compose v1 (accepted by + # compose_cmd) errors on it. On v1, RECREATE the sidecar once before + # the loop instead: only a new container starts with an empty log + # buffer, so the scrape cannot resurface stale consumed URLs from + # earlier runs (restart keeps the same container and its history). + LOG_SINCE="--since $SCRIPT_START_EPOCH" + if [[ "$COMPOSE" != "docker compose" ]]; then + LOG_SINCE="" + $COMPOSE rm -sf tailscale >/dev/null 2>&1 || true + $COMPOSE up -d tailscale >/dev/null 2>&1 || true + fi + LOGIN_URL="" + # On v2, skip the scrape when the sidecar does not answer status calls: + # it is crash-looping and will never print a URL - let the wait loop + # below hit its fast sidecar-down bail-out instead of burning the full + # scrape window first. (v1 just recreated the container, so it always + # scrapes.) Probe a few times before concluding: right after up -d, + # tailscaled is often still booting and status transiently fails + # ("Unknown") even on a healthy host. + _p=0 + while [[ -z "$TS_STATE" || "$TS_STATE" == "Unknown" ]] && (( _p++ < 5 )); do + sleep 2 + TS_STATUS=$(ts_status) + TS_STATE="${TS_STATUS%% *}" + done + if [[ "$COMPOSE" != "docker compose" || -n "$TS_STATE" && "$TS_STATE" != "Unknown" ]]; then + _i=0 + # while + (( )), not `for $(seq ...)`: stock macOS has no seq, and the + # loop would silently run zero times there. + while (( _i++ < 20 )); do + LOGIN_URL=$($COMPOSE logs $LOG_SINCE tailscale 2>/dev/null | grep -o 'https://login\.tailscale\.com/a/[A-Za-z0-9]*' | tail -n 1 || true) + [[ -n "$LOGIN_URL" ]] && break + sleep 3 + done + fi + if [[ -n "$LOGIN_URL" ]]; then + printf "\n" + printf " ${BOLD}Approve this node in your Tailscale account:${RESET}\n" + printf " ${CYAN}${BOLD}${LOGIN_URL}${RESET}\n" + printf " ${DIM}(up to 5 minutes - this continues automatically once approved)${RESET}\n\n" + else + warn "No login URL in the recent sidecar logs." + hint "Run '${COMPOSE} restart tailscale' for a fresh URL, then watch" + hint "'${COMPOSE} logs -f tailscale' and approve it - this setup keeps" + hint "waiting and finishes automatically once you approve." + fi + fi + + TS_FQDN="" + RUNNING_NO_DNS=0 + TS_DOWN=0 + TS_MAX_WAIT=30 # ~90 s with a pre-set auth key + [[ -z "$TS_AUTHKEY" && "$TS_STATE" != "Running" ]] && TS_MAX_WAIT=100 # ~5 min for manual approval + # while + (( )), not `for $(seq ...)`: stock macOS has no seq. + _i=0 + while (( _i++ < TS_MAX_WAIT )); do + TS_STATUS=$(ts_status) + TS_STATE="${TS_STATUS%% *}" # empty input -> "" (exec failed) + TS_FQDN="${TS_STATUS#* }" + [[ -n "$TS_FQDN" ]] && break + if [[ "$TS_STATE" == "Running" ]]; then + TS_DOWN=0 + # Running without a DNS name may be the transient window right after + # approval (DNSName fills in shortly after Running) - require ~10 + # consecutive observations (~30 s) before concluding MagicDNS/HTTPS + # certificates are disabled. + (( RUNNING_NO_DNS++ >= 10 )) && break + elif [[ "$TS_STATE" == "NeedsLogin" ]]; then + # Sidecar is healthy and waiting for approval - keep polling. + RUNNING_NO_DNS=0 + TS_DOWN=0 + else + # Healthy-but-not-Running states (Starting, NeedsMachineAuth) still + # answer status calls - keep polling them within TS_MAX_WAIT. Only + # failed status calls ("", Unknown) mean a down/crash-looping sidecar + # (e.g. /dev/net/tun denied): bail out early instead of stalling the + # whole window on a "pending approval" that never was. + RUNNING_NO_DNS=0 + if [[ -z "$TS_STATE" || "$TS_STATE" == "Unknown" ]]; then + (( TS_DOWN++ >= 10 )) && break + else + TS_DOWN=0 + fi + fi + # Quiet progress feedback: one dim dot per poll (3 s), so a long wait + # reads as "alive" instead of hung. + printf "${GRAY}.${RESET}" + sleep 3 + done + printf "\n" + + if [[ -n "$TS_FQDN" ]]; then + ENV_OK="true" + env_set WEB_GUI_HOST "$TS_FQDN" || ENV_OK="false" + env_set PASSKEY_RP_ID "$TS_FQDN" || ENV_OK="false" + env_set PASSKEY_ORIGIN "https://$TS_FQDN" || ENV_OK="false" + if [[ "$ENV_OK" != "true" ]]; then + warn "Could not write the real hostname into .env." + hint "Set WEB_GUI_HOST=$TS_FQDN, PASSKEY_RP_ID=$TS_FQDN and" + hint "PASSKEY_ORIGIN=https://$TS_FQDN in .env, then:" + hint "docker compose up -d web-gui" + fi + WEB_GUI_HOST="$TS_FQDN" + PASSKEY_RP_ID="$TS_FQDN" + PASSKEY_ORIGIN="https://$TS_FQDN" + # Joined: with TS_AUTH_ONCE=true the key is no longer needed (state + # persists in the tailscale-state volume) - shorten the window a valid + # tailnet key sits in a credentials-bearing file. + if [[ -n "$TS_AUTHKEY" ]]; then + env_set TS_AUTHKEY "" || warn "Could not blank TS_AUTHKEY in .env - remove it manually once joined." + fi + # Recreate web-gui so the real hostname lands in the container env. + RECREATE_OUT=$($COMPOSE up -d web-gui 2>&1) || { + warn "web-gui was not recreated with the new hostname." + hint "Run: docker compose up -d web-gui - until then the GUI keeps" + hint "placeholder WEB_GUI_HOST/PASSKEY_* values." + printf '%s\n' "$RECREATE_OUT" | tail -n 5 | sed 's/^/ /' + } + ok "Joined your tailnet as https://$TS_FQDN" + else + if [[ "$TS_STATE" == "Running" ]]; then + warn "Joined, but MagicDNS returned no DNS name." + hint "Enable MagicDNS + HTTPS certificates in the Tailscale admin" + hint "console (DNS tab), then restart the sidecar" + hint "(${COMPOSE} restart tailscale) and read the name:" + hint " ${COMPOSE} exec tailscale tailscale status --json" + hint "Set WEB_GUI_HOST and PASSKEY_RP_ID in .env to that name (bare)," + hint "PASSKEY_ORIGIN to https://, then:" + hint "${COMPOSE} up -d web-gui" + elif [[ -z "$TS_STATE" || "$TS_STATE" == "Unknown" ]]; then + warn "The Tailscale sidecar is not responding to status checks." + hint "It is probably crash-looping - check: docker compose logs tailscale" + hint "On hosts that deny /dev/net/tun (unprivileged LXC, rootless" + hint "Docker) the sidecar cannot start; re-run ./init.sh to pick a" + hint "different access mode." + else + warn "The node did not join within the wait window." + if [[ -n "$TS_AUTHKEY" ]]; then + hint "The auth key may be expired or already used - create a new one" + hint "under Admin console -> Settings -> Keys, put it in TS_AUTHKEY" + hint "(.env), then run: ${COMPOSE} up -d tailscale" + else + hint "Check '${COMPOSE} logs -f tailscale' for the login URL." + hint "After approving, set in .env:" + hint " WEB_GUI_HOST=..ts.net" + hint " PASSKEY_RP_ID=..ts.net (bare DNS name - no https://)" + hint " PASSKEY_ORIGIN=https://..ts.net" + hint "then run: ${COMPOSE} up -d web-gui" + fi + fi + fi + fi fi divider @@ -1026,11 +1554,37 @@ if [[ "$WEB_GUI_TLS" == "true" ]]; then printf " ${DIM}root from Settings -> HTTPS to silence it permanently on your devices.${RESET}\n" printf " ${DIM}Passkeys are available automatically since you have a proper hostname.${RESET}\n" fi +if [[ "$TAILSCALE_ENABLED" == "true" ]]; then + printf "\n" + printf " ${DIM}Tailscale: only devices logged into your tailnet can reach the GUI -${RESET}\n" + printf " ${DIM}nothing is published to the LAN or the internet. This machine keeps${RESET}\n" + printf " ${DIM}its local access at http://localhost:${WEB_GUI_PORT} (password + TOTP only -${RESET}\n" + printf " ${DIM}passkeys are bound to the ts.net name and fail on localhost).${RESET}\n" + if [[ -n "${TS_FQDN:-}" ]]; then + printf " ${DIM}Remote: https://${TS_FQDN}${RESET}\n" + else + printf " ${DIM}Remote: join pending - once the stack is up (${COMPOSE} up -d),${RESET}\n" + printf " ${DIM}${COMPOSE} logs -f tailscale shows the login URL. After approving:${RESET}\n" + printf " ${DIM}set WEB_GUI_HOST and PASSKEY_RP_ID in .env to ..ts.net${RESET}\n" + printf " ${DIM}(bare DNS name), PASSKEY_ORIGIN to https://, then run${RESET}\n" + printf " ${DIM}${COMPOSE} up -d web-gui (passkeys stay broken until then).${RESET}\n" + fi + printf " ${DIM}Prerequisites (one-time, Tailscale admin console): MagicDNS and${RESET}\n" + printf " ${DIM}HTTPS certificates enabled. Optional hardening: tag the node${RESET}\n" + printf " ${DIM}(TS_EXTRA_ARGS=--advertise-tags=tag:nexus) and scope tailnet ACLs${RESET}\n" + printf " ${DIM}to it (dst tag:nexus:443). Sidecar logs: docker compose logs -f tailscale${RESET}\n" +fi printf "\n" # ── Open browser ────────────────────────────────────────────────────────────── if [[ "$START" == "yes" ]]; then - OPEN_URL="${PASSKEY_ORIGIN}/setup" + # Tailscale mode: the local browser reaches the loopback publish - the + # ts.net URL needs a tailnet login this machine may not have. + if [[ "$TAILSCALE_ENABLED" == "true" ]]; then + OPEN_URL="http://localhost:${WEB_GUI_PORT}/setup" + else + OPEN_URL="${PASSKEY_ORIGIN}/setup" + fi # Give the web-gui container a moment to finish starting sleep 2 @@ -1041,7 +1595,7 @@ if [[ "$START" == "yes" ]]; then elif command -v xdg-open &>/dev/null; then xdg-open "$OPEN_URL" elif command -v cmd.exe &>/dev/null; then - cmd.exe /c start "$OPEN_URL" + cmd.exe /c start "" "$OPEN_URL" else printf " ${YELLOW}▲${RESET} Could not detect a browser opener. Visit manually:\n" printf " ${CYAN}${OPEN_URL}${RESET}\n\n" diff --git a/tailscale/serve-config.json b/tailscale/serve-config.json new file mode 100644 index 0000000..647de2a --- /dev/null +++ b/tailscale/serve-config.json @@ -0,0 +1,16 @@ +{ + "TCP": { + "443": { + "HTTPS": true + } + }, + "Web": { + "${TS_CERT_DOMAIN}:443": { + "Handlers": { + "/": { + "Backend": "http://web-gui:4321" + } + } + } + } +} diff --git a/tools/test-env-set.sh b/tools/test-env-set.sh new file mode 100755 index 0000000..a9e7918 --- /dev/null +++ b/tools/test-env-set.sh @@ -0,0 +1,162 @@ +#!/usr/bin/env bash +# Smoke test for env_set() from init.sh - the credential-critical .env +# rewrite helper. Run from anywhere: ./tools/test-env-set.sh +# +# Covers: existing-key replace, missing-key append, trailing-newline +# normalization, newline-in-key/value rejection (exit non-zero, .env +# untouched), 0600 mode on rewrite, and stale temp-file handling. +# Also smoke-tests the ts_status() JSON parser extracted from init.sh. +set -euo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" + +fail() { printf 'FAIL: %s\n' "$1" >&2; exit 1; } +pass() { printf 'ok: %s\n' "$1"; } +command -v node >/dev/null || fail "node is required (same prerequisite as init.sh)" + +# ok - wrapper for expected-to-succeed env_set calls: a regression would +# otherwise abort under set -e without naming the failed case. +ok() { env_set "$@" || fail "env_set unexpectedly rejected [$*]"; } + +# Extract only the env_set function body from init.sh. Guard that the range +# actually hit the closing brace: a reformatted init.sh would otherwise make +# sed emit the remainder of the file and source installer code here. +ENV_SET_FRAG="$(sed -n '/^env_set()/,/^}/p' "$ROOT/init.sh")" || fail "env_set extraction failed (init.sh missing or unreadable)" +[[ "$(tail -n 1 <<<"$ENV_SET_FRAG")" == "}" ]] || fail "env_set extraction truncated (missing closing brace)" +# shellcheck disable=SC1091 +source <(printf '%s\n' "$ENV_SET_FRAG") +declare -f env_set >/dev/null || fail "could not extract env_set from init.sh" + +TMP="$(mktemp -d)" +trap 'rm -rf "$TMP"' EXIT +cd "$TMP" + +# mode PATH - file permissions, portable across GNU (stat -c) and BSD (stat -f). +mode() { stat -c %a "$1" 2>/dev/null || stat -f '%Lp' "$1"; } + +# 1. Existing key replaced, missing key appended, trailing newline normalized. +printf 'FOO=1\nWEB_GUI_HOST=old' > .env # no trailing newline, on purpose +chmod 644 .env +ok WEB_GUI_HOST "nexus.tailabc.ts.net" +ok APPENDED_KEY "v" +grep -Fqx 'WEB_GUI_HOST=nexus.tailabc.ts.net' .env || fail "existing key not replaced" +grep -Fqx 'APPENDED_KEY=v' .env || fail "missing key not appended" +# Prefix-similar keys must survive: matching is startsWith(key + "="). +printf 'WEB_GUI_HOST=old\nWEB_GUI_HOST_EX=keep\n' > .env +ok WEB_GUI_HOST "nexus.tailabc.ts.net" +[[ "$(grep -Fcx 'WEB_GUI_HOST=nexus.tailabc.ts.net' .env)" == "1" ]] || fail "prefix-similar key present: target not replaced in place" +grep -Fqx 'WEB_GUI_HOST_EX=keep' .env || fail "prefix-similar key was rewritten" +# Duplicate keys in a hand-edited .env: env_set rewrites every matching line +# (no dedup), so both 'DUP=' lines become 'DUP=3'. Pin that behavior. +printf 'DUP=1\nOTHER=x\nDUP=2\n' > .env +ok DUP "3" +[[ "$(grep -cx 'DUP=3' .env)" == "2" ]] || fail "duplicate-key rewrite behavior changed" +# Indented / `export KEY=` lines must be rewritten in place (env_set trims +# and strips the export prefix); a regression appends a duplicate instead. +printf ' export WEB_GUI_HOST=old\n' > .env +ok WEB_GUI_HOST "nexus.tailabc.ts.net" +grep -Fqx 'WEB_GUI_HOST=nexus.tailabc.ts.net' .env || fail "indented/export key not replaced" +[[ "$(grep -cx 'WEB_GUI_HOST=nexus.tailabc.ts.net' .env)" == "1" ]] || fail "indented/export key duplicated" +[[ -z "$(tail -c 1 .env)" ]] || fail "trailing newline missing" +pass "replace + append + trailing newline" + +# 2. Newline in key or value rejected; .env untouched. +cp .env before.env +out=$(env_set "EVIL +KEY" "x" 2>&1) && fail "newline in key accepted" +grep -q 'must not contain newlines' <<<"$out" || fail "newline in key rejected for an unrelated reason: $out" +out=$(env_set K2 "x +y" 2>&1) && fail "newline in value accepted" +grep -q 'must not contain newlines' <<<"$out" || fail "newline in value rejected for an unrelated reason: $out" +# Byte-exact (cmp, not $(cat) comparison): command substitution strips trailing +# newlines, which would hide a regression in the trailing-newline normalization. +cmp -s before.env .env || fail ".env modified by a rejected call" +pass "newline rejection" + +# 3. .env ends up 0600 even when it started looser. +chmod 644 .env +ok WEB_GUI_HOST "nexus2.tailabc.ts.net" +[[ "$(mode .env)" == "600" ]] || fail "permissions not tightened to 0600" +pass "0600 mode" + +# 3b. Special characters plausible in real credentials / production call +# sites (PASSKEY_ORIGIN carries '/:', compose expands $VAR in .env values). +# $ is rejected (compose would expand it in .env values) - explicit case: +out=$(env_set SPECIAL '$VAR' 2>&1) && fail "value with $ accepted" +grep -qF 'must not contain $' <<<"$out" || fail "value with $ rejected for an unrelated reason: $out" +for v in 'https://a.b.ts.net' 'a=b' 'p@ss"w'\''ord' ''; do + ok SPECIAL "$v" + [[ "$(grep -Fcx "SPECIAL=$v" .env)" == "1" ]] || fail "special value corrupted or duplicated: [$v]" +done +# Rejected CR calls must leave .env byte-identical and no temp residue: +# snapshot BEFORE (a later rewrite would destroy the evidence). +cp .env before-cr.env +out=$(env_set $'CR\rVAL' "x" 2>&1) && fail "CR in key accepted" +grep -q 'must not contain newlines' <<<"$out" || fail "CR in key rejected for an unrelated reason: $out" +out=$(env_set K3 $'x\ry' 2>&1) && fail "CR in value accepted" +grep -q 'must not contain newlines' <<<"$out" || fail "CR in value rejected for an unrelated reason: $out" +cmp -s before-cr.env .env || fail ".env modified by a rejected CR call" +ls .env.tmp.* >/dev/null 2>&1 && fail "rejected CR call left temp residue" +# CRLF line endings in .env are normalized to LF (even untouched lines) - pin it. +printf 'A=1\r\nB=2\r\n' > .env +ok A "1" +printf 'A=1\nB=2\n' | cmp -s - .env || fail "CRLF in .env not normalized to LF" +rm -f .env +out=$(env_set LOST "v" 2>&1) && fail "missing .env accepted silently" +grep -q 'env_set:' <<<"$out" || fail "missing .env failed for an unrelated reason: $out" +[[ ! -e .env ]] || fail "missing .env created by env_set" +pass "special values + CR rejection + missing .env" + +# 4. A stale temp file from another process is never read into .env +# (env_set only ever rewrites its own pid-suffixed temp file). +printf 'FOO=1\n' > .env # 3b removed .env; 4 needs a fresh one +chmod 644 .env +printf 'JUNK=stale\n' > ".env.tmp.999999" +chmod 644 ".env.tmp.999999" +ok FOO "2" +grep -Fqx 'FOO=2' .env || fail "env_set did not write" +grep -q 'JUNK' .env && fail "stale temp content leaked into .env" +grep -Fqx 'JUNK=stale' ".env.tmp.999999" || fail "env_set modified another process's temp file" +rm -f ".env.tmp.999999" +pass "stale temp isolation" + +echo "all env_set tests passed" + +# ── ts_status parser (extracted from init.sh, tested standalone) ───────────── +# Pull the node program out of the ts_status() helper and run sample +# `tailscale status --json` payloads through it. +TS_PROG="$(awk '/^ ts_status\(\) \{/{f=1} f && /node -e /{p=1; next} p && /^ . 2>\/dev\/null \|\| true$/{found=1; exit} p{print} END{exit found?0:1}' "$ROOT/init.sh")" || fail "ts_status extraction truncated (no end marker)" +# here-string, not a pipe: grep -q + pipefail would SIGPIPE a long TS_PROG. +grep -q 'BackendState' <<<"$TS_PROG" || fail "could not extract ts_status parser from init.sh" + +# Keep node's stderr visible: a truncated extraction surfaces as a SyntaxError, +# not as a silent empty-output failure (set -e would kill the script undiagnosed). +run_ts() { printf '%s' "$1" | node -e "$TS_PROG" || fail "ts_status node failed for payload [$1]"; } + +out=$(run_ts '{"BackendState":"Running","Self":{"DNSName":"nexus.x.ts.net."}}') +[[ "$out" == "Running nexus.x.ts.net" ]] || fail "ts_status: trailing dot not stripped (got: $out)" + +out=$(run_ts '{"BackendState":"Running","Self":{}}') +[[ "$out" == "Running " ]] || fail "ts_status: Running without DNS (got: $out)" + +out=$(run_ts '{"BackendState":"NeedsLogin"}') +[[ "$out" == "NeedsLogin " ]] || fail "ts_status: NeedsLogin state lost (got: $out)" + +out=$(run_ts 'garbage') +[[ "$out" == "Unknown " ]] || fail "ts_status: malformed JSON not handled (got: $out)" + +out=$(run_ts '{"BackendState":"Running","Self":{"DNSName":""}}') +[[ "$out" == "Running " ]] || fail "ts_status: empty DNSName mishandled (got: $out)" + +out=$(run_ts '{"BackendState":"NeedsLogin","Self":{"DNSName":"x.ts.net."}}') +[[ "$out" == "NeedsLogin " ]] || fail "ts_status: non-Running DNS leaked (got: $out)" + +out=$(run_ts '') +[[ "$out" == "Unknown " ]] || fail "ts_status: empty stdin not handled (got: $out)" + +out=$(run_ts '{"Self":{}}') +[[ "$out" == "Unknown " ]] || fail "ts_status: missing BackendState not defaulted (got: $out)" + +pass "ts_status parser (8 payloads)" + +echo "all ts_status tests passed"