#!/usr/bin/env python3 """ Deploy the Tansy UI build to the cPanel shared host. Replaces the old manual flow: no manual deletion, no manual overwrite. The cPanel-side PHP does the extraction and prunes whatever the new build did not bring with it, so the docroot always matches exactly one build. Usage: python3 scripts/deploy.py # build + deploy python3 scripts/deploy.py --build-only # just build + package python3 scripts/deploy.py --deploy-only # deploy the existing /tmp payload python3 scripts/deploy.py --dry-run # package, print, upload nothing Credentials come from the environment, never from the repo: CPANEL_HOST, CPANEL_USER, CPANEL_PASS, CPANEL_SUB, ORIGIN_IP Fallbacks live in scripts/deploy.env (gitignored, chmod 600). """ from __future__ import annotations import argparse import base64 import hashlib import json import os import shutil import subprocess import sys import time import urllib.error import urllib.parse import urllib.request import zipfile from pathlib import Path REPO = Path(__file__).resolve().parent.parent STAGE = Path("/tmp/tansy-stage") ZIP = Path("/tmp/tansy-deploy.zip") ENV_FILE = REPO / "scripts" / "deploy.env" SITE_DIST = REPO / "apps" / "site" / "dist" STORYBOOK = REPO / "apps" / "docs" / "storybook-static" # The docroot must keep these regardless of what a build contains: cPanel # writes them, and removing .htaccess would take the site offline. KEEP_TOP = ["cgi-bin", ".well-known", "php.ini", ".user.ini", ".htaccess"] # The probe prints the marker only when PHP runs it: the source splits the # string, so a copy served as plain text never contains PROBE_MARK. PROBE_MARK = "PHPEXEC-OK" PROBE_PHP = " php_value error_log "/home/__CPANEL_USER__/logs/php.error.log" php_flag log_errors On php_value error_log "/home/__CPANEL_USER__/logs/php.error.log" php_flag log_errors On Options -Indexes +FollowSymLinks DirectoryIndex index.html RewriteEngine On RewriteBase / RewriteRule ^docs$ docs/ [R=301,L] # A missing asset must 404. Falling back to index.html would answer a stale # page's request for a pruned bundle with HTML, which silently blanks # Storybook's canvas instead of failing visibly. RewriteCond %{REQUEST_URI} !\\.(?:js|mjs|css|json|map|svg|png|jpe?g|webp|ico|woff2?)$ [NC] RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-d RewriteRule ^docs/(.*) docs/index.html [L] RewriteCond %{REQUEST_URI} !\\.(?:js|mjs|css|json|map|svg|png|jpe?g|webp|ico|woff2?)$ [NC] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . index.html [L] Header set X-Content-Type-Options "nosniff" Header set Referrer-Policy "strict-origin-when-cross-origin" # Revalidate everything by default: HTML, index.json and Storybook's # fixed-name manager bundles change on every deploy. Content-hashed files # get a long cache from the .htaccess that package() puts in each assets/. Header set Cache-Control "no-cache" """ # Written into assets/ and docs/assets/, whose files are all content-hashed, # so they can be cached for good. It overrides the root no-cache. HTACCESS_ASSETS = """ Header set Cache-Control "public, max-age=31536000, immutable" """ HTACCESS_HARDENED = HTACCESS_DEPLOY + """ # Deployment complete: static only. php_flag engine off RemoveHandler .php .phtml .php3 .php4 .php5 .php7 .php8 RemoveType .php """ def log(msg: str) -> None: print(f"[deploy] {msg}", flush=True) def die(msg: str, code: int = 1) -> None: print(f"[deploy] ERROR: {msg}", file=sys.stderr, flush=True) sys.exit(code) # -------------------------------------------------------------------------- # config # -------------------------------------------------------------------------- def load_config() -> dict: cfg = dict(os.environ) if ENV_FILE.exists(): for line in ENV_FILE.read_text().splitlines(): line = line.strip() if not line or line.startswith("#") or "=" not in line: continue key, _, val = line.partition("=") cfg.setdefault(key.strip(), val.strip().strip("'\"")) missing = [k for k in ("CPANEL_HOST", "CPANEL_USER", "CPANEL_PASS", "CPANEL_SUB", "ORIGIN_IP") if not cfg.get(k)] if missing: die(f"missing config: {', '.join(missing)}\n" f" set them in the environment or in {ENV_FILE}") return cfg # -------------------------------------------------------------------------- # build # -------------------------------------------------------------------------- def run(cmd: list[str], cwd: Path = REPO, timeout: int = 900) -> None: log("$ " + " ".join(cmd)) r = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, timeout=timeout) if r.returncode != 0: die(f"{cmd[0]} failed ({r.returncode})\n{r.stdout[-2500:]}\n{r.stderr[-2500:]}") tail = "\n".join(r.stdout.strip().splitlines()[-6:]) if tail: print(tail, flush=True) def build() -> None: run(["npm", "ci"]) run(["npm", "run", "lint"]) run(["npm", "test"]) # Builds the package, then the landing page and Storybook. run(["npm", "run", "build"]) if not (STORYBOOK / "index.json").exists(): die(f"{STORYBOOK}/index.json missing after the Storybook build") def git(*args: str) -> str: return subprocess.run(["git", *args], cwd=REPO, capture_output=True, text=True, check=True).stdout.strip() def require_clean_tree() -> None: """Refuse to ship work that is not committed, so every deploy is a commit.""" dirty = git("status", "--porcelain") if dirty: die("uncommitted changes - commit them first, or pass --allow-dirty:\n" + dirty) def build_stamp() -> dict: version = json.loads((REPO / "packages" / "ui" / "package.json").read_text())["version"] return { "version": version, "commit": git("rev-parse", "--short", "HEAD"), "dirty": bool(git("status", "--porcelain")), "built_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), } def package() -> dict: dist = SITE_DIST sb = STORYBOOK for d in (dist, sb): if not d.is_dir(): die(f"{d} does not exist - run: npm run build") if STAGE.exists(): shutil.rmtree(STAGE) STAGE.mkdir(parents=True) shutil.copytree(dist, STAGE, dirs_exist_ok=True) (STAGE / "docs").mkdir(exist_ok=True) shutil.copytree(sb, STAGE / "docs", dirs_exist_ok=True) for assets in (STAGE / "assets", STAGE / "docs" / "assets"): if assets.is_dir(): (assets / ".htaccess").write_text(HTACCESS_ASSETS) stamp = build_stamp() (STAGE / "version.json").write_text(json.dumps(stamp, indent=2) + "\n") files = [p for p in STAGE.rglob("*") if p.is_file()] if ZIP.exists(): ZIP.unlink() with zipfile.ZipFile(ZIP, "w", zipfile.ZIP_DEFLATED, compresslevel=9) as z: for p in files: z.write(p, p.relative_to(STAGE).as_posix()) raw = ZIP.read_bytes() b64 = base64.b64encode(raw).decode() with zipfile.ZipFile(ZIP) as z: if z.testzip() is not None: die("zip integrity check failed") entries = len(z.namelist()) info = { "files": entries, "zip_bytes": len(raw), "b64_bytes": len(b64), "sha256": hashlib.sha256(raw).hexdigest(), "stamp": stamp, } log(f"packaged {entries} files, {len(raw)/1024/1024:.2f} MB zip, " f"{len(b64)/1024/1024:.2f} MB base64") log(f"sha256 {info['sha256'][:32]}") log(f"version {stamp['version']} at {stamp['commit']}" + (" (dirty)" if stamp["dirty"] else "")) (STAGE.parent / "tansy-payload.json").write_text(json.dumps(info, indent=2)) return info # -------------------------------------------------------------------------- # cPanel session # -------------------------------------------------------------------------- class Panel: def __init__(self, cfg: dict): import http.cookiejar self.base = f"https://{cfg['CPANEL_HOST']}:2083" self.sub = cfg["CPANEL_SUB"] self.ip = cfg["ORIGIN_IP"] self.token = "" self.docroot = f"/home/{cfg['CPANEL_USER']}/{cfg['CPANEL_SUB']}" self._jar = http.cookiejar.CookieJar() self._opener = urllib.request.build_opener( urllib.request.HTTPCookieProcessor(self._jar)) self._login(cfg) def _http(self, url: str, data: dict | None = None, timeout: int = 240) -> str: body = urllib.parse.urlencode(data).encode() if data else None req = urllib.request.Request(url, data=body) if body: req.add_header("Content-Type", "application/x-www-form-urlencoded") try: return self._opener.open(req, timeout=timeout).read().decode( "utf-8", "replace") except urllib.error.HTTPError as e: return e.read().decode("utf-8", "replace") def _login(self, cfg: dict) -> None: out = self._http(f"{self.base}/login/?login_only=1", {"user": cfg["CPANEL_USER"], "pass": cfg["CPANEL_PASS"]}) try: self.token = json.loads(out)["security_token"] except Exception: die(f"login failed: {out[:200]}") log("logged in") def uapi(self, module: str, fn: str, params: dict | None = None) -> dict: url = f"{self.base}{self.token}/execute/{module}/{fn}" if params: url += "?" + urllib.parse.urlencode(params) return json.loads(self._http(url)) def write_file(self, name: str, content: str) -> None: out = self._http( f"{self.base}{self.token}/execute/Fileman/save_file_content", {"dir": self.docroot, "file": name, "content": content}) try: ok = json.loads(out).get("status") == 1 except Exception: ok = False if not ok: die(f"failed to write {name}: {out[:200]}") log(f"wrote {name} ({len(content)} bytes)") def delete_file(self, name: str) -> None: """Permanently delete one file from the docroot (API 2 Fileman::fileop).""" params = { "cpanel_jsonapi_apiversion": 2, "cpanel_jsonapi_module": "Fileman", "cpanel_jsonapi_func": "fileop", "op": "unlink", "sourcefiles": f"{self.docroot}/{name}", "doubledecode": 1, } out = self._http(f"{self.base}{self.token}/json-api/cpanel?" + urllib.parse.urlencode(params)) try: ok = json.loads(out)["cpanelresult"]["data"][0]["result"] == 1 except Exception: ok = False if not ok: die(f"failed to delete {name}: {out[:200]}") log(f"deleted {name}") def read_file(self, name: str) -> str: out = self._http(f"{self.base}{self.token}/execute/Fileman/get_file_content", {"dir": self.docroot, "file": name}) try: return json.loads(out).get("data", {}).get("content", "") or "" except Exception: return "" def get_from_origin(self, path: str, timeout: int = 300) -> str: """GET the docroot over plain HTTP, bypassing Cloudflare. The Host header matters: without it the request lands on the server's default vhost and cPanel answers with its own 404 page instead of the site's document root. """ return self._origin(f"http://{self.ip}{path}", method="GET", timeout=timeout) def post_to_origin(self, path: str, data: dict, timeout: int = 600) -> str: """POST to the docroot over plain HTTP, with the Host header set.""" return self._origin(f"http://{self.ip}{path}", method="POST", data=data, timeout=timeout) def _origin(self, url: str, method: str = "GET", data: dict | None = None, timeout: int = 300) -> str: body = urllib.parse.urlencode(data).encode() if data else None req = urllib.request.Request(url, data=body, method=method) req.add_header("Host", self.sub) req.add_header("User-Agent", "tansy-deploy/1") if body: req.add_header("Content-Type", "application/x-www-form-urlencoded") try: return urllib.request.urlopen(req, timeout=timeout).read().decode( "utf-8", "replace") except urllib.error.HTTPError as e: return e.read().decode("utf-8", "replace") except urllib.error.URLError as e: die(f"POST {url} failed: {e.reason}") # -------------------------------------------------------------------------- # verify # -------------------------------------------------------------------------- def verify(panel: Panel) -> None: import hashlib as _h log("verifying…") local_stamp = json.loads((STAGE / "version.json").read_text()) try: live_stamp = json.loads(panel.get_from_origin("/version.json")) except Exception: live_stamp = {} if live_stamp != local_stamp: die(f"version.json mismatch\n live {live_stamp}\n local {local_stamp}") log(f"live version {live_stamp['version']} at {live_stamp['commit']}") idx = panel.get_from_origin("/index.html") live_sha = _h.sha256(idx.encode()).hexdigest() local_sha = _h.sha256((SITE_DIST / "index.html").read_bytes()).hexdigest() if live_sha != local_sha: die(f"index.html mismatch\n live {live_sha[:32]}\n local {local_sha[:32]}") log("index.html matches the local build") sb = panel.get_from_origin("/docs/index.json") sb_sha = _h.sha256(sb.encode()).hexdigest() sb_local = _h.sha256((STORYBOOK / "index.json").read_bytes()).hexdigest() if sb_sha != sb_local: die("docs/index.json mismatch") log("docs/index.json matches") for path in ("/", "/docs/", "/docs/iframe.html"): req = urllib.request.Request(f"http://{panel.ip}{path}", headers={"Host": panel.sub}) with urllib.request.urlopen(req, timeout=30) as r: status = r.status if status != 200: die(f"{path} returned {status}") log(f" {path} -> 200") entries = panel.uapi("Fileman", "list_files", {"dir": panel.docroot, "show_hidden": 1}) names = sorted(f.get("file") for f in entries.get("data") or []) leftovers = [n for n in names if n.startswith("_") and n.endswith(".php")] if leftovers: die(f"deploy scripts left in the docroot: {leftovers}") log(f"docroot clean: {names}") def check_php_syntax(path: Path) -> bool: """`php -l` the deployer. True if it parses (or the check was skipped).""" if SKIP_PHP_LINT: log("skipping php -l (--skip-php-lint)") return True php = shutil.which("php") if php is None: log("no local php binary; cannot lint the deployer") return False r = subprocess.run([php, "-l", str(path)], capture_output=True, text=True) if r.returncode != 0: log(f"php -l failed:\n{r.stdout}{r.stderr}") return False log("php -l ok") return True # -------------------------------------------------------------------------- def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--build-only", action="store_true") ap.add_argument("--deploy-only", action="store_true") ap.add_argument("--dry-run", action="store_true") ap.add_argument("--skip-php-lint", action="store_true", help="ship cpanel-deploy.php without `php -l`") ap.add_argument("--allow-dirty", action="store_true", help="deploy even with uncommitted changes") args = ap.parse_args() global SKIP_PHP_LINT SKIP_PHP_LINT = args.skip_php_lint uploading = not (args.build_only or args.dry_run) if uploading and not args.allow_dirty: require_clean_tree() if not args.deploy_only: build() info = package() if args.build_only: log("build + package only; nothing uploaded") return if args.dry_run: log(f"dry run: would POST {info['b64_bytes']/1024/1024:.2f} MB to cPanel") return cfg = load_config() panel = Panel(cfg) htaccess_deploy = HTACCESS_DEPLOY.replace("__CPANEL_USER__", cfg["CPANEL_USER"]) htaccess_hardened = HTACCESS_HARDENED.replace("__CPANEL_USER__", cfg["CPANEL_USER"]) # Guard against the failure that cost a whole deploy cycle: a PHP parse # error makes the server return an empty body and leave _deploy.php on # disk, which looks identical to "upload was ignored". `php -l` needs a # local PHP binary, so when there is none, refuse to guess and require an # explicit override rather than silently shipping a broken script. if not check_php_syntax(Path(REPO / "scripts" / "cpanel-deploy.php")): die("cpanel-deploy.php failed `php -l`, or no local PHP is available " "to check it. Install php-cli or run the deploy with " "--skip-php-lint if you are certain the file parses.") # 1. PHP must be on for the uploader to run. From here on, any exit # (an error, a timeout, Ctrl-C) must put the hardened file back. panel.write_file(".htaccess", htaccess_deploy) try: time.sleep(2) # 2. Prove PHP actually executes before relying on it. panel.write_file("_probe.php", PROBE_PHP) body = panel.get_from_origin("/_probe.php", timeout=30) if PROBE_MARK not in body: die(f"PHP is not executing in the docroot (probe returned: {body[:80]!r})") log("PHP execution confirmed") # 3. Ship the self-pruning deployer and the payload. The prune also # removes _probe.php, and _deploy.php deletes itself. deployer = (REPO / "scripts" / "cpanel-deploy.php").read_text() panel.write_file("_deploy.php", deployer) b64 = base64.b64encode(ZIP.read_bytes()).decode() log(f"uploading {len(b64)/1024/1024:.2f} MB …") out = panel.post_to_origin("/_deploy.php", {"data": b64, "keep": json.dumps(KEEP_TOP)}, timeout=600) log("server said: " + out.strip()[:300]) try: result = json.loads(out) except Exception: die("deployer did not return JSON - check the response above") if not result.get("ok"): die(f"deploy failed: {result}") log(f"extracted {result['extracted']} files, " f"pruned {result['pruned_files']} stale files / {result['pruned_dirs']} dirs") finally: # 4. Re-harden no matter how the steps above ended. panel.write_file(".htaccess", htaccess_hardened) # 5. Confirm PHP is off again with a fresh probe. Its source never contains # the joined marker, so a served-as-text file cannot pass for execution. time.sleep(2) panel.write_file("_probe.php", PROBE_PHP) after = panel.get_from_origin("/_probe.php", timeout=30) panel.delete_file("_probe.php") if PROBE_MARK in after: die("PHP is still enabled after hardening - investigate the .htaccess") log("PHP re-disabled") verify(panel) log("done") if __name__ == "__main__": main()