#!/usr/bin/env python3 """Extract only the token from ntfy's CLI response; never print the credential.""" import os from pathlib import Path import re import sys def save_token(output, directory): tokens = re.findall(r"\btk_[A-Za-z0-9]{29}\b", output) if len(tokens) != 1: raise ValueError("ntfy did not return exactly one token; existing credentials were not changed") directory = Path(directory) secrets = directory / "secrets" secrets.mkdir(mode=0o700, exist_ok=True) secrets.chmod(0o700) path = secrets / "ntfy-token.txt" 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") # Compose's file secret is a bind mount. Container uid 10001 needs read access; # the private host parent directory restricts access by other host users. path.chmod(0o444) if __name__ == "__main__": try: save_token(sys.stdin.read(), Path(__file__).resolve().parents[1]) except ValueError as error: sys.exit(str(error)) print("Saved ntfy publishing token; restart pipelines if it was already running.")