Tansy UI: a themeable React component kit
Tansy UI is a React component kit by OpenKhalix, named after the tansy
flower ("golden buttons"). It has two surfaces:
- A landing page built entirely from the kit's own components, with
five featured parts, a palette-switching playground form, and links
into Storybook
- A Storybook workshop with Tansy branding, a Welcome page, palette
toolbar and accessibility checks
Includes 15 components with colocated tokens and stories, seven brand
palettes, a palette-aware logo, a Docker/nginx image, a scripted
cPanel deploy, and a generator that keeps the landing page catalogue
in sync with Storybook.
This commit is contained in:
commit
9d406d6d2a
81 files changed
+14240
No files matched your search
@@ -0,0 +1,427 @@
|
||||
#!/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"
|
||||
|
||||
# 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"]
|
||||
|
||||
# Set from --skip-php-lint in main().
|
||||
SKIP_PHP_LINT = False
|
||||
|
||||
# PHP is disabled in the hardened .htaccess, so it has to be lifted for the
|
||||
# duration of the upload and restored immediately afterwards.
|
||||
# __CPANEL_USER__ is replaced with the configured account when written.
|
||||
HTACCESS_DEPLOY = """<IfModule php8_module>
|
||||
php_value error_log "/home/__CPANEL_USER__/logs/php.error.log"
|
||||
php_flag log_errors On
|
||||
</IfModule>
|
||||
<IfModule lsapi_module>
|
||||
php_value error_log "/home/__CPANEL_USER__/logs/php.error.log"
|
||||
php_flag log_errors On
|
||||
</IfModule>
|
||||
|
||||
Options -Indexes +FollowSymLinks
|
||||
DirectoryIndex index.html
|
||||
|
||||
<IfModule mod_rewrite.c>
|
||||
RewriteEngine On
|
||||
RewriteBase /
|
||||
|
||||
RewriteRule ^docs$ docs/ [R=301,L]
|
||||
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
|
||||
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-d
|
||||
RewriteRule ^docs/(.*) docs/index.html [L]
|
||||
|
||||
RewriteCond %{REQUEST_FILENAME} !-f
|
||||
RewriteCond %{REQUEST_FILENAME} !-d
|
||||
RewriteRule . index.html [L]
|
||||
</IfModule>
|
||||
|
||||
<IfModule mod_headers.c>
|
||||
Header set X-Content-Type-Options "nosniff"
|
||||
Header set Referrer-Policy "strict-origin-when-cross-origin"
|
||||
</IfModule>
|
||||
|
||||
<IfModule mod_expires.c>
|
||||
ExpiresActive On
|
||||
ExpiresByType text/css "access plus 1 year"
|
||||
ExpiresByType application/javascript "access plus 1 year"
|
||||
ExpiresByType image/svg+xml "access plus 1 year"
|
||||
ExpiresByType font/woff2 "access plus 1 year"
|
||||
</IfModule>
|
||||
"""
|
||||
|
||||
HTACCESS_HARDENED = HTACCESS_DEPLOY + """
|
||||
# Deployment complete: static only.
|
||||
<IfModule mod_php.c>
|
||||
php_flag engine off
|
||||
</IfModule>
|
||||
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", "run", "build"])
|
||||
if not (REPO / "storybook-static" / "index.json").exists():
|
||||
die("storybook-static/index.json missing - run: npm run build-storybook")
|
||||
run(["npm", "run", "build-storybook"])
|
||||
|
||||
|
||||
def package() -> dict:
|
||||
dist = REPO / "dist"
|
||||
sb = REPO / "storybook-static"
|
||||
for d in (dist, sb):
|
||||
if not d.is_dir():
|
||||
die(f"{d} does not exist - run: npm run build && npm run build-storybook")
|
||||
|
||||
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)
|
||||
|
||||
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(),
|
||||
}
|
||||
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]}")
|
||||
(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(f"logged in, token {self.token}")
|
||||
|
||||
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 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…")
|
||||
|
||||
idx = panel.get_from_origin("/index.html")
|
||||
live_sha = _h.sha256(idx.encode()).hexdigest()
|
||||
local_sha = _h.sha256((REPO / "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((REPO / "storybook-static" / "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`")
|
||||
args = ap.parse_args()
|
||||
global SKIP_PHP_LINT
|
||||
SKIP_PHP_LINT = args.skip_php_lint
|
||||
|
||||
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.
|
||||
panel.write_file(".htaccess", htaccess_deploy)
|
||||
time.sleep(2)
|
||||
|
||||
# 2. Prove PHP actually executes before relying on it.
|
||||
panel.write_file("_probe.php", "<?php echo 'PHPEXEC-OK', PHP_VERSION;")
|
||||
body = panel.get_from_origin("/_probe.php", timeout=30)
|
||||
if "PHPEXEC-OK" not in body:
|
||||
panel.write_file(".htaccess", htaccess_hardened)
|
||||
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.
|
||||
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:
|
||||
panel.write_file(".htaccess", htaccess_hardened)
|
||||
die("deployer did not return JSON - check the response above")
|
||||
if not result.get("ok"):
|
||||
panel.write_file(".htaccess", htaccess_hardened)
|
||||
die(f"deploy failed: {result}")
|
||||
log(f"extracted {result['extracted']} files, "
|
||||
f"pruned {result['pruned_files']} stale files / {result['pruned_dirs']} dirs")
|
||||
|
||||
# 4. Re-harden, then confirm PHP is shut off again.
|
||||
panel.write_file(".htaccess", htaccess_hardened)
|
||||
time.sleep(2)
|
||||
after = panel.get_from_origin("/_probe.php", timeout=30)
|
||||
if "PHPEXEC-OK" in after:
|
||||
die("PHP is still enabled after hardening - investigate the .htaccess")
|
||||
log("PHP re-disabled")
|
||||
|
||||
verify(panel)
|
||||
log("done")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user