diff --git a/.github/workflows/package-manual.yml b/.github/workflows/package-manual.yml index aa9afb92..242bc0ba 100644 --- a/.github/workflows/package-manual.yml +++ b/.github/workflows/package-manual.yml @@ -1,5 +1,7 @@ name: Manual package artifacts (unverified) -# Source-only addition. No push/release trigger and no publication permissions. +# Builds and packages one commit for every target, smoke-tests each packaged binary on +# its native runner, and keeps the results as workflow artifacts. It holds no +# publication permissions itself; release.yml calls it and publishes what it builds. on: workflow_dispatch: inputs: @@ -140,6 +142,42 @@ jobs: raise finally: (out / 'lane.json').write_text(json.dumps(receipt, indent=2, sort_keys=True) + '\n', encoding='utf-8') + # Every lane runs on its target's native architecture, so the packaged + # binary itself can be started here. This catches a package that unpacks + # to a binary that does not launch, which the receipts alone cannot see. + - name: Smoke-test the packaged binary on its native runner + shell: python + run: | + import hashlib, json, os, pathlib, subprocess, tarfile, tempfile, zipfile + out = pathlib.Path(os.environ['RUNNER_TEMP']) / ('modsync-package-' + os.environ['BUILD_TARGET']) + packages = sorted(p for p in (out / 'packages').iterdir() if p.name.endswith(('.zip', '.tar.gz'))) + if len(packages) != 1: + raise SystemExit(f'Expected one package, found {[p.name for p in packages]}') + name = 'modsync.exe' if os.environ['TARGET_OS'] == 'windows' else 'modsync' + expected = json.loads((out / 'produced' / 'build-receipt.json').read_text())['binaries']['modsync'] + lane = json.loads((out / 'lane.json').read_text()) + with tempfile.TemporaryDirectory() as temp: + root = pathlib.Path(temp) + if packages[0].name.endswith('.zip'): + with zipfile.ZipFile(packages[0]) as archive: + archive.extractall(root) + else: + with tarfile.open(packages[0]) as archive: + archive.extractall(root, filter='data') + found = [p for p in root.rglob(name) if p.is_file()] + if len(found) != 1: + raise SystemExit(f'Expected one {name} in the package, found {len(found)}') + binary = found[0] + if hashlib.sha256(binary.read_bytes()).hexdigest() != expected: + raise SystemExit('Packaged binary differs from the build receipt') + binary.chmod(0o755) + result = subprocess.run([str(binary), '--version'], capture_output=True, text=True, timeout=120) + print(result.stdout + result.stderr) + if result.returncode != 0 or not result.stdout.startswith('modsync '): + raise SystemExit(f'Packaged binary failed to start (exit {result.returncode})') + lane['smokeTest'] = {'command': '--version', 'output': result.stdout.strip(), 'binary': binary.relative_to(root).as_posix()} + lane['status'] = 'packaged-smoke-tested' + (out / 'lane.json').write_text(json.dumps(lane, indent=2, sort_keys=True) + '\n', encoding='utf-8') - name: Retain source-bound receipts and artifacts, including failed lanes if: always() uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6, node24 diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index 023ace75..99c10273 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -10,6 +10,7 @@ on: paths: - "site/**" - ".github/workflows/pages.yml" + - "tools/modsync-ci/site_check.py" workflow_dispatch: permissions: @@ -30,6 +31,8 @@ jobs: steps: - name: Checkout uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + - name: Refuse a site with a missing entry page or broken local links + run: python3 tools/modsync-ci/site_check.py site - name: Configure Pages uses: actions/configure-pages@45bfe0192ca1faeb007ade9deae92b16b8254a0d # v6 - name: Upload site diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 084f4144..9440a2cb 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -76,6 +76,14 @@ jobs: echo "::error::A release named $TAG already exists. Pick a new version." exit 1 fi + # gh release create ignores --target when the tag already exists, so a tag + # left behind by a failed run must point at the commit being packaged. + if tag_sha=$(gh api "repos/$GH_REPO/commits/$TAG" --jq .sha 2>/dev/null); then + if [ "$tag_sha" != "$SHA" ]; then + echo "::error::Tag $TAG already exists at $tag_sha, but this run packages $SHA. Delete the stale tag or pick a new version." + exit 1 + fi + fi { echo "version=$VERSION" echo "tag=$TAG" @@ -106,8 +114,17 @@ jobs: SHA: ${{ needs.prepare.outputs.sha }} PRERELEASE: ${{ needs.prepare.outputs.prerelease }} steps: + - name: Read the target list at the release commit + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + with: + ref: ${{ needs.prepare.outputs.sha }} + path: source + sparse-checkout: packaging/targets.json + sparse-checkout-cone-mode: false + persist-credentials: false + - name: Download the packaged targets - uses: actions/download-artifact@v4 + uses: actions/download-artifact@018cc2cf5baa6db3ef3c5f8a56943fffe632ef53 # v6.0.0, matches upload-artifact v6 with: pattern: modsync-${{ needs.prepare.outputs.sha }}-* path: lanes @@ -119,11 +136,17 @@ jobs: # Build receipts and raw binaries stay in the workflow artifacts only. find lanes -path '*/packages/*' -type f \( -name '*.zip' -o -name '*.tar.gz' -o -name '*.receipt.json' \) \ -exec cp -n {} release/ \; - count=$(find release -type f \( -name '*.zip' -o -name '*.tar.gz' \) | wc -l) - if [ "$count" -eq 0 ]; then - echo '::error::The package workflow produced no packages.' - exit 1 - fi + # Every target in packaging/targets.json must have exactly one package; a + # release must never go out with a platform silently missing. + missing=0 + for target in $(jq -r '.targets | keys[]' source/packaging/targets.json); do + n=$(find release -maxdepth 1 -type f \( -name "*-$target-*.zip" -o -name "*-$target-*.tar.gz" \) | wc -l) + if [ "$n" -ne 1 ]; then + echo "::error::Expected exactly one package for $target, found $n." + missing=1 + fi + done + [ "$missing" -eq 0 ] || exit 1 (cd release && find . -maxdepth 1 -type f \( -name '*.zip' -o -name '*.tar.gz' \) -printf '%f\n' | sort | xargs sha256sum > SHA256SUMS.txt) ls -l release @@ -206,7 +229,10 @@ jobs: echo '::error::Nexus file display names must be 50 characters or fewer.' exit 1 fi - if gh release view "$TAG" --json assets | jq -e --arg m "$MARKER" 'any(.assets[]; .name == $m)' >/dev/null; then + # Read the asset list first: inside an `if`, a failed `gh` would otherwise + # look like "no marker" and upload a duplicate that archives the live file. + assets=$(gh release view "$TAG" --json assets) + if jq -e --arg m "$MARKER" 'any(.assets[]; .name == $m)' <<< "$assets" >/dev/null; then skip "$TAG already reached Nexus Mods." fi echo "enabled=true" >> "$GITHUB_OUTPUT" @@ -256,7 +282,7 @@ jobs: - name: Upload to Nexus Mods if: steps.config.outputs.enabled == 'true' id: upload - uses: Nexus-Mods/upload-action@v1.0.0-beta.11 + uses: Nexus-Mods/upload-action@98532f7670c27cbecc78fae03fa3e278147827e2 # v1.0.0-beta.11; receives the API key, so pinned to a commit with: api_key: ${{ secrets.NEXUSMODS_API_KEY }} file_id: ${{ vars[matrix.file_id_variable] }} diff --git a/packaging/README.md b/packaging/README.md index e07ae2e2..74317141 100644 --- a/packaging/README.md +++ b/packaging/README.md @@ -26,7 +26,7 @@ For MSVC use `--kind msvc --compiler `. The output is a COFF resource ob Vehicles are a versioned Linux tar.gz, a Windows ZIP with both executable roles, and a ZIP containing ModSync.app. Manifest records include source commit, Cargo.lock SHA256, file hashes/sizes/modes, patcher capability, and explicit unsigned/unnotarized pre-release status. The manifest excludes itself to avoid recursive hashes; the outer artifact receipt records its digest and the archive digest. Archive entry ordering, modes, timestamps, owner metadata and gzip header timestamp are fixed from source commit time. Reproducibility still depends on identical binary/icon inputs and compression implementation. -Outputs use no-clobber publication. A manual artifact-only workflow is included; no publication action is included. The native matrix retains Linux x86_64/aarch64, Windows x86/i686, x86_64 and aarch64, and macOS x86_64/aarch64. Older Windows reference lanes remain explicit unresolved exceptions. +Outputs use no-clobber publication. The manual workflow (`package-manual.yml`) builds every target, unpacks each package on its native runner and starts the packaged `modsync --version`, then keeps the results as workflow artifacts. It does not publish; `release.yml` calls it and publishes a GitHub release (and optionally Nexus Mods) from its packages. The native matrix retains Linux x86_64/aarch64, Windows x86/i686, x86_64 and aarch64, and macOS x86_64/aarch64. Older Windows reference lanes remain explicit unresolved exceptions. ## Patcher authority diff --git a/tools/modsync-ci/site_check.py b/tools/modsync-ci/site_check.py new file mode 100644 index 00000000..07ea9214 --- /dev/null +++ b/tools/modsync-ci/site_check.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python3 +"""Refuse to deploy a static site with a missing entry page or a broken local link. + +Every href/src that is not an external URL, a mail/tel link or a pure #fragment must +resolve to a file inside the site directory; links that escape the directory fail too. +""" + +import argparse +from html.parser import HTMLParser +import json +from pathlib import Path +import sys +from urllib.parse import unquote, urlsplit + +EXTERNAL = ("http", "https", "mailto", "tel", "data", "javascript") + + +class Links(HTMLParser): + def __init__(self): + super().__init__() + self.targets = [] + + def handle_starttag(self, tag, attrs): + for name, value in attrs: + if name in ("href", "src") and value: + self.targets.append(value.strip()) + + +def broken_links(site): + site = Path(site).resolve() + problems = [] + if not (site / "index.html").is_file(): + problems.append("index.html is missing") + pages = sorted(site.rglob("*.html")) + if not pages: + problems.append("no HTML pages found") + for page in pages: + parser = Links() + parser.feed(page.read_text(encoding="utf-8")) + for target in parser.targets: + parts = urlsplit(target) + if parts.scheme in EXTERNAL or target.startswith("//") or not parts.path: + continue + path = unquote(parts.path) + resolved = (site / path.lstrip("/")) if path.startswith("/") else (page.parent / path) + resolved = resolved.resolve() + if resolved.is_dir(): + resolved = resolved / "index.html" + where = page.relative_to(site).as_posix() + if not resolved.is_relative_to(site): + problems.append(f"{where}: {target} points outside the site") + elif not resolved.is_file(): + problems.append(f"{where}: {target} does not exist") + return len(pages), problems + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("site", type=Path) + args = parser.parse_args(argv) + if not args.site.is_dir(): + print(f"::error::Site directory {args.site} does not exist", file=sys.stderr) + return 1 + pages, problems = broken_links(args.site) + for problem in problems: + print(f"::error title=Site check::{problem}", file=sys.stderr) + print(json.dumps({"event": "site_check", "pages": pages, "problems": len(problems)})) + return 1 if problems else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/modsync-ci/test_site_check.py b/tools/modsync-ci/test_site_check.py new file mode 100644 index 00000000..f868b1db --- /dev/null +++ b/tools/modsync-ci/test_site_check.py @@ -0,0 +1,54 @@ +import contextlib +import io +import tempfile +import unittest +from pathlib import Path + +import site_check + +ROOT = Path(__file__).resolve().parents[2] + + +class SiteCheck(unittest.TestCase): + def site(self, files): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + root = Path(temp.name) + for name, body in files.items(): + (root / name).parent.mkdir(parents=True, exist_ok=True) + (root / name).write_text(body, encoding="utf-8") + return root + + def problems(self, files): + return site_check.broken_links(self.site(files))[1] + + def test_a_site_whose_local_links_all_resolve_passes(self): + self.assertEqual(self.problems({ + "index.html": 'x' + 'extfrag' + 'mdir', + "faq.html": "

faq

", "assets/logo.svg": "", "docs/index.html": "

d

"}), []) + + def test_a_missing_local_target_fails(self): + self.assertEqual(self.problems({"index.html": 'x'}), + ["index.html: gone.html does not exist"]) + + def test_a_link_escaping_the_site_fails(self): + self.assertEqual(self.problems({"index.html": 'x'}), + ["index.html: ../secret.html points outside the site"]) + + def test_a_site_without_an_entry_page_fails(self): + self.assertIn("index.html is missing", self.problems({"other.html": "

x

"})) + + def test_an_empty_site_fails(self): + self.assertIn("no HTML pages found", self.problems({})) + + def test_main_exits_nonzero_on_problems_and_zero_on_the_real_site(self): + broken = self.site({"index.html": ''}) + with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): + self.assertEqual(site_check.main([str(broken)]), 1) + self.assertEqual(site_check.main([str(ROOT / "site")]), 0) + + +if __name__ == "__main__": + unittest.main()