From 14f0fed131829e69c6e8099b31c0c2994ed56abf Mon Sep 17 00:00:00 2001 From: Hakuna <35168804+TrezorHannes@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:38:10 +0100 Subject: [PATCH 1/4] feat(installer): add unified ./install.sh CLI manager for all 19 scripts - Add thin root bootstrapper ./install.sh (non-root guard, Python 3.11-3.13 detection) and pure-stdlib lpt_installer package. - Registry covers all 19 scripts with risk tiers, host profiles (node/vps), supported execution modes, config requirements, and legacy unit metadata. - Supports uv fast-path + stdlib venv fallback, OS CA trust bundle bindings (SSL_CERT_FILE/REQUESTS_CA_BUNDLE) across all systemd units and cron blocks, systemd sandboxing (ProtectSystem=full / strict for HTTP-only pocketmoney), TimeoutStartSec=300, and flock-guarded cron blocks. - Adds fail-closed unmanaged duplicate detection, .lpt-backups/ snapshots, legacy unit migration, guided chmod 600 config copy + placeholder validation, clean uninstall preserving configs by default, MIT/self-verify disclaimer, and subtle hodlmetight.org footer. - Remove legacy LNBits/install_pocketmoney_service.sh and Other/install_fee_adjuster_service.sh; update tests/test_ca_trust_hardening.py, add tests/test_lpt_installer.py (87.90% coverage on lpt_installer), and add systemd-analyze verify + 85% coverage gates in CI. --- .agents/agents.md | 4 +- .github/workflows/tests.yml | 65 ++- LNBits/install_pocketmoney_service.sh | 119 ---- Other/fee_adjuster.md | 5 +- Other/install_fee_adjuster_service.sh | 94 ---- README.md | 14 +- install.sh | 32 ++ lpt_installer/__init__.py | 31 ++ lpt_installer/__main__.py | 10 + lpt_installer/adapters.py | 170 ++++++ lpt_installer/cli.py | 481 ++++++++++++++++ lpt_installer/configs.py | 222 ++++++++ lpt_installer/env.py | 252 +++++++++ lpt_installer/registry.py | 450 +++++++++++++++ lpt_installer/scheduler.py | 754 ++++++++++++++++++++++++++ lpt_installer/state.py | 54 ++ pyproject.toml | 2 +- tests/test_ca_trust_hardening.py | 54 +- tests/test_lpt_installer.py | 657 ++++++++++++++++++++++ 19 files changed, 3222 insertions(+), 248 deletions(-) delete mode 100644 LNBits/install_pocketmoney_service.sh delete mode 100644 Other/install_fee_adjuster_service.sh create mode 100755 install.sh create mode 100644 lpt_installer/__init__.py create mode 100644 lpt_installer/__main__.py create mode 100644 lpt_installer/adapters.py create mode 100644 lpt_installer/cli.py create mode 100644 lpt_installer/configs.py create mode 100644 lpt_installer/env.py create mode 100644 lpt_installer/registry.py create mode 100644 lpt_installer/scheduler.py create mode 100644 lpt_installer/state.py create mode 100644 tests/test_lpt_installer.py diff --git a/.agents/agents.md b/.agents/agents.md index a2abb8a..ead7185 100644 --- a/.agents/agents.md +++ b/.agents/agents.md @@ -65,7 +65,7 @@ This document serves as an architectural, operational, and development guide for | File | Type | Description | | :--- | :--- | :--- | -| `fee_adjuster.py` | Systemd Timer / Cronjob | **Dynamic Liquidity Fee Controller**: Adjusts outbound and inbound channel fees using Amboss Space statistics, 5-band liquidity curves, and stuck-channel decay, with `charge-lnd` export and inbound discount protection. Documented in `Other/fee_adjuster.md`; systemd installer in `Other/install_fee_adjuster_service.sh`. | +| `fee_adjuster.py` | Systemd Timer / Cronjob | **Dynamic Liquidity Fee Controller**: Adjusts outbound and inbound channel fees using Amboss Space statistics, 5-band liquidity curves, and stuck-channel decay, with `charge-lnd` export and inbound discount protection. Documented in `Other/fee_adjuster.md`; managed via `./install.sh` (`lpt_installer`). | | `rebalance_guard.py` | Cronjob / CLI | **Standalone Rebalance Guard**: Audits all open LNDg channels across native Auto-Fees and `fee_adjuster.py`. Locks `ar_out_target = 100%` when an inbound discount is active and restores baseline targets (`data/rebalance_targets_baseline.json`) via dynamic hysteresis once liquidity recovers. | | `swap_out-loop.py` | CLI Tool | **Economically Optimized Loop Out**: Ranks channels by net effective PPM, runs live fake-hash prepay route probes (with 2-hop direct Loop fallback), supports multi-channel MPP selection (`litloop` / `loopd`), interactive TTY multi-select, and native `loop_sqlite.db` history/CSV accounting. Documented in `Other/swap_out-loop.md`. | | `boltz_swap-out.py` | CLI Tool | Executes reverse submarine swaps (Lightning to Liquid L-BTC) via `boltzd` / `boltzcli` using LNDg candidate channels, multi-batch payment retries, and `--debug` dry-run mode. | @@ -78,7 +78,7 @@ This document serves as an architectural, operational, and development guide for | File | Type | Description | | :--- | :--- | :--- | -| `pocketmoney.py` | Systemd Timer / Daemon | Distributes scheduled fiat-denominated satoshi allowances from a parent LNbits wallet to child wallets defined in `wallets.json` (`--run-once` supported). Systemd timer installer in `LNBits/install_pocketmoney_service.sh`. | +| `pocketmoney.py` | Systemd Timer / Daemon | Distributes scheduled fiat-denominated satoshi allowances from a parent LNbits wallet to child wallets defined in `wallets.json` (`--run-once` supported). Managed via `./install.sh` (`lpt_installer`). | --- diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 4d743b2..44f205f 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -45,11 +45,12 @@ jobs: shell: bash run: | set -o pipefail - pytest tests/ -v --cov=LNDg --cov=Magma --cov=Other --cov=Peerswap --cov=LNBits --cov-report=term --cov-fail-under=35 | tee pytest_cov.txt + pytest tests/ -v --cov=LNDg --cov=Magma --cov=Other --cov=Peerswap --cov=LNBits --cov=lpt_installer --cov-report=term --cov-fail-under=35 | tee pytest_cov.txt + pytest tests/test_lpt_installer.py tests/test_ca_trust_hardening.py --cov=lpt_installer --cov-report=term --cov-fail-under=85 { echo "### Pytest Coverage (Python ${{ matrix.python-version }})" echo '```text' - tail -n 30 pytest_cov.txt + tail -n 35 pytest_cov.txt echo '```' } >> "$GITHUB_STEP_SUMMARY" @@ -74,13 +75,65 @@ jobs: - name: Install ruff run: pip install -r requirements-dev.txt - - name: Run ruff check on modern/updated tests - run: ruff check tests/test_p0_runtime_safety.py tests/test_ca_trust_hardening.py tests/test_repo_hygiene.py + - name: Run ruff check on installer and updated tests + run: ruff check lpt_installer tests/test_lpt_installer.py tests/test_p0_runtime_safety.py tests/test_ca_trust_hardening.py tests/test_repo_hygiene.py - name: Validate shell scripts run: | - bash -n LNBits/install_pocketmoney_service.sh Other/install_fee_adjuster_service.sh - shellcheck -S error LNBits/install_pocketmoney_service.sh Other/install_fee_adjuster_service.sh + bash -n install.sh + shellcheck -S warning install.sh + + - name: Verify rendered systemd units with systemd-analyze + shell: bash + run: | + UNIT_DIR="$RUNNER_TEMP/lpt-units" + mkdir -p "$UNIT_DIR" + python3 - "$UNIT_DIR" <<'PY' + import grp, os, sys + from pathlib import Path + from lpt_installer.registry import get_tool + from lpt_installer.scheduler import render_systemd_service, render_systemd_timer + + out_dir = Path(sys.argv[1]) + repo = Path.cwd() + user = os.environ["USER"] + group = grp.getgrgid(os.getgid()).gr_name + py_bin = Path(sys.executable) + + for tid, cal in (("pocketmoney", "Fri *-*-* 09:00:00"), ("fee-adjuster", "*:0/20:00")): + tool = get_tool(tid) + (out_dir / f"lpt-{tid}.service").write_text( + render_systemd_service( + tool, + repo, + user=user, + group=group, + mode="systemd-timer", + python_bin=py_bin, + unit_exists=lambda _: False, + ), + encoding="utf-8", + ) + (out_dir / f"lpt-{tid}.timer").write_text( + render_systemd_timer(tool, cal), + encoding="utf-8", + ) + + magma = get_tool("magma-sale") + (out_dir / "lpt-magma-sale.service").write_text( + render_systemd_service( + magma, + repo, + user=user, + group=group, + mode="systemd-service", + python_bin=py_bin, + unit_exists=lambda _: False, + ), + encoding="utf-8", + ) + PY + SYSTEMD_UNIT_PATH="$UNIT_DIR:/etc/systemd/system" systemd-analyze verify --man=no "$UNIT_DIR"/*.service "$UNIT_DIR"/*.timer security: runs-on: ubuntu-latest diff --git a/LNBits/install_pocketmoney_service.sh b/LNBits/install_pocketmoney_service.sh deleted file mode 100644 index 118a0b4..0000000 --- a/LNBits/install_pocketmoney_service.sh +++ /dev/null @@ -1,119 +0,0 @@ -#!/bin/bash - -# --- Documentation --- -# Script Name: install_pocketmoney_service.sh -# Description: Installs a systemd timer and service for the pocketmoney.py script. -# Author: @TrezorHannes -# Date: 2025-01-11 -# -# Requirements: -# - sudo privileges -# - Python 3 virtual environment (../.venv) -# - pocketmoney.py script -# - config.ini in the parent directory -# -# Usage: -# 1. Make the script executable: chmod +x install_pocketmoney_service.sh -# 2. Run the script with sudo: sudo ./install_pocketmoney_service.sh -# --- End Documentation --- - -# --- Script --- - -# Check for sudo privileges -if [[ $EUID -ne 0 ]]; then - echo "Error: This script must be run with sudo. Please run 'sudo $0'" 1>&2 - exit 1 -fi - -# Get the absolute path of the script's directory -SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) - -# Define paths -VENV_PYTHON="$SCRIPT_DIR/../.venv/bin/python3" -POCKETMONEY_SCRIPT="$SCRIPT_DIR/pocketmoney.py" -SYSTEMD_DIR="/etc/systemd/system" -SERVICE_NAME="pocketmoney.service" -TIMER_NAME="pocketmoney.timer" -SERVICE_FILE="$SYSTEMD_DIR/$SERVICE_NAME" -TIMER_FILE="$SYSTEMD_DIR/$TIMER_NAME" -CONFIG_FILE="$SCRIPT_DIR/../config.ini" - -# Check if the virtual environment Python executable exists -if [[ ! -f "$VENV_PYTHON" ]]; then - echo "Error: Python virtual environment not found at $VENV_PYTHON. Please refer to the GH repo documentation to create it and try again." 1>&2 - exit 1 -fi - -# Check if the pocketmoney.py script exists -if [[ ! -f "$POCKETMONEY_SCRIPT" ]]; then - echo "Error: pocketmoney.py script not found at $POCKETMONEY_SCRIPT. Please make sure it exists." 1>&2 - exit 1 -fi - -# Check if config.ini exists -if [[ ! -f "$CONFIG_FILE" ]]; then - echo "Error: config.ini not found at $CONFIG_FILE." 1>&2 - exit 1 -fi - -# Extract scheduling variables using awk (handles basic ini formatting) -RECURRENCE=$(awk -F '=' '/^recurrence/ {print $2}' "$CONFIG_FILE" | tr -d ' ' | head -n 1) -TIME=$(awk -F '=' '/^time/ {print $2}' "$CONFIG_FILE" | tr -d ' ' | head -n 1) -DAY_OF_WEEK=$(awk -F '=' '/^day_of_week/ {print $2}' "$CONFIG_FILE" | tr -d ' ' | head -n 1) - -# Format OnCalendar string based on recurrence -if [ "$RECURRENCE" = "daily" ]; then - ON_CALENDAR="*-*-* $TIME:00" -elif [ "$RECURRENCE" = "weekly" ]; then - # Capitalize first letter of day for systemd - DAY_CAP=$(echo "$DAY_OF_WEEK" | awk '{print toupper(substr($0,1,1))tolower(substr($0,2))}') - ON_CALENDAR="$DAY_CAP *-*-* $TIME:00" -else - echo "Error: Invalid recurrence '$RECURRENCE' in config.ini. Must be 'daily' or 'weekly'." - exit 1 -fi - -echo "Configuring timer for: $ON_CALENDAR" - -# Create the systemd service file (Type=oneshot for timer-triggered scripts) -cat > "$SERVICE_FILE" << EOF -[Unit] -Description=Pocket Money Service -After=network.target - -[Service] -Type=oneshot -User=$SUDO_USER -WorkingDirectory=$SCRIPT_DIR -Environment="SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt" -Environment="REQUESTS_CA_BUNDLE=/etc/ssl/certs/ca-certificates.crt" -ExecStart=$VENV_PYTHON $POCKETMONEY_SCRIPT --run-once -EOF - -# Create the systemd timer file -cat > "$TIMER_FILE" << EOF -[Unit] -Description=Timer for Pocket Money Service - -[Timer] -OnCalendar=$ON_CALENDAR -Persistent=true - -[Install] -WantedBy=timers.target -EOF - -# Stop and disable the old service if it was running as a daemon -systemctl stop "$SERVICE_NAME" 2>/dev/null -systemctl disable "$SERVICE_NAME" 2>/dev/null - -# Reload systemd to recognize the new units -systemctl daemon-reload - -# Enable and start the timer -systemctl enable "$TIMER_NAME" -systemctl start "$TIMER_NAME" - -echo "Successfully installed and started the pocketmoney timer." - -# --- End Script --- diff --git a/Other/fee_adjuster.md b/Other/fee_adjuster.md index b438dc4..9bae528 100644 --- a/Other/fee_adjuster.md +++ b/Other/fee_adjuster.md @@ -65,10 +65,9 @@ config_file = file:///home/admin/.chargelnd/.config/fee_adjuster.txt ## Installation (systemd Timer or Crontab) -Use the included installer script to set up `fee_adjuster.service` and an hourly `fee_adjuster.timer`: +Use the unified installer (`./install.sh`) to configure `lpt-fee-adjuster.service` + `lpt-fee-adjuster.timer` (or a managed cron entry): ```bash -chmod +x Other/install_fee_adjuster_service.sh -sudo ./Other/install_fee_adjuster_service.sh +./install.sh install fee-adjuster --scheduler systemd ``` Or schedule via `crontab -e`: diff --git a/Other/install_fee_adjuster_service.sh b/Other/install_fee_adjuster_service.sh deleted file mode 100644 index 029e62d..0000000 --- a/Other/install_fee_adjuster_service.sh +++ /dev/null @@ -1,94 +0,0 @@ -#!/bin/bash - -# --- Documentation --- -# Script Name: install_fee_adjuster_service.sh -# Description: Installs a systemd service for the fee_adjuster.py script. -# Author: @TrezorHannes -# Date: 2025-01-19 -# -# Requirements: -# - sudo privileges -# - Python 3 virtual environment (../.venv) -# - fee_adjuster.py script -# - copy of feeConfig.json.example to feeConfig.json located in parent directory -# -# Usage: -# 1. Make the script executable: chmod +x install_fee_adjuster_service.sh -# 2. Run the script with sudo: sudo ./install_fee_adjuster_service.sh -# --- End Documentation --- - -# --- Script --- - -# Check for sudo privileges -if [[ $EUID -ne 0 ]]; then - echo "Error: This script must be run with sudo. Please run 'sudo $0'" 1>&2 - exit 1 -fi - -# Get the absolute path of the script's directory -SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) - -# Define paths -VENV_PYTHON="$SCRIPT_DIR/../.venv/bin/python3" -FEE_ADJUSTER_SCRIPT="$SCRIPT_DIR/fee_adjuster.py" -SYSTEMD_DIR="/etc/systemd/system" -SERVICE_NAME="fee_adjuster.service" -TIMER_NAME="fee_adjuster.timer" -SERVICE_FILE="$SYSTEMD_DIR/$SERVICE_NAME" -TIMER_FILE="$SYSTEMD_DIR/$TIMER_NAME" - -# Check if the virtual environment Python executable exists -if [[ ! -f "$VENV_PYTHON" ]]; then - echo "Error: Python virtual environment not found at $VENV_PYTHON. Please refer to the GH repo documentation to create it and try again." 1>&2 - exit 1 -fi - -# Check if the fee_adjuster.py script exists -if [[ ! -f "$FEE_ADJUSTER_SCRIPT" ]]; then - echo "Error: fee_adjuster.py script not found at $FEE_ADJUSTER_SCRIPT. Please make sure it exists." 1>&2 - exit 1 -fi - -# Create the systemd service file -cat > "$SERVICE_FILE" << EOF -[Unit] -Description=Fee Adjuster Service -After=network.target - -[Service] -Type=oneshot -User=$SUDO_USER -WorkingDirectory=$SCRIPT_DIR -Environment="SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt" -Environment="REQUESTS_CA_BUNDLE=/etc/ssl/certs/ca-certificates.crt" -ExecStart=$VENV_PYTHON $FEE_ADJUSTER_SCRIPT -RemainAfterExit=no - -[Install] -WantedBy=multi-user.target -EOF - -# Create the systemd timer file -cat > "$TIMER_FILE" << EOF -[Unit] -Description=Run Fee Adjuster Service Hourly - -[Timer] -OnCalendar=*:00:00 -Unit=$SERVICE_NAME -AccuracySec=1min - -[Install] -WantedBy=timers.target -EOF - -# Reload systemd to recognize the new service -systemctl daemon-reload - -# Enable and start the timer -systemctl enable "$TIMER_NAME" -systemctl start "$TIMER_NAME" - -echo "Successfully installed and started the fee_adjuster service and timer." - -# --- End Script --- \ No newline at end of file diff --git a/README.md b/README.md index 9117184..5f55abd 100644 --- a/README.md +++ b/README.md @@ -157,17 +157,15 @@ chmod 600 config.ini Magma/magma_config.ini feeConfig.json wallets.json ## Running as Background Services -### Automated Systemd Service Installers -Helper scripts are included to generate and enable `systemd` oneshot services and timers (pre-configured with OS CA trust bundle environment variables): +### Unified Service & Scheduler Installer +Use the interactive CLI manager (`./install.sh`) to set up `.venv`, copy/harden configs (`chmod 600`), and generate `systemd` services/timers or `cron` jobs (pre-configured with OS CA trust bundle environment variables): ```bash -# Install hourly fee_adjuster.service + fee_adjuster.timer -chmod +x Other/install_fee_adjuster_service.sh -sudo ./Other/install_fee_adjuster_service.sh +chmod +x install.sh +./install.sh -# Install scheduled pocketmoney.service + pocketmoney.timer (reads [Schedule] from config.ini) -chmod +x LNBits/install_pocketmoney_service.sh -sudo ./LNBits/install_pocketmoney_service.sh +# Or install non-interactively via CLI: +./install.sh install fee-adjuster pocketmoney --scheduler systemd --accept-disclaimer ``` ### Systemd Daemon Example diff --git a/install.sh b/install.sh new file mode 100755 index 0000000..cf39738 --- /dev/null +++ b/install.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +set -euo pipefail + +if [ "${EUID:-$(id -u)}" -eq 0 ]; then + echo "Error: Do not run ./install.sh as root or via sudo." >&2 + echo "Run as your regular node operator user (e.g. admin)." >&2 + echo "The installer elevates via sudo only when writing system-wide systemd units." >&2 + exit 1 +fi + +SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" + +PYTHON_BIN="" +for candidate in python3 python3.13 python3.12 python3.11; do + if command -v "$candidate" >/dev/null 2>&1; then + if "$candidate" -c 'import sys; sys.exit(0 if (3, 11) <= sys.version_info < (3, 14) else 1)' 2>/dev/null; then + PYTHON_BIN="$candidate" + break + fi + fi +done + +if [ -z "$PYTHON_BIN" ]; then + echo "Error: Python 3.11, 3.12, or 3.13 is required to run Lightning-Python-Tools." >&2 + echo "On Debian/Ubuntu, install it with: sudo apt-get update && sudo apt-get install -y python3 python3-venv" >&2 + exit 1 +fi + +export LPT_REPO_ROOT="$SCRIPT_DIR" +export PYTHONPATH="$SCRIPT_DIR${PYTHONPATH:+:$PYTHONPATH}" + +exec "$PYTHON_BIN" -m lpt_installer "$@" diff --git a/lpt_installer/__init__.py b/lpt_installer/__init__.py new file mode 100644 index 0000000..7e701c3 --- /dev/null +++ b/lpt_installer/__init__.py @@ -0,0 +1,31 @@ +"""Unified installer and manager for Lightning-Python-Tools (pure Python stdlib).""" + +from __future__ import annotations + +VERSION = "1.0.0" +DISCLAIMER_VERSION = "2026-11" +DONATION_URL = "https://hodlmetight.org" + +DISCLAIMER_TEXT = ( + "WARNING / OPERATOR DISCLAIMER\n" + "1. Self-Verify Before Running: Several scripts move mainnet Bitcoin/Lightning funds\n" + " or modify live channel fee policies. Verify configs, run --dry-run / --debug\n" + " previews, and inspect the source code before enabling automation.\n" + "2. No Warranty / No Liability: This software is provided 'AS IS' under the MIT\n" + " License without warranty of any kind. The open-source developer accepts no\n" + " liability for lost funds, routing losses, or misconfigured nodes.\n" + "3. Stay Updated: Watch the GitHub repository (Releases & Security Advisories) and\n" + " review SECURITY.md regularly for vulnerability patches (main is supported)." +) + +DONATION_FOOTER = ( + f"Enjoying Lightning-Python-Tools? Support open-source development: {DONATION_URL}" +) + +__all__ = [ + "VERSION", + "DISCLAIMER_VERSION", + "DONATION_URL", + "DISCLAIMER_TEXT", + "DONATION_FOOTER", +] diff --git a/lpt_installer/__main__.py b/lpt_installer/__main__.py new file mode 100644 index 0000000..4ea3611 --- /dev/null +++ b/lpt_installer/__main__.py @@ -0,0 +1,10 @@ +"""Entrypoint for `python3 -m lpt_installer`.""" + +from __future__ import annotations + +import sys + +from lpt_installer.cli import main + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/lpt_installer/adapters.py b/lpt_installer/adapters.py new file mode 100644 index 0000000..70334f4 --- /dev/null +++ b/lpt_installer/adapters.py @@ -0,0 +1,170 @@ +"""Injectable OS/subprocess/systemd/cron adapters for lpt_installer.""" + +from __future__ import annotations + +import grp +import os +import pwd +import shutil +import subprocess +import tempfile +from dataclasses import dataclass +from pathlib import Path + + +@dataclass(frozen=True) +class CommandResult: + """Result of an external command invocation.""" + + returncode: int + stdout: str + stderr: str + + +class SystemEnv: + """Concrete OS adapter wrapping subprocess, filesystem, systemd, and cron.""" + + CA_BUNDLE_CANDIDATES: tuple[str, ...] = ( + "/etc/ssl/certs/ca-certificates.crt", + "/etc/pki/tls/certs/ca-bundle.crt", + "/etc/ssl/cert.pem", + ) + + def __init__( + self, + *, + systemd_dir: Path | None = None, + user_systemd_dir: Path | None = None, + ) -> None: + self.systemd_dir = systemd_dir or Path("/etc/systemd/system") + self.user_systemd_dir = user_systemd_dir or ( + Path.home() / ".config" / "systemd" / "user" + ) + + def run( + self, + argv: list[str], + *, + input_text: str | None = None, + check: bool = False, + env_vars: dict[str, str] | None = None, + interactive: bool = False, + ) -> CommandResult: + merged_env = os.environ.copy() + if env_vars: + merged_env.update(env_vars) + if interactive: + proc = subprocess.run(argv, env=merged_env, check=False) + result = CommandResult(proc.returncode, "", "") + else: + proc = subprocess.run( + argv, + input=input_text, + capture_output=True, + text=True, + env=merged_env, + check=False, + ) + result = CommandResult(proc.returncode, proc.stdout, proc.stderr) + if check and result.returncode != 0: + raise RuntimeError( + f"Command {' '.join(argv)} failed (exit {result.returncode}): {result.stderr.strip()}" + ) + return result + + def which(self, binary: str) -> str | None: + return shutil.which(binary) + + def current_uid(self) -> int: + return os.geteuid() + + def current_user_group(self) -> tuple[str, str]: + uid = os.getuid() + pw = pwd.getpwuid(uid) + gr = grp.getgrgid(pw.pw_gid) + return pw.pw_name, gr.gr_name + + def home_dir(self) -> Path: + return Path.home() + + def env_var(self, name: str, default: str = "") -> str: + return os.environ.get(name, default) + + def detect_ca_bundle(self) -> str | None: + for candidate in self.CA_BUNDLE_CANDIDATES: + path = Path(candidate) + if path.is_file(): + return candidate + return None + + def systemd_unit_exists(self, unit_name: str) -> bool: + return (self.systemd_dir / unit_name).exists() + + def list_systemd_units(self, pattern: str = "*.service") -> list[Path]: + if not self.systemd_dir.is_dir(): + return [] + return sorted(self.systemd_dir.glob(pattern)) + + def list_user_systemd_units(self, pattern: str = "*.service") -> list[Path]: + if not self.user_systemd_dir.is_dir(): + return [] + return sorted(self.user_systemd_dir.glob(pattern)) + + def sudo_install_file( + self, content: str, dest: Path, mode: str = "0644" + ) -> CommandResult: + with tempfile.NamedTemporaryFile( + "w", encoding="utf-8", delete=False, prefix="lpt_unit_" + ) as tmp: + tmp.write(content) + tmp_path = Path(tmp.name) + try: + return self.run( + [ + "sudo", + "install", + "-m", + mode, + "-o", + "root", + "-g", + "root", + str(tmp_path), + str(dest), + ], + check=True, + ) + finally: + tmp_path.unlink(missing_ok=True) + + def sudo_remove_file(self, dest: Path) -> CommandResult: + return self.run(["sudo", "rm", "-f", str(dest)], check=True) + + def systemctl( + self, *args: str, use_sudo: bool = True, check: bool = True + ) -> CommandResult: + cmd = ["sudo", "systemctl", *args] if use_sudo else ["systemctl", *args] + return self.run(cmd, check=check) + + def read_crontab(self) -> str: + res = self.run(["crontab", "-l"], check=False) + if res.returncode != 0: + # No crontab installed yet for current user + return "" + return res.stdout + + def write_crontab(self, content: str) -> CommandResult: + if not content.strip(): + # Keep user crontab empty cleanly without failing if none existed + res = self.run(["crontab", "-r"], check=False) + if res.returncode == 0 or "no crontab" in res.stderr.lower(): + return CommandResult(0, "", "") + return self.run(["crontab", "-"], input_text="", check=True) + normalized = content if content.endswith("\n") else f"{content}\n" + return self.run(["crontab", "-"], input_text=normalized, check=True) + + def running_processes(self) -> list[str]: + res = self.run(["ps", "-eo", "pid=,args="], check=False) + if res.returncode != 0: + return [] + return [line.strip() for line in res.stdout.splitlines() if line.strip()] diff --git a/lpt_installer/cli.py b/lpt_installer/cli.py new file mode 100644 index 0000000..5cefe8b --- /dev/null +++ b/lpt_installer/cli.py @@ -0,0 +1,481 @@ +"""Interactive CLI menu and non-interactive subcommands for lpt_installer.""" + +from __future__ import annotations + +import argparse +import json +import os +from collections.abc import Callable +from pathlib import Path + +from lpt_installer import ( + DISCLAIMER_TEXT, + DISCLAIMER_VERSION, + DONATION_FOOTER, + VERSION, +) +from lpt_installer.adapters import SystemEnv +from lpt_installer.configs import ( + CONFIG_TEMPLATES, + ensure_configs, + open_in_editor, + validate_configs, +) +from lpt_installer.env import run_doctor, setup_venv +from lpt_installer.registry import ( + TOOLS, + ToolSpec, + filter_tools, + get_tool, + render_overview_table, +) +from lpt_installer.scheduler import collect_statuses, install_tool, uninstall_tools +from lpt_installer.state import load_state, save_state + +InputFn = Callable[[str], str] +OutputFn = Callable[[str], None] + + +def resolve_repo_root(cli_root: str | None = None) -> Path: + if cli_root: + return Path(cli_root).resolve() + env_root = os.environ.get("LPT_REPO_ROOT") + if env_root: + return Path(env_root).resolve() + return Path(__file__).resolve().parent.parent + + +def ensure_disclaimer_accepted( + repo_root: Path, + *, + accept_flag: bool, + interactive: bool, + input_fn: InputFn = input, + output_fn: OutputFn = print, +) -> bool: + """Require one-time disclaimer acknowledgment persisted in .lpt-state.json.""" + state = load_state(repo_root) + if state.get("disclaimer_version") == DISCLAIMER_VERSION: + return True + + output_fn("") + output_fn(DISCLAIMER_TEXT) + output_fn("") + + if accept_flag: + state["disclaimer_version"] = DISCLAIMER_VERSION + save_state(repo_root, state) + return True + + if not interactive: + output_fn( + "Error: Non-interactive install requires --accept-disclaimer to acknowledge the warning above." + ) + return False + + answer = input_fn("Type 'yes' or press Enter after reviewing to accept (q to abort): ").strip().lower() + if answer in ("q", "quit", "no", "n"): + output_fn("Aborted by user.") + return False + if answer not in ("", "y", "yes"): + output_fn("Aborted: disclaimer not accepted.") + return False + + state["disclaimer_version"] = DISCLAIMER_VERSION + save_state(repo_root, state) + return True + + +def build_parser() -> argparse.ArgumentParser: + shared = argparse.ArgumentParser(add_help=False) + shared.add_argument("--repo-root", default=argparse.SUPPRESS, help="Override repository root path.") + shared.add_argument("--json", action="store_true", default=argparse.SUPPRESS, help="Emit JSON output.") + + parser = argparse.ArgumentParser( + prog="install.sh", + description="Unified installer & operations manager for Lightning-Python-Tools.", + ) + parser.add_argument("--version", action="version", version=f"%(prog)s {VERSION}") + parser.add_argument("--repo-root", default=None, help="Override repository root path.") + parser.add_argument( + "--profile", + choices=("all", "node", "vps"), + default="all", + help="Filter scripts by host profile (node, vps, or all).", + ) + parser.add_argument("--json", action="store_true", default=False, help="Emit JSON output.") + + sub = parser.add_subparsers(dest="command") + + sub.add_parser("list", parents=[shared], help="Show overview table of all 19 scripts and statuses.") + sub.add_parser("status", parents=[shared], help="Show installation status of all scripts.") + + env_p = sub.add_parser("env", parents=[shared], help="Create or update the repo .venv environment.") + env_p.add_argument("--db", action="store_true", help="Install optional PostgreSQL/pandas extras.") + env_p.add_argument("--recreate", action="store_true", help="Recreate .venv from scratch.") + env_p.add_argument("--dry-run", action="store_true", help="Preview commands without running.") + + cfg_p = sub.add_parser( + "config", + parents=[shared], + help="Copy missing *.example configs, harden 0600 perms, and validate.", + ) + cfg_p.add_argument("--tools", nargs="*", help="Limit config check/copy to specific tool IDs.") + cfg_p.add_argument("--edit", metavar="FILE", help="Open config file in $EDITOR after copying.") + cfg_p.add_argument("--dry-run", action="store_true", help="Preview without modifying files.") + + inst_p = sub.add_parser("install", parents=[shared], help="Install and schedule one or more scripts.") + inst_p.add_argument("tools", nargs="+", help="Tool IDs to install (see 'list').") + inst_p.add_argument( + "--scheduler", + choices=("auto", "systemd", "cron", "manual"), + default="auto", + help="Scheduler backend (default: auto chooses each tool's default).", + ) + inst_p.add_argument("--skip-env", action="store_true", help="Skip .venv creation/update.") + inst_p.add_argument("--skip-config-check", action="store_true", help="Skip config placeholder check.") + inst_p.add_argument("--accept-disclaimer", action="store_true", help="Acknowledge operator disclaimer.") + inst_p.add_argument("--dry-run", action="store_true", help="Render and preview without applying.") + + uninst_p = sub.add_parser("uninstall", parents=[shared], help="Remove managed systemd units / cron entries.") + uninst_p.add_argument("tools", nargs="*", help="Tool IDs to uninstall.") + uninst_p.add_argument("--all", action="store_true", help="Uninstall all managed tools.") + uninst_p.add_argument("--remove-venv", action="store_true", help="Also delete .venv directory.") + uninst_p.add_argument( + "--purge-configs", + action="store_true", + help="Delete user config files (requires --yes; preserved by default).", + ) + uninst_p.add_argument("--yes", action="store_true", help="Confirm destructive flags.") + uninst_p.add_argument("--dry-run", action="store_true", help="Preview without modifying system.") + + sub.add_parser("doctor", parents=[shared], help="Run environment, CA trust, permission, and conflict diagnostics.") + return parser + + +def _resolve_mode(tool: ToolSpec, scheduler: str) -> str: + if scheduler == "auto": + return tool.default_mode + if scheduler == "manual": + if "manual" in tool.supported_modes: + return "manual" + raise ValueError(f"Tool {tool.id!r} cannot run in 'manual' mode.") + if scheduler == "cron": + if "cron" in tool.supported_modes: + return "cron" + raise ValueError( + f"Tool {tool.id!r} does not support cron (supported: {', '.join(tool.supported_modes)})." + ) + if scheduler == "systemd": + for candidate in ("systemd-timer", "systemd-service"): + if candidate in tool.supported_modes: + return candidate + raise ValueError( + f"Tool {tool.id!r} does not support systemd (supported: {', '.join(tool.supported_modes)})." + ) + raise ValueError(f"Unknown scheduler option: {scheduler!r}") + + +def run_interactive_menu( + repo_root: Path, + env: SystemEnv, + *, + profile: str = "all", + input_fn: InputFn = input, + output_fn: OutputFn = print, +) -> int: + """Interactive numbered CLI menu for operators.""" + if not ensure_disclaimer_accepted( + repo_root, + accept_flag=False, + interactive=True, + input_fn=input_fn, + output_fn=output_fn, + ): + return 1 + + while True: + tools = filter_tools(profile) + statuses = collect_statuses(repo_root, env) + output_fn("") + output_fn(f"=== Lightning-Python-Tools Manager v{VERSION} (profile: {profile}) ===") + output_fn(render_overview_table(tools, statuses)) + output_fn("") + output_fn("Actions:") + output_fn(" 1) Setup / update Python .venv") + output_fn(" 2) Copy & validate config files (chmod 600)") + output_fn(" 3) Install / schedule tools (systemd or cron)") + output_fn(" 4) Uninstall managed tools (preserves configs)") + output_fn(" 5) Run diagnostics (doctor)") + output_fn(" 6) Switch host profile (all / node / vps)") + output_fn(" q) Quit") + + choice = input_fn("Select action: ").strip().lower() + if choice in ("q", "quit", "exit"): + output_fn("") + output_fn(DONATION_FOOTER) + return 0 + if choice == "1": + db_ans = input_fn("Include PostgreSQL/pandas extras for offline_summary? [y/N]: ").strip().lower() + extras = ("db",) if db_ans in ("y", "yes") else () + res = setup_venv(repo_root, env, extras=extras) + output_fn(f"Environment ready via {res['backend']} at {res['venv_dir']}") + elif choice == "2": + summary = ensure_configs(repo_root) + output_fn( + f"Configs copied: {summary['copied'] or 'none'} | preserved: {summary['preserved'] or 'none'}" + ) + edit_ans = input_fn( + "Edit a config file now? Enter path (e.g. config.ini) or press Enter to skip: " + ).strip() + if edit_ans: + if edit_ans in CONFIG_TEMPLATES: + open_in_editor(repo_root / edit_ans, env) + else: + output_fn(f"Unknown config file: {edit_ans}") + errors = validate_configs(repo_root, tools) + if errors: + output_fn("Config warnings:") + for err in errors: + output_fn(f" - {err}") + else: + output_fn("Config validation passed.") + elif choice == "3": + raw_sel = input_fn( + "Enter tool numbers or IDs (comma-separated, e.g. 1,4 or fee-adjuster): " + ).strip() + if not raw_sel: + continue + selected: list[ToolSpec] = [] + try: + for token in [t.strip() for t in raw_sel.split(",") if t.strip()]: + if token.isdigit(): + idx = int(token) + if not (1 <= idx <= len(tools)): + raise ValueError(f"Index out of range: {idx}") + selected.append(tools[idx - 1]) + else: + selected.append(get_tool(token)) + except (KeyError, ValueError) as exc: + output_fn(f"Selection error: {exc}") + continue + + if any(t.risk_tier == "FUNDS" for t in selected): + output_fn( + "[FUNDS WARNING] Selected funds-moving tool(s). Double-check config.ini and run dry-run previews!" + ) + sched_choice = ( + input_fn("Scheduler [auto / systemd / cron / manual] (default: auto): ") + .strip() + .lower() + or "auto" + ) + cfg_res = ensure_configs(repo_root, selected) + if cfg_res["copied"]: + output_fn(f"Copied templates: {', '.join(cfg_res['copied'])} (mode 0600)") + cfg_errors = validate_configs(repo_root, selected) + if cfg_errors: + output_fn("Please resolve configuration errors before enabling automation:") + for err in cfg_errors: + output_fn(f" - {err}") + continue + setup_venv( + repo_root, + env, + extras=tuple(sorted({e for t in selected for e in t.optional_extras})), + ) + for tool in selected: + try: + mode = _resolve_mode(tool, sched_choice) + res = install_tool(tool, repo_root, env, mode=mode) + output_fn(f"Installed {res['tool']} ({res['mode']})") + except Exception as exc: + output_fn(f"Failed installing {tool.id}: {exc}") + elif choice == "4": + raw_ids = input_fn( + "Enter tool IDs to uninstall (comma-separated, or 'all'): " + ).strip() + if not raw_ids: + continue + target_ids = ( + [t.id for t in TOOLS] + if raw_ids.lower() == "all" + else [t.strip() for t in raw_ids.split(",") if t.strip()] + ) + try: + res = uninstall_tools(target_ids, repo_root, env) + output_fn( + f"Removed units={res['removed_units']} cron={res['removed_cron']} (configs preserved)." + ) + except Exception as exc: + output_fn(f"Uninstall failed: {exc}") + elif choice == "5": + for check in run_doctor(repo_root, env): + output_fn(f"[{check['status'].upper()}] {check['name']}: {check['detail']}") + elif choice == "6": + new_prof = input_fn("Profile [all / node / vps]: ").strip().lower() + if new_prof in ("all", "node", "vps"): + profile = new_prof + else: + output_fn(f"Invalid profile: {new_prof}") + else: + output_fn(f"Unknown option: {choice!r}") + + +def main( + argv: list[str] | None = None, + *, + env: SystemEnv | None = None, + input_fn: InputFn = input, + output_fn: OutputFn = print, +) -> int: + parser = build_parser() + args = parser.parse_args(argv) + sys_env = env or SystemEnv() + repo_root = resolve_repo_root(args.repo_root) + + if args.command is None: + return run_interactive_menu( + repo_root, + sys_env, + profile=args.profile, + input_fn=input_fn, + output_fn=output_fn, + ) + + if args.command in ("list", "status"): + tools = filter_tools(args.profile) + statuses = collect_statuses(repo_root, sys_env) + if args.json: + payload = [ + { + "id": t.id, + "script_path": t.script_path, + "risk_tier": t.risk_tier, + "default_mode": t.default_mode, + "supported_modes": list(t.supported_modes), + "host_profiles": list(t.host_profiles), + "status": statuses[t.id], + } + for t in tools + ] + output_fn(json.dumps(payload, indent=2)) + else: + output_fn(render_overview_table(tools, statuses)) + return 0 + + if args.command == "doctor": + checks = run_doctor(repo_root, sys_env) + if args.json: + output_fn(json.dumps(checks, indent=2)) + else: + for item in checks: + output_fn(f"[{item['status'].upper()}] {item['name']}: {item['detail']}") + has_fail = any(item["status"] == "fail" for item in checks) + return 1 if has_fail else 0 + + if args.command == "env": + extras = ("db",) if args.db else () + res = setup_venv( + repo_root, + sys_env, + extras=extras, + dry_run=args.dry_run, + recreate=args.recreate, + ) + if args.json: + output_fn(json.dumps(res, indent=2)) + else: + output_fn(f"Environment ready via {res['backend']} ({res['python']})") + output_fn(DONATION_FOOTER) + return 0 + + if args.command == "config": + selected = [get_tool(tid) for tid in args.tools] if args.tools else list(TOOLS) + summary = ensure_configs(repo_root, selected, dry_run=args.dry_run) + if args.edit and not args.dry_run: + if args.edit not in CONFIG_TEMPLATES: + output_fn(f"Unknown config file: {args.edit}") + return 1 + open_in_editor(repo_root / args.edit, sys_env) + errors = [] if args.dry_run else validate_configs(repo_root, selected) + if args.json: + output_fn(json.dumps({"summary": summary, "errors": errors}, indent=2)) + else: + output_fn( + f"Configs copied: {summary['copied']} | preserved: {summary['preserved']} | hardened: {summary['hardened']}" + ) + for err in errors: + output_fn(f"[ERROR] {err}") + return 1 if errors else 0 + + if args.command == "install": + selected = [get_tool(tid) for tid in args.tools] + if not args.dry_run and not ensure_disclaimer_accepted( + repo_root, + accept_flag=args.accept_disclaimer, + interactive=False, + input_fn=input_fn, + output_fn=output_fn, + ): + return 1 + + if any(t.risk_tier == "FUNDS" for t in selected) and not args.json: + output_fn( + "[FUNDS WARNING] Installing funds-moving tool(s). Verify config.ini and run dry-run previews!" + ) + + if not args.dry_run: + ensure_configs(repo_root, selected) + if not args.skip_config_check: + cfg_errors = validate_configs(repo_root, selected) + if cfg_errors: + for err in cfg_errors: + output_fn(f"[CONFIG ERROR] {err}") + return 1 + if not args.skip_env: + extras = tuple(sorted({e for t in selected for e in t.optional_extras})) + setup_venv(repo_root, sys_env, extras=extras) + + results = [] + for tool in selected: + mode = _resolve_mode(tool, args.scheduler) + results.append( + install_tool(tool, repo_root, sys_env, mode=mode, dry_run=args.dry_run) + ) + + if args.json: + output_fn(json.dumps(results, indent=2)) + else: + for item in results: + output_fn(f"Installed {item['tool']} ({item['mode']})") + output_fn(DONATION_FOOTER) + return 0 + + if args.command == "uninstall": + if args.purge_configs and not args.yes: + output_fn("Error: --purge-configs requires --yes to confirm deleting user configs.") + return 1 + target_ids = [t.id for t in TOOLS] if args.all else list(args.tools) + if not target_ids: + output_fn("Error: specify tool IDs or --all.") + return 1 + res = uninstall_tools( + target_ids, + repo_root, + sys_env, + remove_venv=args.remove_venv, + purge_configs=args.purge_configs, + dry_run=args.dry_run, + ) + if args.json: + output_fn(json.dumps(res, indent=2)) + else: + output_fn( + f"Uninstalled units={res['removed_units']} cron={res['removed_cron']} " + f"(configs preserved: {res['configs_preserved']})" + ) + output_fn(DONATION_FOOTER) + return 0 + + return 1 diff --git a/lpt_installer/configs.py b/lpt_installer/configs.py new file mode 100644 index 0000000..52a7fcd --- /dev/null +++ b/lpt_installer/configs.py @@ -0,0 +1,222 @@ +"""Configuration template copying, permission hardening, and validation.""" + +from __future__ import annotations + +import configparser +import json +import os +import shlex +import shutil +from datetime import datetime +from pathlib import Path + +from lpt_installer.adapters import SystemEnv +from lpt_installer.registry import ToolSpec + +CONFIG_TEMPLATES: dict[str, str] = { + "config.ini": "config.ini.example", + "Magma/magma_config.ini": "Magma/magma_config.ini.example", + "feeConfig.json": "feeConfig.json.example", + "wallets.json": "wallets.json.example", +} + +PLACEHOLDER_VALUES: dict[tuple[str, str], set[str]] = { + ("LNBits", "base_url"): {"https://yourdomain.com", "yourdomain.com"}, + ("LNBits", "admin_key"): {"admin_key_1"}, + ("lnd", "rpcserver"): {"your_lnd_host:port"}, + ("lnd", "tlscertpath"): {"/path/to/your/lnd/tls.cert"}, + ("lnd", "macaroonpath"): {"/path/to/your/lnd/admin.macaroon"}, +} + +VALID_DAYS_OF_WEEK = { + "monday", + "tuesday", + "wednesday", + "thursday", + "friday", + "saturday", + "sunday", +} + + +def required_configs_for_tools(tools: list[ToolSpec]) -> list[str]: + """Return deduplicated config paths required by the selected tools.""" + ordered: list[str] = [] + for tool in tools: + for cfg in tool.config_templates: + if cfg not in ordered: + ordered.append(cfg) + return ordered + + +def ensure_configs( + repo_root: Path, + tools: list[ToolSpec] | None = None, + *, + dry_run: bool = False, +) -> dict[str, list[str]]: + """Copy missing configs from *.example (never clobber) and enforce 0600/0700 perms.""" + targets = ( + required_configs_for_tools(tools) + if tools is not None + else list(CONFIG_TEMPLATES.keys()) + ) + copied: list[str] = [] + preserved: list[str] = [] + hardened: list[str] = [] + + for rel_path in targets: + example_rel = CONFIG_TEMPLATES[rel_path] + src = repo_root / example_rel + dst = repo_root / rel_path + if not src.is_file(): + raise FileNotFoundError(f"Missing template file: {src}") + + if dst.exists(): + preserved.append(rel_path) + if not dry_run: + os.chmod(dst, 0o600) + hardened.append(rel_path) + else: + copied.append(rel_path) + if not dry_run: + dst.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(src, dst) + os.chmod(dst, 0o600) + hardened.append(rel_path) + + for dir_name in ("logs", "data"): + dir_path = repo_root / dir_name + if not dry_run: + dir_path.mkdir(parents=True, exist_ok=True) + os.chmod(dir_path, 0o700) + + return {"copied": copied, "preserved": preserved, "hardened": hardened} + + +def validate_configs(repo_root: Path, tools: list[ToolSpec]) -> list[str]: + """Validate required config files, INI keys, schedules, and JSON syntax.""" + errors: list[str] = [] + needed = required_configs_for_tools(tools) + + for rel_path in needed: + if not (repo_root / rel_path).is_file(): + errors.append( + f"Missing {rel_path} (copy from {CONFIG_TEMPLATES[rel_path]} first)." + ) + + cfg = configparser.ConfigParser() + config_ini = repo_root / "config.ini" + if "config.ini" in needed and config_ini.is_file(): + try: + cfg.read(config_ini, encoding="utf-8") + except configparser.Error as exc: + errors.append(f"Invalid INI syntax in config.ini: {exc}") + cfg = None + + if cfg is not None: + checked: set[tuple[str, str]] = set() + for tool in tools: + for section, key in tool.required_ini_keys: + if (section, key) in checked: + continue + checked.add((section, key)) + if not cfg.has_section(section): + errors.append(f"config.ini missing section [{section}] (for {tool.id}).") + continue + raw_val = cfg.get(section, key, fallback="").strip() + if not raw_val: + errors.append( + f"config.ini [{section}] {key} is empty (required by {tool.id})." + ) + continue + placeholders = PLACEHOLDER_VALUES.get((section, key), set()) + if raw_val in placeholders: + errors.append( + f"config.ini [{section}] {key} still uses placeholder {raw_val!r}." + ) + + if any(tool.id == "pocketmoney" for tool in tools): + errors.extend(_validate_pocketmoney_schedule(cfg)) + + if "Magma/magma_config.ini" in needed: + magma_ini = repo_root / "Magma" / "magma_config.ini" + if magma_ini.is_file(): + magma_cfg = configparser.ConfigParser() + try: + magma_cfg.read(magma_ini, encoding="utf-8") + except configparser.Error as exc: + errors.append(f"Invalid INI syntax in Magma/magma_config.ini: {exc}") + + if "feeConfig.json" in needed: + fee_json = repo_root / "feeConfig.json" + if fee_json.is_file(): + try: + data = json.loads(fee_json.read_text(encoding="utf-8")) + if not isinstance(data, dict) or "nodes" not in data: + errors.append("feeConfig.json must be a JSON object containing 'nodes'.") + except (OSError, json.JSONDecodeError) as exc: + errors.append(f"Invalid JSON in feeConfig.json: {exc}") + + if "wallets.json" in needed: + wallets_json = repo_root / "wallets.json" + if wallets_json.is_file(): + try: + data = json.loads(wallets_json.read_text(encoding="utf-8")) + if not isinstance(data, dict) or not data: + errors.append("wallets.json must be a non-empty JSON object of child wallets.") + else: + for name, info in data.items(): + if not isinstance(info, dict): + errors.append(f"wallets.json entry {name!r} must be an object.") + continue + if info.get("wallet_id", "").startswith("WALLETID"): + errors.append( + f"wallets.json entry {name!r} still uses placeholder wallet_id." + ) + if info.get("invoice_key", "").startswith("INVOICEKEY"): + errors.append( + f"wallets.json entry {name!r} still uses placeholder invoice_key." + ) + except (OSError, json.JSONDecodeError) as exc: + errors.append(f"Invalid JSON in wallets.json: {exc}") + + return errors + + +def _validate_pocketmoney_schedule(cfg: configparser.ConfigParser) -> list[str]: + errors: list[str] = [] + recurrence = cfg.get("Schedule", "recurrence", fallback="weekly").split("#")[0].strip().lower() + if recurrence not in ("daily", "weekly"): + errors.append( + f"config.ini [Schedule] recurrence={recurrence!r} must be 'daily' or 'weekly'." + ) + time_str = cfg.get("Schedule", "time", fallback="09:00").split("#")[0].strip() + try: + datetime.strptime(time_str, "%H:%M") + except ValueError: + errors.append(f"config.ini [Schedule] time={time_str!r} must use HH:MM format.") + if recurrence == "weekly": + day = cfg.get("Schedule", "day_of_week", fallback="friday").split("#")[0].strip().lower() + if day not in VALID_DAYS_OF_WEEK: + errors.append( + f"config.ini [Schedule] day_of_week={day!r} must be a valid weekday name." + ) + return errors + + +def open_in_editor(config_path: Path, env: SystemEnv) -> bool: + """Launch user's preferred editor ($VISUAL/$EDITOR/nano/vi) on a config file.""" + for candidate in ( + env.env_var("VISUAL"), + env.env_var("EDITOR"), + "nano", + "vi", + ): + if not candidate: + continue + parts = shlex.split(candidate) + if parts and env.which(parts[0]): + res = env.run([*parts, str(config_path)], check=False, interactive=True) + return res.returncode == 0 + return False diff --git a/lpt_installer/env.py b/lpt_installer/env.py new file mode 100644 index 0000000..4e68b1e --- /dev/null +++ b/lpt_installer/env.py @@ -0,0 +1,252 @@ +"""Python virtual environment setup and operator diagnostics (doctor).""" + +from __future__ import annotations + +import sys +from pathlib import Path + +from lpt_installer.adapters import SystemEnv +from lpt_installer.configs import CONFIG_TEMPLATES +from lpt_installer.registry import TOOLS + +MIN_CERTIFI_VERSION = (2026, 10, 19) + + +def _parse_version(raw: str) -> tuple[int, ...]: + parts: list[int] = [] + for piece in raw.strip().split("."): + digits = "".join(ch for ch in piece if ch.isdigit()) + if not digits: + break + parts.append(int(digits)) + return tuple(parts) + + +def venv_python_path(repo_root: Path) -> Path: + return repo_root / ".venv" / "bin" / "python3" + + +def setup_venv( + repo_root: Path, + env: SystemEnv, + *, + extras: tuple[str, ...] = (), + dry_run: bool = False, + recreate: bool = False, +) -> dict[str, object]: + """Create/update repo .venv using uv fast-path or stdlib venv + pip.""" + if env.current_uid() == 0: + raise PermissionError("Refusing to create or modify .venv as root.") + + req_file = repo_root / "requirements.txt" + if not req_file.is_file(): + raise FileNotFoundError(f"Missing requirements.txt at {req_file}") + + venv_dir = repo_root / ".venv" + venv_py = venv_python_path(repo_root) + uv_bin = env.which("uv") + backend = "uv" if uv_bin else "venv" + commands: list[list[str]] = [] + + if recreate or not venv_py.exists(): + if uv_bin: + cmd = [uv_bin, "venv", str(venv_dir), "--python", sys.executable] + if recreate: + cmd.append("--clear") + commands.append(cmd) + else: + cmd = [sys.executable, "-m", "venv"] + if recreate: + cmd.append("--clear") + cmd.append(str(venv_dir)) + commands.append(cmd) + + if uv_bin: + commands.append( + [uv_bin, "pip", "install", "--python", str(venv_py), "-r", str(req_file)] + ) + if "db" in extras: + commands.append( + [ + uv_bin, + "pip", + "install", + "--python", + str(venv_py), + "psycopg2-binary", + "pandas", + ] + ) + else: + commands.append([str(venv_py), "-m", "pip", "install", "--upgrade", "pip"]) + commands.append([str(venv_py), "-m", "pip", "install", "-r", str(req_file)]) + if "db" in extras: + commands.append( + [str(venv_py), "-m", "pip", "install", "psycopg2-binary", "pandas"] + ) + + if not dry_run: + for cmd in commands: + env.run(cmd, check=True) + + return { + "backend": backend, + "venv_dir": str(venv_dir), + "python": str(venv_py), + "extras": list(extras), + "commands": [" ".join(c) for c in commands], + } + + +def run_doctor(repo_root: Path, env: SystemEnv) -> list[dict[str, str]]: + """Run non-destructive environment, TLS/CA trust, permission, and conflict checks.""" + checks: list[dict[str, str]] = [] + + # 1. Host Python check + ver = sys.version_info[:3] + ver_str = f"{ver[0]}.{ver[1]}.{ver[2]}" + if (3, 11) <= sys.version_info < (3, 14): + checks.append({"name": "python", "status": "ok", "detail": f"Python {ver_str}"}) + else: + checks.append( + { + "name": "python", + "status": "fail", + "detail": f"Python {ver_str} outside supported 3.11-3.13 range", + } + ) + + # 2. .venv & certifi check + venv_py = venv_python_path(repo_root) + if venv_py.exists(): + res = env.run( + [str(venv_py), "-c", "import certifi; print(certifi.__version__)"], + check=False, + ) + if res.returncode == 0: + certifi_ver = res.stdout.strip() + if _parse_version(certifi_ver) >= MIN_CERTIFI_VERSION: + checks.append( + { + "name": "venv-certifi", + "status": "ok", + "detail": f".venv active (certifi {certifi_ver})", + } + ) + else: + checks.append( + { + "name": "venv-certifi", + "status": "warn", + "detail": f"certifi {certifi_ver} < 2026.10.19; run env setup to upgrade", + } + ) + else: + checks.append( + { + "name": "venv-certifi", + "status": "warn", + "detail": ".venv exists but certifi could not be imported", + } + ) + else: + checks.append( + { + "name": "venv-certifi", + "status": "warn", + "detail": ".venv not created yet (run './install.sh env')", + } + ) + + # 3. OS CA trust bundle check + ca_bundle = env.detect_ca_bundle() + if ca_bundle: + checks.append( + {"name": "ca-bundle", "status": "ok", "detail": f"OS CA bundle: {ca_bundle}"} + ) + else: + checks.append( + { + "name": "ca-bundle", + "status": "fail", + "detail": "No OS CA bundle found in standard /etc/ssl or /etc/pki paths", + } + ) + + # 4. Config file permissions check (0600) + for rel_path in CONFIG_TEMPLATES: + cfg_path = repo_root / rel_path + if not cfg_path.exists(): + continue + mode = cfg_path.stat().st_mode & 0o777 + if mode & 0o077: + checks.append( + { + "name": f"perms:{rel_path}", + "status": "warn", + "detail": f"{rel_path} mode {oct(mode)} is group/world readable; run 'config --harden'", + } + ) + else: + checks.append( + { + "name": f"perms:{rel_path}", + "status": "ok", + "detail": f"{rel_path} permissions {oct(mode)}", + } + ) + + # 5. Root-owned files inside logs/ or data/ + if env.current_uid() != 0: + root_owned: list[str] = [] + for sub in ("logs", "data"): + sub_dir = repo_root / sub + if not sub_dir.is_dir(): + continue + for item in sorted(sub_dir.iterdir()): + try: + if item.stat().st_uid == 0: + root_owned.append(str(item.relative_to(repo_root))) + except OSError: + continue + if root_owned: + checks.append( + { + "name": "ownership", + "status": "warn", + "detail": ( + "Root-owned runtime files found (" + + ", ".join(root_owned) + + "); fix with sudo chown before switching services from root" + ), + } + ) + else: + checks.append( + { + "name": "ownership", + "status": "ok", + "detail": "No root-owned files in logs/ or data/", + } + ) + + # 6. Legacy unit hints + legacy_found: list[str] = [] + for tool in TOOLS: + for unit in tool.legacy_units: + if env.systemd_unit_exists(unit): + legacy_found.append(unit) + if legacy_found: + checks.append( + { + "name": "legacy-units", + "status": "warn", + "detail": ( + "Legacy systemd units detected (" + + ", ".join(sorted(set(legacy_found))) + + "); installing via ./install.sh will back up and migrate them" + ), + } + ) + + return checks diff --git a/lpt_installer/registry.py b/lpt_installer/registry.py new file mode 100644 index 0000000..07d6edc --- /dev/null +++ b/lpt_installer/registry.py @@ -0,0 +1,450 @@ +"""Single-source-of-truth registry for all 19 Lightning-Python-Tools scripts.""" + +from __future__ import annotations + +from dataclasses import dataclass + + +@dataclass(frozen=True) +class ToolSpec: + """Metadata describing an installable/manageable Lightning-Python-Tools script.""" + + id: str + script_path: str + category: str + summary: str + risk_tier: str # "FUNDS", "FEES/POLICY", "READ-ONLY" + host_profiles: tuple[str, ...] # subset of ("node", "vps") + supported_modes: tuple[str, ...] # ("systemd-service", "systemd-timer", "cron", "manual") + default_mode: str + unattended_args: tuple[str, ...] = () + default_on_calendar: str | None = None + default_cron: str | None = None + persistent_timer: bool = False + sandbox_level: str = "full" # "strict" (HTTP-only) or "full" + after_units: tuple[str, ...] = () + wants_units: tuple[str, ...] = () + config_templates: tuple[str, ...] = () + required_ini_keys: tuple[tuple[str, str], ...] = () + optional_extras: tuple[str, ...] = () + dry_run_args: tuple[str, ...] | None = None + legacy_units: tuple[str, ...] = () + + @property + def is_schedulable(self) -> bool: + return any( + mode in ("systemd-service", "systemd-timer", "cron") + for mode in self.supported_modes + ) + + +TOOLS: tuple[ToolSpec, ...] = ( + ToolSpec( + id="pocketmoney", + script_path="LNBits/pocketmoney.py", + category="LNBits", + summary="Scheduled fiat-to-sat child allowances via LNbits + Telegram alerts", + risk_tier="FUNDS", + host_profiles=("node", "vps"), + supported_modes=("systemd-timer", "cron", "systemd-service"), + default_mode="systemd-timer", + unattended_args=("--run-once",), + default_on_calendar="dynamic", + default_cron="dynamic", + persistent_timer=True, + sandbox_level="strict", + config_templates=("config.ini", "wallets.json"), + required_ini_keys=( + ("LNBits", "base_url"), + ("LNBits", "admin_key"), + ("telegram", "lnbits_bot_token"), + ("telegram", "telegram_user_id"), + ), + legacy_units=("pocketmoney.service", "pocketmoney.timer"), + ), + ToolSpec( + id="magma-sale", + script_path="Magma/magma_sale_process.py", + category="Magma", + summary="Auto-pilot daemon for Amboss Magma channel sale orders", + risk_tier="FUNDS", + host_profiles=("node",), + supported_modes=("systemd-service",), + default_mode="systemd-service", + after_units=("lnd.service",), + config_templates=("config.ini",), + required_ini_keys=( + ("credentials", "amboss_authorization"), + ("telegram", "magma_bot_token"), + ("telegram", "telegram_user_id"), + ("paths", "lncli_path"), + ), + legacy_units=("magma-sale.service", "magma-autosale-bot.service"), + ), + ToolSpec( + id="magma-market-fee", + script_path="Magma/magma_market_fee.py", + category="Magma", + summary="Analyzes Magma offers and updates seller offer pricing/status", + risk_tier="FEES/POLICY", + host_profiles=("node",), + supported_modes=("systemd-timer", "cron", "manual"), + default_mode="systemd-timer", + unattended_args=("--force",), + default_on_calendar="daily", + default_cron="0 6 * * *", + dry_run_args=("--dry-run",), + config_templates=("config.ini", "Magma/magma_config.ini"), + required_ini_keys=( + ("credentials", "amboss_authorization"), + ("paths", "lncli_path"), + ), + ), + ToolSpec( + id="fee-adjuster", + script_path="Other/fee_adjuster.py", + category="Other", + summary="Dynamic 5-band + stuck-channel + inbound-discount fee optimizer", + risk_tier="FEES/POLICY", + host_profiles=("node", "vps"), + supported_modes=("systemd-timer", "cron", "manual"), + default_mode="systemd-timer", + default_on_calendar="*:0/20:00", + default_cron="*/20 * * * *", + persistent_timer=True, + dry_run_args=("--debug",), + config_templates=("config.ini", "feeConfig.json"), + required_ini_keys=( + ("credentials", "amboss_authorization"), + ("credentials", "lndg_username"), + ("credentials", "lndg_password"), + ("lndg", "lndg_api_url"), + ), + legacy_units=("fee_adjuster.service", "fee_adjuster.timer"), + ), + ToolSpec( + id="rebalance-guard", + script_path="Other/rebalance_guard.py", + category="Other", + summary="Locks ar_out_target=100% on discounted channels with hysteresis", + risk_tier="FEES/POLICY", + host_profiles=("node", "vps"), + supported_modes=("systemd-timer", "cron", "manual"), + default_mode="systemd-timer", + default_on_calendar="*:05/20:00", + default_cron="5,25,45 * * * *", + dry_run_args=("--dry-run",), + config_templates=("config.ini", "feeConfig.json"), + required_ini_keys=( + ("credentials", "lndg_username"), + ("credentials", "lndg_password"), + ("lndg", "lndg_api_url"), + ), + ), + ToolSpec( + id="amboss-pull", + script_path="LNDg/amboss_pull.py", + category="LNDg", + summary="Syncs Magma leases to LNDg notes/auto-fees and charge-lnd caps", + risk_tier="FEES/POLICY", + host_profiles=("node", "vps"), + supported_modes=("systemd-timer", "cron", "manual"), + default_mode="systemd-timer", + default_on_calendar="hourly", + default_cron="0 * * * *", + persistent_timer=True, + config_templates=("config.ini",), + required_ini_keys=( + ("credentials", "amboss_authorization"), + ("credentials", "lndg_username"), + ("credentials", "lndg_password"), + ("lndg", "lndg_api_url"), + ), + ), + ToolSpec( + id="channel-base-fee", + script_path="LNDg/channel_base-fee.py", + category="LNDg", + summary="Resets base_fee to 0 on open active LNDg channels", + risk_tier="FEES/POLICY", + host_profiles=("node", "vps"), + supported_modes=("systemd-timer", "cron", "manual"), + default_mode="systemd-timer", + default_on_calendar="*:59:00", + default_cron="59 * * * *", + config_templates=("config.ini",), + required_ini_keys=( + ("credentials", "lndg_username"), + ("credentials", "lndg_password"), + ("lndg", "lndg_api_url"), + ), + ), + ToolSpec( + id="channel-fee-pull", + script_path="LNDg/channel_fee-pull.py", + category="LNDg", + summary="Exports 0 ppm open channel IDs to ~/.chargelnd/.config/0_fee.txt", + risk_tier="FEES/POLICY", + host_profiles=("node",), + supported_modes=("systemd-timer", "cron", "manual"), + default_mode="systemd-timer", + default_on_calendar="*:58:00", + default_cron="58 * * * *", + config_templates=("config.ini",), + required_ini_keys=( + ("credentials", "lndg_username"), + ("credentials", "lndg_password"), + ("lndg", "lndg_api_url"), + ), + ), + ToolSpec( + id="disabled-fee-accelerator", + script_path="LNDg/disabled_fee-accelerator.py", + category="LNDg", + summary="Bumps local_fee_rate on depleted channels disabled by charge-lnd", + risk_tier="FEES/POLICY", + host_profiles=("node", "vps"), + supported_modes=("systemd-timer", "cron", "manual"), + default_mode="systemd-timer", + default_on_calendar="*:02:00", + default_cron="2 * * * *", + config_templates=("config.ini",), + required_ini_keys=( + ("credentials", "lndg_username"), + ("credentials", "lndg_password"), + ("lndg", "lndg_api_url"), + ), + ), + ToolSpec( + id="mempool-rebalancer-trigger", + script_path="LNDg/mempool_rebalancer_trigger.py", + category="LNDg", + summary="Polls mempool.space and toggles LNDg AR-Enabled on fee spikes", + risk_tier="FEES/POLICY", + host_profiles=("node", "vps"), + supported_modes=("systemd-service",), + default_mode="systemd-service", + config_templates=("config.ini",), + required_ini_keys=( + ("credentials", "lndg_username"), + ("credentials", "lndg_password"), + ("lndg", "lndg_api_url"), + ), + legacy_units=("mempool_rebalancer_trigger.service",), + ), + ToolSpec( + id="offline-summary", + script_path="LNDg/offline_summary.py", + category="LNDg", + summary="Monthly peer offline-duration report from LNDg PostgreSQL", + risk_tier="READ-ONLY", + host_profiles=("node",), + supported_modes=("manual",), + default_mode="manual", + optional_extras=("db",), + config_templates=("config.ini",), + required_ini_keys=(("database", "name"),), + ), + ToolSpec( + id="swap-out-candidates", + script_path="LNDg/swap_out-candidates.py", + category="LNDg", + summary="Lists high-local low-PPM swap-out candidates (+ optional bos export)", + risk_tier="READ-ONLY", + host_profiles=("node",), + supported_modes=("manual", "systemd-timer", "cron"), + default_mode="manual", + default_on_calendar="daily", + default_cron="0 4 * * *", + config_templates=("config.ini",), + required_ini_keys=( + ("credentials", "lndg_username"), + ("credentials", "lndg_password"), + ("lndg", "lndg_api_url"), + ), + ), + ToolSpec( + id="swap-out-loop", + script_path="Other/swap_out-loop.py", + category="Other", + summary="Economically scored Loop Out optimizer with live route probing", + risk_tier="FUNDS", + host_profiles=("node",), + supported_modes=("manual",), + default_mode="manual", + dry_run_args=("--dry-run",), + config_templates=("config.ini",), + required_ini_keys=( + ("credentials", "lndg_username"), + ("credentials", "lndg_password"), + ("lndg", "lndg_api_url"), + ("paths", "lncli_path"), + ), + ), + ToolSpec( + id="boltz-swap-out", + script_path="Other/boltz_swap-out.py", + category="Other", + summary="Reverse submarine swaps (LN -> Liquid L-BTC) via boltzcli", + risk_tier="FUNDS", + host_profiles=("node",), + supported_modes=("manual",), + default_mode="manual", + dry_run_args=("--debug",), + config_templates=("config.ini",), + required_ini_keys=( + ("credentials", "lndg_username"), + ("credentials", "lndg_password"), + ("lndg", "lndg_api_url"), + ("paths", "boltzcli_path"), + ), + ), + ToolSpec( + id="swap-wallet", + script_path="Other/swap_wallet.py", + category="Other", + summary="Interactive batched LN payments to Lightning Address via bos send", + risk_tier="FUNDS", + host_profiles=("node",), + supported_modes=("manual",), + default_mode="manual", + config_templates=("config.ini",), + required_ini_keys=( + ("paths", "lncli_path"), + ("system", "full_path_bos"), + ), + ), + ToolSpec( + id="lnd-utxo-consolidator", + script_path="Other/lnd_utxo_consolidator.py", + category="Other", + summary="Interactive UTXO selector printing a lncli sendcoins command", + risk_tier="READ-ONLY", + host_profiles=("node",), + supported_modes=("manual",), + default_mode="manual", + config_templates=("config.ini",), + required_ini_keys=(("paths", "lncli_path"),), + ), + ToolSpec( + id="peerswap-bot", + script_path="Peerswap/peerswap-bot.py", + category="Peerswap", + summary="Telegram bot daemon wrapping pscli swaps and L-BTC sends", + risk_tier="FUNDS", + host_profiles=("node",), + supported_modes=("systemd-service",), + default_mode="systemd-service", + after_units=("peerswapd.service",), + wants_units=("peerswapd.service",), + config_templates=("config.ini",), + required_ini_keys=( + ("telegram", "peerswap_bot_token"), + ("telegram", "telegram_user_id"), + ), + legacy_units=("peerswap-bot.service",), + ), + ToolSpec( + id="peerswap-lndg-push", + script_path="Peerswap/peerswap-lndg_push.py", + category="Peerswap", + summary="Pushes PeerSwap swap stats from pscli into LNDg channel notes", + risk_tier="READ-ONLY", + host_profiles=("node",), + supported_modes=("systemd-timer", "cron", "manual"), + default_mode="systemd-timer", + unattended_args=("-a",), + default_on_calendar="hourly", + default_cron="0 * * * *", + dry_run_args=("-a", "--dry-run"), + config_templates=("config.ini",), + required_ini_keys=( + ("credentials", "lndg_username"), + ("credentials", "lndg_password"), + ("lndg", "lndg_api_url"), + ("paths", "pscli_path"), + ), + ), + ToolSpec( + id="ps-peers", + script_path="Peerswap/ps_peers.py", + category="Peerswap", + summary="Terminal table of L-BTC balance and PeerSwap peer channel policies", + risk_tier="READ-ONLY", + host_profiles=("node",), + supported_modes=("manual",), + default_mode="manual", + config_templates=(), + required_ini_keys=(), + ), +) + +TOOLS_BY_ID: dict[str, ToolSpec] = {tool.id: tool for tool in TOOLS} + + +def get_tool(tool_id: str) -> ToolSpec: + """Return a ToolSpec by ID or raise KeyError with helpful context.""" + if tool_id not in TOOLS_BY_ID: + raise KeyError(f"Unknown tool ID: {tool_id!r}") + return TOOLS_BY_ID[tool_id] + + +def filter_tools(profile: str = "all") -> list[ToolSpec]: + """Return tools matching the requested host profile ('node', 'vps', 'all').""" + if profile == "all": + return list(TOOLS) + if profile not in ("node", "vps"): + raise ValueError(f"Invalid host profile: {profile!r}") + return [tool for tool in TOOLS if profile in tool.host_profiles] + + +def schedulable_tools(profile: str = "all") -> list[ToolSpec]: + """Return tools that support systemd or cron scheduling.""" + return [tool for tool in filter_tools(profile) if tool.is_schedulable] + + +def render_overview_table( + tools: list[ToolSpec], statuses: dict[str, str] | None = None +) -> str: + """Render an aligned plain-text overview table for CLI navigation.""" + headers = ("#", "ID", "Risk", "Default Mode", "Hosts", "Status", "Description") + rows: list[tuple[str, ...]] = [] + for idx, tool in enumerate(tools, start=1): + status_str = (statuses or {}).get(tool.id, "unmanaged") + hosts = ",".join(tool.host_profiles) + rows.append( + ( + str(idx), + tool.id, + tool.risk_tier, + tool.default_mode, + hosts, + status_str, + tool.summary, + ) + ) + + widths = [ + max(len(headers[col]), *(len(row[col]) for row in rows)) if rows else len(headers[col]) + for col in range(len(headers)) + ] + fmt = " ".join(f"{{:<{w}}}" for w in widths) + lines = [fmt.format(*headers), fmt.format(*("-" * w for w in widths))] + lines.extend(fmt.format(*row) for row in rows) + return "\n".join(lines) + + +def render_markdown_overview_table(tools: tuple[ToolSpec, ...] = TOOLS) -> str: + """Render a Markdown overview table kept in sync with registry.TOOLS.""" + lines = [ + "| ID | Script | Risk | Modes | Hosts | Description |", + "| :--- | :--- | :--- | :--- | :--- | :--- |", + ] + for tool in tools: + modes = ", ".join(tool.supported_modes) + hosts = ", ".join(tool.host_profiles) + lines.append( + f"| `{tool.id}` | `{tool.script_path}` | **{tool.risk_tier}** | " + f"{modes} | {hosts} | {tool.summary} |" + ) + return "\n".join(lines) diff --git a/lpt_installer/scheduler.py b/lpt_installer/scheduler.py new file mode 100644 index 0000000..bfb7262 --- /dev/null +++ b/lpt_installer/scheduler.py @@ -0,0 +1,754 @@ +"""Systemd unit & cron scheduling, duplicate detection, migration, and uninstall.""" + +from __future__ import annotations + +import configparser +import os +import re +import shlex +from dataclasses import dataclass +from datetime import datetime +from pathlib import Path +from typing import Any + +from lpt_installer.adapters import SystemEnv +from lpt_installer.env import venv_python_path +from lpt_installer.registry import TOOLS, ToolSpec, get_tool +from lpt_installer.state import load_state, save_state + +TOOL_ID_RE = re.compile(r"^[a-z0-9-]+$") +DEFAULT_CA_BUNDLE = "/etc/ssl/certs/ca-certificates.crt" + +CRON_BEGIN = "# >>> Lightning-Python-Tools managed block (do not edit manually)" +CRON_END = "# <<< Lightning-Python-Tools managed block" + +WEEKDAY_MAP: dict[str, tuple[str, int]] = { + "sunday": ("Sun", 0), + "monday": ("Mon", 1), + "tuesday": ("Tue", 2), + "wednesday": ("Wed", 3), + "thursday": ("Thu", 4), + "friday": ("Fri", 5), + "saturday": ("Sat", 6), +} + + +@dataclass(frozen=True) +class ConflictReport: + """Existing unmanaged or legacy executions discovered for a tool.""" + + legacy_units: tuple[str, ...] + unmanaged_units: tuple[str, ...] + unmanaged_cron: tuple[str, ...] + running_processes: tuple[str, ...] + + @property + def has_unmanaged(self) -> bool: + return bool( + self.unmanaged_units or self.unmanaged_cron or self.running_processes + ) + + +def validate_tool_id(tool_id: str) -> str: + if not TOOL_ID_RE.fullmatch(tool_id): + raise ValueError(f"Unsafe tool id: {tool_id!r}") + return tool_id + + +def unit_prefix(tool_id: str) -> str: + return f"lpt-{validate_tool_id(tool_id)}" + + +def build_runtime_path(home_dir: Path | None = None) -> str: + home = home_dir or Path.home() + candidates = [ + str(home / ".local" / "bin"), + str(home / "go" / "bin"), + "/usr/local/sbin", + "/usr/local/bin", + "/usr/sbin", + "/usr/bin", + "/sbin", + "/bin", + ] + deduped: list[str] = [] + for entry in candidates: + if entry not in deduped: + deduped.append(entry) + return ":".join(deduped) + + +def resolve_pocketmoney_schedule(repo_root: Path) -> tuple[str, str]: + """Read [Schedule] from config.ini and return (systemd OnCalendar, cron expr).""" + cfg = configparser.ConfigParser() + cfg_path = repo_root / "config.ini" + if cfg_path.is_file(): + cfg.read(cfg_path, encoding="utf-8") + + recurrence = ( + cfg.get("Schedule", "recurrence", fallback="weekly") + .split("#")[0] + .strip() + .lower() + ) + time_str = cfg.get("Schedule", "time", fallback="09:00").split("#")[0].strip() + day_of_week = ( + cfg.get("Schedule", "day_of_week", fallback="friday") + .split("#")[0] + .strip() + .lower() + ) + + parsed_time = datetime.strptime(time_str, "%H:%M") + hh = parsed_time.strftime("%H") + mm = parsed_time.strftime("%M") + minute_int = int(mm) + hour_int = int(hh) + + if recurrence == "daily": + return f"*-*-* {hh}:{mm}:00", f"{minute_int} {hour_int} * * *" + if recurrence == "weekly": + if day_of_week not in WEEKDAY_MAP: + raise ValueError( + f"Invalid [Schedule] day_of_week={day_of_week!r} in config.ini" + ) + systemd_day, cron_day = WEEKDAY_MAP[day_of_week] + return ( + f"{systemd_day} *-*-* {hh}:{mm}:00", + f"{minute_int} {hour_int} * * {cron_day}", + ) + raise ValueError(f"Invalid [Schedule] recurrence={recurrence!r} in config.ini") + + +def resolve_schedule(tool: ToolSpec, repo_root: Path) -> tuple[str | None, str | None]: + """Return (OnCalendar, cron_expr) for a tool.""" + if tool.id == "pocketmoney": + return resolve_pocketmoney_schedule(repo_root) + return tool.default_on_calendar, tool.default_cron + + +def render_systemd_service( + tool: ToolSpec, + repo_root: Path, + *, + user: str, + group: str, + ca_bundle: str = DEFAULT_CA_BUNDLE, + mode: str | None = None, + python_bin: Path | None = None, + home_dir: Path | None = None, + unit_exists: Any | None = None, +) -> str: + """Render a hardened systemd .service unit for the given tool.""" + validate_tool_id(tool.id) + chosen_mode = mode or tool.default_mode + if chosen_mode not in ("systemd-service", "systemd-timer"): + raise ValueError( + f"Mode {chosen_mode!r} does not generate a systemd unit for {tool.id}." + ) + if chosen_mode not in tool.supported_modes: + raise ValueError(f"Tool {tool.id!r} does not support mode {chosen_mode!r}.") + + py_exe = python_bin or venv_python_path(repo_root) + script_abs = repo_root / tool.script_path + exec_parts = [str(py_exe), str(script_abs), *tool.unattended_args] + exec_start = " ".join(shlex.quote(part) for part in exec_parts) + + after_list = ["network-online.target"] + wants_list = ["network-online.target"] + for unit in tool.after_units: + if unit_exists is None or unit_exists(unit): + after_list.append(unit) + for unit in tool.wants_units: + if unit_exists is None or unit_exists(unit): + wants_list.append(unit) + + lines = [ + "[Unit]", + f"Description=Lightning-Python-Tools: {tool.id} ({tool.risk_tier})", + f"After={' '.join(after_list)}", + f"Wants={' '.join(wants_list)}", + "", + "[Service]", + ] + + if chosen_mode == "systemd-timer": + lines.extend( + [ + "Type=oneshot", + "TimeoutStartSec=300", + ] + ) + else: + lines.extend( + [ + "Type=simple", + "Restart=on-failure", + "RestartSec=10", + ] + ) + + runtime_path = build_runtime_path(home_dir) + lines.extend( + [ + f"User={user}", + f"Group={group}", + f"WorkingDirectory={repo_root}", + f'Environment="SSL_CERT_FILE={ca_bundle}"', + f'Environment="REQUESTS_CA_BUNDLE={ca_bundle}"', + f'Environment="PATH={runtime_path}"', + f"ExecStart={exec_start}", + "StandardOutput=journal", + "StandardError=journal", + f"SyslogIdentifier={unit_prefix(tool.id)}", + "NoNewPrivileges=true", + "PrivateTmp=true", + "ProtectKernelTunables=true", + "ProtectKernelModules=true", + "ProtectControlGroups=true", + ] + ) + + if tool.sandbox_level == "strict": + logs_dir = repo_root / "logs" + data_dir = repo_root / "data" + lines.extend( + [ + "ProtectSystem=strict", + f"ReadWritePaths=-{logs_dir} -{data_dir}", + ] + ) + else: + lines.append("ProtectSystem=full") + + if chosen_mode == "systemd-service": + lines.extend( + [ + "", + "[Install]", + "WantedBy=multi-user.target", + ] + ) + + return "\n".join(lines) + "\n" + + +def render_systemd_timer(tool: ToolSpec, on_calendar: str) -> str: + """Render a systemd .timer unit targeting lpt-.service.""" + prefix = unit_prefix(tool.id) + lines = [ + "[Unit]", + f"Description=Schedule for {prefix}.service", + "", + "[Timer]", + f"OnCalendar={on_calendar}", + f"Unit={prefix}.service", + "AccuracySec=1min", + ] + if tool.persistent_timer: + lines.append("Persistent=true") + lines.extend( + [ + "", + "[Install]", + "WantedBy=timers.target", + "", + ] + ) + return "\n".join(lines) + + +def _split_cron_blocks(existing_crontab: str) -> tuple[list[str], dict[str, str]]: + """Split crontab into unmanaged lines and {tool_id: command_line} inside managed block.""" + unmanaged: list[str] = [] + managed: dict[str, str] = {} + in_block = False + pending_tool_id: str | None = None + + for raw_line in existing_crontab.splitlines(): + stripped = raw_line.strip() + if stripped == CRON_BEGIN: + in_block = True + pending_tool_id = None + continue + if stripped == CRON_END: + in_block = False + pending_tool_id = None + continue + if not in_block: + unmanaged.append(raw_line) + continue + if stripped.startswith("# lpt-tool:"): + pending_tool_id = stripped.split(":", 1)[1].strip() + continue + if pending_tool_id and stripped and not stripped.startswith("#"): + managed[pending_tool_id] = stripped + pending_tool_id = None + + while unmanaged and unmanaged[-1] == "": + unmanaged.pop() + + return unmanaged, managed + + +def render_cron_entry( + tool: ToolSpec, + cron_expr: str, + repo_root: Path, + *, + python_bin: Path | None = None, +) -> str: + validate_tool_id(tool.id) + py_exe = python_bin or venv_python_path(repo_root) + script_abs = repo_root / tool.script_path + cmd_parts = [str(py_exe), str(script_abs), *tool.unattended_args] + cmd_str = " ".join(shlex.quote(part) for part in cmd_parts) + log_path = shlex.quote(str(repo_root / "logs" / f"cron_{tool.id}.log")) + lock_path = shlex.quote(f"/tmp/lpt-{tool.id}.lock") + repo_quoted = shlex.quote(str(repo_root)) + return ( + f"{cron_expr} cd {repo_quoted} && flock -n {lock_path} {cmd_str} >> {log_path} 2>&1" + ) + + +def _assemble_crontab( + unmanaged: list[str], + managed: dict[str, str], + *, + ca_bundle: str, + home_dir: Path | None = None, +) -> str: + lines = list(unmanaged) + if managed: + if lines: + lines.append("") + lines.extend( + [ + CRON_BEGIN, + f"SSL_CERT_FILE={ca_bundle}", + f"REQUESTS_CA_BUNDLE={ca_bundle}", + f"PATH={build_runtime_path(home_dir)}", + ] + ) + for tool_id in sorted(managed): + lines.append(f"# lpt-tool: {tool_id}") + lines.append(managed[tool_id]) + lines.append(CRON_END) + + if not lines: + return "" + return "\n".join(lines) + "\n" + + +def upsert_cron_block( + existing_crontab: str, + updates: dict[str, str], + *, + ca_bundle: str = DEFAULT_CA_BUNDLE, + home_dir: Path | None = None, +) -> str: + """Idempotently upsert managed cron entries while preserving user lines verbatim.""" + unmanaged, managed = _split_cron_blocks(existing_crontab) + for tool_id, entry in updates.items(): + validate_tool_id(tool_id) + managed[tool_id] = entry + return _assemble_crontab( + unmanaged, managed, ca_bundle=ca_bundle, home_dir=home_dir + ) + + +def remove_cron_tools( + existing_crontab: str, + tool_ids: list[str], + *, + ca_bundle: str = DEFAULT_CA_BUNDLE, + home_dir: Path | None = None, +) -> str: + """Remove specified tool IDs from the managed cron block, preserving user lines.""" + unmanaged, managed = _split_cron_blocks(existing_crontab) + for tool_id in tool_ids: + managed.pop(tool_id, None) + return _assemble_crontab( + unmanaged, managed, ca_bundle=ca_bundle, home_dir=home_dir + ) + + +def detect_conflicts(tool: ToolSpec, env: SystemEnv) -> ConflictReport: + """Scan systemd units, crontab, and running processes for duplicate executions.""" + script_name = Path(tool.script_path).name + managed_service = f"{unit_prefix(tool.id)}.service" + + legacy_found: list[str] = [] + unmanaged_units: list[str] = [] + + for unit_path in env.list_systemd_units("*.service"): + if unit_path.name == managed_service: + continue + try: + content = unit_path.read_text(encoding="utf-8", errors="ignore") + except OSError: + continue + if script_name in content or unit_path.name in tool.legacy_units: + if unit_path.name in tool.legacy_units: + legacy_found.append(unit_path.name) + timer_name = f"{unit_path.stem}.timer" + if env.systemd_unit_exists(timer_name): + legacy_found.append(timer_name) + else: + unmanaged_units.append(str(unit_path)) + + for unit_name in tool.legacy_units: + if unit_name.endswith(".timer") and env.systemd_unit_exists(unit_name): + legacy_found.append(unit_name) + + for user_unit in env.list_user_systemd_units("*.service"): + try: + content = user_unit.read_text(encoding="utf-8", errors="ignore") + except OSError: + continue + if script_name in content: + unmanaged_units.append(str(user_unit)) + + unmanaged_cron_lines: list[str] = [] + unmanaged_lines, _ = _split_cron_blocks(env.read_crontab()) + for line in unmanaged_lines: + stripped = line.strip() + if not stripped or stripped.startswith("#"): + continue + if script_name in stripped: + unmanaged_cron_lines.append(stripped) + + running: list[str] = [] + if not legacy_found: + for proc_line in env.running_processes(): + if script_name in proc_line and "lpt_installer" not in proc_line: + running.append(proc_line) + + return ConflictReport( + legacy_units=tuple(sorted(set(legacy_found))), + unmanaged_units=tuple(sorted(set(unmanaged_units))), + unmanaged_cron=tuple(unmanaged_cron_lines), + running_processes=tuple(running), + ) + + +def create_backup_snapshot( + repo_root: Path, + env: SystemEnv, + legacy_units: tuple[str, ...] = (), +) -> Path: + """Create a 0700 backup directory with current crontab and legacy unit files.""" + backups_root = repo_root / ".lpt-backups" + backups_root.mkdir(parents=True, exist_ok=True) + os.chmod(backups_root, 0o700) + + stamp = datetime.now().strftime("%Y%m%d-%H%M%S") + snapshot_dir = backups_root / stamp + suffix = 1 + while snapshot_dir.exists(): + suffix += 1 + snapshot_dir = backups_root / f"{stamp}-{suffix}" + snapshot_dir.mkdir(parents=True, exist_ok=True) + os.chmod(snapshot_dir, 0o700) + + cron_text = env.read_crontab() + if cron_text: + cron_bak = snapshot_dir / "crontab.bak" + cron_bak.write_text(cron_text, encoding="utf-8") + os.chmod(cron_bak, 0o600) + + for unit_name in legacy_units: + src = env.systemd_dir / unit_name + if src.is_file(): + try: + content = src.read_text(encoding="utf-8", errors="ignore") + dst = snapshot_dir / unit_name + dst.write_text(content, encoding="utf-8") + os.chmod(dst, 0o600) + except OSError: + continue + + return snapshot_dir + + +def _migrate_legacy_units( + legacy_units: tuple[str, ...], env: SystemEnv, *, dry_run: bool +) -> list[str]: + migrated: list[str] = [] + for unit_name in legacy_units: + if not dry_run: + env.systemctl("disable", "--now", unit_name, use_sudo=True, check=False) + env.sudo_remove_file(env.systemd_dir / unit_name) + migrated.append(unit_name) + if legacy_units and not dry_run: + env.systemctl("daemon-reload", use_sudo=True, check=True) + return migrated + + +def install_tool( + tool: ToolSpec, + repo_root: Path, + env: SystemEnv, + *, + mode: str | None = None, + dry_run: bool = False, +) -> dict[str, Any]: + """Install/schedule a tool cleanly with duplicate checks, backup, and migration.""" + if env.current_uid() == 0: + raise PermissionError("Refusing to run installation as root.") + + chosen_mode = mode or tool.default_mode + if chosen_mode not in tool.supported_modes: + raise ValueError( + f"Tool {tool.id!r} does not support mode {chosen_mode!r} " + f"(supported: {', '.join(tool.supported_modes)})." + ) + + if chosen_mode == "manual": + state = load_state(repo_root) + state["installed"][tool.id] = { + "mode": "manual", + "script": tool.script_path, + } + if not dry_run: + save_state(repo_root, state) + return { + "tool": tool.id, + "mode": "manual", + "command": f"{venv_python_path(repo_root)} {repo_root / tool.script_path}", + "dry_run": dry_run, + } + + conflicts = detect_conflicts(tool, env) + if conflicts.has_unmanaged: + details = [ + *conflicts.unmanaged_units, + *conflicts.unmanaged_cron, + *conflicts.running_processes, + ] + raise RuntimeError( + f"Refusing to install {tool.id}: unmanaged duplicate execution detected: " + + "; ".join(details) + ) + + ca_bundle = env.detect_ca_bundle() or DEFAULT_CA_BUNDLE + user, group = env.current_user_group() + on_calendar, cron_expr = resolve_schedule(tool, repo_root) + + backup_dir: Path | None = None + migrated: list[str] = [] + if not dry_run: + backup_dir = create_backup_snapshot(repo_root, env, conflicts.legacy_units) + if conflicts.legacy_units: + migrated = _migrate_legacy_units(conflicts.legacy_units, env, dry_run=False) + + prefix = unit_prefix(tool.id) + state = load_state(repo_root) + + if chosen_mode in ("systemd-service", "systemd-timer"): + service_content = render_systemd_service( + tool, + repo_root, + user=user, + group=group, + ca_bundle=ca_bundle, + mode=chosen_mode, + home_dir=env.home_dir(), + unit_exists=env.systemd_unit_exists, + ) + service_path = env.systemd_dir / f"{prefix}.service" + timer_path = env.systemd_dir / f"{prefix}.timer" + timer_content: str | None = None + + if chosen_mode == "systemd-timer": + if not on_calendar: + raise ValueError(f"No OnCalendar schedule defined for {tool.id}.") + timer_content = render_systemd_timer(tool, on_calendar) + + if not dry_run: + # Ensure no leftover managed cron entry runs alongside systemd + updated_cron = remove_cron_tools( + env.read_crontab(), + [tool.id], + ca_bundle=ca_bundle, + home_dir=env.home_dir(), + ) + env.write_crontab(updated_cron) + + env.sudo_install_file(service_content, service_path) + if timer_content is not None: + env.sudo_install_file(timer_content, timer_path) + env.systemctl("daemon-reload", use_sudo=True, check=True) + env.systemctl("enable", "--now", f"{prefix}.timer", use_sudo=True, check=True) + else: + if timer_path.exists(): + env.systemctl("disable", "--now", f"{prefix}.timer", use_sudo=True, check=False) + env.sudo_remove_file(timer_path) + env.systemctl("daemon-reload", use_sudo=True, check=True) + env.systemctl("enable", "--now", f"{prefix}.service", use_sudo=True, check=True) + + state["installed"][tool.id] = { + "mode": chosen_mode, + "unit": f"{prefix}.timer" if chosen_mode == "systemd-timer" else f"{prefix}.service", + "backup_dir": str(backup_dir) if backup_dir else None, + } + save_state(repo_root, state) + + return { + "tool": tool.id, + "mode": chosen_mode, + "service_path": str(service_path), + "timer_path": str(timer_path) if timer_content else None, + "service_content": service_content, + "timer_content": timer_content, + "migrated_legacy": migrated or list(conflicts.legacy_units), + "backup_dir": str(backup_dir) if backup_dir else None, + "dry_run": dry_run, + } + + # chosen_mode == "cron" + if not cron_expr: + raise ValueError(f"No cron schedule defined for {tool.id}.") + cron_entry = render_cron_entry(tool, cron_expr, repo_root) + new_crontab = upsert_cron_block( + env.read_crontab(), + {tool.id: cron_entry}, + ca_bundle=ca_bundle, + home_dir=env.home_dir(), + ) + if not dry_run: + # Stop/remove any managed systemd unit for this tool before switching to cron + for suffix in (".timer", ".service"): + unit_name = f"{prefix}{suffix}" + if env.systemd_unit_exists(unit_name): + env.systemctl("disable", "--now", unit_name, use_sudo=True, check=False) + env.sudo_remove_file(env.systemd_dir / unit_name) + env.systemctl("daemon-reload", use_sudo=True, check=False) + (repo_root / "logs").mkdir(parents=True, exist_ok=True) + env.write_crontab(new_crontab) + state["installed"][tool.id] = { + "mode": "cron", + "schedule": cron_expr, + "backup_dir": str(backup_dir) if backup_dir else None, + } + save_state(repo_root, state) + + return { + "tool": tool.id, + "mode": "cron", + "cron_entry": cron_entry, + "migrated_legacy": migrated or list(conflicts.legacy_units), + "backup_dir": str(backup_dir) if backup_dir else None, + "dry_run": dry_run, + } + + +def uninstall_tools( + tool_ids: list[str], + repo_root: Path, + env: SystemEnv, + *, + remove_venv: bool = False, + purge_configs: bool = False, + dry_run: bool = False, +) -> dict[str, Any]: + """Stop/remove managed systemd units and cron entries while preserving configs by default.""" + if env.current_uid() == 0: + raise PermissionError("Refusing to uninstall as root.") + + for tid in tool_ids: + get_tool(tid) + validate_tool_id(tid) + + ca_bundle = env.detect_ca_bundle() or DEFAULT_CA_BUNDLE + removed_units: list[str] = [] + removed_cron: list[str] = [] + removed_configs: list[str] = [] + + if not dry_run and tool_ids: + create_backup_snapshot(repo_root, env) + + reload_needed = False + for tid in tool_ids: + prefix = unit_prefix(tid) + for suffix in (".timer", ".service"): + unit_name = f"{prefix}{suffix}" + unit_path = env.systemd_dir / unit_name + if env.systemd_unit_exists(unit_name): + removed_units.append(unit_name) + if not dry_run: + env.systemctl("disable", "--now", unit_name, use_sudo=True, check=False) + env.sudo_remove_file(unit_path) + reload_needed = True + + if reload_needed and not dry_run: + env.systemctl("daemon-reload", use_sudo=True, check=True) + + current_cron = env.read_crontab() + _, current_managed = _split_cron_blocks(current_cron) + for tid in tool_ids: + if tid in current_managed: + removed_cron.append(tid) + updated_cron = remove_cron_tools( + current_cron, + tool_ids, + ca_bundle=ca_bundle, + home_dir=env.home_dir(), + ) + if removed_cron and not dry_run: + env.write_crontab(updated_cron) + + state = load_state(repo_root) + for tid in tool_ids: + state["installed"].pop(tid, None) + if not dry_run: + save_state(repo_root, state) + + venv_removed = False + venv_dir = repo_root / ".venv" + if remove_venv and venv_dir.exists(): + venv_removed = True + if not dry_run: + import shutil + + shutil.rmtree(venv_dir) + + if purge_configs: + for rel_cfg in ("config.ini", "Magma/magma_config.ini", "feeConfig.json", "wallets.json"): + cfg_path = repo_root / rel_cfg + if cfg_path.exists(): + removed_configs.append(rel_cfg) + if not dry_run: + cfg_path.unlink() + + return { + "removed_units": removed_units, + "removed_cron": removed_cron, + "venv_removed": venv_removed, + "removed_configs": removed_configs, + "configs_preserved": not purge_configs, + "dry_run": dry_run, + } + + +def collect_statuses(repo_root: Path, env: SystemEnv) -> dict[str, str]: + """Return runtime status label for each tool in the registry.""" + state = load_state(repo_root) + _, managed_cron = _split_cron_blocks(env.read_crontab()) + statuses: dict[str, str] = {} + + for tool in TOOLS: + prefix = unit_prefix(tool.id) + if env.systemd_unit_exists(f"{prefix}.timer"): + statuses[tool.id] = "systemd-timer" + elif env.systemd_unit_exists(f"{prefix}.service"): + statuses[tool.id] = "systemd-service" + elif tool.id in managed_cron: + statuses[tool.id] = "cron" + elif any(env.systemd_unit_exists(u) for u in tool.legacy_units): + statuses[tool.id] = "legacy-systemd" + elif tool.id in state.get("installed", {}): + statuses[tool.id] = str(state["installed"][tool.id].get("mode", "installed")) + else: + statuses[tool.id] = "unmanaged" + return statuses diff --git a/lpt_installer/state.py b/lpt_installer/state.py new file mode 100644 index 0000000..dea93b7 --- /dev/null +++ b/lpt_installer/state.py @@ -0,0 +1,54 @@ +"""State manifest (.lpt-state.json) persistence for Lightning-Python-Tools.""" + +from __future__ import annotations + +import json +import os +import tempfile +from pathlib import Path +from typing import Any + +STATE_FILENAME = ".lpt-state.json" + + +def state_file_path(repo_root: Path) -> Path: + return repo_root / STATE_FILENAME + + +def load_state(repo_root: Path) -> dict[str, Any]: + """Load installer state manifest, returning a clean default dict if absent.""" + path = state_file_path(repo_root) + if not path.is_file(): + return {"disclaimer_version": None, "installed": {}} + try: + data = json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + return {"disclaimer_version": None, "installed": {}} + if not isinstance(data, dict): + return {"disclaimer_version": None, "installed": {}} + installed = data.get("installed") + if not isinstance(installed, dict): + installed = {} + return { + "disclaimer_version": data.get("disclaimer_version"), + "installed": installed, + } + + +def save_state(repo_root: Path, state: dict[str, Any]) -> Path: + """Atomically persist installer state manifest with 0o600 permissions.""" + path = state_file_path(repo_root) + payload = json.dumps(state, indent=2, sort_keys=True) + "\n" + fd, tmp_name = tempfile.mkstemp(prefix=".lpt-state_", suffix=".tmp", dir=repo_root) + tmp_path = Path(tmp_name) + try: + with os.fdopen(fd, "w", encoding="utf-8") as handle: + handle.write(payload) + handle.flush() + os.fsync(handle.fileno()) + os.chmod(tmp_path, 0o600) + os.replace(tmp_path, path) + except Exception: + tmp_path.unlink(missing_ok=True) + raise + return path diff --git a/pyproject.toml b/pyproject.toml index ba50ac3..470755f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -49,7 +49,7 @@ select = ["E", "F", "W", "B", "UP"] ignore = ["E501"] [tool.coverage.run] -source = ["LNDg", "Magma", "Other", "Peerswap", "LNBits"] +source = ["LNDg", "Magma", "Other", "Peerswap", "LNBits", "lpt_installer"] omit = ["tests/*"] [tool.coverage.report] diff --git a/tests/test_ca_trust_hardening.py b/tests/test_ca_trust_hardening.py index c10a59b..ec6551e 100644 --- a/tests/test_ca_trust_hardening.py +++ b/tests/test_ca_trust_hardening.py @@ -1,10 +1,19 @@ """Regression tests for CA trust store hardening (eMudhra / certifi>=2026.10.19).""" -from pathlib import Path +from __future__ import annotations + import re +from pathlib import Path import certifi +from lpt_installer.registry import TOOLS +from lpt_installer.scheduler import ( + DEFAULT_CA_BUNDLE, + render_cron_entry, + render_systemd_service, + upsert_cron_block, +) REPO_ROOT = Path(__file__).resolve().parent.parent @@ -50,17 +59,32 @@ def test_requirements_pins_and_installed_hardened_tls_dependencies(): ) -def test_systemd_installers_export_os_ca_bundle(): - """Systemd service installers must bind SSL_CERT_FILE and REQUESTS_CA_BUNDLE to the OS trust store.""" - installers = [ - REPO_ROOT / "LNBits" / "install_pocketmoney_service.sh", - REPO_ROOT / "Other" / "install_fee_adjuster_service.sh", - ] - for script in installers: - content = script.read_text(encoding="utf-8") - assert 'Environment="SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt"' in content, ( - f"{script.name} missing SSL_CERT_FILE systemd Environment directive" - ) - assert 'Environment="REQUESTS_CA_BUNDLE=/etc/ssl/certs/ca-certificates.crt"' in content, ( - f"{script.name} missing REQUESTS_CA_BUNDLE systemd Environment directive" - ) +def test_unified_systemd_and_cron_generators_export_os_ca_bundle(): + """Every systemd unit and managed cron block must bind SSL_CERT_FILE and REQUESTS_CA_BUNDLE.""" + for tool in TOOLS: + for mode in tool.supported_modes: + if mode not in ("systemd-service", "systemd-timer"): + continue + unit_text = render_systemd_service( + tool, + REPO_ROOT, + user="admin", + group="admin", + ca_bundle=DEFAULT_CA_BUNDLE, + mode=mode, + ) + assert f'Environment="SSL_CERT_FILE={DEFAULT_CA_BUNDLE}"' in unit_text, ( + f"{tool.id} ({mode}) missing SSL_CERT_FILE systemd Environment directive" + ) + assert f'Environment="REQUESTS_CA_BUNDLE={DEFAULT_CA_BUNDLE}"' in unit_text, ( + f"{tool.id} ({mode}) missing REQUESTS_CA_BUNDLE systemd Environment directive" + ) + + cron_tool = next(t for t in TOOLS if "cron" in t.supported_modes) + cron_text = upsert_cron_block( + "", + {cron_tool.id: render_cron_entry(cron_tool, "0 * * * *", REPO_ROOT)}, + ca_bundle=DEFAULT_CA_BUNDLE, + ) + assert f"SSL_CERT_FILE={DEFAULT_CA_BUNDLE}" in cron_text + assert f"REQUESTS_CA_BUNDLE={DEFAULT_CA_BUNDLE}" in cron_text diff --git a/tests/test_lpt_installer.py b/tests/test_lpt_installer.py new file mode 100644 index 0000000..b1e01c6 --- /dev/null +++ b/tests/test_lpt_installer.py @@ -0,0 +1,657 @@ +"""Tests for unified installer/manager package (lpt_installer).""" + +from __future__ import annotations + +import json +import stat +from pathlib import Path + +import pytest + +from lpt_installer import DISCLAIMER_VERSION, DONATION_URL +from lpt_installer.adapters import CommandResult, SystemEnv +from lpt_installer.cli import main as cli_main +from lpt_installer.configs import ensure_configs, validate_configs +from lpt_installer.env import run_doctor, setup_venv +from lpt_installer.registry import ( + TOOLS, + TOOLS_BY_ID, + filter_tools, + get_tool, + render_markdown_overview_table, + render_overview_table, + schedulable_tools, +) +from lpt_installer.scheduler import ( + CRON_BEGIN, + CRON_END, + detect_conflicts, + install_tool, + remove_cron_tools, + render_cron_entry, + render_systemd_service, + render_systemd_timer, + resolve_pocketmoney_schedule, + uninstall_tools, + upsert_cron_block, +) +from lpt_installer.state import load_state, save_state + +REPO_ROOT = Path(__file__).resolve().parent.parent + + +class FakeEnv(SystemEnv): + """In-memory / tmp_path SystemEnv double so production installer code runs without root.""" + + def __init__( + self, + tmp_path: Path, + *, + uid: int = 1000, + uv_available: bool = True, + ca_bundle: str | None = "/etc/ssl/certs/ca-certificates.crt", + crontab: str = "", + processes: list[str] | None = None, + ) -> None: + super().__init__( + systemd_dir=tmp_path / "etc_systemd", + user_systemd_dir=tmp_path / "user_systemd", + ) + self.systemd_dir.mkdir(parents=True, exist_ok=True) + self.user_systemd_dir.mkdir(parents=True, exist_ok=True) + self._uid = uid + self._uv_available = uv_available + self._ca_bundle = ca_bundle + self.crontab = crontab + self._processes = processes or [] + self.commands: list[list[str]] = [] + self.installed_files: dict[Path, str] = {} + + def run( + self, + argv: list[str], + *, + input_text: str | None = None, + check: bool = False, + env_vars: dict[str, str] | None = None, + interactive: bool = False, + ) -> CommandResult: + self.commands.append(list(argv)) + if len(argv) >= 3 and argv[1] == "-c" and "certifi.__version__" in argv[2]: + return CommandResult(0, "2026.11.20\n", "") + return CommandResult(0, "", "") + + def which(self, binary: str) -> str | None: + if binary == "uv": + return "/usr/local/bin/uv" if self._uv_available else None + if binary in ("nano", "vi"): + return f"/usr/bin/{binary}" + return None + + def current_uid(self) -> int: + return self._uid + + def current_user_group(self) -> tuple[str, str]: + return ("admin", "admin") + + def home_dir(self) -> Path: + return self.systemd_dir.parent / "home" + + def detect_ca_bundle(self) -> str | None: + return self._ca_bundle + + def sudo_install_file( + self, content: str, dest: Path, mode: str = "0644" + ) -> CommandResult: + self.commands.append(["sudo", "install", "-m", mode, str(dest)]) + dest.parent.mkdir(parents=True, exist_ok=True) + dest.write_text(content, encoding="utf-8") + self.installed_files[dest] = content + return CommandResult(0, "", "") + + def sudo_remove_file(self, dest: Path) -> CommandResult: + self.commands.append(["sudo", "rm", "-f", str(dest)]) + dest.unlink(missing_ok=True) + self.installed_files.pop(dest, None) + return CommandResult(0, "", "") + + def systemctl( + self, *args: str, use_sudo: bool = True, check: bool = True + ) -> CommandResult: + cmd = ["sudo", "systemctl", *args] if use_sudo else ["systemctl", *args] + self.commands.append(cmd) + return CommandResult(0, "", "") + + def read_crontab(self) -> str: + return self.crontab + + def write_crontab(self, content: str) -> CommandResult: + self.crontab = content + return CommandResult(0, "", "") + + def running_processes(self) -> list[str]: + return list(self._processes) + + +def _seed_repo(tmp_path: Path, *, valid_configs: bool = True) -> Path: + repo = tmp_path / "repo" + repo.mkdir(parents=True, exist_ok=True) + for rel in ( + "config.ini.example", + "feeConfig.json.example", + "wallets.json.example", + "Magma/magma_config.ini.example", + "requirements.txt", + ): + src = REPO_ROOT / rel + dst = repo / rel + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(src.read_text(encoding="utf-8"), encoding="utf-8") + + venv_py = repo / ".venv" / "bin" / "python3" + venv_py.parent.mkdir(parents=True, exist_ok=True) + venv_py.write_text("#!/bin/sh\n", encoding="utf-8") + + if valid_configs: + (repo / "config.ini").write_text( + "\n".join( + [ + "[credentials]", + "amboss_authorization = real-amboss-token", + "lndg_username = lndgadmin", + "lndg_password = secretpass", + "[lndg]", + "lndg_api_url = http://localhost:8889", + "[paths]", + "lncli_path = /usr/local/bin/lncli", + "pscli_path = /usr/local/bin/pscli", + "boltzcli_path = /usr/local/bin/boltzcli", + "[telegram]", + "magma_bot_token = 123:abc", + "peerswap_bot_token = 456:def", + "lnbits_bot_token = 789:ghi", + "telegram_user_id = 424242", + "[LNBits]", + "base_url = https://lnbits.node.local", + "admin_key = real-admin-key", + "[Schedule]", + "recurrence = weekly # inline comment", + "time = 09:30", + "day_of_week = friday", + "[database]", + "name = lndg", + "[system]", + "full_path_bos = /usr/bin/bos", + ] + ) + + "\n", + encoding="utf-8", + ) + (repo / "feeConfig.json").write_text('{"nodes": []}\n', encoding="utf-8") + (repo / "wallets.json").write_text( + json.dumps( + { + "Alice": { + "wallet_id": "real_wallet_1", + "invoice_key": "real_inv_1", + "fiat_amount": 5, + "fiat_currency": "EUR", + } + } + ), + encoding="utf-8", + ) + (repo / "Magma" / "magma_config.ini").write_text("[magma_autoprice]\n", encoding="utf-8") + return repo + + +def test_registry_covers_all_19_scripts_and_files_exist(): + assert len(TOOLS) == 19 + assert len(TOOLS_BY_ID) == 19 + + disk_scripts = { + str(path.relative_to(REPO_ROOT)) + for folder in ("LNBits", "LNDg", "Magma", "Other", "Peerswap") + for path in (REPO_ROOT / folder).glob("*.py") + } + registry_scripts = {tool.script_path for tool in TOOLS} + assert registry_scripts == disk_scripts + + for tool in TOOLS: + assert (REPO_ROOT / tool.script_path).is_file() + assert tool.default_mode in tool.supported_modes + + vps_ids = {t.id for t in filter_tools("vps")} + assert "pocketmoney" in vps_ids + assert "fee-adjuster" in vps_ids + assert "magma-sale" not in vps_ids + assert any(t.id == "fee-adjuster" for t in schedulable_tools("node")) + assert "pocketmoney" in render_overview_table(list(TOOLS)) + assert "| `pocketmoney` |" in render_markdown_overview_table() + + +def test_render_systemd_units_hardening_and_sandbox(tmp_path): + repo = _seed_repo(tmp_path) + pm = get_tool("pocketmoney") + pm_service = render_systemd_service( + pm, + repo, + user="admin", + group="admin", + mode="systemd-timer", + unit_exists=lambda _: False, + ) + assert "Type=oneshot" in pm_service + assert "TimeoutStartSec=300" in pm_service + assert "ProtectSystem=strict" in pm_service + assert "--run-once" in pm_service + assert "[Install]" not in pm_service + + pm_timer = render_systemd_timer(pm, "Fri *-*-* 09:30:00") + assert "OnCalendar=Fri *-*-* 09:30:00" in pm_timer + assert "Persistent=true" in pm_timer + assert "Unit=lpt-pocketmoney.service" in pm_timer + + fa = get_tool("fee-adjuster") + fa_service = render_systemd_service( + fa, + repo, + user="admin", + group="admin", + mode="systemd-timer", + unit_exists=lambda _: False, + ) + assert "ProtectSystem=full" in fa_service + + magma = get_tool("magma-sale") + magma_service = render_systemd_service( + magma, + repo, + user="admin", + group="admin", + mode="systemd-service", + unit_exists=lambda u: u == "lnd.service", + ) + assert "Type=simple" in magma_service + assert "After=network-online.target lnd.service" in magma_service + assert "WantedBy=multi-user.target" in magma_service + + +def test_resolve_pocketmoney_schedule_daily_and_weekly(tmp_path): + repo = _seed_repo(tmp_path) + assert resolve_pocketmoney_schedule(repo) == ("Fri *-*-* 09:30:00", "30 9 * * 5") + + (repo / "config.ini").write_text( + "[Schedule]\nrecurrence = daily\ntime = 07:05\n", encoding="utf-8" + ) + assert resolve_pocketmoney_schedule(repo) == ("*-*-* 07:05:00", "5 7 * * *") + + +def test_cron_managed_block_idempotency_and_preservation(tmp_path): + repo = _seed_repo(tmp_path) + user_cron = "0 3 * * * /home/admin/tools/pull_lndg_backup.sh >/dev/null 2>&1\n" + fa = get_tool("fee-adjuster") + entry = render_cron_entry(fa, "*/20 * * * *", repo) + + first = upsert_cron_block(user_cron, {"fee-adjuster": entry}) + second = upsert_cron_block(first, {"fee-adjuster": entry}) + assert first == second + assert CRON_BEGIN in first + assert CRON_END in first + assert "flock -n /tmp/lpt-fee-adjuster.lock" in first + assert "pull_lndg_backup.sh" in first + + cleaned = remove_cron_tools(first, ["fee-adjuster"]) + assert cleaned == user_cron + + +def test_config_copy_no_clobber_chmod_600_and_validation(tmp_path): + repo = _seed_repo(tmp_path, valid_configs=False) + res1 = ensure_configs(repo, [get_tool("pocketmoney")]) + assert set(res1["copied"]) == {"config.ini", "wallets.json"} + assert stat.S_IMODE((repo / "config.ini").stat().st_mode) == 0o600 + assert stat.S_IMODE((repo / "wallets.json").stat().st_mode) == 0o600 + assert stat.S_IMODE((repo / "logs").stat().st_mode) == 0o700 + + # Placeholders must fail validation + errors = validate_configs(repo, [get_tool("pocketmoney")]) + assert any("base_url" in err for err in errors) + assert any("admin_key" in err for err in errors) + assert any("WALLETID" in err or "wallet_id" in err for err in errors) + + # Custom contents must never be clobbered on second run + (repo / "config.ini").write_text("[LNBits]\nbase_url = https://my.node\n", encoding="utf-8") + res2 = ensure_configs(repo, [get_tool("pocketmoney")]) + assert res2["copied"] == [] + assert "config.ini" in res2["preserved"] + assert "https://my.node" in (repo / "config.ini").read_text(encoding="utf-8") + + +def test_install_migrates_legacy_units_with_backup_and_blocks_unmanaged(tmp_path): + repo = _seed_repo(tmp_path) + env = FakeEnv( + tmp_path, + crontab="0 2 * * * /home/admin/backup.sh\n", + ) + # Seed legacy fee_adjuster units on disk + (env.systemd_dir / "fee_adjuster.service").write_text( + "ExecStart=/path/Other/fee_adjuster.py\n", encoding="utf-8" + ) + (env.systemd_dir / "fee_adjuster.timer").write_text("[Timer]\n", encoding="utf-8") + + fa = get_tool("fee-adjuster") + res = install_tool(fa, repo, env, mode="systemd-timer") + assert set(res["migrated_legacy"]) == {"fee_adjuster.service", "fee_adjuster.timer"} + assert (env.systemd_dir / "lpt-fee-adjuster.service").is_file() + assert (env.systemd_dir / "lpt-fee-adjuster.timer").is_file() + assert not (env.systemd_dir / "fee_adjuster.service").exists() + assert not (env.systemd_dir / "fee_adjuster.timer").exists() + + backup_dir = Path(res["backup_dir"]) + assert (backup_dir / "crontab.bak").is_file() + assert (backup_dir / "fee_adjuster.service").is_file() + + # Unmanaged duplicate crontab must fail closed + env_conflict = FakeEnv( + tmp_path / "conflict", + crontab="0 * * * * python3 /repo/LNDg/amboss_pull.py\n", + ) + report = detect_conflicts(get_tool("amboss-pull"), env_conflict) + assert report.has_unmanaged + with pytest.raises(RuntimeError, match="unmanaged duplicate"): + install_tool(get_tool("amboss-pull"), repo, env_conflict, mode="cron") + + +def test_uninstall_preserves_configs_by_default_and_purges_on_flag(tmp_path): + repo = _seed_repo(tmp_path) + env = FakeEnv(tmp_path) + install_tool(get_tool("amboss-pull"), repo, env, mode="cron") + assert "amboss_pull.py" in env.crontab + + out = uninstall_tools(["amboss-pull"], repo, env) + assert out["removed_cron"] == ["amboss-pull"] + assert out["configs_preserved"] is True + assert (repo / "config.ini").is_file() + + out_purge = uninstall_tools(["amboss-pull"], repo, env, remove_venv=True, purge_configs=True) + assert out_purge["venv_removed"] is True + assert "config.ini" in out_purge["removed_configs"] + assert not (repo / "config.ini").exists() + assert not (repo / ".venv").exists() + + +def test_setup_venv_uv_and_fallback_plus_doctor(tmp_path): + repo = _seed_repo(tmp_path) + env_uv = FakeEnv(tmp_path / "uv", uv_available=True) + res_uv = setup_venv(repo, env_uv, extras=("db",), recreate=True) + assert res_uv["backend"] == "uv" + assert any("psycopg2-binary" in cmd for cmd in res_uv["commands"]) + + env_pip = FakeEnv(tmp_path / "pip", uv_available=False) + res_pip = setup_venv(repo, env_pip, recreate=True) + assert res_pip["backend"] == "venv" + assert any("-m venv" in cmd for cmd in res_pip["commands"]) + + # Doctor flags world-readable config permissions + (repo / "config.ini").chmod(0o644) + checks = {c["name"]: c for c in run_doctor(repo, env_uv)} + assert checks["venv-certifi"]["status"] == "ok" + assert checks["ca-bundle"]["status"] == "ok" + assert checks["perms:config.ini"]["status"] == "warn" + + +def test_cli_disclaimer_donation_dry_run_and_interactive_menu(tmp_path): + repo = _seed_repo(tmp_path) + env = FakeEnv(tmp_path) + lines: list[str] = [] + + # Non-interactive install without --accept-disclaimer fails closed + rc = cli_main( + ["--repo-root", str(repo), "install", "pocketmoney", "--skip-env"], + env=env, + output_fn=lines.append, + ) + assert rc == 1 + assert any("MIT" in line or "DISCLAIMER" in line for line in lines) + + # With --accept-disclaimer + --dry-run succeeds and emits donation footer + lines.clear() + rc = cli_main( + [ + "--repo-root", + str(repo), + "install", + "pocketmoney", + "--scheduler", + "systemd", + "--accept-disclaimer", + "--dry-run", + ], + env=env, + output_fn=lines.append, + ) + assert rc == 0 + assert any(DONATION_URL in line for line in lines) + + # Interactive menu flow: accept disclaimer -> doctor (5) -> quit (q) + save_state(repo, {"disclaimer_version": None, "installed": {}}) + answers = iter(["yes", "5", "q"]) + menu_out: list[str] = [] + rc_menu = cli_main( + ["--repo-root", str(repo)], + env=env, + input_fn=lambda _prompt: next(answers), + output_fn=menu_out.append, + ) + assert rc_menu == 0 + assert load_state(repo)["disclaimer_version"] == DISCLAIMER_VERSION + assert any(DONATION_URL in line for line in menu_out) + + # JSON list & doctor subcommands + json_out: list[str] = [] + assert cli_main(["--repo-root", str(repo), "--json", "list"], env=env, output_fn=json_out.append) == 0 + parsed = json.loads("\n".join(json_out)) + assert len(parsed) == 19 + + +def test_cli_subcommands_env_config_doctor_install_uninstall_and_menu_actions(tmp_path): + repo = _seed_repo(tmp_path) + env = FakeEnv(tmp_path) + out: list[str] = [] + + assert cli_main(["--repo-root", str(repo), "status"], env=env, output_fn=out.append) == 0 + assert cli_main(["--repo-root", str(repo), "env", "--db"], env=env, output_fn=out.append) == 0 + assert cli_main(["--repo-root", str(repo), "--json", "env", "--dry-run"], env=env, output_fn=out.append) == 0 + assert cli_main(["--repo-root", str(repo), "config", "--edit", "config.ini"], env=env, output_fn=out.append) == 0 + assert cli_main(["--repo-root", str(repo), "config", "--edit", "unknown.ini"], env=env, output_fn=out.append) == 1 + assert cli_main(["--repo-root", str(repo), "--json", "doctor"], env=env, output_fn=out.append) == 0 + assert cli_main(["--repo-root", str(repo), "doctor"], env=env, output_fn=out.append) == 0 + + # Real non-dry-run install (systemd + cron + manual) & uninstall subcommands + assert ( + cli_main( + [ + "--repo-root", + str(repo), + "install", + "fee-adjuster", + "amboss-pull", + "--scheduler", + "systemd", + "--accept-disclaimer", + ], + env=env, + output_fn=out.append, + ) + == 0 + ) + assert ( + cli_main( + [ + "--repo-root", + str(repo), + "install", + "channel-base-fee", + "--scheduler", + "cron", + "--accept-disclaimer", + ], + env=env, + output_fn=out.append, + ) + == 0 + ) + assert ( + cli_main( + [ + "--repo-root", + str(repo), + "install", + "ps-peers", + "--scheduler", + "manual", + "--accept-disclaimer", + ], + env=env, + output_fn=out.append, + ) + == 0 + ) + assert cli_main(["--repo-root", str(repo), "uninstall", "--purge-configs"], env=env, output_fn=out.append) == 1 + assert cli_main(["--repo-root", str(repo), "uninstall"], env=env, output_fn=out.append) == 1 + assert ( + cli_main( + ["--repo-root", str(repo), "uninstall", "--all", "--json"], + env=env, + output_fn=out.append, + ) + == 0 + ) + + # Interactive menu actions: 1 (env), 2 (config+edit), 3 (install), 4 (uninstall), 6 (profile), bad option, quit + menu_out: list[str] = [] + answers = iter( + [ + "1", + "n", + "2", + "config.ini", + "3", + "fee-adjuster", + "cron", + "4", + "fee-adjuster", + "6", + "vps", + "99", + "q", + ] + ) + rc = cli_main( + ["--repo-root", str(repo)], + env=env, + input_fn=lambda _p: next(answers), + output_fn=menu_out.append, + ) + assert rc == 0 + assert any("Unknown option" in line for line in menu_out) + + +def test_configs_validation_edge_cases_and_editor(tmp_path): + repo = _seed_repo(tmp_path, valid_configs=False) + env = FakeEnv(tmp_path) + + # Missing config files detected cleanly + errs = validate_configs(repo, [get_tool("fee-adjuster"), get_tool("magma-market-fee")]) + assert any("Missing config.ini" in e for e in errs) + assert any("Missing feeConfig.json" in e for e in errs) + + # Invalid INI / JSON / Schedule values + (repo / "config.ini").write_text("[bad\n", encoding="utf-8") + (repo / "feeConfig.json").write_text("{not-json", encoding="utf-8") + (repo / "wallets.json").write_text("[]", encoding="utf-8") + (repo / "Magma" / "magma_config.ini").write_text("[bad\n", encoding="utf-8") + errs2 = validate_configs( + repo, + [get_tool("pocketmoney"), get_tool("fee-adjuster"), get_tool("magma-market-fee")], + ) + assert any("Invalid INI syntax in config.ini" in e for e in errs2) + assert any("Invalid JSON in feeConfig.json" in e for e in errs2) + assert any("wallets.json" in e for e in errs2) + assert any("Magma/magma_config.ini" in e for e in errs2) + + (repo / "config.ini").write_text( + "[Schedule]\nrecurrence = hourly\ntime = 99:99\n", encoding="utf-8" + ) + errs3 = validate_configs(repo, [get_tool("pocketmoney")]) + assert any("recurrence" in e for e in errs3) + assert any("HH:MM" in e for e in errs3) + + (repo / "config.ini").write_text( + "[Schedule]\nrecurrence = weekly\ntime = 09:00\nday_of_week = funday\n", + encoding="utf-8", + ) + errs4 = validate_configs(repo, [get_tool("pocketmoney")]) + assert any("day_of_week" in e for e in errs4) + + from lpt_installer.configs import open_in_editor + + assert open_in_editor(repo / "config.ini", env) is True + + +def test_doctor_warnings_and_system_env_adapter(tmp_path, monkeypatch): + repo = _seed_repo(tmp_path) + (repo / "logs").mkdir(exist_ok=True) + (repo / "logs" / "root.log").write_text("x", encoding="utf-8") + + # Exercise doctor when .venv is missing, ca_bundle is missing, legacy unit exists, and file uid == 0 + (repo / ".venv" / "bin" / "python3").unlink() + env = FakeEnv(tmp_path, ca_bundle=None) + (env.systemd_dir / "fee_adjuster.service").write_text("[Service]\n", encoding="utf-8") + + orig_stat = Path.stat + + class FakeStat: + def __init__(self, real_st, force_root: bool): + self.st_mode = real_st.st_mode + self.st_uid = 0 if force_root else real_st.st_uid + + monkeypatch.setattr( + Path, + "stat", + lambda self, *a, **kw: FakeStat( + orig_stat(self, *a, **kw), self.name == "root.log" + ), + ) + checks = {c["name"]: c for c in run_doctor(repo, env)} + assert checks["venv-certifi"]["status"] == "warn" + assert checks["ca-bundle"]["status"] == "fail" + assert checks["ownership"]["status"] == "warn" + assert checks["legacy-units"]["status"] == "warn" + + # Exercise real SystemEnv methods with mocked subprocess.run + real_env = SystemEnv( + systemd_dir=tmp_path / "sys_etc", + user_systemd_dir=tmp_path / "sys_user", + ) + real_env.systemd_dir.mkdir() + (real_env.systemd_dir / "demo.service").write_text("x", encoding="utf-8") + assert real_env.systemd_unit_exists("demo.service") is True + assert len(real_env.list_systemd_units()) == 1 + assert real_env.list_user_systemd_units() == [] + assert isinstance(real_env.current_user_group(), tuple) + + class FakeProc: + def __init__(self, rc=0, stdout="ok", stderr=""): + self.returncode = rc + self.stdout = stdout + self.stderr = stderr + + monkeypatch.setattr("subprocess.run", lambda *a, **kw: FakeProc(0, "123 python\n", "")) + assert real_env.read_crontab() == "123 python\n" + assert real_env.running_processes() == ["123 python"] + assert real_env.write_crontab("0 * * * * echo ok").returncode == 0 + assert real_env.sudo_install_file("[Unit]\n", tmp_path / "out.service").returncode == 0 + assert real_env.sudo_remove_file(tmp_path / "out.service").returncode == 0 + assert real_env.systemctl("daemon-reload").returncode == 0 + From ddd46a4005a97d19c4092603e65ca7a9b5e7083a Mon Sep 17 00:00:00 2001 From: Hakuna <35168804+TrezorHannes@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:39:18 +0100 Subject: [PATCH 2/4] fix(lint): remove unused sys import in lpt_installer.__main__ --- lpt_installer/__main__.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/lpt_installer/__main__.py b/lpt_installer/__main__.py index 4ea3611..50b83a4 100644 --- a/lpt_installer/__main__.py +++ b/lpt_installer/__main__.py @@ -2,8 +2,6 @@ from __future__ import annotations -import sys - from lpt_installer.cli import main if __name__ == "__main__": From 261a8940855dac437ce5ecf541d6c406d9a30a1c Mon Sep 17 00:00:00 2001 From: Hakuna <35168804+TrezorHannes@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:40:23 +0100 Subject: [PATCH 3/4] fix(ci): preserve default systemd unit search path in systemd-analyze verify --- .github/workflows/tests.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 44f205f..d36978b 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -133,7 +133,7 @@ jobs: encoding="utf-8", ) PY - SYSTEMD_UNIT_PATH="$UNIT_DIR:/etc/systemd/system" systemd-analyze verify --man=no "$UNIT_DIR"/*.service "$UNIT_DIR"/*.timer + SYSTEMD_UNIT_PATH="$UNIT_DIR:" systemd-analyze verify --man=no "$UNIT_DIR"/*.service "$UNIT_DIR"/*.timer security: runs-on: ubuntu-latest From ea4f510b5d97ebf8c070f0d518eaf77fa5b39dd2 Mon Sep 17 00:00:00 2001 From: Hakuna <35168804+TrezorHannes@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:45:48 +0100 Subject: [PATCH 4/4] fix(installer): address TunnelSentinel review findings (P1/P2/P3) - lpt_installer/configs.py: reject INVOICEID*, INVOICEKEY*, empty, and non-string values for wallets.json wallet_id/invoice_key. - lpt_installer/adapters.py: degrade gracefully when crontab binary is missing (return empty crontab on read, succeed on empty write, clear error on non-empty cron write). - lpt_installer/scheduler.py: only pass tool.unattended_args (--run-once) in systemd-timer mode (not systemd-service daemon mode), move cron flock lock file from /tmp into 0700 repo logs/, ignore managed MainPID when re-installing an active lpt-* daemon, and run systemctl try-restart after service unit updates. - lpt_installer/cli.py: catch KeyError for unknown tool IDs across config, install, and uninstall subcommands. - tests/test_lpt_installer.py: add regression tests for all 6 findings (223/223 passing, 88.80% lpt_installer coverage). --- lpt_installer/adapters.py | 8 ++++++ lpt_installer/cli.py | 32 ++++++++++++++------- lpt_installer/configs.py | 14 +++++++-- lpt_installer/scheduler.py | 40 ++++++++++++++++++++------ tests/test_lpt_installer.py | 57 +++++++++++++++++++++++++++++++++++-- 5 files changed, 127 insertions(+), 24 deletions(-) diff --git a/lpt_installer/adapters.py b/lpt_installer/adapters.py index 70334f4..ba18f49 100644 --- a/lpt_installer/adapters.py +++ b/lpt_installer/adapters.py @@ -147,6 +147,8 @@ def systemctl( return self.run(cmd, check=check) def read_crontab(self) -> str: + if self.which("crontab") is None: + return "" res = self.run(["crontab", "-l"], check=False) if res.returncode != 0: # No crontab installed yet for current user @@ -154,6 +156,12 @@ def read_crontab(self) -> str: return res.stdout def write_crontab(self, content: str) -> CommandResult: + if self.which("crontab") is None: + if not content.strip(): + return CommandResult(0, "", "") + raise RuntimeError( + "crontab binary not found; install cron or use --scheduler systemd." + ) if not content.strip(): # Keep user crontab empty cleanly without failing if none existed res = self.run(["crontab", "-r"], check=False) diff --git a/lpt_installer/cli.py b/lpt_installer/cli.py index 5cefe8b..501e278 100644 --- a/lpt_installer/cli.py +++ b/lpt_installer/cli.py @@ -391,7 +391,11 @@ def main( return 0 if args.command == "config": - selected = [get_tool(tid) for tid in args.tools] if args.tools else list(TOOLS) + try: + selected = [get_tool(tid) for tid in args.tools] if args.tools else list(TOOLS) + except KeyError as exc: + output_fn(f"Error: {exc}") + return 1 summary = ensure_configs(repo_root, selected, dry_run=args.dry_run) if args.edit and not args.dry_run: if args.edit not in CONFIG_TEMPLATES: @@ -410,7 +414,11 @@ def main( return 1 if errors else 0 if args.command == "install": - selected = [get_tool(tid) for tid in args.tools] + try: + selected = [get_tool(tid) for tid in args.tools] + except KeyError as exc: + output_fn(f"Error: {exc}") + return 1 if not args.dry_run and not ensure_disclaimer_accepted( repo_root, accept_flag=args.accept_disclaimer, @@ -460,14 +468,18 @@ def main( if not target_ids: output_fn("Error: specify tool IDs or --all.") return 1 - res = uninstall_tools( - target_ids, - repo_root, - sys_env, - remove_venv=args.remove_venv, - purge_configs=args.purge_configs, - dry_run=args.dry_run, - ) + try: + res = uninstall_tools( + target_ids, + repo_root, + sys_env, + remove_venv=args.remove_venv, + purge_configs=args.purge_configs, + dry_run=args.dry_run, + ) + except KeyError as exc: + output_fn(f"Error: {exc}") + return 1 if args.json: output_fn(json.dumps(res, indent=2)) else: diff --git a/lpt_installer/configs.py b/lpt_installer/configs.py index 52a7fcd..249f554 100644 --- a/lpt_installer/configs.py +++ b/lpt_installer/configs.py @@ -170,11 +170,21 @@ def validate_configs(repo_root: Path, tools: list[ToolSpec]) -> list[str]: if not isinstance(info, dict): errors.append(f"wallets.json entry {name!r} must be an object.") continue - if info.get("wallet_id", "").startswith("WALLETID"): + wallet_id = info.get("wallet_id") + if not isinstance(wallet_id, str) or not wallet_id.strip(): + errors.append( + f"wallets.json entry {name!r} is missing a valid wallet_id." + ) + elif wallet_id.strip().startswith("WALLETID"): errors.append( f"wallets.json entry {name!r} still uses placeholder wallet_id." ) - if info.get("invoice_key", "").startswith("INVOICEKEY"): + invoice_key = info.get("invoice_key") + if not isinstance(invoice_key, str) or not invoice_key.strip(): + errors.append( + f"wallets.json entry {name!r} is missing a valid invoice_key." + ) + elif invoice_key.strip().startswith(("INVOICEID", "INVOICEKEY")): errors.append( f"wallets.json entry {name!r} still uses placeholder invoice_key." ) diff --git a/lpt_installer/scheduler.py b/lpt_installer/scheduler.py index bfb7262..2e3dbb5 100644 --- a/lpt_installer/scheduler.py +++ b/lpt_installer/scheduler.py @@ -151,7 +151,8 @@ def render_systemd_service( py_exe = python_bin or venv_python_path(repo_root) script_abs = repo_root / tool.script_path - exec_parts = [str(py_exe), str(script_abs), *tool.unattended_args] + cli_args = tool.unattended_args if chosen_mode == "systemd-timer" else () + exec_parts = [str(py_exe), str(script_abs), *cli_args] exec_start = " ".join(shlex.quote(part) for part in exec_parts) after_list = ["network-online.target"] @@ -304,7 +305,7 @@ def render_cron_entry( cmd_parts = [str(py_exe), str(script_abs), *tool.unattended_args] cmd_str = " ".join(shlex.quote(part) for part in cmd_parts) log_path = shlex.quote(str(repo_root / "logs" / f"cron_{tool.id}.log")) - lock_path = shlex.quote(f"/tmp/lpt-{tool.id}.lock") + lock_path = shlex.quote(str(repo_root / "logs" / f".lpt-{tool.id}.lock")) repo_quoted = shlex.quote(str(repo_root)) return ( f"{cron_expr} cd {repo_quoted} && flock -n {lock_path} {cmd_str} >> {log_path} 2>&1" @@ -420,8 +421,26 @@ def detect_conflicts(tool: ToolSpec, env: SystemEnv) -> ConflictReport: running: list[str] = [] if not legacy_found: + managed_pid: str | None = None + if env.systemd_unit_exists(managed_service): + pid_res = env.systemctl( + "show", + "-p", + "MainPID", + "--value", + managed_service, + use_sudo=False, + check=False, + ) + candidate_pid = pid_res.stdout.strip() + if pid_res.returncode == 0 and candidate_pid.isdigit() and int(candidate_pid) > 0: + managed_pid = candidate_pid + for proc_line in env.running_processes(): if script_name in proc_line and "lpt_installer" not in proc_line: + proc_pid = proc_line.split(None, 1)[0] + if managed_pid and proc_pid == managed_pid: + continue running.append(proc_line) return ConflictReport( @@ -567,13 +586,15 @@ def install_tool( if not dry_run: # Ensure no leftover managed cron entry runs alongside systemd - updated_cron = remove_cron_tools( - env.read_crontab(), - [tool.id], - ca_bundle=ca_bundle, - home_dir=env.home_dir(), - ) - env.write_crontab(updated_cron) + existing_cron = env.read_crontab() + if tool.id in _split_cron_blocks(existing_cron)[1]: + updated_cron = remove_cron_tools( + existing_cron, + [tool.id], + ca_bundle=ca_bundle, + home_dir=env.home_dir(), + ) + env.write_crontab(updated_cron) env.sudo_install_file(service_content, service_path) if timer_content is not None: @@ -586,6 +607,7 @@ def install_tool( env.sudo_remove_file(timer_path) env.systemctl("daemon-reload", use_sudo=True, check=True) env.systemctl("enable", "--now", f"{prefix}.service", use_sudo=True, check=True) + env.systemctl("try-restart", f"{prefix}.service", use_sudo=True, check=True) state["installed"][tool.id] = { "mode": chosen_mode, diff --git a/tests/test_lpt_installer.py b/tests/test_lpt_installer.py index b1e01c6..708189b 100644 --- a/tests/test_lpt_installer.py +++ b/tests/test_lpt_installer.py @@ -247,6 +247,17 @@ def test_render_systemd_units_hardening_and_sandbox(tmp_path): assert "--run-once" in pm_service assert "[Install]" not in pm_service + pm_daemon = render_systemd_service( + pm, + repo, + user="admin", + group="admin", + mode="systemd-service", + unit_exists=lambda _: False, + ) + assert "Type=simple" in pm_daemon + assert "--run-once" not in pm_daemon + pm_timer = render_systemd_timer(pm, "Fri *-*-* 09:30:00") assert "OnCalendar=Fri *-*-* 09:30:00" in pm_timer assert "Persistent=true" in pm_timer @@ -298,7 +309,8 @@ def test_cron_managed_block_idempotency_and_preservation(tmp_path): assert first == second assert CRON_BEGIN in first assert CRON_END in first - assert "flock -n /tmp/lpt-fee-adjuster.lock" in first + assert "logs/.lpt-fee-adjuster.lock" in first + assert "/tmp/lpt-" not in first assert "pull_lndg_backup.sh" in first cleaned = remove_cron_tools(first, ["fee-adjuster"]) @@ -313,11 +325,12 @@ def test_config_copy_no_clobber_chmod_600_and_validation(tmp_path): assert stat.S_IMODE((repo / "wallets.json").stat().st_mode) == 0o600 assert stat.S_IMODE((repo / "logs").stat().st_mode) == 0o700 - # Placeholders must fail validation + # Placeholders must fail validation (including INVOICEID1 from wallets.json.example) errors = validate_configs(repo, [get_tool("pocketmoney")]) assert any("base_url" in err for err in errors) assert any("admin_key" in err for err in errors) - assert any("WALLETID" in err or "wallet_id" in err for err in errors) + assert any("wallet_id" in err for err in errors) + assert any("invoice_key" in err for err in errors) # Custom contents must never be clobbered on second run (repo / "config.ini").write_text("[LNBits]\nbase_url = https://my.node\n", encoding="utf-8") @@ -655,3 +668,41 @@ def __init__(self, rc=0, stdout="ok", stderr=""): assert real_env.sudo_remove_file(tmp_path / "out.service").returncode == 0 assert real_env.systemctl("daemon-reload").returncode == 0 + # Missing crontab binary must not crash read_crontab or empty write_crontab + monkeypatch.setattr(real_env, "which", lambda _b: None) + assert real_env.read_crontab() == "" + assert real_env.write_crontab("").returncode == 0 + with pytest.raises(RuntimeError, match="crontab binary not found"): + real_env.write_crontab("0 * * * * echo hi") + + +def test_reinstall_running_managed_daemon_and_unknown_tool_errors(tmp_path): + repo = _seed_repo(tmp_path) + + class DaemonEnv(FakeEnv): + def systemctl(self, *args: str, use_sudo: bool = True, check: bool = True) -> CommandResult: + self.commands.append(["systemctl", *args]) + if args[:4] == ("show", "-p", "MainPID", "--value"): + return CommandResult(0, "5555\n", "") + return CommandResult(0, "", "") + + env = DaemonEnv(tmp_path, processes=[]) + magma = get_tool("magma-sale") + # First install creates managed unit + install_tool(magma, repo, env, mode="systemd-service") + # Re-install with MainPID=5555 active must succeed and call try-restart + env._processes.append("5555 /repo/.venv/bin/python3 Magma/magma_sale_process.py") + install_tool(magma, repo, env, mode="systemd-service") + assert any(cmd == ["systemctl", "try-restart", "lpt-magma-sale.service"] for cmd in env.commands) + + # An extra unmanaged PID must still fail closed + env._processes.append("6666 python3 magma_sale_process.py") + with pytest.raises(RuntimeError, match="unmanaged duplicate"): + install_tool(magma, repo, env, mode="systemd-service") + + # Unknown tool IDs in CLI subcommands must exit 1 cleanly (no KeyError traceback) + out: list[str] = [] + assert cli_main(["--repo-root", str(repo), "install", "no-such-tool"], env=env, output_fn=out.append) == 1 + assert cli_main(["--repo-root", str(repo), "config", "--tools", "no-such-tool"], env=env, output_fn=out.append) == 1 + assert cli_main(["--repo-root", str(repo), "uninstall", "no-such-tool"], env=env, output_fn=out.append) == 1 +