"""Private guest provisioner, invoked by host.py inside the selected LXC. Not a host entry point.""" import argparse import hashlib import json import os from pathlib import Path, PurePosixPath import pwd import secrets import shutil import subprocess import sys import tarfile import tempfile import time import urllib.request import uuid INSTALLER = "finaltoken-proxmox-v1" ETC = Path("/etc/finaltoken") APP = Path("/opt/finaltoken") BUILD = Path("/var/cache/finaltoken-build") SERVER_HOME = Path("/var/lib/finaltoken-server") WORKER_HOME = Path("/var/lib/finaltoken-worker") PROXY_HOME = Path("/var/lib/finaltoken-proxy") SYSTEMD = Path("/etc/systemd/system") def run(command, *, check=True, capture=False, cwd=None): return subprocess.run([str(a) for a in command], check=check, text=True, stdout=subprocess.PIPE if capture else None, stderr=subprocess.PIPE if capture else None, cwd=cwd) def atomic(path, data, mode=0o600, *, once=False): """D5: same-directory replace; existing operator configuration is never overwritten.""" if once and path.exists(): return False path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_name(path.name + "." + uuid.uuid4().hex + ".tmp") try: fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, mode) with os.fdopen(fd, "w", encoding="utf-8") as stream: stream.write(data) stream.flush() os.fsync(stream.fileno()) os.replace(temporary, path) finally: temporary.unlink(missing_ok=True) return True def json_file(path, data, *, once=False): return atomic(path, json.dumps(data, indent=2) + "\n", once=once) def unpack(archive_path, destination): """No links, devices, absolute paths, traversal or unbounded archive expansion.""" destination.mkdir(parents=True, exist_ok=True) with tarfile.open(archive_path, "r:gz") as archive: members = archive.getmembers() if len(members) > 10000 or sum(m.size for m in members) > 256 * 1024 * 1024: raise ValueError("Source archive exceeds its metadata/size bound") for member in members: path = PurePosixPath(member.name) if path.is_absolute() or ".." in path.parts or not member.isfile() or member.size > 16 * 1024 * 1024: raise ValueError("Source archive has an unsafe entry") target = destination.joinpath(*path.parts) target.parent.mkdir(parents=True, exist_ok=True) with archive.extractfile(member) as source, target.open("xb") as output: shutil.copyfileobj(source, output) target.chmod(0o644) def user(name, home): try: entry = pwd.getpwnam(name) if entry.pw_dir != str(home): raise ValueError("Existing service user has an unexpected home: " + name) except KeyError: run(["useradd", "--system", "--create-home", "--home-dir", home, "--shell", "/bin/bash", "--user-group", name]) entry = pwd.getpwnam(name) home.mkdir(parents=True, exist_ok=True) os.chown(home, entry.pw_uid, entry.pw_gid) home.chmod(0o750) return entry def as_user(name, home, command, cwd=None): # Do not inherit host/root provider secrets, proxy overrides or build credentials. return run(["runuser", "--user", name, "--", "env", "-i", "HOME=" + str(home), "PATH=" + str(home / ".local/bin") + ":/usr/local/bin:/usr/bin:/bin", "DOTNET_CLI_HOME=" + str(home), "DOTNET_CLI_TELEMETRY_OPTOUT=1", "DOTNET_NOLOGO=1", *command], cwd=cwd or home) def packages(role, providers): run(["apt-get", "update"]) wanted = ["ca-certificates", "curl", "clang", "zlib1g-dev", "libicu-dev", "libssl-dev", "tzdata"] if role != "worker": wanted.append("caddy") if role != "server" and "codex" in providers: wanted.extend(["nodejs", "npm"]) run(["env", "DEBIAN_FRONTEND=noninteractive", "apt-get", "install", "-y", *wanted]) repository = Path("/etc/apt/sources.list.d/microsoft-prod.list") if not repository.exists(): with tempfile.TemporaryDirectory(prefix="finaltoken-sdk-") as tmp: package = Path(tmp) / "packages-microsoft-prod.deb" run(["curl", "--fail", "--silent", "--show-error", "--location", "--proto", "=https", "--tlsv1.2", "https://packages.microsoft.com/config/debian/13/packages-microsoft-prod.deb", "--output", package]) run(["dpkg", "-i", package]) run(["apt-get", "update"]) run(["env", "DEBIAN_FRONTEND=noninteractive", "apt-get", "install", "-y", "dotnet-sdk-10.0"]) def official_clis(providers): """Install official clients as their own OS user; never run a login or read auth files.""" if "claude" in providers and not (WORKER_HOME / ".local/bin/claude").exists(): with tempfile.TemporaryDirectory(prefix="finaltoken-claude-") as tmp: os.chmod(tmp, 0o755) script = Path(tmp) / "install.sh" run(["curl", "--fail", "--silent", "--show-error", "--location", "--proto", "=https", "--tlsv1.2", "https://claude.ai/install.sh", "--output", script]) script.chmod(0o644) as_user("finaltoken", WORKER_HOME, ["bash", str(script), "stable"]) if "codex" in providers and not (WORKER_HOME / ".local/bin/codex").exists(): as_user("finaltoken", WORKER_HOME, ["npm", "install", "--global", "--prefix", str(WORKER_HOME / ".local"), "@openai/codex@latest"]) for provider in providers: as_user("finaltoken", WORKER_HOME, [str(WORKER_HOME / ".local/bin" / provider), "--version"]) def service_unit(role): server = role == "server" home = SERVER_HOME if server else WORKER_HOME account = "finaltoken-server" if server else "finaltoken" executable = APP / "current" / ("web/FinalToken.Web" if server else "worker/finaltoken-worker") arguments = "" if server else " " + str(ETC / "worker.json") return f"""[Unit] Description=FinalToken {role} Wants=network-online.target After=network-online.target [Service] Type=exec User={account} Group={account} WorkingDirectory={executable.parent} EnvironmentFile={ETC}/{role}.env Environment=HOME={home} Environment=PATH={WORKER_HOME}/.local/bin:/usr/local/bin:/usr/bin:/bin ExecStart={executable}{arguments} Restart=on-failure RestartSec=5 TimeoutStopSec=75 KillMode=control-group UMask=0077 NoNewPrivileges=true StandardOutput=null StandardError=null [Install] WantedBy=multi-user.target """ def proxy_unit(): return f"""[Unit] Description=FinalToken HTTPS proxy After=network-online.target finaltoken-server.service Wants=network-online.target [Service] Type=exec User=finaltoken-proxy Group=finaltoken-proxy Environment=HOME={PROXY_HOME} Environment=XDG_DATA_HOME={PROXY_HOME} ExecStart=/usr/bin/caddy run --config {ETC}/Caddyfile --adapter caddyfile ExecReload=/usr/bin/caddy reload --config {ETC}/Caddyfile --adapter caddyfile Restart=on-failure RestartSec=5 AmbientCapabilities=CAP_NET_BIND_SERVICE CapabilityBoundingSet=CAP_NET_BIND_SERVICE NoNewPrivileges=true UMask=0077 [Install] WantedBy=multi-user.target """ def configure(meta, enrollment_key=None): role, providers = meta["role"], meta["providers"] ETC.mkdir(parents=True, exist_ok=True) ETC.chmod(0o755) if role != "worker": user("finaltoken-server", SERVER_HOME) user("finaltoken-proxy", PROXY_HOME) if role != "server": user("finaltoken", WORKER_HOME) keys_path = ETC / "transport-keys.json" if not keys_path.exists(): json_file(keys_path, {"dashboard": secrets.token_hex(32), "worker": enrollment_key or secrets.token_hex(32)}, once=True) keys = json.loads(keys_path.read_text(encoding="utf-8")) if role != "worker": accounts = [{"id": p, "provider": p.capitalize(), "label": p.capitalize(), "expectedEmail": meta["emails"][p], "timeZone": meta["timezone"]} for p in providers if meta["emails"].get(p)] machines = [] if role == "server" else [{"id": meta["machineId"], "label": f"LXC {meta['ctid']}", "osUser": "finaltoken", "profiles": [{"id": p, "accountId": p} for p in providers]}] json_file(ETC / "server.json", {"accounts": accounts, "machines": machines}, once=True) atomic(ETC / "server.env", f"FINALTOKEN_SERVER_CONFIG={ETC}/server.json\nFINALTOKEN_SERVER_DATA={SERVER_HOME}/data\n" f"FINALTOKEN_DASHBOARD_KEY={keys['dashboard']}\nFINALTOKEN_PUBLIC_ORIGIN=https://{meta['domain']}\n" f"ASPNETCORE_URLS=http://127.0.0.1:5187\nFINALTOKEN_MACHINE_{meta['machineId']}={keys['worker']}\n", once=True) atomic(ETC / "dashboard-key", keys["dashboard"] + "\n", once=True) atomic(ETC / "worker-key", keys["worker"] + "\n", once=True) tls = " tls internal\n" if meta["tls"] == "internal" else "" atomic(ETC / "Caddyfile", f"{meta['domain']} {{\n{tls} reverse_proxy 127.0.0.1:5187\n}}\n", 0o644, once=True) atomic(SYSTEMD / "finaltoken-server.service", service_unit("server"), 0o644, once=True) atomic(SYSTEMD / "finaltoken-proxy.service", proxy_unit(), 0o644, once=True) run(["systemctl", "disable", "--now", "caddy.service"]) if role != "server": profiles = [{"id": p, "provider": p.capitalize(), "expectedEmail": meta["emails"][p], "configDirectory": str(WORKER_HOME / (".claude" if p == "claude" else ".codex")), "dataDirectory": str(WORKER_HOME / "history" / p), "cliPath": str(WORKER_HOME / ".local/bin" / p)} for p in providers] json_file(ETC / "worker.json", {"machineId": meta["machineId"], "serverUrl": "http://127.0.0.1:5187" if role == "both" else meta["serverUrl"], "stateDirectory": str(WORKER_HOME / "collector"), "profiles": profiles}, once=True) atomic(ETC / "worker.env", "FINALTOKEN_WORKER_KEY=" + keys["worker"] + "\n", once=True) atomic(SYSTEMD / "finaltoken-worker.service", service_unit("worker"), 0o644, once=True) # systemd reads env files as root. Only the intended service user can read its JSON config. for filename, account in (("server.json", "finaltoken-server"), ("worker.json", "finaltoken")): path = ETC / filename if path.exists(): path.chmod(0o640) os.chown(path, 0, pwd.getpwnam(account).pw_gid) def build(archive, meta): entry = user("finaltoken-build", BUILD) temporary = Path(tempfile.mkdtemp(prefix="build-", dir=BUILD)) try: source = temporary / "src" unpack(archive, source) for path in [temporary, *temporary.rglob("*")]: os.chown(path, entry.pw_uid, entry.pw_gid) release = temporary / "release" for project, output in (("FinalToken.Web", "web"), ("FinalToken.Worker", "worker")): if meta["role"] == "server" and output == "worker" or meta["role"] == "worker" and output == "web": continue # D1: build on target Linux with NativeAOT, never copy a Windows executable into LXC. as_user("finaltoken-build", BUILD, ["dotnet", "publish", str(source / "src" / project / (project + ".csproj")), "-c", "Release", "-r", "linux-x64", "--self-contained", "true", "-p:PublishAot=true", "-o", str(release / output)], cwd=source) if meta["role"] != "worker" and not (release / "web/wwwroot/index.html").is_file(): shutil.copytree(source / "src/FinalToken.Web/wwwroot", release / "web/wwwroot", dirs_exist_ok=True) shutil.copy2(source / "LICENSE", release / "LICENSE") destination = APP / "releases" / (meta["sourceSha256"][:16] + "-" + uuid.uuid4().hex[:8]) destination.parent.mkdir(parents=True, exist_ok=True) APP.chmod(0o755) destination.parent.chmod(0o755) shutil.copytree(release, destination) destination.chmod(0o755) for path in destination.rglob("*"): path.chmod(0o755 if path.is_dir() else 0o644) for executable in (destination / "web/FinalToken.Web", destination / "worker/finaltoken-worker"): wanted = meta["role"] != ("worker" if executable.name == "FinalToken.Web" else "server") if wanted: if not executable.is_file(): raise ValueError("Native build did not produce its expected executable") with executable.open("rb") as stream: header = stream.read(20) if header[:4] != b"\x7fELF" or header[18:20] != b"\x3e\x00": raise ValueError("Published executable is not a Linux x64 ELF binary") executable.chmod(0o755) return destination finally: # Only this invocation's fresh build directory, never profiles, state or previous releases. shutil.rmtree(temporary) def switch(release): if release.parent.resolve() != (APP / "releases").resolve() or not release.is_dir(): raise ValueError("Release must be an existing direct child of the releases directory") pending = APP / (".current-" + uuid.uuid4().hex) try: pending.symlink_to(release, target_is_directory=True) os.replace(pending, APP / "current") finally: pending.unlink(missing_ok=True) def units(role): return (["finaltoken-server.service", "finaltoken-proxy.service"] if role != "worker" else []) + (["finaltoken-worker.service"] if role != "server" else []) def healthy(services, meta): for _ in range(20): live = all(run(["systemctl", "is-active", "--quiet", s], check=False, capture=True).returncode == 0 for s in services) if live and "finaltoken-server.service" in services: try: request = urllib.request.Request("http://127.0.0.1:5187/", headers={"Host": meta["domain"]}) with urllib.request.urlopen(request, timeout=2) as response: live = response.status == 200 except OSError: live = False if live: # Catch immediate startup failures. Remote provider login is deliberately not a health probe. time.sleep(2) return all(run(["systemctl", "is-active", "--quiet", s], check=False, capture=True).returncode == 0 for s in services) time.sleep(1) return False def activate(release, meta, first): current = APP / "current" previous = current.resolve() if current.is_symlink() else None services = units(meta["role"]) active = services if first else [s for s in services if run(["systemctl", "is-active", "--quiet", s], check=False, capture=True).returncode == 0] try: switch(release) run(["systemctl", "daemon-reload"]) if first: run(["systemctl", "enable", *services]) if active: run(["systemctl", "restart", *active]) if not healthy(active, meta): raise ValueError("New release did not pass local service/HTTP health checks") except Exception: if previous is not None: switch(previous) if active: run(["systemctl", "restart", *active], check=False) print("Activation failed; previous binary release restored. State/configuration were not rewound.", file=sys.stderr) else: run(["systemctl", "disable", "--now", *services], check=False) raise def provision(manifest, archive): if os.geteuid() != 0 or os.uname().machine != "x86_64": raise ValueError("Guest setup requires root in a Linux x86_64 CT") os_release = Path("/etc/os-release").read_text(encoding="utf-8") if 'ID=debian' not in os_release or 'VERSION_ID="13"' not in os_release: raise ValueError("Only Debian 13 amd64 guests are supported") if manifest.get("installer") != INSTALLER or manifest.get("action") not in ("install", "update"): raise ValueError("Unsupported deployment manifest") with archive.open("rb") as stream: digest = hashlib.file_digest(stream, "sha256").hexdigest() if digest != manifest.get("sourceSha256"): raise ValueError("Uploaded source checksum mismatch") marker = ETC / "install.json" if manifest["action"] == "update": meta = json.loads(marker.read_text(encoding="utf-8")) if meta.get("installer") != INSTALLER or meta.get("ctid") != manifest["ctid"]: raise ValueError("Guest marker does not match selected CT") meta["sourceSha256"] = digest else: if marker.exists(): raise ValueError("An install marker already exists; use update") meta = {k: v for k, v in manifest.items() if k != "workerKey"} meta["installed"] = False json_file(ETC / "transport-keys.json", {"dashboard": secrets.token_hex(32), "worker": manifest.get("workerKey") or secrets.token_hex(32)}, once=True) json_file(marker, meta, once=True) # Partial installs can be resumed through update. first = not meta.get("installed", False) packages(meta["role"], meta["providers"]) if first: configure(meta, manifest.get("workerKey")) if meta["role"] != "server": official_clis(meta["providers"]) release = build(archive, meta) activate(release, meta, first) meta.update(installed=True, release=str(release)) json_file(marker, meta) if meta["role"] != "worker": print("Dashboard: https://" + meta["domain"]) print("Dashboard key is root-readable at /etc/finaltoken/dashboard-key (not printed).") print("Official CLI login still requires your browser authorization. No provider credentials were copied.") if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--manifest", type=Path, required=True) parser.add_argument("--archive", type=Path, required=True) args = parser.parse_args() try: provision(json.loads(args.manifest.read_text(encoding="utf-8")), args.archive) except (ValueError, OSError, subprocess.CalledProcessError) as error: print("Guest setup failed: " + (str(error) if isinstance(error, ValueError) else type(error).__name__), file=sys.stderr) print("Configuration, history and CLI profiles were retained. Inspect services; retry with host update.", file=sys.stderr) sys.exit(1)