Add versioning and harden deploy caching (v0.2.0)
Versioning: - package.json is the single source of the version (0.2.0); the build injects it into the landing page and Storybook via src/version.ts - Add CHANGELOG.md and a release section in the README Deploy: - Refuse to deploy uncommitted work unless --allow-dirty is passed - Stamp each deploy with version.json and verify the live stamp - Serve HTML and JSON with Cache-Control: no-cache and cache only the content-hashed assets/ folders long-term - Return 404 for missing assets instead of index.html, which blanked the Storybook canvas for browsers holding a stale page - Always restore the hardened .htaccess, even when a step fails - Make the post-deploy PHP-off check real, build Storybook before checking for its index, and stop logging the session token
This commit is contained in:
1 parent
9d406d6d2a
commit
dc5e6ff800
10 files changed
+224
-52
No files matched your search
+28
-2
@@ -8,11 +8,15 @@ archive as the complete truth for the docroot and prunes everything else.
|
||||
|
||||
```bash
|
||||
python3 scripts/deploy.py # build + package + upload + verify
|
||||
python3 scripts/deploy.py --deploy-only # upload the existing build
|
||||
python3 scripts/deploy.py --deploy-only # upload the existing build (must be built from HEAD)
|
||||
python3 scripts/deploy.py --build-only # build and package, upload nothing
|
||||
python3 scripts/deploy.py --dry-run # package and report, upload nothing
|
||||
```
|
||||
|
||||
Commit before deploying. The script refuses to upload while the working tree
|
||||
has uncommitted changes, so what is live always matches a commit. Pass
|
||||
`--allow-dirty` to override.
|
||||
|
||||
## One-time setup
|
||||
|
||||
```bash
|
||||
@@ -33,7 +37,29 @@ environment instead, which is what CI should do.
|
||||
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
|
||||
6. Rewrite the hardened `.htaccess` (always, even if a step above failed),
|
||||
confirm PHP is off again, and verify the site, including `/version.json`
|
||||
|
||||
## Caching
|
||||
|
||||
The root `.htaccess` sends `Cache-Control: no-cache`, so browsers revalidate
|
||||
`index.html`, `docs/index.json` and Storybook's fixed-name manager bundles on
|
||||
every visit. `package()` adds an `.htaccess` to `assets/` and `docs/assets/`
|
||||
that caches those content-hashed files for a year. Missing asset URLs return
|
||||
404 instead of falling back to `index.html`. A stale page that asks for a pruned
|
||||
bundle then fails visibly, instead of receiving HTML and rendering an empty
|
||||
Storybook canvas.
|
||||
|
||||
## Version stamp
|
||||
|
||||
Each deploy writes `version.json` at the docroot:
|
||||
|
||||
```json
|
||||
{ "version": "0.2.0", "commit": "abc1234", "dirty": false, "built_at": "…" }
|
||||
```
|
||||
|
||||
`verify()` checks that the live stamp matches the one just uploaded. To see
|
||||
what is running, open `https://<your-subdomain>/version.json`.
|
||||
|
||||
## Why the archive can be authoritative
|
||||
|
||||
|
||||
+128
-43
@@ -42,6 +42,11 @@ ENV_FILE = REPO / "scripts" / "deploy.env"
|
||||
# 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 echo 'PHPEXEC-' . 'OK', PHP_VERSION;"
|
||||
|
||||
# Set from --skip-php-lint in main().
|
||||
SKIP_PHP_LINT = False
|
||||
|
||||
@@ -65,10 +70,16 @@ DirectoryIndex index.html
|
||||
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]
|
||||
@@ -77,14 +88,17 @@ DirectoryIndex index.html
|
||||
<IfModule mod_headers.c>
|
||||
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"
|
||||
</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"
|
||||
# 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 = """<IfModule mod_headers.c>
|
||||
Header set Cache-Control "public, max-age=31536000, immutable"
|
||||
</IfModule>
|
||||
"""
|
||||
|
||||
@@ -144,9 +158,32 @@ 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"])
|
||||
if not (REPO / "storybook-static" / "index.json").exists():
|
||||
die("storybook-static/index.json missing after build-storybook")
|
||||
|
||||
|
||||
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 / "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:
|
||||
@@ -162,6 +199,11 @@ def package() -> dict:
|
||||
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():
|
||||
@@ -182,10 +224,13 @@ def package() -> dict:
|
||||
"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
|
||||
|
||||
@@ -224,7 +269,7 @@ class Panel:
|
||||
self.token = json.loads(out)["security_token"]
|
||||
except Exception:
|
||||
die(f"login failed: {out[:200]}")
|
||||
log(f"logged in, token {self.token}")
|
||||
log("logged in")
|
||||
|
||||
def uapi(self, module: str, fn: str, params: dict | None = None) -> dict:
|
||||
url = f"{self.base}{self.token}/execute/{module}/{fn}"
|
||||
@@ -244,6 +289,26 @@ class Panel:
|
||||
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})
|
||||
@@ -290,6 +355,15 @@ 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((REPO / "dist" / "index.html").read_bytes()).hexdigest()
|
||||
@@ -347,10 +421,16 @@ def main() -> None:
|
||||
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()
|
||||
@@ -377,45 +457,50 @@ def main() -> None:
|
||||
"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.
|
||||
# 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)
|
||||
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")
|
||||
time.sleep(2)
|
||||
|
||||
# 4. Re-harden, then confirm PHP is shut off again.
|
||||
panel.write_file(".htaccess", htaccess_hardened)
|
||||
# 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)
|
||||
if "PHPEXEC-OK" in after:
|
||||
panel.delete_file("_probe.php")
|
||||
if PROBE_MARK in after:
|
||||
die("PHP is still enabled after hardening - investigate the .htaccess")
|
||||
log("PHP re-disabled")
|
||||
|
||||
|
||||
Reference in new issue
Block a user