"""Create/update an unprivileged Debian 13 LXC from a local FinalToken source snapshot.""" import argparse import hashlib import ipaddress import json import os from pathlib import Path import re import shutil import subprocess import sys import tarfile import tempfile import time from urllib.parse import urlsplit import uuid sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from source_policy import is_private_path ROOT = Path(__file__).resolve().parents[2] PROJECTS = ("FinalToken.Core", "FinalToken.Fleet", "FinalToken.Web", "FinalToken.Worker") TEMPLATE = re.compile(r"debian-13-standard_[A-Za-z0-9.+_-]+_amd64\.tar\.(?:zst|xz|gz)\Z") def run(command, *, capture=False, check=True): command = [str(a) for a in command] if command[:2] == ["pct", "exec"]: # Proxmox defaults differ between versions; never forward the host's secret environment. command[3:3] = ["--keep-env", "0"] return subprocess.run(command, check=check, text=True, stdout=subprocess.PIPE if capture else None, stderr=subprocess.PIPE if capture else None) def identifier(value): if not re.fullmatch(r"[A-Za-z][A-Za-z0-9_]{0,63}", value): raise ValueError("Machine id must start with a letter and contain only letters, digits and underscores") return value def domain_name(value): if len(value) > 253 or not all(re.fullmatch(r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?", p) for p in value.split(".")) or "." not in value: raise ValueError("Domain must be a DNS name without a scheme, port, path or shell syntax") return value.lower() def server_url(value): url = urlsplit(value) if url.scheme != "https" or not url.hostname or url.username or url.password or url.path not in ("", "/") or url.query or url.fragment: raise ValueError("Remote server URL must be an HTTPS origin") _ = url.port return value.rstrip("/") def parser(): p = argparse.ArgumentParser(description=__doc__) p.add_argument("action", choices=("install", "update")) p.add_argument("--ctid", type=int, help="New CT id; defaults to Proxmox nextid. Required for update.") p.add_argument("--source", type=Path, default=ROOT, help="Local checkout including uncommitted source") p.add_argument("--storage", help="Proxmox rootdir storage, e.g. local-lvm (required for install)") p.add_argument("--template-storage", default="local") p.add_argument("--template", help="Optional Debian 13 amd64 standard template filename") p.add_argument("--bridge", default="vmbr0") p.add_argument("--ip", default="dhcp", help="dhcp or static IPv4 CIDR") p.add_argument("--gateway") p.add_argument("--vlan", type=int) p.add_argument("--memory", type=int, default=4096, help="MiB; builds need at least 4096") p.add_argument("--cores", type=int, default=2) p.add_argument("--disk", type=int, default=20, help="GiB") p.add_argument("--role", choices=("both", "server", "worker"), help="Install default: both; update preserves role") p.add_argument("--domain", help="Dashboard DNS name; required for server/both") p.add_argument("--tls", choices=("acme", "internal"), default="acme") p.add_argument("--email", help="Expected provider email for both selected providers") p.add_argument("--claude-email") p.add_argument("--codex-email") p.add_argument("--providers", default="claude,codex") p.add_argument("--machine-id", help="Default: lxc_") p.add_argument("--timezone", default="UTC") p.add_argument("--server-url", help="Existing HTTPS dashboard, for worker-only install") p.add_argument("--worker-key-file", type=Path, help="Root-readable enrollment key file; never pass the key as an argument") p.add_argument("--dry-run", action="store_true", help="Print validated plan; do not run Proxmox or create files") return p def validate(args): if args.ctid is not None and not 100 <= args.ctid <= 999999999: raise ValueError("CT id must be between 100 and 999999999") if args.action == "update" and args.ctid is None: raise ValueError("Update requires --ctid") args.source = args.source.resolve() for project in PROJECTS: if not (args.source / "src" / project / (project + ".csproj")).is_file(): raise ValueError("Source must include the web/worker implementation: " + project) if args.action == "update": if args.role or args.domain or args.email or args.claude_email or args.codex_email or args.machine_id or args.server_url or args.worker_key_file: raise ValueError("Update preserves identity/configuration; pass only CT id and source (plus --dry-run)") return args.role = args.role or "both" for value in (args.storage or "", args.template_storage, args.bridge): if not re.fullmatch(r"[A-Za-z][A-Za-z0-9_-]{0,63}", value): raise ValueError("Install requires valid --storage, template-storage and bridge identifiers") if args.memory < 4096 or args.cores < 1 or args.disk < 12: raise ValueError("Require memory >=4096 MiB, cores >=1 and disk >=12 GiB for native builds") if args.vlan is not None and not 1 <= args.vlan <= 4094: raise ValueError("VLAN must be in 1..4094") if args.ip != "dhcp": if not isinstance(ipaddress.ip_interface(args.ip), ipaddress.IPv4Interface): raise ValueError("Use an IPv4 CIDR") if not args.gateway: raise ValueError("Static IP requires --gateway") if args.gateway: if args.ip == "dhcp" or not isinstance(ipaddress.ip_address(args.gateway), ipaddress.IPv4Address): raise ValueError("Gateway is only supported with static IPv4") if args.template and not TEMPLATE.fullmatch(args.template): raise ValueError("Template must be a Debian 13 standard amd64 template filename") if args.role != "worker": if not args.domain: raise ValueError("Server/both requires --domain for HTTPS; use --tls internal for a private CA") args.domain = domain_name(args.domain) else: if not args.server_url or not args.worker_key_file: raise ValueError("Worker-only install requires --server-url and --worker-key-file") args.server_url = server_url(args.server_url) args.providers = args.providers.split(",") if not args.providers or len(set(args.providers)) != len(args.providers) or any(p not in ("claude", "codex") for p in args.providers): raise ValueError("Providers must be claude, codex, or claude,codex") for provider in args.providers: email = getattr(args, provider + "_email") or args.email if args.role != "server" and (not email or not re.fullmatch(r"[^\s@\x00-\x1f]+@[^\s@\x00-\x1f]+", email) or len(email) > 320): raise ValueError("Worker/both requires --email or a provider-specific email for each selected provider") if args.machine_id: identifier(args.machine_id) if not re.fullmatch(r"[A-Za-z0-9_+/-]{1,100}", args.timezone) or ".." in args.timezone: raise ValueError("Invalid timezone id") if args.role == "worker" and not args.dry_run: key = args.worker_key_file.read_text(encoding="utf-8").strip() if not re.fullmatch(r"[A-Za-z0-9_-]{32,512}", key): raise ValueError("Enrollment file must contain one 32+ character transport key") args.enrollment_key = key def create_command(args, ctid, template): network = f"name=eth0,bridge={args.bridge},ip={args.ip},type=veth,firewall=1" if args.gateway: network += ",gw=" + args.gateway if args.vlan: network += ",tag=" + str(args.vlan) return ["pct", "create", str(ctid), f"{args.template_storage}:vztmpl/{template}", "--hostname", f"finaltoken-{ctid}", "--ostype", "debian", "--arch", "amd64", "--unprivileged", "1", "--onboot", "1", "--memory", str(args.memory), "--swap", "2048", "--cores", str(args.cores), "--rootfs", f"{args.storage}:{args.disk}", "--net0", network, "--description", "FinalToken installer; retains configuration and CLI profiles on update"] def snapshot(source, destination): """Allowlist source inputs, including uncommitted changes, excluding secrets, outputs and symlinks.""" files = [source / n for n in ("Directory.Build.props", "Directory.Packages.props", "global.json", "LICENSE")] for project in PROJECTS: directory = source / "src" / project if directory.is_symlink() or directory.resolve() != directory.absolute(): raise ValueError("Source snapshot refuses a symlinked project or parent: " + project) files.extend(directory.rglob("*")) total, count = 0, 0 with tarfile.open(destination, "w:gz") as archive: for path in sorted(set(files)): relative = path.relative_to(source) if is_private_path(relative): continue # .gitignore does not apply to tarfile: do not copy local deployment data. if any(p in ("bin", "obj", "artifacts", ".git", "node_modules") or p.startswith(".") for p in relative.parts): continue if path.is_symlink(): raise ValueError("Source snapshot refuses symlinks: " + str(relative)) if path.is_dir(): continue if not path.is_file(): raise ValueError("Missing or non-regular source file: " + str(relative)) size = path.stat().st_size total += size count += 1 if size > 16 * 1024 * 1024 or total > 256 * 1024 * 1024 or count > 10000: raise ValueError("Source snapshot exceeds the guest archive bounds") archive.add(path, arcname=relative.as_posix(), recursive=False) return hashlib.sha256(destination.read_bytes()).hexdigest() def execute(args): if not sys.platform.startswith("linux") or os.geteuid() != 0: raise ValueError("Run as root on the Proxmox host; --dry-run works without Proxmox") for program in ("pct", "pvesh", "pveam", "pvesm"): if not shutil.which(program): raise ValueError("Missing Proxmox host command: " + program) import fcntl with open("/run/lock/finaltoken-proxmox.lock", "w", encoding="utf-8") as lock: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) # Prepare and validate the complete source bundle before creating any CT. with tempfile.TemporaryDirectory(prefix="finaltoken-source-") as directory: archive = Path(directory) / "source.tar.gz" sha = snapshot(args.source, archive) deploy(args, archive, sha) def deploy(args, archive, sha): ctid = args.ctid or int(json.loads(run(["pvesh", "get", "/cluster/nextid", "--output-format", "json"], capture=True).stdout)) status = run(["pct", "status", ctid], capture=True, check=False) if args.action == "install": if status.returncode == 0: raise ValueError("CT already exists; refusing to overwrite it. Use update for a managed installation.") run(["pveam", "update"]) template = args.template if not template: available = run(["pveam", "available", "--section", "system"], capture=True).stdout candidates = [word for word in available.split() if TEMPLATE.fullmatch(word)] if not candidates: raise ValueError("No Debian 13 amd64 template found; pass --template explicitly") template = sorted(candidates, key=lambda s: [int(p) if p.isdigit() else p for p in re.split(r"(\d+)", s)])[-1] path = run(["pvesm", "path", f"{args.template_storage}:vztmpl/{template}"], capture=True, check=False) if path.returncode or not Path(path.stdout.strip()).is_file(): run(["pveam", "download", args.template_storage, template]) run(create_command(args, ctid, template)) else: if status.returncode: raise ValueError("Cannot access selected CT") # Reject foreign CTs before starting them or installing packages. metadata = json.loads(run(["pct", "exec", ctid, "--", "cat", "/etc/finaltoken/install.json"], capture=True).stdout) if "running" in status.stdout else None if metadata is None: raise ValueError("Start the existing managed CT before updating; stopped CTs are not modified") if metadata.get("installer") != "finaltoken-proxmox-v1" or metadata.get("ctid") != ctid: raise ValueError("Selected CT is not managed by this installer") if args.action == "install": run(["pct", "start", ctid]) for _ in range(30): if run(["pct", "exec", ctid, "--", "test", "-d", "/run/systemd/system"], capture=True, check=False).returncode == 0: break time.sleep(1) else: raise ValueError("CT did not become ready; it was retained for inspection") guest = Path(__file__).with_name("guest.py") token = uuid.uuid4().hex remote = "/tmp/finaltoken-" + token with tempfile.TemporaryDirectory(prefix="finaltoken-proxmox-") as tmp: tmp = Path(tmp) manifest = {"installer": "finaltoken-proxmox-v1", "ctid": ctid, "action": args.action, "sourceSha256": sha} if args.action == "install": manifest.update(role=args.role, domain=args.domain, tls=args.tls, machineId=args.machine_id or f"lxc_{ctid}", timezone=args.timezone, providers=args.providers, serverUrl=args.server_url, emails={p: getattr(args, p + "_email") or args.email for p in args.providers}) if args.role == "worker": manifest["workerKey"] = args.enrollment_key manifest_path = tmp / "manifest.json" manifest_path.write_text(json.dumps(manifest), encoding="utf-8") manifest_path.chmod(0o600) # Only CT packages are changed. The Proxmox host package configuration is untouched. run(["pct", "exec", ctid, "--", "apt-get", "update"]) run(["pct", "exec", ctid, "--", "env", "DEBIAN_FRONTEND=noninteractive", "apt-get", "install", "-y", "python3", "ca-certificates"]) try: for local, suffix in ((guest, ".py"), (archive, ".tar.gz"), (manifest_path, ".json")): run(["pct", "push", ctid, local, remote + suffix, "--perms", "0600"]) run(["pct", "exec", ctid, "--", "python3", remote + ".py", "--manifest", remote + ".json", "--archive", remote + ".tar.gz"]) finally: run(["pct", "exec", ctid, "--", "rm", "-f", remote + ".py", remote + ".json", remote + ".tar.gz"], capture=True, check=False) print(f"FinalToken {args.action} finished in CT {ctid}. Configuration and state are inside that CT.") print(f"Inspect services: pct exec {ctid} -- systemctl status 'finaltoken-*'") print(f"Read dashboard access key, when server installed: pct exec {ctid} -- cat /etc/finaltoken/dashboard-key") print("No container, profile or history is ever automatically deleted on failure.") def main(argv=None): args = parser().parse_args(argv) validate(args) if args.dry_run: role = args.role or "preserve installed role" print(f"Plan: {args.action} CT {args.ctid or ''}; role={role}; source={args.source}") print("Unprivileged Debian 13 amd64; build NativeAOT inside CT; preserve config, keys, history and CLI profiles.") if args.action == "install": print(f"Root storage={args.storage}; template storage={args.template_storage}; bridge={args.bridge}; IP={args.ip}") print(f"Dashboard={('https://' + args.domain) if args.domain else args.server_url}; TLS={args.tls}") return 0 execute(args) return 0 if __name__ == "__main__": try: sys.exit(main()) except (ValueError, OSError, subprocess.CalledProcessError) as error: # Never dump captured command output or the manifest (contains service keys). print("FinalToken setup failed: " + (str(error) if isinstance(error, ValueError) else type(error).__name__), file=sys.stderr) print("The CT and existing data were retained. Inspect it before retrying.", file=sys.stderr) sys.exit(1)