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,80 @@
|
||||
# Deploying Tansy UI to cPanel
|
||||
|
||||
One command replaces the old manual sequence. There is nothing to delete
|
||||
first and no manual overwrite: the cPanel-side script treats the uploaded
|
||||
archive as the complete truth for the docroot and prunes everything else.
|
||||
|
||||
## Use
|
||||
|
||||
```bash
|
||||
python3 scripts/deploy.py # build + package + upload + verify
|
||||
python3 scripts/deploy.py --deploy-only # upload the existing build
|
||||
python3 scripts/deploy.py --build-only # build and package, upload nothing
|
||||
python3 scripts/deploy.py --dry-run # package and report, upload nothing
|
||||
```
|
||||
|
||||
## One-time setup
|
||||
|
||||
```bash
|
||||
cp scripts/deploy.env.example scripts/deploy.env
|
||||
$EDITOR scripts/deploy.env # fill in CPANEL_PASS
|
||||
chmod 600 scripts/deploy.env
|
||||
```
|
||||
|
||||
`scripts/deploy.env` is gitignored. Every value can also come from the
|
||||
environment instead, which is what CI should do.
|
||||
|
||||
## How it works
|
||||
|
||||
1. `npm ci`, `npm run lint`, `npm run build`, `npm run build-storybook`
|
||||
2. Stage `dist/` at the root and `storybook-static/` under `docs/`, zip with
|
||||
Python's `zipfile` (there is no `zip` binary on the build host), base64 it
|
||||
3. Upload `scripts/cpanel-deploy.php` to the docroot over the cPanel UAPI
|
||||
4. POST the base64 payload to it with a `Host` header for the subdomain,
|
||||
pointed at the origin IP so Cloudflare is bypassed
|
||||
5. The PHP extracts, then deletes anything the archive did not contain
|
||||
6. Rewrite the hardened `.htaccess` and verify the site
|
||||
|
||||
## Why the archive can be authoritative
|
||||
|
||||
Vite and Storybook both emit content-hashed filenames
|
||||
(`index-DHOur7R8.js`, `Alert.stories-CL8ipgGJ.js`), so a new build never
|
||||
overwrites an old file. Without pruning, every deploy leaves its previous
|
||||
bundles behind. The prune step is what keeps the docroot at exactly one
|
||||
build.
|
||||
|
||||
`KEEP_TOP` in `deploy.py` lists the names the prune must never touch:
|
||||
`.htaccess`, `.user.ini`, `php.ini`, `cgi-bin`, `.well-known`. cPanel owns
|
||||
those; removing `.htaccess` would take the site down.
|
||||
|
||||
## Traps this script works around
|
||||
|
||||
- **PHP is disabled in the hardened `.htaccess`.** The deployer cannot run
|
||||
until it is lifted, so the script writes a PHP-enabled copy, deploys, then
|
||||
restores the hardened one. It verifies PHP executes *before* trusting the
|
||||
upload, and verifies PHP is off again afterwards.
|
||||
- **A PHP parse error is nearly invisible.** The server returns an empty
|
||||
body and leaves `_deploy.php` on disk, which looks identical to "the
|
||||
upload was ignored". The real cause only shows up in
|
||||
`/home/<CPANEL_USER>/logs/php.error.log`. The script therefore runs `php -l`
|
||||
locally before uploading and aborts if it fails. This is why `php-cli` and
|
||||
`php-zip` are required on the build host.
|
||||
- **`protected` is a reserved PHP keyword.** `const PROTECTED = [...]` is a
|
||||
parse error. The constant is `PRESERVE`.
|
||||
- **The `Host` header is required.** Without it the request hits the
|
||||
server's default vhost and cPanel answers with its own 404 page.
|
||||
|
||||
## Verifying a change to the prune logic
|
||||
|
||||
The prune step deletes files, so test it against a fixture rather than
|
||||
production. Build a fake docroot containing a previous build plus cPanel's
|
||||
files, run the real script under `php-cli`, and assert that current files
|
||||
survive, stale ones are gone, and the preserved names are untouched.
|
||||
|
||||
## Wiring it into CI
|
||||
|
||||
`scripts/deploy.py` is the whole deploy; a workflow only has to supply
|
||||
credentials and run it. Note that the Gitea runner's job timeout is 360 s
|
||||
and `npm ci` plus a cold Storybook build is likely to exceed that, so either
|
||||
raise `runner.timeout` in the runner config or run this from a machine that
|
||||
already has `node_modules`.
|
||||
@@ -0,0 +1,215 @@
|
||||
<?php
|
||||
/**
|
||||
* cPanel static deployer: extract a base64 ZIP, then prune anything the
|
||||
* upload did not bring with it.
|
||||
*
|
||||
* Post fields:
|
||||
* data - base64 of a ZIP whose entries are relative paths
|
||||
* keep - optional JSON array of extra top-level names to preserve
|
||||
*
|
||||
* The archive is authoritative for everything except the names in
|
||||
* $keepNames. After extraction anything else is stale output from a
|
||||
* previous build and is removed, so the docroot always matches exactly
|
||||
* one build and old content-hashed assets do not accumulate.
|
||||
*
|
||||
* Self-deletes as its first action so it cannot be replayed.
|
||||
*/
|
||||
|
||||
$self = __FILE__;
|
||||
@unlink($self);
|
||||
|
||||
header('Content-Type: text/plain');
|
||||
|
||||
// Named PRESERVE, not PROTECTED - `protected` is a reserved PHP keyword
|
||||
// and a const with that name is a parse error.
|
||||
const PRESERVE = ['.', '..', '.htaccess', '.user.ini', 'php.ini', 'cgi-bin', '.well-known'];
|
||||
|
||||
function fail(string $msg): never {
|
||||
echo "ERROR: {$msg}\n";
|
||||
exit(1);
|
||||
}
|
||||
|
||||
if (!isset($_POST['data'])) {
|
||||
fail('no data payload');
|
||||
}
|
||||
|
||||
$raw = base64_decode($_POST['data'], true);
|
||||
if ($raw === false || $raw === '') {
|
||||
fail('base64 decode failed');
|
||||
}
|
||||
|
||||
$extraKeep = [];
|
||||
if (isset($_POST['keep'])) {
|
||||
$decoded = json_decode($_POST['keep'], true);
|
||||
if (is_array($decoded)) {
|
||||
$extraKeep = $decoded;
|
||||
}
|
||||
}
|
||||
$keepNames = array_merge(PRESERVE, $extraKeep);
|
||||
|
||||
$tmp = tempnam(sys_get_temp_dir(), 'dep');
|
||||
if ($tmp === false) {
|
||||
fail('tempnam failed');
|
||||
}
|
||||
file_put_contents($tmp, $raw);
|
||||
|
||||
$zip = new ZipArchive();
|
||||
if ($zip->open($tmp) !== TRUE) {
|
||||
@unlink($tmp);
|
||||
fail('zip open failed');
|
||||
}
|
||||
|
||||
$root = __DIR__;
|
||||
$writtenFiles = []; // every relative file path the archive produced
|
||||
$writtenDirs = ['']; // every relative directory the archive produced
|
||||
$extracted = 0;
|
||||
|
||||
for ($i = 0; $i < $zip->numFiles; $i++) {
|
||||
$name = $zip->getNameIndex($i);
|
||||
if ($name === false || $name === '' || str_ends_with($name, '/')) {
|
||||
continue;
|
||||
}
|
||||
// Reject traversal and absolute paths outright.
|
||||
if (str_contains($name, '..') || $name[0] === '/' || $name[0] === '\\') {
|
||||
fail("refusing suspicious archive path: {$name}");
|
||||
}
|
||||
|
||||
// Record every parent directory as part of the new build.
|
||||
$parts = explode('/', $name);
|
||||
array_pop($parts);
|
||||
$acc = '';
|
||||
foreach ($parts as $part) {
|
||||
$acc = $acc === '' ? $part : $acc . '/' . $part;
|
||||
$writtenDirs[$acc] = true;
|
||||
}
|
||||
|
||||
$dest = $root . '/' . $name;
|
||||
$writtenFiles[$name] = true;
|
||||
|
||||
$dir = dirname($dest);
|
||||
if (!is_dir($dir) && !@mkdir($dir, 0755, true) && !is_dir($dir)) {
|
||||
fail("mkdir failed: {$dir}");
|
||||
}
|
||||
|
||||
$stream = $zip->getStream($name);
|
||||
if ($stream === false) {
|
||||
fail("getStream failed: {$name}");
|
||||
}
|
||||
$out = fopen($dest, 'wb');
|
||||
if ($out === false) {
|
||||
fclose($stream);
|
||||
fail("fopen failed: {$dest}");
|
||||
}
|
||||
stream_copy_to_stream($stream, $out);
|
||||
fclose($out);
|
||||
fclose($stream);
|
||||
$extracted++;
|
||||
}
|
||||
|
||||
$zip->close();
|
||||
@unlink($tmp);
|
||||
|
||||
if ($extracted === 0) {
|
||||
fail('archive contained no files');
|
||||
}
|
||||
|
||||
// --- prune stale output -------------------------------------------------
|
||||
$removed = 0;
|
||||
$prunedDirs = 0;
|
||||
|
||||
function rmTree(string $dir): void {
|
||||
global $removed, $prunedDirs;
|
||||
$items = @scandir($dir);
|
||||
if ($items === false) {
|
||||
return;
|
||||
}
|
||||
foreach ($items as $item) {
|
||||
if ($item === '.' || $item === '..') {
|
||||
continue;
|
||||
}
|
||||
$path = $dir . '/' . $item;
|
||||
if (is_dir($path)) {
|
||||
rmTree($path);
|
||||
if (@rmdir($path)) {
|
||||
$prunedDirs++;
|
||||
}
|
||||
} elseif (@unlink($path)) {
|
||||
$removed++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete everything inside $absDir that the new build did not write, then
|
||||
* remove the directory itself if this build did not produce it.
|
||||
*/
|
||||
function pruneDir(string $absDir, string $relDir): void {
|
||||
global $removed, $prunedDirs, $writtenFiles, $writtenDirs;
|
||||
|
||||
$items = @scandir($absDir);
|
||||
if ($items === false) {
|
||||
return;
|
||||
}
|
||||
foreach ($items as $item) {
|
||||
if ($item === '.' || $item === '..') {
|
||||
continue;
|
||||
}
|
||||
$rel = $relDir === '' ? $item : $relDir . '/' . $item;
|
||||
$path = $absDir . '/' . $item;
|
||||
|
||||
if (is_dir($path)) {
|
||||
pruneDir($path, $rel);
|
||||
// Only remove the directory if this build did not put anything
|
||||
// inside it - that is what makes assets/ and docs/ survive.
|
||||
if (!isset($writtenDirs[$rel]) && @rmdir($path)) {
|
||||
$prunedDirs++;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!isset($writtenFiles[$rel]) && @unlink($path)) {
|
||||
$removed++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$top = @scandir($root);
|
||||
if ($top === false) {
|
||||
fail('scandir failed on docroot');
|
||||
}
|
||||
|
||||
foreach ($top as $entry) {
|
||||
if (in_array($entry, $keepNames, true)) {
|
||||
continue;
|
||||
}
|
||||
$path = $root . '/' . $entry;
|
||||
if (is_dir($path)) {
|
||||
pruneDir($path, $entry);
|
||||
if (!isset($writtenDirs[$entry]) && @rmdir($path)) {
|
||||
$prunedDirs++;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (!isset($writtenFiles[$entry]) && @unlink($path)) {
|
||||
$removed++;
|
||||
}
|
||||
}
|
||||
|
||||
$bytes = 0;
|
||||
foreach (array_keys($writtenFiles) as $name) {
|
||||
$bytes += @filesize($root . '/' . $name) ?: 0;
|
||||
}
|
||||
|
||||
// Post-deploy sanity check: the docroot must still contain what was written.
|
||||
if (!file_exists($root . '/index.html')) {
|
||||
fail('post-deploy check failed: index.html is missing');
|
||||
}
|
||||
|
||||
echo json_encode([
|
||||
'ok' => true,
|
||||
'extracted' => $extracted,
|
||||
'pruned_files' => $removed,
|
||||
'pruned_dirs' => $prunedDirs,
|
||||
'bytes' => $bytes,
|
||||
'docroot' => $root,
|
||||
], JSON_PRETTY_PRINT) . "\n";
|
||||
@@ -0,0 +1,21 @@
|
||||
# cPanel deploy credentials for scripts/deploy.py
|
||||
#
|
||||
# This file is gitignored. Copy it to deploy.env, fill it in, and keep it at
|
||||
# mode 600. The same values can come from the environment instead:
|
||||
# CPANEL_HOST, CPANEL_USER, CPANEL_PASS, CPANEL_SUB, ORIGIN_IP
|
||||
|
||||
# Hostname the cPanel panel is served on (without :2083)
|
||||
CPANEL_HOST=cpanel.example.com
|
||||
|
||||
# cPanel account username
|
||||
CPANEL_USER=cpaneluser
|
||||
|
||||
# Account password
|
||||
CPANEL_PASS=change-me
|
||||
|
||||
# Subdomain the build is served from; also the docroot's directory name
|
||||
CPANEL_SUB=ui.example.com
|
||||
|
||||
# Origin IP of the cPanel server, used to POST the payload with a Host header
|
||||
# that bypasses Cloudflare. DNS for the subdomain must point here, unproxied.
|
||||
ORIGIN_IP=203.0.113.10
|
||||
@@ -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()
|
||||
@@ -0,0 +1,228 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Generate the landing page's component catalogue from the built Storybook
|
||||
index, so it cannot drift from the stories again.
|
||||
|
||||
Run it after `npm run build-storybook` and before `npm run build` when you
|
||||
add or remove a component. It prints the entries to paste into
|
||||
src/data/catalogue.ts and writes /tmp/component_catalogue.json.
|
||||
|
||||
python3 scripts/gen_catalogue.py # print entries
|
||||
python3 scripts/gen_catalogue.py --patch # also rewrite src/data/catalogue.ts
|
||||
|
||||
Story ids are `<group>-<component>--<story>`, but the group is not always
|
||||
a single segment: TextField publishes as `data-entry-text-field--*`. So
|
||||
components are matched by longest known name against `base` or
|
||||
`base.endswith("-" + name)`, with aliases for the hyphenated spellings.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parent.parent
|
||||
IDX = REPO / "storybook-static" / "index.json"
|
||||
CATALOGUE = REPO / "src" / "data" / "catalogue.ts"
|
||||
OUT = Path("/tmp/component_catalogue.json")
|
||||
|
||||
# component id -> group slug
|
||||
GROUPS = {
|
||||
"button": "actions",
|
||||
"accordion": "navigation",
|
||||
"text-field": "data-entry",
|
||||
"textfield": "data-entry",
|
||||
"input": "forms",
|
||||
"featuredinput": "forms",
|
||||
"featured-input": "forms",
|
||||
"select": "forms",
|
||||
"checkbox": "forms",
|
||||
"radio": "forms",
|
||||
"switch": "forms",
|
||||
"textarea": "forms",
|
||||
"text-area": "forms",
|
||||
"alert": "feedback",
|
||||
"spinner": "feedback",
|
||||
"badge": "display",
|
||||
"card": "layout",
|
||||
"tooltip": "overlays",
|
||||
}
|
||||
|
||||
# alias id key -> canonical component key
|
||||
CANON = {
|
||||
"text-field": "textfield",
|
||||
"featured-input": "featuredinput",
|
||||
"text-area": "textarea",
|
||||
}
|
||||
|
||||
SPECIAL = {
|
||||
"textfield": "Text field",
|
||||
"featuredinput": "FeaturedInput",
|
||||
"textarea": "TextArea",
|
||||
"checkbox": "Checkbox",
|
||||
"spinner": "Spinner",
|
||||
"accordion": "Accordion",
|
||||
"tooltip": "Tooltip",
|
||||
"button": "Button",
|
||||
"select": "Select",
|
||||
"radio": "Radio",
|
||||
"switch": "Switch",
|
||||
"alert": "Alert",
|
||||
"badge": "Badge",
|
||||
"card": "Card",
|
||||
"input": "Input",
|
||||
}
|
||||
|
||||
GROUP_LABEL = {
|
||||
"actions": "Actions",
|
||||
"navigation": "Navigation",
|
||||
"data": "Data entry",
|
||||
"data-entry": "Data entry",
|
||||
"forms": "Forms",
|
||||
"feedback": "Feedback",
|
||||
"display": "Display",
|
||||
"layout": "Layout",
|
||||
"overlays": "Overlays",
|
||||
"misc": "Other",
|
||||
}
|
||||
|
||||
# display order on the landing page
|
||||
ORDER = [
|
||||
"button", "accordion", "textfield",
|
||||
"input", "featuredinput", "select", "checkbox", "radio", "switch", "textarea",
|
||||
"alert", "spinner",
|
||||
"badge", "card",
|
||||
"tooltip",
|
||||
]
|
||||
|
||||
# one-line coverage summary shown in the index row
|
||||
DETAIL = {
|
||||
"button": "Variants · sizes · disabled",
|
||||
"accordion": "Disclosure · multiple",
|
||||
"textfield": "Labels · hints · errors",
|
||||
"input": "Plain · themed · icon slot",
|
||||
"featuredinput": "Floating label · password · number",
|
||||
"select": "Searchable · featured · async",
|
||||
"checkbox": "Themes · tooltip · uncontrolled",
|
||||
"radio": "Themes · horizontal · required",
|
||||
"switch": "Themes · required · described",
|
||||
"textarea": "Resize · featured · prefilled",
|
||||
"alert": "Variants · colors · auto-close",
|
||||
"spinner": "Sizes · variants · dark",
|
||||
"badge": "Colors · floating · pulse",
|
||||
"card": "Themes · shadows · horizontal",
|
||||
"tooltip": "Positions · rich content · sizes",
|
||||
}
|
||||
|
||||
|
||||
def collect():
|
||||
if not IDX.is_file():
|
||||
sys.exit(f"{IDX} not found - run: npm run build-storybook")
|
||||
|
||||
entries = json.loads(IDX.read_text())["entries"]
|
||||
ids = [v.get("id", k) if isinstance(v, dict) else k for k, v in entries.items()]
|
||||
|
||||
comps: dict[str, dict] = {}
|
||||
for sid in ids:
|
||||
if "--" not in sid:
|
||||
continue
|
||||
base, story = sid.split("--", 1)
|
||||
comp = next(
|
||||
(CANON.get(c, c) for c in sorted(GROUPS, key=len, reverse=True)
|
||||
if base == c or base.endswith("-" + c)),
|
||||
None,
|
||||
)
|
||||
if comp is None:
|
||||
print(f" WARN unmapped story id: {sid}", file=sys.stderr)
|
||||
continue
|
||||
g = comps.setdefault(comp, {"group": GROUPS[comp], "doc": None,
|
||||
"count": 0})
|
||||
g["count"] += 1
|
||||
if story in ("documentation", "docs"):
|
||||
g["doc"] = sid
|
||||
|
||||
out = []
|
||||
for i, comp in enumerate(ORDER, start=1):
|
||||
g = comps.get(comp)
|
||||
if not g or not g["doc"]:
|
||||
print(f" WARN {comp}: no documentation story, skipped", file=sys.stderr)
|
||||
continue
|
||||
out.append({
|
||||
"number": f"{i:02d}",
|
||||
"group": GROUP_LABEL.get(g["group"], g["group"].title()),
|
||||
"name": SPECIAL.get(comp, comp.title()),
|
||||
"detail": DETAIL.get(comp, f"{g['count']} stories"),
|
||||
"href": f"/docs/?path=/docs/{g['doc']}",
|
||||
"count": g["count"],
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
def as_tsx(entries) -> str:
|
||||
body = "".join(
|
||||
" {\n"
|
||||
f" number: '{e['number']}',\n"
|
||||
f" group: '{e['group']}',\n"
|
||||
f" name: '{e['name']}',\n"
|
||||
f" detail: '{e['detail']}',\n"
|
||||
f" href: '{e['href']}',\n"
|
||||
" },\n"
|
||||
for e in entries
|
||||
)
|
||||
return f"export const documentation: CatalogueEntry[] = [\n{body}]\n"
|
||||
|
||||
|
||||
def as_counts(entries) -> str:
|
||||
lines = []
|
||||
for e in entries:
|
||||
key = e["name"] if re.fullmatch(r"[A-Za-z][A-Za-z0-9]*", e["name"]) \
|
||||
else f"'{e['name']}'"
|
||||
lines.append(f" {key}: {e['count']},")
|
||||
return ("export const storyCounts: Record<string, number> = {\n"
|
||||
+ "\n".join(lines) + "\n}\n")
|
||||
|
||||
|
||||
def patch_catalogue(entries) -> None:
|
||||
src = CATALOGUE.read_text()
|
||||
|
||||
src, n = re.subn(r"export const documentation\b[^=]*= \[.*?\n\]\n",
|
||||
lambda _: as_tsx(entries), src, count=1, flags=re.S)
|
||||
if n == 0:
|
||||
sys.exit(f"could not find the documentation array in {CATALOGUE}")
|
||||
|
||||
src, n2 = re.subn(r"export const storyCounts\b[^=]*= \{.*?\n\}\n",
|
||||
lambda _: as_counts(entries), src, count=1, flags=re.S)
|
||||
if n2 == 0:
|
||||
sys.exit(f"could not find the storyCounts block in {CATALOGUE}")
|
||||
|
||||
CATALOGUE.write_text(src)
|
||||
print(f"patched {CATALOGUE} with {len(entries)} components")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--patch", action="store_true",
|
||||
help="rewrite the catalogue and story counts in src/data/catalogue.ts")
|
||||
args = ap.parse_args()
|
||||
|
||||
entries = collect()
|
||||
if not entries:
|
||||
sys.exit("no components with a documentation story were found")
|
||||
|
||||
total = sum(e["count"] for e in entries)
|
||||
for e in entries:
|
||||
print(f" {e['number']} {e['name']:<16} {e['group']:<12} "
|
||||
f"{e['count']:>2} stories {e['href']}")
|
||||
|
||||
OUT.write_text(json.dumps(entries, indent=1))
|
||||
print(f"\n{len(entries)} components, {total} stories -> {OUT}")
|
||||
|
||||
if args.patch:
|
||||
patch_catalogue(entries)
|
||||
print("now run: npm run build")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user