"""Local-only ZitPlane backend helper (Python stdlib, no dependencies). Run from any folder: py core/backend/zitadel/dev.py init py core/backend/zitadel/dev.py up py core/backend/zitadel/dev.py check py core/backend/zitadel/dev.py down No credentials are printed, committed or transmitted by this script. """ from __future__ import annotations import argparse import os from pathlib import Path import secrets import shutil import string import subprocess import sys import urllib.error import urllib.request ROOT = Path(__file__).resolve().parents[3] COMPOSE = ROOT / "deployment" / "docker" / "compose.backend.dev.yaml" ENV = ROOT / ".env" VARIABLES = ( "POSTGRES_PASSWORD", "ZITADEL_MASTERKEY", "ZITADEL_FIRSTINSTANCE_ORG_HUMAN_PASSWORD", "LOGIN_SESSION_COOKIE_SECRET", ) def random_chars(alphabet: str, length: int) -> str: return "".join(secrets.choice(alphabet) for _ in range(length)) def create_dev_env() -> bool: """Generate local secrets once and never overwrite an existing .env.""" if ENV.exists(): print("Existing .env preserved (credentials were not regenerated).") return False alphabet = string.ascii_letters + string.digits values = { "POSTGRES_PASSWORD": random_chars(alphabet, 48), "ZITADEL_MASTERKEY": random_chars(alphabet, 32), "ZITADEL_FIRSTINSTANCE_ORG_HUMAN_PASSWORD": ( "Zp!7" + random_chars(alphabet, 29) ), "LOGIN_SESSION_COOKIE_SECRET": random_chars(alphabet, 48), } lines = [ "# Local ZitPlane development only. NEVER COMMIT or deploy to Coolify.", "# The first admin is zitadel-admin@zitadel.localhost.", "# Keep this file: rotating the ZITADEL master key will break existing encrypted data.", ] lines.extend(f"{key}={value}" for key, value in values.items()) try: with ENV.open("x", encoding="utf-8", newline="\n") as fh: fh.write("\n".join(lines) + "\n") except FileExistsError: print("Existing .env preserved (race-safe).") return False if os.name != "nt": os.chmod(ENV, 0o600) print("Created ignored .env with random development credentials; values hidden.") return True def validate_env() -> None: if not ENV.is_file(): raise RuntimeError("Missing .env. Run: py core/backend/zitadel/dev.py init") data: dict[str, str] = {} for line in ENV.read_text(encoding="utf-8").splitlines(): if not line.strip() or line.lstrip().startswith("#"): continue if "=" not in line: raise RuntimeError("Invalid .env entry.") key, value = line.split("=", 1) data[key] = value if any(not data.get(key) for key in VARIABLES): raise RuntimeError("Local .env is missing one or more required variables.") if len(data["ZITADEL_MASTERKEY"]) != 32: raise RuntimeError("ZITADEL_MASTERKEY must be exactly 32 characters.") if len(data["LOGIN_SESSION_COOKIE_SECRET"]) < 32: raise RuntimeError("LOGIN_SESSION_COOKIE_SECRET must be >= 32 characters.") if len(data["ZITADEL_FIRSTINSTANCE_ORG_HUMAN_PASSWORD"]) < 16: raise RuntimeError("Admin password too short.") def docker_compose(*args: str) -> None: if not shutil.which("docker"): raise RuntimeError( "Docker CLI is not installed or not on PATH. Install/start Docker Desktop " "with Linux containers; no Docker installation is performed automatically." ) command = ["docker", "compose", "--env-file", str(ENV), "-f", str(COMPOSE), *args] completed = subprocess.run(command, cwd=ROOT, check=False) if completed.returncode: raise RuntimeError(f"Docker Compose exited with code {completed.returncode}.") def check_ready() -> None: url = "http://localhost:8080/debug/ready" try: with urllib.request.urlopen(url, timeout=8) as response: if response.status != 200: raise RuntimeError(f"Readiness HTTP status: {response.status}") print(f"PASS: ZITADEL ready at {url}") print("Admin console: http://localhost:8080/ui/console") except (urllib.error.URLError, TimeoutError) as exc: raise RuntimeError(f"ZITADEL not ready at {url}: {exc}") from exc def main() -> int: parser = argparse.ArgumentParser(description="ZitPlane local-only ZITADEL backend") parser.add_argument("action", choices=["init", "up", "check", "down", "ps", "config"]) args = parser.parse_args() try: if args.action == "init": create_dev_env() validate_env() return 0 if args.action == "check": check_ready() return 0 validate_env() if args.action == "up": docker_compose("up", "-d", "--wait") check_ready() elif args.action == "down": docker_compose("down") # never remove volumes elif args.action == "ps": docker_compose("ps") elif args.action == "config": docker_compose("config", "--quiet") except RuntimeError as exc: print(f"BLOCKED: {exc}", file=sys.stderr) return 1 return 0 if __name__ == "__main__": raise SystemExit(main())