"""Create an unprivileged Debian 13 LXC. Updates run inside the container.""" import argparse import ipaddress import json import os from pathlib import Path import re import shutil import subprocess import sys import tempfile import time from urllib.parse import urlsplit import uuid from source_bundle import PROJECTS, snapshot ROOT = Path(__file__).resolve().parents[2] 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 not in ("http", "https") or not url.hostname or url.username is not None or url.password is not None or url.path not in ("", "/") or url.query or url.fragment: raise ValueError("Server URL must be an HTTP or HTTPS origin") _ = url.port return value.rstrip("/") def parser(): p = argparse.ArgumentParser(description=__doc__) p.add_argument("action", choices=("install",), help="Create a CT. Run finaltoken-update inside an existing CT.") p.add_argument("--ctid", type=int, help="New CT id; defaults to Proxmox nextid.") 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") p.add_argument("--domain", help="Legacy optional DNS hint; no longer used to restrict access") 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") 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) 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 args.domain: 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 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 status.returncode == 0: raise ValueError("CT already exists; run finaltoken-update inside that container") 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)) 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, network="external", 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("Server=" + args.server_url if role == "worker" else "Dashboard=http://:5187; no hostname or proxy required") 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)