Remove ntfy: notifications go only through the app notification stream

Server: drop ntfy publishing (stage hooks, run outbox, chat attention, chat
tool notify, auto-switch and schedule notices), the chat push outbox (its
table is dropped at startup), ntfy status/endpoints and PIPELINES_NTFY_*.
The app_notifications stream, subscribe/clear and kinds are unchanged.
Notification settings keep run_finished/chat_needs_you/chat_reply_finished;
ntfy_enabled is accepted and ignored and its stored row is never read.

Stage type=ntfy is rejected: "ntfy stages were removed; notifications go to
the Pipelines apps — use the stage notify hook". The notify hook remains.

Installer: no ntfy build, accounts, config or supervisor child; manifest
gets top-level "mode" (legacy ntfy.mode still read). Reinstall retires an
old ntfy (safe PID-file stop, deletes binary, config, data dir, token, log,
with a note in logs/install.log); uninstall cleans leftovers.

App: ntfy settings section replaced by "Notification events"; texts updated.
Docs: docs/ntfy.md folded into docs/notifications.md; install, docker, cli,
author skill references updated; security review M1 marked resolved.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-03 23:24:24 +00:00
parent 806b5eca46
commit fc7dbb0ac0
138 changed files with 1958 additions and 4651 deletions
+6 -25
View File
@@ -5,7 +5,6 @@ import json
import os
from pathlib import Path
import tempfile
from urllib.parse import urlparse
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
@@ -74,49 +73,31 @@ def configure_client(endpoint, environ=None):
return path
def configure(directory, ntfy_url, bind_address, timezone=None, port=8081):
def configure(directory, timezone=None, port=8081):
directory = Path(directory)
url = urlparse(ntfy_url)
if (url.scheme not in ("http", "https") or not url.hostname or url.username
or url.password or url.query or url.fragment or url.path not in ("", "/")):
raise ValueError("--ntfy-url must be an HTTP(S) base URL without credentials or a topic")
timezone = timezone or host_timezone()
ZoneInfo(timezone)
for value in (ntfy_url, bind_address, timezone):
if any(char in value for char in "\r\n\x00$#'\" "):
raise ValueError("Unsafe configuration value")
if any(char in timezone for char in "\r\n\x00$#'\" "):
raise ValueError("Unsafe configuration value")
if not 1 <= port <= 65535:
raise ValueError("Invalid pipeline port")
settings = directory / ".env"
if settings.exists():
raise ValueError(".env exists; edit it rather than overwrite existing settings")
workspace_values = host_workspaces(directory)
secrets = directory / "secrets"
secrets.mkdir(mode=0o700, exist_ok=True)
token = secrets / "ntfy-token.txt"
# Empty until ntfy has issued a token. Never replace an existing credential.
try:
fd = os.open(token, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
os.close(fd)
except FileExistsError:
pass
with settings.open("x") as file:
file.write(f"TZ={timezone}\nNTFY_BASE_URL={ntfy_url.rstrip('/')}\n"
f"NTFY_BIND_ADDRESS={bind_address}\nPIPELINES_PORT={port}\n")
file.write(f"TZ={timezone}\nPIPELINES_PORT={port}\n")
for key, value in workspace_values.items(): file.write(key+"="+value+"\n")
return timezone
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--ntfy-url", required=True)
parser.add_argument("--bind-address", default="0.0.0.0")
parser.add_argument("--timezone")
parser.add_argument("--port", type=int, default=8081)
args = parser.parse_args()
try:
zone = configure(Path(__file__).resolve().parents[1], args.ntfy_url,
args.bind_address, args.timezone, args.port)
zone = configure(Path(__file__).resolve().parents[1], args.timezone, args.port)
except (ValueError, ZoneInfoNotFoundError) as error:
parser.error(str(error))
print(f"Created .env with timezone {zone}. Configure the ntfy token before starting pipelines.")
print(f"Created .env with timezone {zone}.")
+1 -1
View File
@@ -78,4 +78,4 @@ def detect_lan(runner=subprocess.run, platform=sys.platform, route_probe=None):
return address
except OSError:
pass
raise ValueError("No LAN IPv4 address detected. Connect this computer to your LAN and rerun ./install, or override with --ntfy-url and --bind-address.")
raise ValueError("No LAN IPv4 address detected. Connect this computer to your LAN and rerun ./install.")
+101 -75
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
"""One per-user lifecycle for the server, authenticated web proxy and ntfy."""
"""One per-user lifecycle for the server and the authenticated web proxy."""
import argparse
import fcntl
import json
@@ -20,13 +20,12 @@ MARKER = "pipelines-install.json"
SERVICE_MARKER = "Managed by Pipelines native installer"
def ntfy_mode(config):
"""Native ntfy is selected by the manifest; absent/explicit docker uses Compose."""
return (config.get("ntfy") or {}).get("mode", "docker")
def install_mode(config):
""""native" for the native installer's manifest, else "docker".
def ntfy_health_url(config):
return f"http://127.0.0.1:{config['ntfy_port']}/v1/health"
Manifests record a top-level "mode"; ones written before it marked a native
install with ntfy.mode, which is still accepted until the next ./install."""
return config.get("mode") or (config.get("ntfy") or {}).get("mode") or "docker"
def server_address(config):
@@ -84,7 +83,7 @@ def load(prefix):
def run(args, *, env=None, quiet=False, check=True, timeout=120):
result = subprocess.run(args, env=env, capture_output=True, text=True, timeout=timeout)
if check and result.returncode:
# No subprocess output here: ntfy token/password commands may contain secrets.
# No subprocess output here: tool output may contain secrets.
raise RuntimeError(f"Command failed ({result.returncode}): {args[0]} {args[1] if len(args)>1 else ''}")
if not quiet and result.stdout:
print(result.stdout.rstrip())
@@ -142,7 +141,7 @@ def registration(config):
def service_command(config, arguments):
parser = argparse.ArgumentParser(prog="pipelines service",
description="Manage this native installation's server, authenticated web and ntfy login service.")
description="Manage this native installation's server and authenticated web login service.")
parser.add_argument("action", choices=("enable", "disable", "status"))
parser.add_argument("--print", dest="preview", action="store_true",
help="Preview enable's existing service definition without changing or starting anything")
@@ -152,7 +151,7 @@ def service_command(config, arguments):
args = parser.parse_args(arguments)
if args.preview and args.action != "enable":
parser.error("--print is only supported with enable")
if ntfy_mode(config) != "native" or config.get("label") != "net.a-wan.pipelines" or not registration(config):
if install_mode(config) != "native" or config.get("label") != "net.a-wan.pipelines" or not registration(config):
raise ValueError("No native installer login service is recorded; rerun ./install")
path = Path(registration(config))
if platform.system() == "Darwin":
@@ -186,7 +185,7 @@ def service_command(config, arguments):
print(content, end="")
elif args.action == "enable":
start(config)
print("Native login autostart enabled: server, authenticated web and ntfy.")
print("Native login autostart enabled: server and authenticated web.")
elif args.action == "disable":
if platform.system() == "Darwin":
run(["launchctl", "disable", f"gui/{os.getuid()}/{config['label']}"], quiet=True)
@@ -266,48 +265,93 @@ def stop(config):
time.sleep(0.2)
if managed_pid(config) is not None:
raise RuntimeError("Supervisor did not stop; inspect logs before trying again")
if ntfy_mode(config) == "native":
ntfy_stop(config)
else:
compose(config, "stop", "ntfy", quiet=True)
# Installs from before ntfy was removed ran it beside the server.
stop_legacy_ntfy(config)
def ntfy_start(config):
info = config["ntfy"]
log = (Path(config["prefix"]) / "logs/ntfy.log").open("a")
child = subprocess.Popen([info["bin"], "serve", "--config", info["config"]],
stdin=subprocess.DEVNULL, stdout=log, stderr=log, start_new_session=True)
log.close()
(Path(config["prefix"]) / "ntfy.pid").write_text(str(child.pid))
return child
# --- retired ntfy ---------------------------------------------------------
# Pipelines no longer runs ntfy: notifications reach the apps through the
# server's own notification stream. Older installs left a supervised ntfy
# process, its binary, configuration, data and publishing token behind; these
# helpers stop and remove exactly those, idempotently.
def legacy_ntfy_pid(config):
"""The PID in <prefix>/ntfy.pid while it is still the managed `ntfy serve`.
def ntfy_stop(config):
path = Path(config["prefix"]) / "ntfy.pid"
Never an arbitrary/reused PID: the command line must run <prefix>/bin/ntfy
(or the binary the old manifest recorded, or a symlink-resolved form, so a
prefix reached through a symlinked HOME such as macOS /var → /private/var
still matches) with `serve`. A reaped or zombie process no longer matches."""
root = Path(config["prefix"])
try:
pid = int(path.read_text())
pid = int((root / "ntfy.pid").read_text())
except (OSError, ValueError):
return
return None
if pid <= 1:
return
return None
command = process_command(pid)
# Never signal an arbitrary/reused PID: only the managed ntfy serve process.
# Accept the recorded path or its symlink-resolved form so a prefix reached
# through a symlinked HOME (macOS /var → /private/var) is still matched.
binary = str(config["ntfy"]["bin"])
candidates = {binary, str(Path(binary).resolve())}
if command is None or "serve" not in command or not any(candidate in command for candidate in candidates):
path.unlink(missing_ok=True)
return
os.kill(pid, signal.SIGTERM)
deadline = time.monotonic() + 10
while time.monotonic() < deadline:
binaries = {str(root / "bin/ntfy"), str((root / "bin/ntfy").resolve())}
recorded = (config.get("ntfy") or {}).get("bin")
if recorded:
binaries.update((str(recorded), str(Path(recorded).resolve())))
if command is None or "serve" not in command.split() or not any(binary in command for binary in binaries):
return None
return pid
def stop_legacy_ntfy(config, timeout=10):
"""Stops a leftover managed ntfy and forgets its PID file; True if one ran."""
pid = legacy_ntfy_pid(config)
if pid is not None:
try:
os.kill(pid, 0)
os.kill(pid, signal.SIGTERM)
except ProcessLookupError:
break
time.sleep(0.1)
path.unlink(missing_ok=True)
pid = None
deadline = time.monotonic() + timeout
while pid is not None and legacy_ntfy_pid(config) == pid and time.monotonic() < deadline:
time.sleep(0.1)
if pid is not None and legacy_ntfy_pid(config) == pid:
try:
os.kill(pid, signal.SIGKILL)
except ProcessLookupError:
pass
(Path(config["prefix"]) / "ntfy.pid").unlink(missing_ok=True)
return pid is not None
def legacy_ntfy_paths(root):
"""Everything an older install created for ntfy under the prefix."""
root = Path(root)
return [root / "bin/ntfy", root / "ntfy.pid", root / "logs/ntfy.log",
root / "data/ntfy", root / "secrets/publisher-token"]
def retire_ntfy(config, note=print):
"""Stops and removes an older install's ntfy; a no-op once it is gone.
``config`` is the old manifest (or any dict with "prefix"). Before anything
is removed ``note`` receives a line naming what goes (paths and the old
ntfy version, never credentials). Only the fixed paths under the prefix are
removed, never paths read from the manifest. Returns the removed paths."""
root = Path(config["prefix"])
present = [path for path in legacy_ntfy_paths(root) if path.exists() or path.is_symlink()]
legacy = config.get("ntfy") or {}
if not present and not legacy:
stop_legacy_ntfy(config)
return []
version = legacy.get("version") or "unknown"
note(f"Retiring ntfy (version {version}); Pipelines no longer uses it. Removing: "
+ (", ".join(map(str, present)) or "nothing left on disk") + ".")
if stop_legacy_ntfy(config):
note("Stopped the old ntfy server process.")
if install_mode(config) != "native" and (root / "compose.yaml").is_file() and config.get("docker") and config.get("project"):
compose(config, "rm", "--stop", "--force", "ntfy", quiet=True, check=False)
for path in present:
if path.is_dir() and not path.is_symlink():
shutil.rmtree(path)
else:
path.unlink(missing_ok=True)
return present
def server_report(config):
@@ -370,7 +414,8 @@ def update(config):
"""Brings this installation to the newest source: pull, reinstall the same
way it was installed (data and credentials kept), restart, report."""
source = Path(config.get("source") or "")
if not (source / "install.sh").is_file():
# No recorded source must not fall back to the current directory.
if not config.get("source") or not (source / "install.sh").is_file():
raise ValueError("This installation does not record its source checkout; "
"run ./install from your Pipelines checkout to update it")
if healthy(f"http://127.0.0.1:{config['server_port']}/healthz"):
@@ -408,13 +453,12 @@ def supervise(config):
pidfile.write_text(str(os.getpid()))
stopped = False
child = None
ntfy_child = None
web_child = None
def stopping(*_):
nonlocal stopped
stopped = True
for process in (child, ntfy_child, web_child):
for process in (child, web_child):
if process is not None and process.poll() is None:
process.terminate()
@@ -422,20 +466,13 @@ def supervise(config):
signal.signal(signal.SIGINT, stopping)
try:
require_web_app(config)
if ntfy_mode(config) == "native":
ntfy_child = ntfy_start(config)
else:
compose(config, "up", "-d", "ntfy", quiet=True)
wait_health(ntfy_health_url(config))
# An ntfy an older supervisor left running is stopped, not reused.
stop_legacy_ntfy(config)
if stopped:
return
env = dict(os.environ)
env = {key: value for key, value in os.environ.items() if not key.startswith("PIPELINES_NTFY_")}
env.update(config.get("opencode_env", {}))
env.update(HOME=str(Path.home()), PATH=config["path"], TZ=config["timezone"],
PIPELINES_NTFY_URL=f"http://127.0.0.1:{config['ntfy_port']}/{config['topic']}",
PIPELINES_NTFY_PUBLIC_URL=config["public_url"],
PIPELINES_NTFY_TOKEN_FILE=str(root / "secrets/publisher-token"))
env.pop("PIPELINES_NTFY_TOKEN", None)
env.update(HOME=str(Path.home()), PATH=config["path"], TZ=config["timezone"])
# The server requires, and the proxy and every child CLI send, the
# shared token in this file (installs from before it have none).
env.update(server_token_env(config))
@@ -483,17 +520,6 @@ def supervise(config):
except subprocess.TimeoutExpired:
child.kill()
child.wait()
if ntfy_mode(config) == "native":
if ntfy_child is not None and ntfy_child.poll() is None:
ntfy_child.terminate()
try:
ntfy_child.wait(timeout=10)
except subprocess.TimeoutExpired:
ntfy_child.kill()
ntfy_child.wait()
(root / "ntfy.pid").unlink(missing_ok=True)
else:
compose(config, "stop", "ntfy", quiet=True, check=False)
pidfile.unlink(missing_ok=True)
@@ -501,15 +527,17 @@ def uninstall(config, purge=False, yes=False):
root = Path(config["prefix"])
if not yes and input("Uninstall Pipelines? [y/N] ").strip().lower() != "y":
return
if purge and not yes and input("Also DELETE pipeline history, credentials, and this install's ntfy volume? Type DELETE: ") != "DELETE":
if purge and not yes and input("Also DELETE pipeline history and credentials? Type DELETE: ") != "DELETE":
raise ValueError("Purge canceled; nothing deleted")
stop(config)
if registration(config):
if platform.system() != "Darwin":
run(["systemctl", "--user", "disable", config["label"] + ".service"], quiet=True, check=False)
Path(registration(config)).unlink(missing_ok=True)
if ntfy_mode(config) != "native":
compose(config, "down", *(["--volumes"] if purge else []), quiet=True)
# Anything an older install left for ntfy goes too, manifest or not.
retire_ntfy(config)
if install_mode(config) != "native" and (root / "compose.yaml").is_file():
compose(config, "down", "--remove-orphans", *(["--volumes"] if purge else []), quiet=True)
link = Path(config["launcher"])
if link.is_symlink() and link.resolve() == (root / "bin/pipelines").resolve():
if str(link)=="/usr/local/bin/pipelines" and not os.access(link.parent,os.W_OK):
@@ -519,7 +547,7 @@ def uninstall(config, purge=False, yes=False):
if purge:
# Only the explicitly identified, owned installation directory is removed.
shutil.rmtree(root)
print("Removed installation and its pipeline/ntfy data. Host OpenCode was untouched.")
print("Removed installation and its pipeline data. Host OpenCode was untouched.")
else:
for path in (root / "bin", root / "lib"):
if path.exists():
@@ -527,7 +555,7 @@ def uninstall(config, purge=False, yes=False):
config["registration"] = None
config["uninstalled"] = True
(root / MARKER).write_text(json.dumps(config, indent=2))
print(f"Uninstalled. Data and ntfy volume retained at {root}; reinstall to reuse them.")
print(f"Uninstalled. Data retained at {root}; reinstall to reuse it.")
def main():
@@ -569,8 +597,6 @@ def main():
elif args.action in ("status", "doctor"):
report(config)
print("Pipeline server:", "healthy" if healthy(f"http://127.0.0.1:{config['server_port']}/healthz") else "stopped/unhealthy")
print("ntfy:", "healthy" if healthy(ntfy_health_url(config)) else "stopped/unhealthy")
print("Phone server:", config["public_url"], "· topic:", config["topic"], "· username:", config["username"])
if args.action == "doctor":
run([config["opencode"], "api", "get", "/api/info"], quiet=True)
print("Host OpenCode API: responding (model execution is a separate check)")
+2 -36
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
"""Bounded resolution of current harness and ntfy releases for installation.
"""Bounded resolution of current harness releases for installation.
Network I/O is isolated behind an injectable ``fetch`` callable so unit tests
never touch the network. The resolver:
@@ -17,9 +17,6 @@ never touch the network. The resolver:
closed when it is missing or invalid, never falling back to an older version;
* resolves the exact Pi package version and validates its Node engine
constraint fail-closed;
* resolves the exact ntfy release tag that the native installer builds its
server from, because upstream publishes only a client-only binary for macOS
and the server is therefore compiled from the pinned Go module on every host;
* validates untrusted metadata, versions, digests and fixture values;
* refuses any host outside the explicit allowlist (the container registry, the
GitHub API and the npm registry) and refuses any redirect that leaves it.
@@ -43,18 +40,11 @@ NPM = "https://registry.npmjs.org"
OPENCODE_REPOSITORY = "anomalyco/opencode"
OPENCODE_IMAGE = "ghcr.io/anomalyco/opencode"
PI_PACKAGE = "@earendil-works/pi-coding-agent"
NTFY_REPOSITORY = "binwiederhier/ntfy"
# The ntfy Go module the native installer builds a server from. Upstream only
# publishes a client-only binary for macOS, so both platforms compile the server
# from this module at the resolved tag (Go verifies the module via its checksum
# database).
NTFY_MODULE = "heckel.io/ntfy/v2"
MAX_REFS = 1000 # Explicit ceiling on the documented complete matching-refs array.
MAX_BODY = 1 << 20 # Generous ceiling for tag lists and manifest metadata.
SUPPORTED_MAJOR = 2
HTTP_TIMEOUT = 5.0
# Registry, GitHub API and npm metadata hosts only. The native installer builds
# ntfy from its Go module, so no release-asset download hosts are needed.
# Registry, GitHub API and npm metadata hosts only; no release-asset downloads.
ALLOWED_HOSTS = frozenset({"ghcr.io", "api.github.com", "registry.npmjs.org"})
GITHUB_HEADERS = {"Accept": "application/vnd.github+json", "User-Agent": "pipelines-setup"}
MANIFEST_ACCEPT = ", ".join([
@@ -272,30 +262,6 @@ def resolve_pi(fetch=_default_fetch, node_version=None):
return {"package": PI_PACKAGE, "version": version, "engine": engine}
def _github_ntfy_tags(fetch):
"""One bounded request for the complete ntfy vX.Y.Z matching-refs array."""
return _github_matching_refs(fetch, NTFY_REPOSITORY, "v")
def resolve_ntfy(fetch=_default_fetch):
"""Resolve the exact ntfy release the native installer builds from source.
The selected version comes from the complete official matching-refs tag list
(never the moving ``latest`` release and never an older fallback); a missing
or malformed tag list fails closed. The native installer then compiles the
server from the pinned ``heckel.io/ntfy/v2`` module, so no release assets or
their checksums are downloaded here.
"""
candidates = _github_ntfy_tags(fetch)
if not candidates:
raise ReleaseError("no stable ntfy release found in the official tag metadata")
tag = max(candidates, key=lambda name: candidates[name])
version = registry_tag(tag)
if parse_version(version) is None:
raise ReleaseError(f"resolved ntfy tag is not an exact version: {tag!r}")
return {"repository": NTFY_REPOSITORY, "module": NTFY_MODULE, "version": version, "tag": tag}
def resolve(fetch=_default_fetch, node_version=None):
return {"opencode": resolve_opencode(fetch), "pi": resolve_pi(fetch, node_version)}
+1 -9
View File
@@ -1,13 +1,5 @@
#!/bin/sh
# Keep OpenCode local; only ntfy runs in Docker. Public URL contains no secret.
# Run the server from source against the local OpenCode.
set -eu
cd "$(dirname "$0")/.."
if [ -z "${PIPELINES_NTFY_PUBLIC_URL:-}" ]; then
PIPELINES_NTFY_PUBLIC_URL=$(sed -n 's/^NTFY_BASE_URL=//p' .env)
fi
export PIPELINES_NTFY_PUBLIC_URL
export PIPELINES_NTFY_URL="${PIPELINES_NTFY_URL:-http://127.0.0.1:8090/pipelines}"
if [ -z "${PIPELINES_NTFY_TOKEN:-}" ]; then
export PIPELINES_NTFY_TOKEN_FILE="${PIPELINES_NTFY_TOKEN_FILE:-$(pwd)/secrets/ntfy-token.txt}"
fi
exec go run ./cmd/pipelines-server "$@"
-75
View File
@@ -1,75 +0,0 @@
#!/usr/bin/env python3
"""Shared ntfy credential helpers: token extraction and account bootstrap.
Both installers (native and Docker) create the same publisher/reader accounts on
ntfy, so the extraction, symlink/non-empty guard and writing live here once.
Never print a credential.
"""
import os
from pathlib import Path
import re
import sys
TOKEN_PATTERN = re.compile(r"\btk_[A-Za-z0-9]{29}\b")
def save_token(output, path, mode=0o444):
"""Write the single token found in ``output`` to ``path``.
``mode`` is 0444 for Compose's file secret (read by container uid 10001) and
0600 for the native install, whose server runs as the installing user.
"""
tokens = TOKEN_PATTERN.findall(output or "")
if len(tokens) != 1:
raise ValueError("ntfy did not return exactly one token; existing credentials were not changed")
path = Path(path)
path.parent.mkdir(mode=0o700, exist_ok=True)
path.parent.chmod(0o700)
if path.is_symlink() or (path.exists() and path.stat().st_size != 0):
raise ValueError("Token file already contains credentials; refusing to overwrite")
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "w") as file:
file.write(tokens[0] + "\n")
path.chmod(mode)
return path
def bootstrap_accounts(run, token_path, mode=0o444, log=print, publisher_password=None,
reader_password=None):
"""Create the pipeline-publisher and phone-reader accounts on an ntfy server.
``run(args, capture=False, interactive=False, password=None)`` executes the ntfy
CLI (directly or through Compose) and returns the completed process; a given
password is supplied without a prompt. Without one the CLI asks on the
terminal. Existing accounts and an existing token file are preserved on
reinstall.
"""
token_path = Path(token_path)
if token_path.is_symlink():
raise ValueError("Refusing a symlink for the publishing token")
if token_path.exists() and token_path.stat().st_size:
log("Keeping existing ntfy publishing token.")
else:
if publisher_password is None:
log("Set a password for ntfy's pipeline-publisher account (not a model-provider account).")
run(["user", "add", "--ignore-exists", "pipeline-publisher"], interactive=True)
else:
run(["user", "add", "--ignore-exists", "pipeline-publisher"], password=publisher_password)
run(["access", "pipeline-publisher", "pipelines", "write-only"])
result = run(["token", "add", "pipeline-publisher"], capture=True)
save_token(result.stdout + result.stderr, token_path, mode)
# --ignore-exists preserves the phone account's password on reinstall.
if reader_password is None:
log("Set the phone-reader password if this is a new ntfy account; existing accounts are preserved.")
run(["user", "add", "--ignore-exists", "phone-reader"], interactive=True)
else:
run(["user", "add", "--ignore-exists", "phone-reader"], password=reader_password)
run(["access", "phone-reader", "pipelines", "read-only"])
if __name__ == "__main__":
try:
save_token(sys.stdin.read(), Path(__file__).resolve().parents[1] / "secrets/ntfy-token.txt", 0o444)
except ValueError as error:
sys.exit(str(error))
print("Saved ntfy publishing token; restart pipelines if it was already running.")
+53 -55
View File
@@ -2,7 +2,6 @@
"""Configure, authenticate and verify the full Docker installation."""
import argparse
import importlib.util
import ipaddress
import re
import shutil
import json
@@ -21,7 +20,6 @@ def module(name, file):
configure = module("configure_compose", "configure-compose.py")
tokens = module("save_ntfy_token", "save-ntfy-token.py")
lan = module("lan_address", "lan-address.py")
build_metadata = module("build_metadata", "build_metadata.py")
release_lookup = module("resolve_releases", "resolve-releases.py")
@@ -67,32 +65,30 @@ class Setup:
result = self.runner(["docker", "compose", *args], cwd=self.directory,
capture_output=capture, text=True, **kwargs)
if check and result.returncode:
# Captured ntfy output may contain tokens. Never replay it on failure.
# Captured tool output may contain credentials. Never replay it on failure.
raise ValueError(f"Docker setup step failed (exit {result.returncode}); no credentials were replaced")
return result
def settings(self, args):
settings = self.directory / ".env"
bind = str(ipaddress.IPv4Address(args.bind_address or "0.0.0.0"))
if settings.is_symlink():
raise ValueError("Refusing to modify a symlinked .env")
if settings.exists():
if any((args.ntfy_url, args.timezone, args.port)):
if any((args.timezone, args.port)):
raise ValueError(".env already exists; edit it explicitly rather than replace existing configuration")
text = settings.read_text()
for key, value in (("NTFY_BIND_ADDRESS", bind),
("PIPELINES_BIND_ADDRESS", "0.0.0.0")):
if any(line.startswith(key + "=") for line in text.splitlines()):
text = "".join(key + "=" + value + "\n" if line.startswith(key + "=") else line
for line in text.splitlines(keepends=True))
else:
text = text.rstrip("\n") + "\n" + key + "=" + value + "\n"
# ntfy's settings from older installs are dropped (see retire_ntfy).
lines = [line for line in settings.read_text().splitlines(keepends=True)
if not line.startswith(("NTFY_BASE_URL=", "NTFY_BIND_ADDRESS="))]
text = "".join(lines)
key, value = "PIPELINES_BIND_ADDRESS", "0.0.0.0"
if any(line.startswith(key + "=") for line in lines):
text = "".join(key + "=" + value + "\n" if line.startswith(key + "=") else line for line in lines)
else:
text = text.rstrip("\n") + "\n" + key + "=" + value + "\n"
if text != settings.read_text():
settings.write_text(text)
print(f"Docker binds: ntfy {bind}, Pipelines 0.0.0.0; existing URLs, timezone, ports and credentials retained.")
print("Docker binds: Pipelines 0.0.0.0; existing timezone, ports and credentials retained.")
return
address = lan.detect_lan() if not args.ntfy_url else None
url = args.ntfy_url or f"http://{address}:8090"
timezone = args.timezone
if not timezone:
try:
@@ -100,18 +96,35 @@ class Setup:
except ValueError:
timezone = "UTC"
print("Host timezone unavailable; using UTC (override with --timezone if needed).")
configure.configure(self.directory, url, bind, timezone, args.port or 8081)
print(f"LAN notifications configured: {url} (bind {bind}; authentication required).")
print("Use this address on your phone on the same trusted LAN; do not forward this HTTP port to the Internet.")
configure.configure(self.directory, timezone, args.port or 8081)
def bootstrap_ntfy(self):
def run_ntfy(args, capture=False, interactive=False):
# -T is required for the non-interactive calls; the interactive
# `user add` password prompts need the allocated TTY.
exec_args = ["exec"] + ([] if interactive else ["-T"]) + ["ntfy", "ntfy", *args]
return self.compose(*exec_args, capture=capture)
tokens.bootstrap_accounts(run_ntfy, self.directory / "secrets/ntfy-token.txt", 0o444)
def retire_ntfy(self):
"""Removes the ntfy container, volume and token an older Docker install
created; Pipelines no longer runs ntfy. Idempotent."""
project = json.loads(self.compose("config", "--format", "json", capture=True).stdout).get("name") or "pipelines"
if not re.fullmatch(r"[a-z0-9][a-z0-9_-]*", project):
raise ValueError("Unexpected Compose project name; no ntfy resources were removed")
removed = []
containers = self.runner(["docker", "ps", "-aq", "--filter", f"label=com.docker.compose.project={project}",
"--filter", "label=com.docker.compose.service=ntfy"],
capture_output=True, text=True)
ids = [name for name in (containers.stdout or "").split() if re.fullmatch(r"[0-9a-f]+", name)]
if not containers.returncode and ids:
self.runner(["docker", "rm", "-f", *ids], capture_output=True, text=True)
removed.append("container")
volume = f"{project}_ntfy-data"
volumes = self.runner(["docker", "volume", "ls", "-q", "--filter", f"name=^{volume}$"],
capture_output=True, text=True)
if not volumes.returncode and volume in (volumes.stdout or "").split():
self.runner(["docker", "volume", "rm", volume], capture_output=True, text=True)
removed.append(f"volume {volume}")
token = self.directory / "secrets/ntfy-token.txt"
if token.exists() or token.is_symlink():
token.unlink()
removed.append(str(token))
if removed:
print("Retired the old ntfy notification server (" + ", ".join(removed)
+ "); notifications now come through the Pipelines apps.")
def authenticate(self, relogin=False):
def connected():
@@ -257,8 +270,8 @@ exec pipelines provider-check --model "$1" --yes --json --timeout 90s
raise ValueError("Host client update failed; Docker setup is incomplete")
print("Updated host CLI/TUI using go install. Restart the running TUI; an already-running process keeps its old code.")
def publish_address(self):
address = lan.detect_lan()
def publish_address(self, address=None):
address = address or lan.detect_lan()
path = self.directory/".env"
text = path.read_text()
key = "PIPELINES_HOST_IP="
@@ -501,23 +514,11 @@ printf 'node=%s\\n' "$(node --version)"
print("Verified running server build: " + build["version"] + " (" + build["commit"] + ")")
def verify(self):
# Read the token inside the container; never put it in argv or output.
probe = '''set -eu
test -s "$PIPELINES_NTFY_TOKEN_FILE"
printf 'header = "Authorization: Bearer %s"\\n' "$(cat "$PIPELINES_NTFY_TOKEN_FILE")" |
curl --config - --fail --silent --show-error --max-time 10 --output /dev/null \
--data 'Pipelines Docker setup: authenticated publishing verified.' "$PIPELINES_NTFY_URL"
'''
self.compose("exec", "-T", "pipelines", "sh", "-c", probe, capture=True)
result = self.compose("exec", "-T", "pipelines", "pipelines", "--url",
"ws://127.0.0.1:8080/connect", "status", "--json", capture=True)
status = json.loads(result.stdout)
if (status.get("ntfy", {}).get("health") != "healthy"
or not status.get("ntfy", {}).get("url") or status.get("topic") != "pipelines"):
raise ValueError("Pipelines did not report healthy ntfy; check docker compose logs pipelines ntfy")
print("Verified: Pipelines reports healthy ntfy and authenticated publishing succeeded.")
print(f"On your phone: add {status['ntfy']['url']}, log in as phone-reader, subscribe to pipelines.")
print("Phone reception is not verified by this setup check.")
if not isinstance(json.loads(result.stdout), dict):
raise ValueError("Pipelines did not report its status; check docker compose logs pipelines")
print("Verified: Pipelines reports its status. Notifications reach the Pipelines apps (docs/notifications.md).")
address = self.compose("port", "pipelines", "8080", capture=True).stdout.strip()
port = address.rsplit(":", 1)[-1]
if not port.isdigit() or not 1 <= int(port) <= 65535:
@@ -541,11 +542,9 @@ printf 'header = "Authorization: Bearer %s"\\n' "$(cat "$PIPELINES_NTFY_TOKEN_FI
status = json.loads(result.stdout)
except ValueError:
raise ValueError("Host client could not inspect the published Docker server; setup is NOT complete")
if (result.returncode or not isinstance(status, dict)
or not isinstance(status.get("ntfy"), dict)
or status["ntfy"].get("health") != "healthy"):
raise ValueError("Host client did not reach the verified ntfy-enabled Docker server; check the published port before using the TUI")
print("Verified: host client reaches the ntfy-enabled Docker server at " + endpoint)
if result.returncode or not isinstance(status, dict):
raise ValueError("Host client did not reach the verified Docker server; check the published port before using the TUI")
print("Verified: host client reaches the Docker server at " + endpoint)
def configure_client(self, endpoint):
path = configure.configure_client(endpoint)
@@ -562,14 +561,15 @@ printf 'header = "Authorization: Bearer %s"\\n' "$(cat "$PIPELINES_NTFY_TOKEN_FI
# Resolve current releases before touching settings/services; a failure
# keeps the verified pins and stops rather than installing stale copies.
releases = self.resolve_releases()
# The published LAN address is required; find it before writing settings.
address = lan.detect_lan()
self.settings(args)
self.publish_address()
self.publish_address(address)
self.configure_workspaces()
self.update_host_client()
# Validate the actual resolved Compose configuration before starting anything.
self.compose("config", "--quiet", capture=True)
self.compose("up", "-d", "--wait", "--wait-timeout", "60", "ntfy")
self.bootstrap_ntfy()
self.retire_ntfy()
if self.needs_image_build(releases, expected_build, force_dirty=True):
self.compose("build", *build_args, *self.release_build_args(releases), "pipelines")
found = self.verify_harness_versions(releases) or {}
@@ -596,7 +596,7 @@ printf 'header = "Authorization: Bearer %s"\\n' "$(cat "$PIPELINES_NTFY_TOKEN_FI
options += ["--model", args.harness_model]
self.compose("run", "--rm", "--no-deps", "--entrypoint", "pipelines", "pipelines", "harness", "setup", "pi", *options)
# Recreate to reload file secrets and environment, without deleting volumes.
self.compose("up", "-d", "--force-recreate", "--wait", "--wait-timeout", "60", "pipelines")
self.compose("up", "-d", "--force-recreate", "--remove-orphans", "--wait", "--wait-timeout", "60", "pipelines")
self.verify_build(expected_build)
self.verify_workspace()
self.verify()
@@ -608,8 +608,6 @@ printf 'header = "Authorization: Bearer %s"\\n' "$(cat "$PIPELINES_NTFY_TOKEN_FI
def arguments(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--ntfy-url", help="Override the auto-detected LAN ntfy address")
parser.add_argument("--bind-address", help="Override ntfy's default 0.0.0.0 bind address")
parser.add_argument("--timezone", help="Override the detected timezone (fallback: UTC)")
parser.add_argument("--port", type=int)
parser.add_argument("--relogin", action="store_true", help="open OpenCode provider login again without deleting accounts")
+57 -235
View File
@@ -1,15 +1,13 @@
#!/usr/bin/env python3
"""Install Pipelines natively on the host (macOS and Linux).
The installer only detects the tools it needs (go, python3, node, git, curl and a C
compiler for ntfy's SQLite driver); it never installs or upgrades them, and it
never installs, upgrades or downloads OpenCode or Pi. It builds the server, CLI
and ntfy from source into a per-user prefix, generates an ntfy configuration that
mirrors compose.yaml, creates the publishing/phone accounts and writes the
manifest scripts/manage.py loads. ntfy is compiled from its pinned Go module on
every host because upstream publishes no macOS server binary. It reuses existing
host OpenCode configuration; it writes host (non-Docker) harness profiles for the
harnesses it detects and never invents a model.
The installer only detects the tools it needs (go, python3, node, git and curl);
it never installs or upgrades them, and it never installs, upgrades or downloads
OpenCode or Pi. It builds the server and CLI from source into a per-user prefix
and writes the manifest scripts/manage.py loads. Reinstalling over an install
from before ntfy was removed stops and removes that ntfy (see docs/install.md).
It reuses existing host OpenCode configuration; it writes host (non-Docker)
harness profiles for the harnesses it detects and never invents a model.
"""
import argparse
import importlib.util
@@ -41,8 +39,7 @@ def module(name, file):
configure = module("configure_compose", "configure-compose.py")
lan = module("lan_address", "lan-address.py")
release_lookup = module("resolve_releases", "resolve-releases.py")
tokens = module("save_ntfy_token", "save-ntfy-token.py")
manage = module("pipelines_manage", "manage.py")
app_build = module("app_build", "app_build.py")
web_access = module("web_access", "web_access.py")
web_password = module("pipelines_password", "password.py")
@@ -52,25 +49,16 @@ MARKER = "pipelines-install.json"
LABEL = "net.a-wan.pipelines"
SERVICE_MARKER = "Managed by Pipelines native installer"
REQUIRED_TOOLS = ("go", "python3", "git", "curl", "node")
# ntfy's SQLite driver (mattn/go-sqlite3) is cgo, so a C compiler is required to
# build the server. Upstream's macOS release asset is client-only, so both
# platforms compile ntfy from the pinned Go module.
C_COMPILERS = ("cc", "clang", "gcc")
NTFY_BUILD_TAGS = "sqlite_omit_load_extension,osusergo,netgo"
DEFAULT_NTFY_PORT = 8090
DEFAULT_SERVER_PORT = 8080
# Only the authenticated web proxy is exposed; the control API stays loopback.
DEFAULT_BIND_ADDRESS = "127.0.0.1"
class Setup:
def __init__(self, directory, prefix=None, runner=subprocess.run, resolver=None, environ=None,
popen=subprocess.Popen):
def __init__(self, directory, prefix=None, runner=subprocess.run, environ=None):
self.directory = Path(directory)
self.prefix_argument = prefix
self.runner = runner
self.popen = popen
self.resolver = resolver or release_lookup.resolve_ntfy
self.environ = environ if environ is not None else os.environ
self.verbose = False
self.install_log = None
@@ -98,17 +86,6 @@ class Setup:
# --- detection -------------------------------------------------------
def require_compiler(self):
"""ntfy is built locally, so a C toolchain must already be present."""
for compiler in C_COMPILERS:
path = shutil.which(compiler)
if path:
return str(Path(path).resolve())
raise ValueError(
"No C compiler found (tried " + ", ".join(C_COMPILERS)
+ "). ntfy's SQLite driver is cgo, so the server is compiled locally; "
"install a C toolchain (Xcode Command Line Tools on macOS, gcc or clang on Linux) and rerun.")
def require_tools(self):
found, missing = {}, []
for tool in REQUIRED_TOOLS:
@@ -333,7 +310,6 @@ class Setup:
existing = json.loads(path.read_text())
web = existing.get("web") or {}
saved = {"port": existing.get("server_port"),
"ntfy_port": existing.get("ntfy_port"),
"bind_address": existing.get("bind_address"),
"web_port": web.get("port"), "web_host": web.get("host"),
"web_lan": web.get("lan"), "web_lan_plain_login": web.get("lan_plain_login")}
@@ -584,167 +560,6 @@ class Setup:
if result.returncode:
raise ValueError("pipelines skill install failed; the native install is incomplete")
# --- ntfy server build and configuration ----------------------------
def resolve_ntfy(self):
try:
return self.resolver()
except release_lookup.ReleaseError as error:
raise ValueError(
f"Could not resolve the ntfy release ({error}); refusing to build an unverified version") from None
def build_ntfy(self, prefix, resolution):
"""Compile the ntfy server from the pinned Go module on this host.
Upstream publishes no macOS server binary (its darwin asset is built with
``-tags noserver``), so every platform builds here. The module is fetched
through the Go toolchain, which verifies it against the public checksum
database, and cgo is required for ntfy's SQLite driver.
"""
path = prefix / "bin/ntfy"
if path.is_symlink():
raise ValueError("Refusing to replace a symlinked bin/ntfy")
version = resolution.get("tag") or resolution.get("version")
module = resolution.get("module") or release_lookup.NTFY_MODULE
# A previously built binary for the same resolved version is reused.
if path.is_file() and self._existing_ntfy_version(prefix) == version:
return path
self.require_compiler()
pinned = f"{module}@{version}"
result = self.command(["go", "mod", "download", pinned], cwd=str(self.directory))
if result.returncode:
raise ValueError(f"go mod download {pinned} failed; the native install is incomplete")
cache = self.command(["go", "env", "GOMODCACHE"], cwd=str(self.directory),
capture_output=True, text=True)
if cache.returncode or not (cache.stdout or "").strip():
raise ValueError("Could not locate the Go module cache to build ntfy from")
source = Path(cache.stdout.strip()) / f"{module}@{version}"
if not source.is_dir():
raise ValueError(f"the Go module cache has no source for {pinned}")
# Keep source work in the system temp directory, but stage the output
# beside the destination: /tmp may be a different filesystem on Linux.
with tempfile.TemporaryDirectory(prefix="pipelines-ntfy-") as temporary, \
tempfile.TemporaryDirectory(prefix=".ntfy-", dir=path.parent) as staging:
checkout = Path(temporary) / "src"
shutil.copytree(source, checkout, symlinks=True)
# The module cache is read-only and carries no built web assets; the
# upstream Makefile creates the same placeholders for local builds.
self.command(["chmod", "-R", "u+w", str(checkout)])
(checkout / "server/docs").mkdir(parents=True, exist_ok=True)
(checkout / "server/site").mkdir(parents=True, exist_ok=True)
(checkout / "server/docs/index.html").touch()
(checkout / "server/site/app.html").touch()
built = Path(staging) / "ntfy"
env = dict(self.environ)
env["CGO_ENABLED"] = "1"
build = self.command(
["go", "build", "-trimpath", "-tags", NTFY_BUILD_TAGS,
"-ldflags", f"-s -w -X main.version={version}", "-o", str(built), "."],
cwd=str(checkout), env=env)
if build.returncode:
raise ValueError(
"ntfy server build failed; a working C compiler is required for its SQLite driver")
if not built.is_file():
raise ValueError("ntfy server build produced no binary")
os.chmod(built, 0o755)
os.replace(built, path)
return path
def _existing_ntfy_version(self, prefix):
manifest = prefix / MARKER
if manifest.is_symlink() or not manifest.is_file():
return None
try:
data = json.loads(manifest.read_text())
except (OSError, ValueError):
return None
return (data.get("ntfy") or {}).get("version") if isinstance(data, dict) else None
def write_ntfy_config(self, prefix, base_url, ntfy_port):
directory = prefix / "data/ntfy"
directory.mkdir(mode=0o700, exist_ok=True)
directory.chmod(0o700)
path = directory / "server.yml"
if path.is_symlink():
raise ValueError("Refusing to replace a symlinked ntfy configuration")
text = (
f'base-url: "{base_url}"\n'
f'listen-http: ":{ntfy_port}"\n'
f'cache-file: "{directory}/cache.db"\n'
'cache-duration: "168h"\n'
f'auth-file: "{directory}/auth.db"\n'
'auth-default-access: "deny-all"\n'
'enable-login: true\n'
f'attachment-cache-dir: "{directory}/attachments"\n'
'attachment-expiry-duration: "168h"\n'
'attachment-total-size-limit: "1G"\n'
'attachment-file-size-limit: "1M"\n'
)
self._write_atomic(path, text.encode(), 0o600)
return path
# --- ntfy users and publishing token --------------------------------
def ntfy(self, prefix, config_path, args, capture=False, password=None):
# The account subcommands locate the server configuration through
# NTFY_CONFIG_FILE; --config is a `serve`-only flag.
env = dict(self.environ)
env["NTFY_CONFIG_FILE"] = str(config_path)
if password is not None:
# `ntfy user add` takes the password from here instead of a prompt.
env["NTFY_PASSWORD"] = password
result = self.command([str(prefix / "bin/ntfy"), *args], capture_output=capture, text=True, env=env)
if result.returncode:
step = " ".join(args[:2])
raise ValueError(f"ntfy {step} failed; the native install is incomplete")
return result
def ensure_ntfy_auth_db(self, prefix, config_path):
"""ntfy creates its account database the first time its server runs;
the account commands refuse to run before that, so a fresh install
runs it once."""
auth = config_path.parent / "auth.db"
if auth.exists():
return
env = dict(self.environ)
process = self.popen([str(prefix / "bin/ntfy"), "serve", "--config", str(config_path)], env=env)
try:
deadline = time.monotonic() + 20
while not auth.exists():
if process.poll() is not None or time.monotonic() > deadline:
raise ValueError("ntfy did not create its account database; is its port free?")
time.sleep(0.2)
finally:
if process.poll() is None:
process.terminate()
try:
process.wait(timeout=10)
except subprocess.TimeoutExpired:
process.kill()
process.wait()
def reader_password(self, web):
"""The phone's ntfy password, which matches the web password: the one
chosen during this install, else a not yet migrated plaintext file. A
hashed file has no plaintext; an existing ntfy account keeps its own
password and a new one is asked for on the terminal."""
chosen = getattr(self, "chosen_web_password", None)
if chosen is not None:
return chosen
legacy = json.loads(Path(web["auth_file"]).read_text()).get("password")
return legacy if isinstance(legacy, str) else None
def bootstrap_ntfy(self, prefix, config_path, reader_password=None):
def run_ntfy(args, capture=False, interactive=False, password=None):
return self.ntfy(prefix, config_path, list(args), capture=capture, password=password)
self.ensure_ntfy_auth_db(prefix, config_path)
# The publisher authenticates with its token; its password is never
# needed, so it is random. The phone signs in with the web password.
tokens.bootstrap_accounts(run_ntfy, prefix / "secrets/publisher-token", 0o600,
publisher_password=secrets.token_urlsafe(24),
reader_password=reader_password)
# --- Docker migration ------------------------------------------------
def docker_volumes(self):
@@ -763,7 +578,7 @@ class Setup:
raise ValueError(
"Could not inspect Docker volumes for migration; refusing a possibly empty start")
names = set(result.stdout.split())
return tuple(name for name in ("pipelines_pipelines-data", "pipelines_ntfy-data") if name in names)
return tuple(name for name in ("pipelines_pipelines-data",) if name in names)
def _migration_image(self):
result = self.command(["docker", "image", "ls", "--format", "{{.Repository}}:{{.Tag}}"],
@@ -818,14 +633,40 @@ class Setup:
if "pipelines_pipelines-data" in volumes:
self._docker_copy_out(image, "pipelines_pipelines-data", "pipelines.db",
prefix / "data/pipelines.db", replace)
if "pipelines_ntfy-data" in volumes:
directory = prefix / "data/ntfy"
directory.mkdir(mode=0o700, exist_ok=True)
self._docker_copy_out(image, "pipelines_ntfy-data", "auth.db",
directory / "auth.db", replace)
print("Existing Docker data was migrated where it did not already exist.")
return True
# --- retired ntfy ----------------------------------------------------
def previous_manifest(self, prefix):
"""The installed manifest before this run, or {} for a fresh prefix."""
path = prefix / MARKER
if path.is_symlink() or not path.is_file():
return {}
try:
data = json.loads(path.read_text())
except (OSError, ValueError):
return {}
return data if isinstance(data, dict) else {}
def retire_ntfy(self, prefix, previous):
"""Stops and removes the ntfy an older install ran (idempotent).
The install log records what was removed and the old ntfy version first;
no credential is ever written there."""
def note(line):
if self.install_log:
self.install_log.parent.mkdir(parents=True, exist_ok=True)
with self.install_log.open("a") as log:
log.write(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] {line}\n")
removed = manage.retire_ntfy(dict(previous, prefix=str(prefix)), note=note)
if removed:
where = f" (details in {self.install_log})" if self.install_log else ""
self.step("Retired the old ntfy notification server; notifications now come through the Pipelines apps"
+ where)
return removed
# --- manifest --------------------------------------------------------
def write_manifest(self, prefix, values):
@@ -858,12 +699,8 @@ class Setup:
self.preserve_network_settings(prefix, args)
if not 1024 <= args.port <= 65535:
raise ValueError("Invalid server port; choose a value between 1024 and 65535")
if not 1024 <= args.ntfy_port <= 65535:
raise ValueError("Invalid ntfy port; choose a value between 1024 and 65535")
if args.ntfy_port == args.port:
raise ValueError("The server and ntfy ports must differ")
if not 1024 <= args.web_port <= 65535 or args.web_port in (args.port, args.ntfy_port):
raise ValueError("Web port must be between 1024 and 65535 and differ from server/ntfy ports")
if not 1024 <= args.web_port <= 65535 or args.web_port == args.port:
raise ValueError("Web port must be between 1024 and 65535 and differ from the server port")
try:
ipaddress.IPv4Address(args.bind_address)
except ValueError:
@@ -884,14 +721,7 @@ class Setup:
raise ValueError("PIPELINES_WEB_PUBLIC_URL must be an HTTP(S) web origin without credentials, path, query or fragment")
harness = self.harness()
service_path = self.service_path()
# Reuse an already built ntfy binary and skip the release lookup, so a
# reinstall with the same version makes no network requests at all.
installed = self._existing_ntfy_version(prefix)
if (prefix / "bin/ntfy").is_file() and installed:
resolution = {"module": release_lookup.NTFY_MODULE, "version": installed, "tag": installed}
else:
self.require_compiler()
resolution = self.resolve_ntfy()
previous_manifest = self.previous_manifest(prefix)
# All or nothing: the web app and the server are both built before
# either is installed, and a failed build leaves the old pair running.
self.step("Building the web app")
@@ -910,19 +740,18 @@ class Setup:
harness_path = self.configure_harnesses(harness, args.model or "")
harness_config = json.loads(harness_path.read_text())
pipeline_model = harness_config["profiles"][harness_config["default"]]["pipeline_model"]
lan_ip = lan.detect_lan()
base_url = args.ntfy_url or f"http://{lan_ip}:{args.ntfy_port}"
config_path = self.write_ntfy_config(prefix, base_url, args.ntfy_port)
self.build_ntfy(prefix, resolution)
# Migrate existing Docker data before creating native ntfy accounts so a
# migrated auth store (the phone's credentials) is preserved rather than
# shadowed by a freshly bootstrapped one.
try:
lan_ip = lan.detect_lan()
except ValueError:
# Only the printed LAN web address needs it.
lan_ip = "127.0.0.1"
if args.fresh:
print("Starting empty (--fresh); existing Docker volumes are left untouched.")
else:
self.migrate_docker(prefix, args.replace_data)
self.bootstrap_ntfy(prefix, config_path,
reader_password=self.reader_password(web))
# The new server and web app are in place: the old ntfy goes now,
# before the new manifest (which has no ntfy) replaces the old one.
self.retire_ntfy(prefix, previous_manifest)
timezone = args.timezone
if not timezone:
try:
@@ -940,19 +769,17 @@ class Setup:
path_value = str(prefix / "bin") + os.pathsep + self.environ.get("PATH", "")
manifest = {
"format": 1,
# Marks the native installer (older manifests used ntfy.mode).
"mode": "native",
"allow_authoring": allow_authoring,
"prefix": str(prefix),
"python": python,
"server_port": args.port,
"bind_address": args.bind_address,
"ntfy_port": args.ntfy_port,
"opencode": harness["opencode"],
"pi": harness["pi"],
"opencode_env": opencode_env,
"path": path_value,
"topic": "pipelines",
"public_url": base_url,
"username": "phone-reader",
"workspace": str(Path.home()),
"launcher": str(prefix / "bin/pipelines"),
"registration": None,
@@ -960,9 +787,6 @@ class Setup:
"docker": "docker",
"project": "pipelines",
"timezone": timezone,
"ntfy": {"mode": "native", "bin": str(prefix / "bin/ntfy"),
"config": str(config_path), "base_url": base_url,
"version": resolution.get("tag") or resolution.get("version")},
"web": web,
# `pipelines update` re-runs this installer from here, the same way.
"source": str(self.directory),
@@ -976,14 +800,14 @@ class Setup:
endpoint = f"ws://127.0.0.1:{args.port}/connect"
client_path = configure.configure_client(endpoint, self.environ)
self.step("Starting the services")
# Parity with the Docker installer: leave the server and ntfy running.
# Parity with the Docker installer: leave the server and web proxy running.
started = self.command([python, str(prefix / "lib/manage.py"), "start", "--prefix", str(prefix)])
if started.returncode:
raise ValueError(
"The native services were installed but could not be started; run "
f"'PIPELINES_PREFIX={prefix} {prefix}/bin/pipelines start' to see the error. "
"Check your login service manager and that ports "
f"{args.port}, {args.ntfy_port} and {args.web_port} are free (a running Docker installation may use them).")
f"{args.port} and {args.web_port} are free (a running Docker installation may use them).")
self.retire_legacy_web()
self.serve_on_tailnet(opencode_env["PIPELINES_WEB_PUBLIC_URL"], args.web_port)
print("\nPipelines installed")
@@ -1003,7 +827,6 @@ class Setup:
def arguments(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--prefix", type=Path, help="Installation prefix (default: ~/.local/share/pipelines)")
parser.add_argument("--ntfy-url", help="Override the auto-detected LAN ntfy address")
parser.add_argument("--timezone", help="Override the detected timezone (fallback: UTC)")
parser.add_argument("--port", type=int, default=DEFAULT_SERVER_PORT, help="Pipelines server port")
parser.add_argument("--web-port", type=int, default=8082, help="Authenticated web proxy port (default 8082)")
@@ -1018,7 +841,6 @@ def arguments(argv=None):
"(unencrypted; only on a trusted network)")
parser.add_argument("--bind-address", default=DEFAULT_BIND_ADDRESS,
help="Unauthenticated server bind address (default 127.0.0.1; expose only the web proxy)")
parser.add_argument("--ntfy-port", type=int, default=DEFAULT_NTFY_PORT, help="ntfy listen port")
parser.add_argument("--model", help="Explicit PROVIDER/MODEL for starter defaults and missing profile fields; "
"otherwise reuse saved/default OpenCode models or choose within this installer")
role = parser.add_mutually_exclusive_group()
@@ -1029,7 +851,7 @@ def arguments(argv=None):
parser.add_argument("--fresh", action="store_true",
help="Start with empty data even when an earlier Docker installation's volumes exist")
parser.add_argument("--replace-data", action="store_true",
help="Allow Docker migration to replace an existing native database/auth store")
help="Allow Docker migration to replace an existing native database")
parser.add_argument("--verbose", action="store_true", help="Show full build and tool output")
parsed = parser.parse_args(argv)
parsed.argv = list(sys.argv[1:] if argv is None else argv)
+10 -17
View File
@@ -27,31 +27,24 @@ class ConfigureTests(unittest.TestCase):
except ValueError:
self.skipTest("host timezone is unavailable in this environment")
with tempfile.TemporaryDirectory() as directory:
zone = configure.configure(directory, "http://192.168.1.20:8090", "0.0.0.0")
zone = configure.configure(directory)
self.assertTrue(zone)
settings = Path(directory, ".env")
original = settings.read_bytes()
self.assertIn(f"TZ={zone}", settings.read_text())
self.assertEqual(Path(directory, "secrets/ntfy-token.txt").stat().st_mode & 0o777, 0o600)
self.assertNotIn("NTFY", settings.read_text())
self.assertFalse(Path(directory, "secrets").exists())
with self.assertRaises(ValueError):
configure.configure(directory, "http://192.168.1.21:8090", "0.0.0.0")
configure.configure(directory, "Europe/London")
self.assertEqual(settings.read_bytes(), original)
def test_existing_token_is_not_overwritten(self):
with tempfile.TemporaryDirectory() as directory:
secrets = Path(directory, "secrets")
secrets.mkdir()
token = secrets / "ntfy-token.txt"
token.write_text("existing-secret")
configure.configure(directory, "http://192.168.1.20:8090", "0.0.0.0", "Europe/London")
self.assertEqual(token.read_text(), "existing-secret")
def test_reject_bad_url_and_injected_values(self):
for url in ["file:///foo", "https://user:pass@example.com", "https://example.com/topic", "https://example.com?token=secret"]:
with tempfile.TemporaryDirectory() as directory, self.assertRaises(ValueError):
configure.configure(directory, url, "0.0.0.0", "Europe/London")
def test_reject_injected_values(self):
for timezone in ("Europe/London\nEVIL=yes", "Nowhere/Invalid"):
with tempfile.TemporaryDirectory() as directory, self.assertRaises(Exception):
configure.configure(directory, timezone)
self.assertFalse(Path(directory, ".env").exists())
with tempfile.TemporaryDirectory() as directory, self.assertRaises(ValueError):
configure.configure(directory, "https://example.com", "0.0.0.0\nEVIL=yes", "Europe/London")
configure.configure(directory, "Europe/London", port=70000)
def test_client_default_is_saved_privately_and_preserves_other_keys(self):
with tempfile.TemporaryDirectory() as directory:
+4 -4
View File
@@ -11,12 +11,12 @@ class InstallationTests(unittest.TestCase):
result=subprocess.run([str(Path(__file__).resolve().parents[1]/"install"),"--help"],capture_output=True,text=True)
self.assertEqual(result.returncode,0)
self.assertIn("--prefix",result.stdout)
self.assertIn("--ntfy-url",result.stdout)
self.assertNotIn("--ntfy",result.stdout)
def test_docker_installer_is_available_explicitly(self):
result=subprocess.run([str(Path(__file__).resolve().parents[1]/"install"),"--docker","--help"],capture_output=True,text=True)
self.assertEqual(result.returncode,0)
self.assertIn("--ntfy-url",result.stdout)
self.assertNotIn("--ntfy",result.stdout)
self.assertIn("--relogin",result.stdout)
def dispatch(self,*args):
@@ -40,8 +40,8 @@ class InstallationTests(unittest.TestCase):
self.assertEqual(self.dispatch("docker"),["scripts/setup-docker.py"])
def test_docker_mode_forwards_docker_options(self):
self.assertEqual(self.dispatch("--docker","--ntfy-url","http://192.168.1.20:8090"),
["scripts/setup-docker.py","--ntfy-url","http://192.168.1.20:8090"])
self.assertEqual(self.dispatch("--docker","--timezone","Europe/London"),
["scripts/setup-docker.py","--timezone","Europe/London"])
def test_standard_installer_rejects_legacy_provisioning_flags(self):
result=subprocess.run([str(Path(__file__).resolve().parents[1]/"install.sh"),"--system-command"],capture_output=True,text=True)
+142 -57
View File
@@ -152,12 +152,10 @@ class ManageNativeTests(unittest.TestCase):
config = self.config(root)
if role is not None:
config["allow_authoring"] = role
ntfy, server = MagicMock(), MagicMock()
ntfy.poll.return_value = None
server = MagicMock()
server.poll.return_value = 0
server.returncode = 0
with patch.object(manage, "ntfy_start", return_value=ntfy), \
patch.object(manage, "wait_health"), patch.object(manage.signal, "signal"), \
with patch.object(manage.signal, "signal"), \
patch.object(manage.subprocess, "Popen", return_value=server) as popen:
manage.supervise(config)
command = popen.call_args_list[0].args[0]
@@ -178,13 +176,10 @@ class ManageNativeTests(unittest.TestCase):
(root / "lib/app-web").mkdir(parents=True, exist_ok=True)
(root / "lib/app-web/index.html").write_text("app")
return {
"format": 1, "prefix": str(root), "python": "python3", "server_port": 8080,
"ntfy_port": 8090, "opencode": "opencode", "opencode_env": {}, "path": "",
"topic": "pipelines", "public_url": "http://192.168.1.20:8090", "username": "phone-reader",
"format": 1, "mode": mode, "prefix": str(root), "python": "python3", "server_port": 8080,
"opencode": "opencode", "opencode_env": {}, "path": "",
"workspace": str(root), "launcher": str(root / "bin/pipelines"), "registration": None,
"label": "net.a-wan.pipelines", "docker": "docker", "project": "pipelines", "timezone": "UTC",
"ntfy": {"mode": mode, "bin": str(root / "bin/ntfy"),
"config": str(root / "data/ntfy/server.yml"), "base_url": "http://192.168.1.20:8090"},
"web": {"node": "/bin/node", "script": str(root / "lib/web/serve.mjs"), "host": "127.0.0.1",
"port": 8082, "auth_file": str(root / "auth.json"), "root": str(root / "lib/app-web")},
}
@@ -205,11 +200,94 @@ class ManageNativeTests(unittest.TestCase):
run.assert_not_called()
popen.assert_not_called()
def test_mode_selection_defaults_to_docker(self):
self.assertEqual(manage.ntfy_mode({}), "docker")
self.assertEqual(manage.ntfy_mode({"ntfy": {}}), "docker")
self.assertEqual(manage.ntfy_mode({"ntfy": {"mode": "native"}}), "native")
self.assertEqual(manage.ntfy_health_url({"ntfy_port": 8090}), "http://127.0.0.1:8090/v1/health")
def legacy_config(self, root):
"""A manifest written while Pipelines still ran ntfy."""
config = self.config(root)
config.pop("mode")
config.update(ntfy_port=8090, topic="pipelines", public_url="http://192.168.1.20:8090",
username="phone-reader",
ntfy={"mode": "native", "bin": str(root / "bin/ntfy"), "version": "v2.38.1",
"config": str(root / "data/ntfy/server.yml"), "base_url": "http://192.168.1.20:8090"})
return config
def legacy_files(self, root):
for name in ("bin", "logs", "secrets", "data/ntfy/attachments"):
(root / name).mkdir(parents=True, exist_ok=True)
for name in ("bin/ntfy", "logs/ntfy.log", "secrets/publisher-token", "data/ntfy/server.yml",
"data/ntfy/auth.db", "data/ntfy/cache.db"):
(root / name).write_text("x")
(root / "ntfy.pid").write_text("4321")
def test_install_mode_reads_top_level_mode_and_legacy_ntfy_mode(self):
self.assertEqual(manage.install_mode({}), "docker")
self.assertEqual(manage.install_mode({"mode": "native"}), "native")
self.assertEqual(manage.install_mode({"mode": "docker"}), "docker")
self.assertEqual(manage.install_mode({"ntfy": {}}), "docker")
self.assertEqual(manage.install_mode({"ntfy": {"mode": "native"}}), "native")
self.assertEqual(manage.install_mode({"mode": "native", "ntfy": {"mode": "docker"}}), "native")
def test_native_service_accepts_a_legacy_ntfy_mode_manifest(self):
with tempfile.TemporaryDirectory() as directory:
config = self.legacy_config(Path(directory))
# Without any native marker it is not a native install...
with self.assertRaisesRegex(ValueError, "No native installer login service"):
manage.service_command(dict(config, ntfy={}), ["status"])
# ...while the legacy ntfy.mode marker passes the native check.
config["registration"] = str(Path(directory) / "elsewhere.service")
with patch.object(manage.platform, "system", return_value="Linux"), \
self.assertRaisesRegex(ValueError, "unexpected native service definition"):
manage.service_command(config, ["status"])
def test_legacy_ntfy_is_signalled_only_when_its_command_line_matches(self):
cases = {"managed": "{root}/bin/ntfy serve --config {root}/data/ntfy/server.yml",
"other program": "/usr/bin/vim notes.txt",
"other ntfy": "/usr/bin/ntfy serve",
"not serving": "{root}/bin/ntfy user list",
"gone": None}
for name, command in cases.items():
with self.subTest(name), tempfile.TemporaryDirectory() as directory:
root = Path(directory)
self.legacy_files(root)
config = self.config(root)
line = command.format(root=root) if command else None
running = [line]
killed = []
def fake_kill(pid, sig):
killed.append((pid, sig))
running[0] = None
with patch.object(manage, "process_command", side_effect=lambda pid: running[0]), \
patch.object(manage.os, "kill", side_effect=fake_kill):
stopped = manage.stop_legacy_ntfy(config)
self.assertEqual(killed, [(4321, signal.SIGTERM)] if name == "managed" else [])
self.assertEqual(stopped, name == "managed")
self.assertFalse((root / "ntfy.pid").exists())
def test_retire_ntfy_removes_its_files_and_notes_them_once(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
self.legacy_files(root)
(root / "bin/pipelines-server").write_text("keep")
(root / "data/pipelines.db").write_text("keep")
(root / "secrets/other").write_text("keep")
config = self.legacy_config(root)
notes = []
with patch.object(manage, "process_command", return_value=None), \
patch.object(manage.os, "kill", side_effect=AssertionError("signalled a non-ntfy PID")), \
patch.object(manage, "compose", side_effect=AssertionError("compose used for native")):
removed = manage.retire_ntfy(config, note=notes.append)
self.assertEqual(len(removed), 5)
for path in manage.legacy_ntfy_paths(root):
self.assertFalse(path.exists(), path)
for name in ("bin/pipelines-server", "data/pipelines.db", "secrets/other"):
self.assertTrue((root / name).exists(), name)
self.assertEqual(len(notes), 1)
self.assertIn("v2.38.1", notes[0])
self.assertIn(str(root / "bin/ntfy"), notes[0])
# Idempotent: nothing left, nothing noted, with the new manifest.
self.assertEqual(manage.retire_ntfy(self.config(root), note=notes.append), [])
self.assertEqual(len(notes), 1)
def test_registered_start_commands_on_both_platforms(self):
for system in ("Darwin", "Linux"):
@@ -304,13 +382,13 @@ class ManageNativeTests(unittest.TestCase):
"host": "0.0.0.0", "port": 8082, "auth_file": "/private/auth.json",
"server_token_file": "/private/server-token",
"root": str(root / "lib/app-web"), "updates": "/prefix/lib/app-updates"}
ntfy, server, web = MagicMock(), MagicMock(), MagicMock()
ntfy.poll.return_value = None
server, web = MagicMock(), MagicMock()
server.poll.return_value = None
web.poll.side_effect = [1, None]
with patch.object(manage, "ntfy_start", return_value=ntfy), \
patch.object(manage, "wait_health"), patch.object(manage.signal, "signal"), \
patch.dict(os.environ, {"PIPELINES_WEB_AUTH": "disabled"}), \
with patch.object(manage.signal, "signal"), \
patch.dict(os.environ, {"PIPELINES_WEB_AUTH": "disabled",
"PIPELINES_NTFY_URL": "http://127.0.0.1:8090/pipelines",
"PIPELINES_NTFY_TOKEN_FILE": "/old/token"}), \
patch.object(manage.subprocess, "Popen", side_effect=[server, web]) as popen:
with self.assertRaisesRegex(RuntimeError, "web proxy exited"):
manage.supervise(config)
@@ -327,7 +405,29 @@ class ManageNativeTests(unittest.TestCase):
self.assertEqual(manage.server_token_env({"web": None}), {})
web.terminate.assert_called_once()
server.terminate.assert_called_once()
ntfy.terminate.assert_called_once()
def test_supervisor_no_longer_starts_ntfy_or_passes_its_settings(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
(root / "logs").mkdir()
self.legacy_files(root)
# Even an old manifest still on disk starts only the server and web proxy.
config = self.legacy_config(root)
server, web = MagicMock(), MagicMock()
server.poll.return_value = 0
server.returncode = 0
web.poll.return_value = None
with patch.object(manage.signal, "signal"), \
patch.object(manage, "process_command", return_value=None), \
patch.object(manage, "compose", side_effect=AssertionError("compose used for ntfy")), \
patch.dict(os.environ, {"PIPELINES_NTFY_PUBLIC_URL": "http://x:8090"}), \
patch.object(manage.subprocess, "Popen", side_effect=[server, web]) as popen:
manage.supervise(config)
self.assertEqual(len(popen.call_args_list), 2)
for spawned in popen.call_args_list:
self.assertNotIn("ntfy", " ".join(spawned.args[0]))
self.assertFalse([key for key in spawned.kwargs["env"] if key.startswith("PIPELINES_NTFY_")])
self.assertFalse((root / "ntfy.pid").exists())
def test_start_checks_web_login_readiness(self):
with tempfile.TemporaryDirectory() as directory:
@@ -349,47 +449,13 @@ class ManageNativeTests(unittest.TestCase):
self.assertEqual(manage.server_address({"server_port": 8080}), "127.0.0.1:8080")
self.assertEqual(manage.server_address({"server_port": 8080, "bind_address": ""}), "127.0.0.1:8080")
def test_ntfy_start_launches_binary_with_generated_config(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
(root / "bin").mkdir()
(root / "logs").mkdir()
config = self.config(root)
with patch.object(manage.subprocess, "Popen", return_value=FakeProcess(pid=4321)) as popen:
child = manage.ntfy_start(config)
self.assertEqual(popen.call_args[0][0], [config["ntfy"]["bin"], "serve", "--config", config["ntfy"]["config"]])
self.assertEqual(child.pid, 4321)
self.assertEqual((root / "ntfy.pid").read_text(), "4321")
def test_ntfy_stop_terminates_managed_process_and_removes_pid(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
(root / "bin").mkdir()
(root / "bin/ntfy").write_text("")
(root / "ntfy.pid").write_text(str(os.getpid()))
config = self.config(root)
killed = []
def fake_kill(pid, sig):
if sig == 0:
raise ProcessLookupError
killed.append((pid, sig))
with patch.object(manage.subprocess, "check_output",
return_value=str(root / "bin/ntfy") + " serve --config x"), \
patch.object(manage.os, "kill", side_effect=fake_kill), \
patch.object(manage, "compose", side_effect=AssertionError("compose used for native ntfy")):
manage.ntfy_stop(config)
self.assertIn((os.getpid(), signal.SIGTERM), killed)
self.assertFalse((root / "ntfy.pid").exists())
def test_native_stop_never_calls_compose(self):
with tempfile.TemporaryDirectory() as directory:
config = self.config(Path(directory))
with patch.object(manage, "registration", return_value=None), \
patch.object(manage, "managed_pid", return_value=None), \
patch.object(manage, "ntfy_stop") as stop, \
patch.object(manage, "compose", side_effect=AssertionError("compose used for native ntfy")):
patch.object(manage, "stop_legacy_ntfy") as stop, \
patch.object(manage, "compose", side_effect=AssertionError("compose used for native")):
manage.stop(config)
stop.assert_called_once_with(config)
@@ -400,10 +466,29 @@ class ManageNativeTests(unittest.TestCase):
config = self.config(root)
with patch.object(manage, "stop"), \
patch.object(manage, "registration", return_value=None), \
patch.object(manage, "compose", side_effect=AssertionError("compose used for native ntfy")):
patch.object(manage, "compose", side_effect=AssertionError("compose used for native")):
manage.uninstall(config, purge=False, yes=True)
self.assertTrue((root / manage.MARKER).is_file())
def test_uninstall_removes_leftover_ntfy_even_without_a_manifest_entry(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
self.legacy_files(root)
(root / "data/pipelines.db").write_text("keep")
config = self.config(root)
killed = []
with patch.object(manage, "stop"), \
patch.object(manage, "registration", return_value=None), \
patch.object(manage, "process_command",
side_effect=lambda pid: None if killed else f"{root}/bin/ntfy serve --config c"), \
patch.object(manage.os, "kill", side_effect=lambda pid, sig: killed.append((pid, sig))), \
patch.object(manage, "compose", side_effect=AssertionError("compose used for native")):
manage.uninstall(config, purge=False, yes=True)
self.assertEqual(killed, [(4321, signal.SIGTERM)])
for path in manage.legacy_ntfy_paths(root):
self.assertFalse(path.exists(), path)
self.assertTrue((root / "data/pipelines.db").exists())
if __name__ == "__main__":
unittest.main()
-46
View File
@@ -186,51 +186,5 @@ class ReleaseResolutionTests(unittest.TestCase):
resolve_releases.load_fixture(path)
class FakeNtfy:
"""Deterministic ntfy tag fixture served through the same fetch seam."""
VERSION = "2.11.0"
def __init__(self, tags=None, tags_response=None):
self.tags = tags if tags is not None else ["v" + self.VERSION]
self.tags_response = tags_response
self.calls = []
def __call__(self, url, headers=None):
self.calls.append(url)
if "/git/matching-refs/" in url:
if self.tags_response is not None:
return 200, {}, json.dumps(self.tags_response).encode()
return 200, {}, json.dumps([{"ref": "refs/tags/" + tag} for tag in self.tags]).encode()
return 404, {}, b""
class NtfyResolutionTests(unittest.TestCase):
def test_resolves_exact_version_from_official_tags_only(self):
registry = FakeNtfy(tags=["v2.10.0", "v2.11.0"])
result = resolve_releases.resolve_ntfy(registry)
self.assertEqual(result["version"], "2.11.0")
self.assertEqual(result["tag"], "v2.11.0")
self.assertEqual(result["module"], resolve_releases.NTFY_MODULE)
self.assertEqual(result["repository"], resolve_releases.NTFY_REPOSITORY)
# No release assets or checksums are fetched: the native installer builds
# the server from the pinned module instead.
self.assertNotIn("assets", result)
self.assertEqual(len(registry.calls), 1)
self.assertTrue(registry.calls[0].startswith(
"https://api.github.com/repos/binwiederhier/ntfy/git/matching-refs/"))
self.assertFalse(any("releases/latest" in url for url in registry.calls))
def test_malformed_tag_metadata_is_rejected(self):
for tags in ([42], [{"ref": "refs/heads/main"}], [{"ref": "refs/tags/not-a-version"}],
[{"noref": "refs/tags/v2.11.0"}]):
with self.assertRaises(resolve_releases.ReleaseError):
resolve_releases.resolve_ntfy(FakeNtfy(tags_response=tags))
def test_no_stable_release_fails_closed(self):
with self.assertRaisesRegex(resolve_releases.ReleaseError, "no stable ntfy release"):
resolve_releases.resolve_ntfy(FakeNtfy(tags=[]))
if __name__ == "__main__":
unittest.main()
-89
View File
@@ -1,89 +0,0 @@
import subprocess
import importlib.util
from pathlib import Path
import tempfile
import unittest
spec = importlib.util.spec_from_file_location("save_token", Path(__file__).with_name("save-ntfy-token.py"))
save_token = importlib.util.module_from_spec(spec)
spec.loader.exec_module(save_token)
class TokenTests(unittest.TestCase):
def test_extract_prose_and_protect_source_directory(self):
token = "tk_" + "a" * 29
with tempfile.TemporaryDirectory() as directory:
path = Path(directory, "secrets/ntfy-token.txt")
save_token.save_token(f"token {token} created for user pipeline-publisher, never expires\n", path, 0o444)
self.assertEqual(path.read_text(), token + "\n")
self.assertEqual(path.stat().st_mode & 0o777, 0o444)
self.assertEqual(path.parent.stat().st_mode & 0o777, 0o700)
with self.assertRaises(ValueError):
save_token.save_token(f"token {token} created", path, 0o444)
self.assertEqual(path.read_text(), token + "\n")
def test_native_mode_is_private_to_the_installing_user(self):
token = "tk_" + "b" * 29
with tempfile.TemporaryDirectory() as directory:
path = Path(directory, "secrets/publisher-token")
save_token.save_token(f"token {token} created", path, 0o600)
self.assertEqual(path.stat().st_mode & 0o777, 0o600)
def test_failures_do_not_replace_empty_placeholder(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory, "secrets/ntfy-token.txt")
path.parent.mkdir()
path.write_text("")
for output in ["", "connection failed", "tk_" + "a" * 29 + " tk_" + "b" * 29]:
with self.assertRaises(ValueError):
save_token.save_token(output, path, 0o444)
self.assertEqual(path.read_text(), "")
def test_accounts_are_bootstrapped_once_with_the_shared_sequence(self):
token = "tk_" + "c" * 29
class FakeCompleted:
returncode = 0
stdout = f"token {token} created for pipeline-publisher\n"
stderr = ""
with tempfile.TemporaryDirectory() as directory:
path = Path(directory, "secrets/publisher-token")
calls = []
def run(args, capture=False, interactive=False):
calls.append((tuple(args), capture, interactive))
return FakeCompleted()
save_token.bootstrap_accounts(run, path, 0o600, log=lambda _message: None)
self.assertEqual([args for args, _, _ in calls], [
("user", "add", "--ignore-exists", "pipeline-publisher"),
("access", "pipeline-publisher", "pipelines", "write-only"),
("token", "add", "pipeline-publisher"),
("user", "add", "--ignore-exists", "phone-reader"),
("access", "phone-reader", "pipelines", "read-only"),
])
self.assertEqual([capture for _, capture, _ in calls], [False, False, True, False, False])
self.assertEqual([interactive for _, _, interactive in calls], [True, False, False, True, False])
self.assertEqual(path.read_text(), token + "\n")
self.assertEqual(path.stat().st_mode & 0o777, 0o600)
class NonInteractiveAccounts(unittest.TestCase):
def test_given_passwords_are_used_without_prompts(self):
calls = []
def run(args, capture=False, interactive=False, password=None):
calls.append((tuple(args), interactive, password))
out = "token tk_abcdefghijklmnopqrstuvwxyz123 created" if args[0] == "token" else ""
return subprocess.CompletedProcess(args, 0, stdout=out, stderr="")
with tempfile.TemporaryDirectory() as directory:
save_token.bootstrap_accounts(run, Path(directory) / "token", 0o600, log=lambda _m: None,
publisher_password="p1", reader_password="p2")
adds = [(args[3], interactive, password) for args, interactive, password in calls if args[:2] == ("user", "add")]
self.assertEqual(adds, [("pipeline-publisher", False, "p1"), ("phone-reader", False, "p2")])
if __name__ == "__main__":
unittest.main()
+66 -48
View File
@@ -1,4 +1,6 @@
import importlib.util
import io
from contextlib import redirect_stderr, redirect_stdout
import os
from pathlib import Path
import shutil
@@ -302,7 +304,7 @@ class DockerSetupTests(unittest.TestCase):
def test_host_verification_rejects_wrong_unconfigured_server(self):
def runner(command, **kwargs):
return subprocess.CompletedProcess(command, 0, stdout='{"ntfy":{"health":"not configured"}}', stderr="")
return subprocess.CompletedProcess(command, 0, stdout='[]', stderr="")
with patch.object(setup.shutil,"which",return_value="/fixture/go"), self.assertRaises(ValueError):
setup.Setup(".",runner=runner).verify_host_endpoint("ws://127.0.0.1:8081/connect")
@@ -491,20 +493,20 @@ fi
def test_ctrl_c_exits_cleanly_and_retains_configuration(self):
with tempfile.TemporaryDirectory() as directory:
root=Path(directory);scripts=root/"scripts";scripts.mkdir()
for name in ["setup-docker.py","lan-address.py","configure-compose.py","save-ntfy-token.py","build_metadata.py","resolve-releases.py"]:
for name in ["setup-docker.py","lan-address.py","configure-compose.py","build_metadata.py","resolve-releases.py"]:
shutil.copy2(Path(__file__).with_name(name),scripts/name)
fixture=root/"releases.json"
fixture.write_text(setup.json.dumps({"opencode":{"image":"ghcr.io/anomalyco/opencode","version":"2.0.26","digest":"sha256:"+"a"*64},"pi":{"version":"1.1.0","engine":">=22.19.0"}}))
marker=root/"waiting"
docker=root/"docker"
docker.write_text('#!/bin/sh\ncase "$*" in *" up "*) touch "'+str(marker)+'"; exec sleep 30;; *"opencode --version"*) printf "opencode=2.0.26\\npi=1.1.0\\nnode=v22.19.0\\n";; esac\n')
docker.write_text('#!/bin/sh\ncase "$*" in *" config --format json"*) touch "'+str(marker)+'"; exec sleep 30;; *"opencode --version"*) printf "opencode=2.0.26\\npi=1.1.0\\nnode=v22.19.0\\n";; esac\n')
docker.chmod(0o700)
go=root/"go";go.write_text('#!/bin/sh\nexit 0\n');go.chmod(0o700)
git=root/"git";git.write_text('#!/bin/sh\nif [ "$1" = rev-parse ]; then echo '+"a"*40+'; fi\n');git.chmod(0o700)
# The container's default home (/home/pipelines) is rejected by the
# mount guard; give the subprocess its own disposable HOME.
process=subprocess.Popen([sys.executable,str(scripts/"setup-docker.py"),
"--ntfy-url","http://192.168.1.25:8090","--bind-address","192.168.1.25","--timezone","UTC"],
"--timezone","UTC"],
env=dict(os.environ,PATH=str(root)+os.pathsep+os.environ["PATH"],
HOME=str(root/"home"),USERPROFILE=str(root/"home"),
PIPELINES_RELEASE_FIXTURE=str(fixture)),
@@ -525,16 +527,15 @@ fi
os.killpg(process.pid,signal.SIGTERM)
process.communicate(timeout=5)
def test_fresh_defaults_configure_lan_without_any_input(self):
def test_fresh_defaults_configure_without_any_input(self):
with tempfile.TemporaryDirectory() as directory, \
patch.object(setup.lan,"detect_lan",return_value="192.168.1.25"), \
patch.object(setup.configure,"host_timezone",return_value="Europe/London"), \
patch("builtins.input",side_effect=AssertionError("must not ask for network settings")):
setup.Setup(directory).settings(setup.arguments([]))
text=Path(directory,".env").read_text()
self.assertIn("NTFY_BASE_URL=http://192.168.1.25:8090\n",text)
self.assertIn("NTFY_BIND_ADDRESS=0.0.0.0\n",text)
self.assertNotIn("NTFY",text)
self.assertIn("TZ=Europe/London\n",text)
self.assertFalse(Path(directory,"secrets").exists())
def test_timezone_fallback_does_not_prompt(self):
with tempfile.TemporaryDirectory() as directory, \
@@ -544,15 +545,14 @@ fi
self.assertIn("TZ=UTC\n",Path(directory,".env").read_text())
def test_missing_lan_fails_without_partial_settings_or_prompt(self):
with tempfile.TemporaryDirectory() as directory, \
patch.object(setup.lan,"detect_lan",side_effect=ValueError("No LAN")):
with self.assertRaises(ValueError):
setup.Setup(directory).settings(setup.arguments([]))
with tempfile.TemporaryDirectory() as directory:
with self.assertRaisesRegex(ValueError, "No LAN"):
self.exercise(directory, lan_error=ValueError("No LAN"))
self.assertFalse(Path(directory,".env").exists())
def exercise(self, directory, existing=False, fail=None, confirm="yes", harness="opencode"):
def exercise(self, directory, existing=False, fail=None, confirm="yes", harness="opencode",
lan_error=None, ntfy_leftovers=False):
calls = []
token = "tk_" + "a" * 29
logged = existing
def runner(command, **kwargs):
@@ -563,6 +563,10 @@ fi
args = command[2:]
calls.append(args)
code, out = 0, ""
if ntfy_leftovers and command[:3] == ["docker", "ps", "-aq"] and "label=com.docker.compose.service=ntfy" in command:
out = "0123abcd\n"
if ntfy_leftovers and command[:3] == ["docker", "volume", "ls"]:
out = "pipelines_ntfy-data\n"
if args[-4:] == ["auth", "list", "--format", "json"]:
out = '[{"id":"fixture","connections":[{"id":"fixture"}]}]' if logged else '[]'
if "opencode models" in args[-1]:
@@ -571,10 +575,8 @@ fi
out = '{"healthy":true,"session_id":"ses_fixture"}'
if "exec opencode auth login" in args[-1] and confirm == "yes":
logged = True
if "token" in args:
out = f"token {token} created\n"
if args[-2:] == ["status", "--json"]:
out = '{"ntfy":{"health":"healthy","url":"http://192.168.1.20:8090"},"topic":"pipelines"}'
out = '{"type":"status","runs":[]}'
if args[-2:] == ["ping", "--json"]:
out = setup.json.dumps({"type": "pong", "build": {"version": "a" * 12, "commit": "a" * 40, "dirty": False}})
if args[-3:]==["harness","list","--json"]:
@@ -588,23 +590,22 @@ fi
if fail and (fail in args or (fail=="login" and "exec opencode auth login" in args[-1]) or (fail=="provider-check" and any("provider-check" in arg for arg in args))):
code, out = 9, "private provider data/token"
if fail == "host" and command[0] != "docker" and args[-2:] == ["status", "--json"]:
code, out = 9, '{"ntfy":{"health":"not configured"}}'
code, out = 9, '{}'
return subprocess.CompletedProcess(command, code, stdout=out, stderr="")
args = setup.arguments([] if existing else ["--ntfy-url", "http://192.168.1.20:8090",
"--bind-address", "192.168.1.20", "--timezone", "Europe/London"])
args = setup.arguments([] if existing else ["--timezone", "Europe/London"])
args.harness=harness
installer = setup.Setup(directory, runner=runner, prompt=lambda _: "1")
installer.resolver = lambda: {"opencode": {"image": "ghcr.io/anomalyco/opencode", "version": "2.0.26", "digest": "sha256:" + "a" * 64},
"pi": {"version": "1.1.0", "engine": ">=22.19.0"}}
installer.choose_model=lambda models, title, purpose="", step="", current="": models[0]
with patch.object(setup.lan,"detect_lan",return_value="192.168.1.20"):
with patch.object(setup.lan,"detect_lan",return_value="192.168.1.20",side_effect=lan_error):
installer.run(args)
return calls, token
return calls
def test_fresh_pi_setup_skips_opencode_login_and_generation(self):
with tempfile.TemporaryDirectory() as directory:
calls, _ = self.exercise(directory, harness="pi")
calls = self.exercise(directory, harness="pi")
setup_call = next(c for c in calls if "setup" in c and "pi" in c)
self.assertIn("--login", setup_call)
self.assertIn("--default", setup_call)
@@ -634,34 +635,53 @@ fi
for want in ("OpenCode 2.0.26", "Pi 1.1.0", "Node 22.19.0"):
self.assertIn(want, label)
def test_fresh_setup_wires_notifications_and_runs_container_login(self):
def test_fresh_setup_runs_container_login_without_ntfy(self):
with tempfile.TemporaryDirectory() as directory:
calls, token = self.exercise(directory)
calls = self.exercise(directory)
self.assertTrue(any("exec opencode auth login" in c[-1] for c in calls))
self.assertTrue(any("--force-recreate" in c for c in calls))
recreate = next(c for c in calls if "--force-recreate" in c)
# The old ntfy container is an orphan once compose.yaml drops it.
self.assertIn("--remove-orphans", recreate)
build = next(c for c in calls if "build" in c)
self.assertIn("PIPELINES_COMMIT=" + "a" * 40, build)
self.assertIn("PIPELINES_DIRTY=false", build)
self.assertEqual(Path(directory, "secrets/ntfy-token.txt").read_text(), token + "\n")
self.assertFalse(any(token in " ".join(c) for c in calls))
self.assertLess(next(i for i,c in enumerate(calls) if "token" in c), next(i for i,c in enumerate(calls) if "build" in c))
self.assertLess(next(i for i,c in enumerate(calls) if "exec opencode auth login" in c[-1]), next(i for i,c in enumerate(calls) if "--force-recreate" in c))
self.assertTrue(any("curl --config -" in " ".join(c) for c in calls))
self.assertFalse(any(c[:1] == ["up"] and "ntfy" in c for c in calls))
self.assertFalse(any(c[:1] == ["exec"] and "ntfy" in c for c in calls))
self.assertFalse(Path(directory, "secrets/ntfy-token.txt").exists())
self.assertNotIn("NTFY", Path(directory, ".env").read_text())
config = Path(os.environ["XDG_CONFIG_HOME"])/"pipelines/client.json"
self.assertEqual(setup.json.loads(config.read_text())["server_url"],"ws://127.0.0.1:8081/connect")
def test_reinstall_preserves_configuration_tokens_and_provider_setup(self):
def test_reinstall_preserves_configuration_and_provider_setup(self):
with tempfile.TemporaryDirectory() as directory:
self.exercise(directory)
files = [Path(directory, ".env"), Path(directory, "secrets/ntfy-token.txt")]
before = [p.read_bytes() for p in files]
calls, _ = self.exercise(directory, existing=True)
self.assertFalse(any("exec opencode auth login" in c[-1] or "token" in c for c in calls))
self.assertEqual(before[1],files[1].read_bytes())
self.assertEqual(files[0].read_bytes(),before[0].replace(b"NTFY_BIND_ADDRESS=192.168.1.20",b"NTFY_BIND_ADDRESS=0.0.0.0")+b"PIPELINES_BIND_ADDRESS=0.0.0.0\n")
normalized=files[0].read_bytes()
self.exercise(directory,existing=True)
self.assertEqual(normalized,files[0].read_bytes())
settings = Path(directory, ".env")
before = settings.read_bytes()
calls = self.exercise(directory, existing=True)
self.assertFalse(any("exec opencode auth login" in c[-1] for c in calls))
self.assertEqual(settings.read_bytes(), before + b"PIPELINES_BIND_ADDRESS=0.0.0.0\n")
normalized = settings.read_bytes()
self.exercise(directory, existing=True)
self.assertEqual(normalized, settings.read_bytes())
def test_reinstall_retires_the_old_ntfy_container_volume_token_and_settings(self):
with tempfile.TemporaryDirectory() as directory:
self.exercise(directory)
settings = Path(directory, ".env")
settings.write_text(settings.read_text() + "NTFY_BASE_URL=http://192.168.1.20:8090\nNTFY_BIND_ADDRESS=0.0.0.0\n")
Path(directory, "secrets").mkdir()
Path(directory, "secrets/ntfy-token.txt").write_text("tk_old\n")
with redirect_stdout(io.StringIO()) as output:
calls = self.exercise(directory, existing=True, ntfy_leftovers=True)
self.assertIn(["-f", "0123abcd"], calls)
self.assertIn(["rm", "pipelines_ntfy-data"], calls)
self.assertFalse(Path(directory, "secrets/ntfy-token.txt").exists())
self.assertNotIn("NTFY", settings.read_text())
self.assertIn("Retired the old ntfy notification server", output.getvalue())
self.assertNotIn("tk_old", output.getvalue())
# Retirement happens before anything is (re)started.
self.assertLess(calls.index(["-f", "0123abcd"]), next(i for i, c in enumerate(calls) if "--force-recreate" in c))
def test_login_failure_or_cancel_does_not_mark_complete_or_start_server(self):
for fail, confirm in [("login", "yes"), (None, "no")]:
@@ -669,7 +689,7 @@ fi
with self.assertRaises(ValueError) as raised:
self.exercise(directory, fail=fail, confirm=confirm)
self.assertNotIn("private provider", str(raised.exception))
self.assertTrue(Path(directory, "secrets/ntfy-token.txt").stat().st_size)
self.assertTrue(Path(directory, ".env").stat().st_size)
def test_status_and_publication_failures_are_not_success(self):
for failure in ["status", "sh", "provider-check", "host"]:
@@ -681,15 +701,13 @@ fi
path = Path(directory, ".env")
path.write_text("existing settings")
with self.assertRaises(ValueError):
setup.Setup(directory).settings(setup.arguments(["--ntfy-url", "https://example.com"]))
setup.Setup(directory).settings(setup.arguments(["--timezone", "UTC"]))
self.assertEqual(path.read_text(), "existing settings")
def test_existing_env_rejects_unsafe_bind_override(self):
with tempfile.TemporaryDirectory() as directory:
path=Path(directory,".env");path.write_text("NTFY_BIND_ADDRESS=127.0.0.1\n")
with self.assertRaises(ValueError):
setup.Setup(directory).settings(setup.arguments(["--bind-address","0.0.0.0\nOTHER=bad"]))
self.assertEqual(path.read_text(),"NTFY_BIND_ADDRESS=127.0.0.1\n")
def test_ntfy_flags_are_gone(self):
for flag in (["--ntfy-url", "http://192.168.1.20:8090"], ["--bind-address", "0.0.0.0"]):
with self.assertRaises(SystemExit), redirect_stderr(io.StringIO()):
setup.arguments(flag)
def test_existing_env_symlink_is_not_modified(self):
with tempfile.TemporaryDirectory() as directory:
+119 -191
View File
@@ -3,6 +3,7 @@ import io
import json
import os
import plistlib
import shutil
from contextlib import redirect_stdout
from pathlib import Path
import subprocess
@@ -18,41 +19,13 @@ manage_spec = importlib.util.spec_from_file_location("pipelines_manage", Path(__
manage = importlib.util.module_from_spec(manage_spec)
manage_spec.loader.exec_module(manage)
TOKEN = "tk_" + "a" * 29
NTFY_VERSION = "2.11.0"
NTFY_MODULE = "heckel.io/ntfy/v2"
def resolution():
"""The shape resolve_ntfy returns: an exact tag to build the server from."""
return {"repository": "binwiederhier/ntfy", "module": NTFY_MODULE,
"version": NTFY_VERSION, "tag": "v" + NTFY_VERSION}
class _Served:
def poll(self):
return None
def terminate(self):
pass
def wait(self, timeout=None):
return 0
def fake_ntfy_serve(command, **kwargs):
"""`ntfy serve` creates its account database next to its configuration."""
config = Path(command[command.index("--config") + 1])
(config.parent / "auth.db").write_bytes(b"")
return _Served()
OPENSSL = shutil.which("openssl")
class Recorder:
def __init__(self, token=TOKEN, volumes=(), image="pipelines-pipelines:latest",
def __init__(self, volumes=(), image="pipelines-pipelines:latest",
fail_create=False, fail_copy=False, fail_volume_ls=False, fail_build=False, fail_web=False,
host_model="fixture/host-default"):
self.calls = []
self.token = token
self.volumes = volumes
self.image = image
self.fail_create = fail_create
@@ -61,18 +34,8 @@ class Recorder:
self.fail_build = fail_build
self.fail_web = fail_web
self.host_model = host_model
self._module_cache = None
self.kwargs = []
def module_cache(self):
"""A stand-in Go module cache holding the pinned ntfy module source."""
if self._module_cache is None:
self._module_cache = tempfile.mkdtemp(prefix="gomodcache-")
source = Path(self._module_cache) / f"{NTFY_MODULE}@{resolution()['tag']}"
source.mkdir(parents=True)
(source / "go.mod").write_text(f"module {NTFY_MODULE}\n")
return self._module_cache
def __call__(self, command, **kwargs):
command = list(command)
self.calls.append(command)
@@ -106,8 +69,6 @@ class Recorder:
code = 1
else:
Path(command[3]).write_bytes(b"migrated")
elif command[0] == "go" and command[1:3] == ["env", "GOMODCACHE"]:
stdout = self.module_cache() + "\n"
elif command[0] == "go" and command[1:2] == ["build"]:
if self.fail_build:
code = 1
@@ -117,8 +78,6 @@ class Recorder:
output = Path(command[command.index("-o") + 1])
output.write_bytes(b"#!/bin/sh\n")
output.chmod(0o755)
if command[0].endswith("ntfy") and "token" in command:
stdout = f"token {self.token} created for pipeline-publisher\n"
return subprocess.CompletedProcess(command, code, stdout=stdout, stderr="")
def has(self, *parts):
@@ -138,12 +97,15 @@ class SetupNativeTests(unittest.TestCase):
# A disposable XDG config home keeps the client default out of the real
# user configuration during tests.
return setup_native.Setup(directory, prefix=Path(directory) / "prefix", runner=recorder,
resolver=resolution, popen=fake_ntfy_serve,
environ={"XDG_CONFIG_HOME": str(Path(directory) / "config"),
"PIPELINES_WEB_PASSWORD": "chosen tulip orbit canyon"})
"PIPELINES_WEB_PASSWORD": "chosen tulip orbit canyon",
# The update signing key stays in scratch too, made
# with the host OpenSSL (shutil.which is patched).
"PIPELINES_UPDATE_SIGNING_KEY": str(Path(directory) / "update-key.pem"),
"PIPELINES_OPENSSL": OPENSSL or ""})
@staticmethod
def which_all(opencode="/usr/bin/opencode", pi=None, cc="/usr/bin/cc"):
def which_all(opencode="/usr/bin/opencode", pi=None):
mapping = {"go": "/usr/bin/go", "python3": "/usr/bin/python3",
"git": "/usr/bin/git", "curl": "/usr/bin/curl", "node": "/usr/bin/node",
"launchctl": "/bin/launchctl", "systemctl": "/usr/bin/systemctl"}
@@ -151,8 +113,6 @@ class SetupNativeTests(unittest.TestCase):
mapping["opencode"] = opencode
if pi:
mapping["pi"] = pi
if cc:
mapping["cc"] = cc
return lambda name: mapping.get(name)
def test_reinstall_preserves_network_settings_and_explicit_flags_override(self):
@@ -160,17 +120,17 @@ class SetupNativeTests(unittest.TestCase):
installer = self.installer(directory, Recorder())
prefix = installer.resolve_prefix()
prefix.mkdir()
manifest = {"server_port": 8090, "ntfy_port": 8091,
manifest = {"server_port": 8090,
"bind_address": "127.0.0.2",
"web": {"port": 8096, "host": "127.0.0.1"}}
(prefix / setup_native.MARKER).write_text(json.dumps(manifest))
args = setup_native.arguments([])
installer.preserve_network_settings(prefix, args)
self.assertEqual((args.port, args.ntfy_port, args.web_port), (8090, 8091, 8096))
self.assertEqual((args.port, args.web_port), (8090, 8096))
self.assertEqual((args.bind_address, args.web_host), ("127.0.0.2", "127.0.0.1"))
args = setup_native.arguments(["--web-port=8082", "--port", "8080"])
installer.preserve_network_settings(prefix, args)
self.assertEqual((args.port, args.ntfy_port, args.web_port), (8080, 8091, 8082))
self.assertEqual((args.port, args.web_port), (8080, 8082))
(prefix / setup_native.MARKER).unlink()
args = setup_native.arguments([])
installer.preserve_network_settings(prefix, args)
@@ -447,7 +407,7 @@ class SetupNativeTests(unittest.TestCase):
with self.assertRaisesRegex(ValueError, "OpenCode was not found"):
installer.harness()
def test_full_run_writes_manifest_tokens_and_config_without_harness_install(self):
def test_full_run_writes_manifest_and_config_without_harness_install_or_ntfy(self):
with tempfile.TemporaryDirectory() as directory:
recorder = Recorder()
installer = self.installer(directory, recorder)
@@ -462,8 +422,10 @@ class SetupNativeTests(unittest.TestCase):
self.assertEqual(config["prefix"], str(prefix.resolve()))
self.assertEqual(config["server_port"], 8080)
self.assertEqual(config["bind_address"], "127.0.0.1")
self.assertEqual(config["ntfy"]["mode"], "native")
self.assertEqual(config["topic"], "pipelines")
self.assertEqual(config["mode"], "native")
self.assertEqual(manage.install_mode(config), "native")
for key in ("ntfy", "ntfy_port", "topic", "username", "public_url"):
self.assertNotIn(key, config)
self.assertEqual(config["opencode"], "/usr/bin/opencode")
self.assertEqual(config["pi"], "")
self.assertEqual(config["opencode_env"]["PIPELINES_DEFAULT_MODEL"], "fixture/host-default")
@@ -478,25 +440,17 @@ class SetupNativeTests(unittest.TestCase):
self.assertTrue(Path(config["registration"]).is_file())
self.assertTrue(recorder.has("start", "--prefix", str(prefix.resolve())))
self.assertEqual((prefix / setup_native.MARKER).stat().st_mode & 0o777, 0o600)
token_path = prefix / "secrets/publisher-token"
self.assertEqual(token_path.read_text(), TOKEN + "\n")
self.assertEqual(token_path.stat().st_mode & 0o777, 0o600)
text = (prefix / "data/ntfy/server.yml").read_text()
for needle in ('listen-http:', 'base-url: "http://192.168.1.20:8090"', 'cache-file:', 'auth-file:',
'auth-default-access: "deny-all"', 'enable-login: true', 'attachment-cache-dir:',
'attachment-expiry-duration:', 'attachment-total-size-limit:',
'attachment-file-size-limit:'):
self.assertIn(needle, text)
self.assertNotIn("topic", text)
self.assertFalse((prefix / "secrets/publisher-token").exists())
self.assertFalse((prefix / "data/ntfy").exists())
self.assertFalse((prefix / "bin/ntfy").exists())
self.assertNotIn("ntfy", Path(config["registration"]).read_text())
self.assertTrue(recorder.has(str(prefix.resolve() / "bin/pipelines"), "skill", "install"))
self.assertTrue(recorder.has("access", "pipeline-publisher", "pipelines", "write-only"))
self.assertTrue(recorder.has("access", "phone-reader", "pipelines", "read-only"))
self.assertFalse(any("ntfy" in part for call in recorder.calls for part in call))
discovery = [call for call in recorder.calls if call[0].endswith("opencode")]
self.assertEqual(discovery, [["/usr/bin/opencode", "api", "get", "/api/model/default"]])
self.assertFalse(any("pipelines-tui" in part for call in recorder.calls for part in call))
self.assertFalse(any(TOKEN in part for call in recorder.calls for part in call))
def test_reinstall_keeps_existing_publisher_token(self):
def test_reinstall_keeps_settings_and_prints_web_urls_last(self):
with tempfile.TemporaryDirectory() as directory:
recorder = Recorder()
installer = self.installer(directory, recorder)
@@ -505,22 +459,100 @@ class SetupNativeTests(unittest.TestCase):
patch.object(setup_native.lan, "detect_lan", return_value="192.168.1.20"), \
patch.object(setup_native.configure, "host_timezone", return_value="Europe/London"):
installer.run(setup_native.arguments(["--web-port", "8096"]))
before = (prefix / "secrets/publisher-token").read_text()
def refuse_resolution():
raise AssertionError("re-resolved ntfy despite a verified installed binary")
installer.resolver = refuse_resolution
recorder.calls.clear()
with redirect_stdout(io.StringIO()) as output:
installer.run(setup_native.arguments([]))
self.assertEqual((prefix / "secrets/publisher-token").read_text(), before)
self.assertEqual(manage.load(prefix)["web"]["port"], 8096)
self.assertEqual(output.getvalue().splitlines()[-4:], [
" http://localhost:8096/", " http://127.0.0.1:8096/",
"OpenCode is required (default stage and chat harness) and is set up by ./install.",
"Next: set up your agent harnesses: pipelines harness setup claude|codex|opencode|pi"])
self.assertFalse(any("token" in call for call in recorder.calls), "reinstall re-created the token")
self.assertNotIn("ntfy", output.getvalue())
def legacy_install(self, installer, prefix):
"""An install from before ntfy was removed, on disk."""
with patch.object(setup_native.shutil, "which", side_effect=self.which_all()), \
patch.object(setup_native.lan, "detect_lan", return_value="192.168.1.20"), \
patch.object(setup_native.configure, "host_timezone", return_value="Europe/London"), \
redirect_stdout(io.StringIO()):
installer.run(setup_native.arguments([]))
manifest = json.loads((prefix / setup_native.MARKER).read_text())
manifest.pop("mode")
manifest.update(ntfy_port=8090, topic="pipelines", public_url="http://192.168.1.20:8090",
username="phone-reader",
ntfy={"mode": "native", "bin": str(prefix.resolve() / "bin/ntfy"), "version": "v2.38.1",
"config": str(prefix.resolve() / "data/ntfy/server.yml"),
"base_url": "http://192.168.1.20:8090"})
(prefix / setup_native.MARKER).write_text(json.dumps(manifest))
(prefix / "data/ntfy/attachments").mkdir(parents=True)
for name in ("bin/ntfy", "logs/ntfy.log", "data/ntfy/server.yml", "data/ntfy/auth.db"):
(prefix / name).write_text("old")
(prefix / "secrets/publisher-token").write_text("tk_secretsecret\n")
(prefix / "ntfy.pid").write_text("4321")
return manifest
def test_reinstall_retires_the_old_ntfy(self):
for running in (True, False):
with self.subTest(running=running), tempfile.TemporaryDirectory() as directory:
installer = self.installer(directory, Recorder())
prefix = Path(directory) / "prefix"
self.legacy_install(installer, prefix)
installer.install_log = prefix / "logs/install.log"
installer.install_log.write_text("earlier\n")
alive = [running]
killed = []
def command_line(pid):
return f"{prefix.resolve()}/bin/ntfy serve --config x" if pid == 4321 and alive[0] else None
def kill(pid, sig):
killed.append((pid, sig))
alive[0] = False
with patch.object(setup_native.shutil, "which", side_effect=self.which_all()), \
patch.object(setup_native.lan, "detect_lan", return_value="192.168.1.20"), \
patch.object(setup_native.configure, "host_timezone", return_value="Europe/London"), \
patch.object(setup_native.manage, "process_command", side_effect=command_line), \
patch.object(setup_native.manage.os, "kill", side_effect=kill), \
redirect_stdout(io.StringIO()) as output:
installer.run(setup_native.arguments([]))
self.assertEqual(killed, [(4321, setup_native.manage.signal.SIGTERM)] if running else [])
for path in setup_native.manage.legacy_ntfy_paths(prefix):
self.assertFalse(path.exists(), path)
self.assertTrue((prefix / "data").is_dir())
config = manage.load(prefix)
self.assertEqual(config["mode"], "native")
for key in ("ntfy", "ntfy_port", "topic", "username", "public_url"):
self.assertNotIn(key, config)
log = installer.install_log.read_text()
self.assertIn("Retiring ntfy (version v2.38.1)", log)
self.assertIn(str(prefix.resolve() / "bin/ntfy"), log)
self.assertNotIn("tk_secretsecret", log)
self.assertEqual("Stopped the old ntfy server process." in log, running)
self.assertIn("Retired the old ntfy notification server", output.getvalue())
# A second reinstall has nothing left to retire.
with patch.object(setup_native.shutil, "which", side_effect=self.which_all()), \
patch.object(setup_native.lan, "detect_lan", return_value="192.168.1.20"), \
patch.object(setup_native.configure, "host_timezone", return_value="Europe/London"), \
redirect_stdout(io.StringIO()) as output:
installer.run(setup_native.arguments([]))
self.assertEqual(installer.install_log.read_text().count("Retiring ntfy"), 1)
self.assertNotIn("ntfy", output.getvalue())
def test_reinstall_never_signals_a_reused_ntfy_pid(self):
with tempfile.TemporaryDirectory() as directory:
installer = self.installer(directory, Recorder())
prefix = Path(directory) / "prefix"
self.legacy_install(installer, prefix)
with patch.object(setup_native.shutil, "which", side_effect=self.which_all()), \
patch.object(setup_native.lan, "detect_lan", return_value="192.168.1.20"), \
patch.object(setup_native.configure, "host_timezone", return_value="Europe/London"), \
patch.object(setup_native.manage, "process_command", return_value="/usr/bin/sleep 1000"), \
patch.object(setup_native.manage.os, "kill", side_effect=AssertionError("signalled a reused PID")), \
redirect_stdout(io.StringIO()):
installer.run(setup_native.arguments([]))
self.assertFalse((prefix / "ntfy.pid").exists())
self.assertFalse((prefix / "bin/ntfy").exists())
def test_upgrade_keeps_an_all_interfaces_web_host_with_a_warning_and_lan_is_opt_in(self):
with tempfile.TemporaryDirectory() as directory:
@@ -562,97 +594,10 @@ class SetupNativeTests(unittest.TestCase):
with self.assertRaisesRegex(ValueError, "Invalid --web-host"):
installer.run(setup_native.arguments(["--web-host", "everywhere"]))
def test_ntfy_is_built_from_the_pinned_module(self):
with tempfile.TemporaryDirectory() as directory:
recorder = Recorder()
installer = self.installer(directory, recorder)
prefix = Path(directory) / "prefix"
installer.prepare_layout(prefix)
with patch.object(setup_native.shutil, "which", side_effect=self.which_all()):
path = installer.build_ntfy(prefix, resolution())
self.assertTrue(path.is_file())
self.assertTrue(path.stat().st_mode & 0o100)
self.assertTrue(recorder.has("go", "mod", "download", f"{NTFY_MODULE}@v{NTFY_VERSION}"))
build = next(call for call in recorder.calls if call[:2] == ["go", "build"] and call[-1] == ".")
self.assertIn("-trimpath", build)
self.assertIn(setup_native.NTFY_BUILD_TAGS, build)
self.assertTrue(any(f"-X main.version=v{NTFY_VERSION}" in part for part in build))
self.assertTrue(build[build.index("-o") + 1].endswith("/ntfy"))
kwargs = next(kw for call, kw in zip(recorder.calls, recorder.kwargs)
if call[:2] == ["go", "build"] and call[-1] == ".")
self.assertEqual(kwargs.get("env", {}).get("CGO_ENABLED"), "1")
def test_ntfy_install_handles_system_temp_on_another_filesystem(self):
with tempfile.TemporaryDirectory() as directory:
installer = self.installer(directory, Recorder())
prefix = Path(directory) / "prefix"
installer.prepare_layout(prefix)
installed = prefix / "bin/ntfy"
installed.write_bytes(b"previous binary")
replace = os.replace
def cross_device_guard(source, destination):
# Model /tmp on a separate mount from the installation prefix.
if not Path(source).is_relative_to(prefix / "bin"):
import errno
raise OSError(errno.EXDEV, "Invalid cross-device link")
return replace(source, destination)
with patch.object(setup_native.shutil, "which", side_effect=self.which_all()), \
patch.object(setup_native.os, "replace", side_effect=cross_device_guard):
installer.build_ntfy(prefix, resolution())
self.assertNotEqual(installed.read_bytes(), b"previous binary")
self.assertEqual(installed.stat().st_mode & 0o777, 0o755)
self.assertEqual(list((prefix / "bin").glob(".ntfy-*")), [])
def test_ntfy_build_is_reused_for_the_same_version(self):
with tempfile.TemporaryDirectory() as directory:
recorder = Recorder()
installer = self.installer(directory, recorder)
prefix = Path(directory) / "prefix"
installer.prepare_layout(prefix)
with patch.object(setup_native.shutil, "which", side_effect=self.which_all()):
installer.build_ntfy(prefix, resolution())
installer.write_manifest(prefix, {"ntfy": {"version": "v" + NTFY_VERSION}})
recorder.calls.clear()
installer.build_ntfy(prefix, resolution())
self.assertFalse(any(call[:2] == ["go", "build"] for call in recorder.calls),
"rebuilt ntfy for an already installed version")
def test_missing_c_compiler_fails_actionably(self):
installer = setup_native.Setup("/tmp", runner=Recorder(), resolver=resolution, environ={})
with patch.object(setup_native.shutil, "which", side_effect=self.which_all(cc=None)):
with self.assertRaisesRegex(ValueError, "No C compiler found"):
installer.require_compiler()
def test_ntfy_build_failure_is_reported(self):
with tempfile.TemporaryDirectory() as directory:
installer = self.installer(directory, Recorder(fail_build=True))
prefix = Path(directory) / "prefix"
installer.prepare_layout(prefix)
installed = prefix / "bin/ntfy"
installed.write_bytes(b"previous binary")
with patch.object(setup_native.shutil, "which", side_effect=self.which_all()):
with self.assertRaisesRegex(ValueError, "build failed"):
installer.build_ntfy(prefix, resolution())
self.assertEqual(installed.read_bytes(), b"previous binary")
self.assertEqual(list((prefix / "bin").glob(".ntfy-*")), [])
def test_publisher_token_is_never_overwritten(self):
with tempfile.TemporaryDirectory() as directory:
prefix = Path(directory) / "prefix"
(prefix / "secrets").mkdir(parents=True)
path = prefix / "secrets/publisher-token"
setup_native.tokens.save_token(f"token {TOKEN} created", path, 0o600)
self.assertEqual(path.stat().st_mode & 0o777, 0o600)
with self.assertRaises(ValueError):
setup_native.tokens.save_token(f"token {TOKEN} created", path, 0o600)
self.assertEqual(path.read_text(), TOKEN + "\n")
def test_migration_copies_docker_data_only_when_absent(self):
with tempfile.TemporaryDirectory() as directory:
prefix = Path(directory) / "prefix"
(prefix / "data/ntfy").mkdir(parents=True)
(prefix / "data").mkdir(parents=True)
recorder = Recorder(volumes=("pipelines_pipelines-data", "pipelines_ntfy-data"))
installer = self.installer(directory, recorder)
self.assertTrue(installer.migrate_docker(prefix, replace=False))
@@ -660,7 +605,10 @@ class SetupNativeTests(unittest.TestCase):
self.assertTrue(any(call[:2] == ["docker", "cp"] and call[2].endswith("-wal")
for call in installer.runner.calls),
"the SQLite write-ahead log sidecar must be copied with the database")
self.assertEqual((prefix / "data/ntfy/auth.db").read_bytes(), b"migrated")
# ntfy's old Docker volume is not migrated: nothing uses it.
self.assertFalse((prefix / "data/ntfy").exists())
self.assertFalse(any("pipelines_ntfy-data" in part for call in recorder.calls
if call[1:2] == ["create"] for part in call))
def test_migration_keeps_existing_native_data_without_opt_in(self):
with tempfile.TemporaryDirectory() as directory:
@@ -693,7 +641,7 @@ class SetupNativeTests(unittest.TestCase):
with tempfile.TemporaryDirectory() as directory:
installer = setup_native.Setup(directory, prefix=Path(directory) / "prefix",
runner=no_docker, resolver=resolution, environ={})
runner=no_docker, environ={})
self.assertEqual(installer.docker_volumes(), ())
def test_requested_migration_failure_aborts(self):
@@ -705,23 +653,6 @@ class SetupNativeTests(unittest.TestCase):
with self.assertRaisesRegex(ValueError, "install aborted"):
installer.migrate_docker(prefix, replace=False)
def test_full_run_migrates_docker_auth_store_before_native_accounts(self):
with tempfile.TemporaryDirectory() as directory:
recorder = Recorder(volumes=("pipelines_ntfy-data",))
installer = self.installer(directory, recorder)
prefix = Path(directory) / "prefix"
with patch.object(setup_native.shutil, "which", side_effect=self.which_all()), \
patch.object(setup_native.lan, "detect_lan", return_value="192.168.1.20"), \
patch.object(setup_native.configure, "host_timezone", return_value="Europe/London"):
installer.run(setup_native.arguments([]))
# The migrated store must survive bootstrap instead of being shadowed.
self.assertEqual((prefix / "data/ntfy/auth.db").read_bytes(), b"migrated")
copy_index = next(i for i, call in enumerate(recorder.calls)
if call[0] == "docker" and call[1:2] == ["cp"])
add_index = next(i for i, call in enumerate(recorder.calls)
if "pipeline-publisher" in call and "user" in call)
self.assertLess(copy_index, add_index, "auth store migrated after native accounts were created")
def test_missing_local_image_aborts_migration(self):
with tempfile.TemporaryDirectory() as directory:
prefix = Path(directory) / "prefix"
@@ -994,8 +925,7 @@ class SetupNativeTests(unittest.TestCase):
shadow_dir = directory / "earlier"
shadow = self._fake_pipelines(shadow_dir / "pipelines", "old-version", "aaaa")
before = shadow.read_bytes()
installer = setup_native.Setup(directory, prefix=prefix, runner=subprocess.run,
resolver=resolution, environ={})
installer = setup_native.Setup(directory, prefix=prefix, runner=subprocess.run, environ={})
with patch.object(setup_native.shutil, "which", side_effect=lambda name: str(shadow) if name == "pipelines" else None):
output = io.StringIO()
with redirect_stdout(output):
@@ -1015,8 +945,7 @@ class SetupNativeTests(unittest.TestCase):
directory = Path(directory)
prefix = directory / "prefix"
installed = self._fake_pipelines(prefix / "bin/pipelines", "same-version", "cccc")
installer = setup_native.Setup(directory, prefix=prefix, runner=subprocess.run,
resolver=resolution, environ={})
installer = setup_native.Setup(directory, prefix=prefix, runner=subprocess.run, environ={})
with patch.object(setup_native.shutil, "which", return_value=str(installed)):
output = io.StringIO()
with redirect_stdout(output):
@@ -1027,7 +956,7 @@ class SetupNativeTests(unittest.TestCase):
def test_check_path_shadow_is_silent_without_a_path_binary(self):
with tempfile.TemporaryDirectory() as directory:
installer = setup_native.Setup(directory, prefix=Path(directory) / "prefix",
runner=subprocess.run, resolver=resolution, environ={})
runner=subprocess.run, environ={})
with patch.object(setup_native.shutil, "which", return_value=None):
output = io.StringIO()
with redirect_stdout(output):
@@ -1053,8 +982,7 @@ class SetupNativeTests(unittest.TestCase):
installed = self._fake_pipelines(prefix / "bin/pipelines", "new-version", "bbbb")
shadow = self._fake_pipelines(directory / "earlier/pipelines", "old-version", "aaaa")
runner = VersionRunner()
installer = setup_native.Setup(directory, prefix=prefix, runner=runner,
resolver=resolution, environ={})
installer = setup_native.Setup(directory, prefix=prefix, runner=runner, environ={})
with patch.object(setup_native.shutil, "which", return_value=str(shadow)):
output = io.StringIO()
with redirect_stdout(output):
+29
View File
@@ -252,6 +252,35 @@ class UninstallTests(unittest.TestCase):
runner=processes, system="Linux").run()
self.assertEqual(signalled, [40001, 40002, 40003])
def test_leftover_ntfy_is_removed_when_the_manifest_no_longer_mentions_it(self):
self.put(self.prefix / "pipelines-install.json", json.dumps({
"format": 1, "mode": "native", "prefix": str(self.prefix)}))
for name in ("bin/ntfy", "ntfy.pid", "logs/ntfy.log", "data/ntfy/auth.db", "secrets/publisher-token"):
self.put(self.prefix / name)
original = self.recorder
commands = [f"{self.prefix}/bin/ntfy serve --config {self.prefix}/data/ntfy/server.yml",
"/usr/bin/ntfy serve"]
def processes(command, **kwargs):
if command[0] == "ps":
return subprocess.CompletedProcess(command, 0, stdout="\n".join(
f"{40001 + i} {text}" for i, text in enumerate(commands)), stderr="")
return original(command, **kwargs)
signalled = []
def signal_process(pid, number):
if number == 0:
raise ProcessLookupError()
signalled.append(pid)
with patch.object(uninstall.os, "kill", side_effect=signal_process):
uninstall.Uninstall(home=self.home, repo=self.repo, environ={},
runner=processes, system="Linux").run()
self.assertEqual(signalled, [40001])
self.assertFalse(self.prefix.exists())
docker = [c for c in original.calls if c and c[0] == "docker"]
self.assertTrue(any("pipelines_ntfy-data" in c and "rm" in c for c in docker))
def test_macos_reset_uses_only_its_launch_agent(self):
unit = self.put(self.home / "Library/LaunchAgents/net.a-wan.pipelines.plist",
"Managed by Pipelines native installer")
+2
View File
@@ -14,6 +14,8 @@ import time
LABEL = "net.a-wan.pipelines"
MARKER = "Managed by Pipelines native installer"
# pipelines_ntfy-data and <prefix>/bin/ntfy below are leftovers of installs
# from before ntfy was removed; they are cleaned up whatever the manifest says.
BUILD_VOLUMES = {"pipelines-flutter-pub", "pipelines-flutter-gradle", "pipelines-android-sdk",
"pipelines_pipelines-data", "pipelines_ntfy-data"}