From 562e380218c02f1e1f5c0681c21689a8d522c33b Mon Sep 17 00:00:00 2001 From: kubbot Date: Sat, 31 Oct 2026 04:28:41 +0800 Subject: [PATCH] fix: publish the existing Pages snapshot with verified artifacts Signed-off-by: kubbot --- .github/workflows/deploy-github.yml | 100 ++++++++++++++++++----- README.md | 17 ++++ scripts/check-pages-artifact.py | 119 ++++++++++++++++++++++++++++ 3 files changed, 215 insertions(+), 21 deletions(-) create mode 100644 scripts/check-pages-artifact.py diff --git a/.github/workflows/deploy-github.yml b/.github/workflows/deploy-github.yml index b4e299f..3d8d666 100644 --- a/.github/workflows/deploy-github.yml +++ b/.github/workflows/deploy-github.yml @@ -1,22 +1,34 @@ -# Deploy your Hyas site to GitHub Pages - name: GitHub Pages on: push: - branches: - - main + branches: [main] + pull_request: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: pages-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} jobs: - deploy: + build: runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + contents: read + pages: read steps: - uses: actions/checkout@v7 + with: + persist-credentials: false - uses: actions/setup-node@v7 with: node-version-file: .nvmrc - cache: 'npm' - + cache: npm - uses: actions/setup-go@v7 with: go-version: '1.26.10' @@ -25,18 +37,64 @@ jobs: with: hugo-version: '0.121.2' extended: true - - - name: Install dependencies - run: npm ci --ignore-scripts - - - name: Check for linting errors - run: npm test - - - name: Build production website - run: npm run build - - - name: Deploy to GitHub Pages - uses: peaceiris/actions-gh-pages@v3 + - name: Verify the main source build + run: | + npm ci --ignore-scripts + npm test + npm run build + - name: Read existing Pages metadata + id: pages + uses: actions/configure-pages@v5 + with: + enablement: false + - name: Preserve the existing site address + env: + PAGES_BASE_URL: ${{ steps.pages.outputs.base_url }} + PAGES_BASE_PATH: ${{ steps.pages.outputs.base_path }} + run: | + python - <<'PYTHON' + import os + if os.environ['PAGES_BASE_URL'].rstrip('/') != 'https://openkf.github.io/website': + raise SystemExit('The configured Pages site address changed') + if os.environ['PAGES_BASE_PATH'].rstrip('/') != '/website': + raise SystemExit('The configured Pages base path changed') + PYTHON + - name: Check out the existing published content + uses: actions/checkout@v7 + with: + ref: gh-pages + path: published-site + persist-credentials: false + - name: Record the unchanged published byte tree + run: python scripts/check-pages-artifact.py record published-site "$RUNNER_TEMP/pages-source.json" --archive "$RUNNER_TEMP/artifact.tar" + - name: Upload the existing static site + uses: actions/upload-artifact@v4 + with: + name: github-pages + path: ${{ runner.temp }}/artifact.tar + retention-days: 1 + if-no-files-found: error + - name: Download the exact artifact before deployment + uses: actions/download-artifact@v5 with: - github_token: ${{ secrets.BOT_GITHUB_TOKEN }} - publish_dir: ./public + name: github-pages + path: ${{ runner.temp }}/checked-pages-artifact + - name: Verify the uploaded artifact against the published tree + run: python scripts/check-pages-artifact.py verify "$RUNNER_TEMP/pages-source.json" "$RUNNER_TEMP/checked-pages-artifact/artifact.tar" + + deploy: + if: github.ref == 'refs/heads/main' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch') + needs: build + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: read + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - name: Deploy the verified existing Pages artifact + id: deployment + uses: actions/deploy-pages@v4 diff --git a/README.md b/README.md index 5892720..31c701d 100644 --- a/README.md +++ b/README.md @@ -84,3 +84,20 @@ npm run clean ``` This removes `public` and `resources` without deleting the lock file. + +## GitHub Pages delivery + +The [existing Pages site](https://openkf.github.io/website/) continues to use +the compiled content on `gh-pages`. Its existing pages and assets are uploaded +as an exact verified artifact; the empty Docsy scaffold on `main` is built for +validation and is not published over the existing site. Moving real content to +`main` is a separate migration. + +Pushes to `main` and manual runs on `main` republish that `gh-pages` snapshot. +A pull request only builds and verifies the artifact. A push to `gh-pages` does +not automatically run the workflow stored on `main`; run it manually on `main` +after updating the published snapshot. + +Deployment uses the existing `github-pages` environment and GitHub's official +Pages artifact and short-lived token flow, preserving the same site address. +The previous user-managed token is not copied, replaced, or exposed. diff --git a/scripts/check-pages-artifact.py b/scripts/check-pages-artifact.py new file mode 100644 index 0000000..eca0a88 --- /dev/null +++ b/scripts/check-pages-artifact.py @@ -0,0 +1,119 @@ +"""Verify the existing gh-pages byte tree before and after artifact upload.""" + +import argparse +import hashlib +import io +import json +from pathlib import Path, PurePosixPath +import subprocess +import tarfile + + +def payload_path(name): + path = PurePosixPath(name) + if path.is_absolute() or ".." in path.parts or ".git" in path.parts: + raise ValueError("Unexpected path in the published payload") + return str(path) + + +def record_snapshot(root, manifest_file, archive): + root = root.resolve() + git = ["git", "-C", str(root)] + commit = subprocess.check_output(git + ["rev-parse", "HEAD"], text=True).strip() + tree = subprocess.check_output(git + ["rev-parse", "HEAD^{tree}"], text=True).strip() + raw = subprocess.check_output(git + ["ls-tree", "-rtz", "--full-tree", "HEAD"]) + files = {} + directories = {"."} + packed = [] + for entry in raw.split(b"\0"): + if not entry: + continue + metadata, filename = entry.split(b"\t", 1) + mode, kind, blob = metadata.decode("ascii").split() + name = payload_path(filename.decode("utf-8")) + if kind == "tree": + directories.add(name) + continue + if kind != "blob" or mode not in {"100644", "100755"}: + raise ValueError("Pages payload must contain regular tracked files only") + path = root.joinpath(*PurePosixPath(name).parts) + if path.is_symlink() or not path.resolve().is_relative_to(root): + raise ValueError("Pages payload escaped the checked-out snapshot") + content = path.read_bytes() + actual_blob = hashlib.sha1( + b"blob " + str(len(content)).encode("ascii") + b"\0" + content + ).hexdigest() + if actual_blob != blob: + raise ValueError("A published file differs from its Git blob") + files[name] = {"sha256": hashlib.sha256(content).hexdigest(), + "bytes": len(content), "executable": mode == "100755"} + packed.append((name, content, mode, int(path.stat().st_mtime))) + if "index.html" not in files or not files: + raise ValueError("The existing published index is missing") + # Match the official Pages artifact.tar protocol while preserving tracked + # dotfiles such as the existing empty .nojekyll marker. Never pack .git. + with tarfile.open(archive, "w") as payload: + for name in sorted(directories, key=lambda item: (item.count("/"), item)): + entry = tarfile.TarInfo(name) + entry.type = tarfile.DIRTYPE + entry.mode = 0o755 + payload.addfile(entry) + for name, content, mode, mtime in packed: + entry = tarfile.TarInfo(name) + entry.size = len(content) + entry.mode = 0o755 if mode == "100755" else 0o644 + entry.mtime = mtime + payload.addfile(entry, io.BytesIO(content)) + result = {"commit": commit, "tree": tree, "files": files, + "directories": sorted(directories)} + manifest_file.write_text(json.dumps(result, sort_keys=True), encoding="utf-8") + print(f"Recorded published snapshot {commit}, tree {tree}, {len(files)} files") + + +def verify_artifact(manifest_file, archive): + manifest = json.loads(manifest_file.read_text(encoding="utf-8")) + expected = manifest["files"] + expected_dirs = set(manifest["directories"]) + seen = set() + seen_dirs = set() + with tarfile.open(archive, "r:*") as payload: + for member in payload: + name = payload_path(member.name) + if member.isdir(): + if name not in expected_dirs or name in seen_dirs: + raise ValueError("Artifact has an extra or duplicate directory") + seen_dirs.add(name) + continue + if member.type not in {tarfile.REGTYPE, tarfile.AREGTYPE} or name not in expected or name in seen: + raise ValueError("Artifact has an extra, duplicate or non-regular file") + file = expected[name] + if member.size != file["bytes"]: + raise ValueError("Uploaded artifact changed a published file size") + content = payload.extractfile(member).read() + if len(content) != file["bytes"] or ( + hashlib.sha256(content).hexdigest() != file["sha256"] + ) or bool(member.mode & 0o111) != file["executable"]: + raise ValueError("Uploaded artifact changed the published byte tree") + seen.add(name) + if seen != set(expected) or seen_dirs != expected_dirs: + raise ValueError("Uploaded artifact omitted published files or directories") + print(f"Verified uploaded Pages artifact: {len(seen)} unchanged files") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("action", choices=["record", "verify"]) + parser.add_argument("first", type=Path) + parser.add_argument("second", type=Path) + parser.add_argument("--archive", type=Path) + args = parser.parse_args() + if args.action == "record": + if args.archive is None: + parser.error("record requires --archive") + record_snapshot(args.first, args.second, args.archive) + else: + verify_artifact(args.first, args.second) + + +if __name__ == "__main__": + main()