#!/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): """Create the pipeline-publisher and phone-reader accounts on an ntfy server. ``run(args, capture=False, interactive=False)`` executes the ntfy CLI (directly or through Compose) and returns the completed process. 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: log("Set a password for ntfy's pipeline-publisher account (not a model-provider account).") run(["user", "add", "--ignore-exists", "pipeline-publisher"], interactive=True) 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. 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) 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.")