diff --git a/.github/workflows/forever-marketplace-recovery.yml b/.github/workflows/forever-marketplace-recovery.yml new file mode 100644 index 0000000..d8abc24 --- /dev/null +++ b/.github/workflows/forever-marketplace-recovery.yml @@ -0,0 +1,76 @@ +name: Forever marketplace recovery + +on: + workflow_dispatch: + inputs: + tag: + description: Existing Forever alpha prerelease tag (never moved or rebuilt) + required: true + type: string + provider: + description: Select only destinations that have not accepted this file + required: true + type: choice + default: all + options: [all, curseforge, wago] + publish: + description: Upload after GET-only preflight (leave false for diagnosis) + required: true + type: boolean + default: false + +permissions: + contents: read + +concurrency: + group: forever-refs/tags/${{ inputs.tag }} + cancel-in-progress: false + +jobs: + recover: + if: github.ref == 'refs/heads/master' + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + persist-credentials: false + - name: Validate alpha tag format + env: + TAG: ${{ inputs.tag }} + run: | + python3 - <<'PY' + import os, re + if not re.fullmatch(r"forever-v\d+\.\d+\.\d+-alpha\.\d+", os.environ["TAG"]): + raise SystemExit("Only an existing Forever alpha tag is allowed") + PY + - name: Download existing prerelease assets without rebuilding + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + TAG: ${{ inputs.tag }} + run: | + gh release view "$TAG" --repo "$GITHUB_REPOSITORY" --json isDraft,isPrerelease > release-state.json + python3 - <<'PY' + import json + state = json.load(open("release-state.json")) + if state["isDraft"] or not state["isPrerelease"]: + raise SystemExit("Recovery requires an already published prerelease") + PY + gh release download "$TAG" --repo "$GITHUB_REPOSITORY" --dir dist \ + --pattern 'KwikTip_Forever-*.zip' --pattern release.json --pattern SHA256SUMS \ + --pattern source-evidence.json --pattern coverage.json --pattern release-notes.md + - name: GET-only provider metadata preflight + env: + CF_API_KEY: ${{ secrets.CF_API_KEY }} + WAGO_API_TOKEN: ${{ secrets.WAGO_API_TOKEN }} + TAG: ${{ inputs.tag }} + PROVIDER: ${{ inputs.provider }} + run: python3 -B tools/forever_marketplaces.py dist --tag "$TAG" --provider "$PROVIDER" --preflight + - name: Upload exact existing bytes to selected destinations + if: inputs.publish + env: + CF_API_KEY: ${{ secrets.CF_API_KEY }} + WAGO_API_TOKEN: ${{ secrets.WAGO_API_TOKEN }} + TAG: ${{ inputs.tag }} + PROVIDER: ${{ inputs.provider }} + run: python3 -B tools/forever_marketplaces.py dist --tag "$TAG" --provider "$PROVIDER" --publish diff --git a/docs/FOREVER_DISTRIBUTION.md b/docs/FOREVER_DISTRIBUTION.md index 5e9e620..6007332 100644 --- a/docs/FOREVER_DISTRIBUTION.md +++ b/docs/FOREVER_DISTRIBUTION.md @@ -1,8 +1,13 @@ # Forever distribution through GitHub Actions -Status (2026-10-31): implemented for review with offline validation. Review-branch -and GitHub build results are recorded in the PR/checks; no publishing tag is -approved. No addon release has been published. The installed local addon +Status (2026-10-31): PR #3 merged as `3ea8afa`; the approved immutable tag +`forever-v0.1.0-alpha.1` targets that merge. Its build passed and the +[GitHub prerelease](https://github.com/postblink/KwikTip/releases/tag/forever-v0.1.0-alpha.1) +is published. The first marketplace attempt failed HTTP 403 without a provider +success receipt; destination acceptance must be reconciled before retrying. +Wago's public metadata rejects urllib's default user agent but accepts the +truthful KwikTip application identifier now supplied by the helper. +The installed local addon remains the separately verified `0.1.0-test`; source candidate `0.1.0-alpha.1` is not installed. No client load or in-game test is established before November 4. @@ -67,8 +72,8 @@ Its multipart payloads follow the exact pinned packager implementation: CF All checksums/tag/flavor/patch validations and both token-presence checks complete before the first upload. No credentials are given to PR/manual builds. -Actual project token permissions and provider acceptance remain untested until -an approved publication. WoWInterface Forever is disabled pending provider +Project token permissions and provider acceptance must be confirmed from actual +publication results. WoWInterface Forever is disabled pending provider support; no `WOWI_API_TOKEN` is used in this workflow. The standalone folder stays `KwikTip_Forever`; no speculative rename was made. Addon-manager acceptance still needs testing. No marketplace project, token, permission or paid service was created. @@ -77,6 +82,15 @@ Uploads across providers are not atomic. The uploader does not retry POSTs and reports each completed provider. If a later step fails, inspect the existing files before rerunning; do not blindly duplicate a successful upload. +`forever-marketplace-recovery.yml` provides a manual, default-branch-only recovery +path. It requires an already published Forever alpha prerelease, downloads its +existing ZIP and metadata, and verifies their checksums/tag/flavor before any +upload. It never rebuilds, retags, overwrites GitHub assets, or creates another +release. The default is GET-only metadata preflight. After reconciling prior +outcomes, select only providers still needing the file and explicitly enable +upload. Stage logs identify the failing GET or POST; successful provider file +IDs are retained when supplied. POSTs are never automatically retried. + ## Review and first alpha Local commands, using a new output path: @@ -97,9 +111,11 @@ workflow is on the repository's default branch. For a proposed first public `0.1.0-alpha.1`, review actual coverage/client status, set the Forever TOC and README version together, update the authored notes, and rerun the gates. The reviewed candidate now has `0.1.0-alpha.1` metadata prepared; -this does not authorize publication. Obtain approval before pushing `forever-v0.1.0-alpha.1`: that tag is +publication still requires explicit owner authorization. The owner approved and +published `forever-v0.1.0-alpha.1`; for future versions, obtain approval before +pushing a publishing tag: that tag is the concrete publication trigger. Do not use `v0.1.0-alpha.1`, which belongs to -the Retail workflow's tag space. No tag or push was performed here. +the Retail workflow's tag space. That publishing tag will upload to the existing CF/Wago pages and create the GitHub prerelease. A review-branch push and draft PR run build checks only. diff --git a/tests/test_forever_marketplaces.py b/tests/test_forever_marketplaces.py index 572eded..5429b6c 100644 --- a/tests/test_forever_marketplaces.py +++ b/tests/test_forever_marketplaces.py @@ -1,8 +1,12 @@ from pathlib import Path +from contextlib import contextmanager +import io import json import os +import sys import unittest -from unittest.mock import patch +from unittest.mock import MagicMock, patch +from urllib.error import HTTPError from test_forever_release import alpha_source import forever_release @@ -12,6 +16,21 @@ VERSIONS = [{"id": 999001, "name": "1.60.1", "gameVersionTypeID": 88568}, {"id": 999002, "name": "12.1.0", "gameVersionTypeID": 517}] WAGO = {"patches": {"forever": ["1.60.1"], "retail": ["12.1.0"]}} +TAG = "forever-v0.1.0-alpha.1" + + +def response(body, status=200): + result = io.BytesIO(body if isinstance(body, bytes) else json.dumps(body).encode()) + result.status = status + return result + + +@contextmanager +def prepared_release(): + with alpha_source() as root: + directory = root.parent / "dist" + forever_release.prepare(directory, TAG) + yield directory class ForeverMarketplaceTests(unittest.TestCase): @@ -76,8 +95,9 @@ def test_multipart_contract_and_redirects(self): archive = root / "sample.zip" archive.write_bytes(b"verified zip bytes") with patch.object(markets, "open_request") as request: - request.return_value.__enter__.return_value.status = 201 - markets.upload("https://addons.wago.io/api/projects/QN53W7KB/version", {}, {"stability": "alpha"}, archive) + request.return_value = response({"id": "file_123"}, 201) + receipt = markets.upload("https://addons.wago.io/api/projects/QN53W7KB/version", {}, {"stability": "alpha"}, archive) + self.assertEqual(receipt, "file_123") sent = request.call_args.args[0] self.assertEqual(sent.get_method(), "POST") self.assertIn(b'name="metadata"', sent.data) @@ -85,6 +105,196 @@ def test_multipart_contract_and_redirects(self): self.assertIn(archive.read_bytes(), sent.data) self.assertIsNone(markets.NoRedirect().redirect_request(None, None, 302, "redirect", {}, "https://other.example")) + def test_truthful_user_agent_is_on_actual_get_and_post_requests(self): + with prepared_release() as directory, \ + patch.dict(os.environ, {"WAGO_API_TOKEN": "test-wago"}, clear=True), \ + patch.object(markets, "build_opener") as build, patch("builtins.print"): + opener = build.return_value + opener.open.side_effect = [response(WAGO), response({"id": 123}, 201)] + markets.publish(directory, TAG, provider="wago") + requests = [call.args[0] for call in opener.open.call_args_list] + self.assertEqual([request.get_method() for request in requests], ["GET", "POST"]) + for request in requests: + headers = {key.lower(): value for key, value in request.header_items()} + self.assertEqual(headers["user-agent"], markets.USER_AGENT) + self.assertIn("KwikTip", headers["user-agent"]) + self.assertIn("github.com/postblink/KwikTip", headers["user-agent"]) + self.assertNotIn("Mozilla", headers["user-agent"]) + self.assertNotIn("Python-urllib", headers["user-agent"]) + for call in build.call_args_list: + self.assertEqual(len(call.args), 1) + self.assertIsInstance(call.args[0], markets.NoRedirect) + for call in opener.open.call_args_list: + self.assertEqual(call.kwargs, {"timeout": 60}) + + def test_get_only_preflight_never_posts(self): + with prepared_release() as directory, \ + patch.dict(os.environ, {"CF_API_KEY": "test-cf", "WAGO_API_TOKEN": "test-wago"}, clear=True), \ + patch.object(markets, "build_opener") as build, patch("builtins.print"): + opener = build.return_value + opener.open.side_effect = [response(VERSIONS), response(WAGO)] + markets.publish(directory, TAG, preflight_only=True) + requests = [call.args[0] for call in opener.open.call_args_list] + self.assertEqual([request.get_method() for request in requests], ["GET", "GET"]) + self.assertEqual([request.full_url for request in requests], [ + "https://wow.curseforge.com/api/game/wow/versions", + "https://addons.wago.io/api/data/game", + ]) + + def test_http_403_preflight_prevents_every_post_even_after_other_metadata_succeeds(self): + with prepared_release() as directory: + for failed_provider in ("curseforge", "wago"): + with self.subTest(provider=failed_provider), \ + patch.dict(os.environ, {"CF_API_KEY": "test-cf", "WAGO_API_TOKEN": "test-wago"}, clear=True), \ + patch.object(markets, "build_opener") as build, \ + patch.object(markets, "upload") as upload, patch("builtins.print"): + url = ("https://wow.curseforge.com/api/game/wow/versions" if failed_provider == "curseforge" + else "https://addons.wago.io/api/data/game") + error = HTTPError(url, 403, "Forbidden", {}, io.BytesIO(b"private provider error body")) + self.addCleanup(error.close) + build.return_value.open.side_effect = ([error] if failed_provider == "curseforge" + else [response(VERSIONS), error]) + with self.assertRaises(HTTPError): + markets.publish(directory, TAG) + upload.assert_not_called() + requests = [call.args[0] for call in build.return_value.open.call_args_list] + self.assertTrue(all(request.get_method() == "GET" for request in requests)) + self.assertEqual(len(requests), 1 if failed_provider == "curseforge" else 2) + + def test_selected_provider_requires_only_its_token_and_never_contacts_other_provider(self): + cases = [ + ("curseforge", {"CF_API_KEY": "selected-cf"}, VERSIONS, + "https://wow.curseforge.com/api/game/wow/versions", + "https://wow.curseforge.com/api/projects/1478824/upload-file"), + ("wago", {"WAGO_API_TOKEN": "selected-wago"}, WAGO, + "https://addons.wago.io/api/data/game", + "https://addons.wago.io/api/projects/QN53W7KB/version"), + ] + with prepared_release() as directory: + for provider, environment, metadata, get_url, post_url in cases: + with self.subTest(provider=provider), patch.dict(os.environ, environment, clear=True), \ + patch.object(markets, "build_opener") as build, patch("builtins.print"): + build.return_value.open.side_effect = [response(metadata), response({"id": "accepted_1"}, 201)] + markets.publish(directory, TAG, provider=provider) + requests = [call.args[0] for call in build.return_value.open.call_args_list] + self.assertEqual([request.full_url for request in requests], [get_url, post_url]) + self.assertEqual([request.get_method() for request in requests], ["GET", "POST"]) + get_headers, post_headers = [ + {key.lower(): value for key, value in request.header_items()} for request in requests + ] + if provider == "curseforge": + self.assertEqual(get_headers["x-api-token"], "selected-cf") + self.assertEqual(post_headers["x-api-token"], "selected-cf") + self.assertNotIn("authorization", post_headers) + else: + self.assertNotIn("authorization", get_headers) + self.assertEqual(post_headers["authorization"], "Bearer selected-wago") + self.assertNotIn("x-api-token", post_headers) + archive = directory / "KwikTip_Forever-0.1.0-alpha.1.zip" + self.assertIn(archive.read_bytes(), requests[1].data) + + def test_first_upload_success_then_second_failure_has_receipt_without_retry(self): + with prepared_release() as directory: + original_bytes = (directory / "KwikTip_Forever-0.1.0-alpha.1.zip").read_bytes() + with patch.dict(os.environ, {"CF_API_KEY": "test-cf", "WAGO_API_TOKEN": "test-wago"}, clear=True), \ + patch.object(markets, "build_opener") as build, patch("builtins.print") as printed: + error_body = b"private response body with test-wago token" + error = HTTPError("https://addons.wago.io/api/projects/QN53W7KB/version", 403, + "Forbidden", {}, io.BytesIO(error_body)) + self.addCleanup(error.close) + build.return_value.open.side_effect = [ + response(VERSIONS), response(WAGO), response({"id": 7654321}, 201), error, + ] + with self.assertRaises(HTTPError): + markets.publish(directory, TAG) + requests = [call.args[0] for call in build.return_value.open.call_args_list] + self.assertEqual([request.get_method() for request in requests], ["GET", "GET", "POST", "POST"]) + self.assertEqual([request.full_url for request in requests[2:]], [ + "https://wow.curseforge.com/api/projects/1478824/upload-file", + "https://addons.wago.io/api/projects/QN53W7KB/version", + ]) + self.assertTrue(all(original_bytes in request.data for request in requests[2:])) + output = "\n".join(str(call.args[0]) for call in printed.call_args_list) + self.assertIn("CurseForge project 1478824: Forever alpha upload succeeded; file ID 7654321", output) + self.assertNotIn("Wago project QN53W7KB: Forever alpha upload succeeded", output) + self.assertNotIn("private response body", output) + self.assertNotIn("test-wago", output) + + # A separately selected recovery reuses the same frozen assets and + # must not repeat the accepted CurseForge POST. + with patch.dict(os.environ, {"WAGO_API_TOKEN": "test-wago"}, clear=True), \ + patch.object(markets, "build_opener") as build, patch("builtins.print"): + build.return_value.open.side_effect = [response(WAGO), response({}, 201)] + markets.publish(directory, TAG, provider="wago") + self.assertEqual([call.args[0].full_url for call in build.return_value.open.call_args_list], [ + "https://addons.wago.io/api/data/game", "https://addons.wago.io/api/projects/QN53W7KB/version", + ]) + self.assertIn(original_bytes, build.return_value.open.call_args.args[0].data) + + def test_successful_post_receipt_is_optional_sanitized_and_never_retried(self): + cases = [ + ({"id": 123}, "123"), ({"id": "file_ab-9"}, "file_ab-9"), + ({}, None), ({"id": True}, None), ({"id": "../../private"}, None), + ({"id": "unsafe\nreceipt"}, None), ({"id": "x" * 129}, None), + (["provider diagnostic body"], None), (b"not JSON: private provider body", None), + (b"\xff invalid UTF-8", None), + ] + with alpha_source() as root: + archive = root / "sample.zip" + archive.write_bytes(b"verified zip bytes") + for body, expected in cases: + with self.subTest(body=body), patch.object(markets, "open_request") as request, \ + patch("builtins.print") as printed: + request.return_value = response(body, 201) + self.assertEqual(markets.upload("https://addons.wago.io/api/projects/QN53W7KB/version", {}, {}, archive), expected) + request.assert_called_once() + printed.assert_not_called() + + with patch.object(markets, "open_request") as request, patch("builtins.print") as printed: + accepted = MagicMock() + accepted.status = 201 + accepted.read.side_effect = OSError("private receipt read failure") + request.return_value.__enter__.return_value = accepted + self.assertIsNone(markets.upload("https://addons.wago.io/api/projects/QN53W7KB/version", {}, {}, archive)) + request.assert_called_once() + accepted.read.assert_called_once() + printed.assert_not_called() + + def test_cli_preflight_and_publish_are_exclusive_and_plan_makes_no_requests(self): + with patch.object(sys, "argv", ["forever_marketplaces.py", "dist", "--tag", TAG, "--preflight", "--publish"]), \ + patch.object(markets, "publish") as publish, patch("sys.stderr", new_callable=io.StringIO): + with self.assertRaises(SystemExit) as error: + markets.main() + self.assertEqual(error.exception.code, 2) + publish.assert_not_called() + with prepared_release() as directory, patch.dict(os.environ, {}, clear=True), \ + patch.object(sys, "argv", ["forever_marketplaces.py", str(directory), "--tag", TAG]), \ + patch.object(markets, "open_request") as request, patch("builtins.print") as printed: + markets.main() + request.assert_not_called() + self.assertFalse(json.loads(printed.call_args.args[0])["uploaded"]) + + def test_cli_http_error_reports_status_without_provider_body_or_tokens(self): + with prepared_release() as directory: + for mode in ("--preflight", "--publish"): + with self.subTest(mode=mode), patch.dict(os.environ, {"WAGO_API_TOKEN": "private-token"}, clear=True), \ + patch.object(sys, "argv", ["forever_marketplaces.py", str(directory), "--tag", TAG, + "--provider", "wago", mode]), \ + patch.object(markets, "build_opener") as build, patch("builtins.print"): + failure = HTTPError( + "https://addons.wago.io/api/data/game", 403, "private-token", {}, + io.BytesIO(b"private provider response body"), + ) + self.addCleanup(failure.close) + build.return_value.open.side_effect = failure + with self.assertRaises(SystemExit) as error: + markets.main() + message = str(error.exception) + self.assertIn("HTTP 403", message) + self.assertNotIn("private", message) + self.assertEqual(build.return_value.open.call_count, 1) + self.assertEqual(build.return_value.open.call_args.args[0].get_method(), "GET") + if __name__ == "__main__": unittest.main() diff --git a/tests/test_forever_release.py b/tests/test_forever_release.py index 19a68b0..170ad98 100644 --- a/tests/test_forever_release.py +++ b/tests/test_forever_release.py @@ -5,7 +5,9 @@ import hashlib import json from pathlib import Path +import re import shutil +import subprocess import sys import tempfile import unittest @@ -40,6 +42,123 @@ def alpha_source(): class ForeverReleaseTests(unittest.TestCase): + def recovery_workflow(self): + return yaml.load( + (ROOT / ".github/workflows/forever-marketplace-recovery.yml").read_text(), + Loader=yaml.BaseLoader, + ) + + def test_recovery_is_manual_master_only_and_defaults_to_no_upload(self): + workflow = self.recovery_workflow() + self.assertEqual(set(workflow["on"]), {"workflow_dispatch"}) + inputs = workflow["on"]["workflow_dispatch"]["inputs"] + self.assertEqual(inputs["tag"]["type"], "string") + self.assertEqual(inputs["tag"]["required"], "true") + self.assertEqual(inputs["provider"]["type"], "choice") + self.assertEqual(inputs["provider"]["default"], "all") + self.assertEqual(inputs["provider"]["options"], ["all", "curseforge", "wago"]) + self.assertEqual(inputs["provider"]["required"], "true") + self.assertEqual(inputs["publish"]["type"], "boolean") + self.assertEqual(inputs["publish"]["required"], "true") + self.assertEqual(inputs["publish"]["default"], "false") + self.assertEqual(workflow["permissions"], {"contents": "read"}) + self.assertEqual(set(workflow["jobs"]), {"recover"}) + recover = workflow["jobs"]["recover"] + self.assertEqual(recover["if"], "github.ref == 'refs/heads/master'") + self.assertNotIn("permissions", recover) + self.assertEqual(workflow["concurrency"]["group"], "forever-refs/tags/${{ inputs.tag }}") + self.assertEqual(workflow["concurrency"]["cancel-in-progress"], "false") + checkout = next(step for step in recover["steps"] if "actions/checkout@" in step.get("uses", "")) + self.assertEqual(checkout["with"]["persist-credentials"], "false") + + def test_recovery_executes_alpha_and_already_published_prerelease_guards(self): + steps = self.recovery_workflow()["jobs"]["recover"]["steps"] + validate = next(step for step in steps if "Validate alpha tag" in step.get("name", "")) + download = next(step for step in steps if "gh release download" in step.get("run", "")) + + def embedded_python(step): + scripts = re.findall(r"python3 - <<'PY'\n(.*?)\nPY", step["run"], flags=re.S) + self.assertEqual(len(scripts), 1) + return scripts[0] + + tag_guard, state_guard = embedded_python(validate), embedded_python(download) + for tag, accepted in [ + ("forever-v0.1.0-alpha.1", True), ("forever-v12.3.4-alpha.25", True), + ("v3.5.0", False), ("forever-v0.1.0", False), + ("forever-v0.1.0-beta.1", False), ("forever-v0.1.0-test.2", False), + ("forever-v0.1.0-alpha.1\nextra", False), + ("forever-v$(echo unsafe)", False), + ]: + with self.subTest(tag=tag): + result = subprocess.run( + [sys.executable, "-B", "-c", tag_guard], + env={"TAG": tag}, capture_output=True, text=True, + ) + self.assertEqual(result.returncode == 0, accepted, result.stderr) + with tempfile.TemporaryDirectory() as directory: + for draft, prerelease, accepted in [(False, True, True), (True, True, False), + (False, False, False), (True, False, False)]: + with self.subTest(draft=draft, prerelease=prerelease): + Path(directory, "release-state.json").write_text(json.dumps({ + "isDraft": draft, "isPrerelease": prerelease, + })) + result = subprocess.run( + [sys.executable, "-B", "-c", state_guard], cwd=directory, + capture_output=True, text=True, + ) + self.assertEqual(result.returncode == 0, accepted, result.stderr) + + def test_recovery_downloads_existing_assets_without_release_mutation_or_rebuild(self): + workflow = self.recovery_workflow() + steps = workflow["jobs"]["recover"]["steps"] + command = next(step["run"] for step in steps if "gh release download" in step.get("run", "")) + self.assertLess(command.index("gh release view"), command.index("gh release download")) + self.assertLess(command.index('state["isDraft"]'), command.index("gh release download")) + self.assertIn('--json isDraft,isPrerelease', command) + self.assertIn('gh release download "$TAG" --repo "$GITHUB_REPOSITORY" --dir dist', command) + for asset in ["'KwikTip_Forever-*.zip'", "release.json", "SHA256SUMS", + "source-evidence.json", "coverage.json", "release-notes.md"]: + self.assertIn("--pattern " + asset, command) + all_commands = "\n".join(step.get("run", "") for step in steps) + self.assertNotRegex(all_commands, r"\bgh\s+release\s+(create|edit|delete|upload)\b") + self.assertNotRegex(all_commands, r"\bgit\s+(tag|push|commit|reset)\b") + for builder in ["tools/forever_release.py", "tools/package_forever.py", "--clobber", "--force"]: + self.assertNotIn(builder, all_commands) + self.assertNotIn("${{ inputs.tag }}", all_commands) + self.assertNotIn("${{ inputs.provider }}", all_commands) + + def test_recovery_preflight_precedes_opt_in_upload_with_scoped_provider_secrets(self): + workflow = self.recovery_workflow() + recover = workflow["jobs"]["recover"] + self.assertNotIn("env", workflow) + self.assertNotIn("env", recover) + steps = recover["steps"] + preflight = next(step for step in steps if "--preflight" in step.get("run", "")) + upload = next(step for step in steps if "--publish" in step.get("run", "")) + download = next(step for step in steps if "gh release download" in step.get("run", "")) + validate = next(step for step in steps if "Validate alpha tag" in step.get("name", "")) + self.assertLess(steps.index(validate), steps.index(download)) + self.assertLess(steps.index(download), steps.index(preflight)) + self.assertLess(steps.index(preflight), steps.index(upload)) + self.assertNotIn("if", preflight) + self.assertEqual(upload["if"], "inputs.publish") + self.assertNotIn("--publish", preflight["run"]) + self.assertNotIn("--preflight", upload["run"]) + marketplace_steps = [step for step in steps if "CF_API_KEY" in step.get("env", {})] + self.assertEqual(marketplace_steps, [preflight, upload]) + for step in marketplace_steps: + self.assertEqual(set(step["env"]), {"CF_API_KEY", "WAGO_API_TOKEN", "TAG", "PROVIDER"}) + self.assertEqual(step["env"]["CF_API_KEY"], "${{ secrets.CF_API_KEY }}") + self.assertEqual(step["env"]["WAGO_API_TOKEN"], "${{ secrets.WAGO_API_TOKEN }}") + self.assertEqual(step["env"]["TAG"], "${{ inputs.tag }}") + self.assertEqual(step["env"]["PROVIDER"], "${{ inputs.provider }}") + self.assertIn('tools/forever_marketplaces.py dist --tag "$TAG" --provider "$PROVIDER"', step["run"]) + self.assertNotIn("GH_TOKEN", step["env"]) + gh_steps = [step for step in steps if "GH_TOKEN" in step.get("env", {})] + self.assertEqual(gh_steps, [download]) + self.assertEqual(download["env"]["GH_TOKEN"], "${{ secrets.GITHUB_TOKEN }}") + self.assertNotIn("WOWI_API_TOKEN", str(workflow)) + def test_tag_validation_is_disjoint_alpha_only_and_matches_toc(self): forever_release.validate_tag("forever-v0.1.0-alpha.1", "0.1.0-alpha.1") for tag in ["v3.5.0", "forever-v0.1.0", "forever-v0.1.0-beta.1", diff --git a/tools/forever_marketplaces.py b/tools/forever_marketplaces.py index 63605c9..05c1779 100644 --- a/tools/forever_marketplaces.py +++ b/tools/forever_marketplaces.py @@ -11,6 +11,7 @@ import json import os from pathlib import Path +import re from urllib.error import HTTPError from urllib.request import HTTPRedirectHandler, Request, build_opener import uuid @@ -21,6 +22,7 @@ WAGO_PROJECT = "QN53W7KB" PATCH = "1.60.1" CF_FOREVER_TYPE = 88568 +USER_AGENT = "KwikTip-Forever-Publisher/0.1 (+https://github.com/postblink/KwikTip)" class NoRedirect(HTTPRedirectHandler): @@ -30,24 +32,30 @@ def redirect_request(self, request, fp, code, message, headers, newurl): def open_request(request): # Upload credentials stay on the explicitly named provider endpoint. + # Wago rejects urllib's generic default; identify this application honestly. + request.add_header("User-Agent", USER_AGENT) return build_opener(NoRedirect()).open(request, timeout=60) -def payloads(cf_versions: list, wago_game: dict, version: str, notes: str) -> tuple[dict, dict]: +def curseforge_payload(cf_versions: list, version: str, notes: str) -> dict: matches = [row["id"] for row in cf_versions if row.get("gameVersionTypeID") == CF_FOREVER_TYPE and row.get("name") == PATCH] if len(matches) != 1 or not isinstance(matches[0], int) or isinstance(matches[0], bool) or matches[0] <= 0: raise ValueError("Need one exact CurseForge Forever patch ID; no fallback is allowed") + return {"displayName": f"KwikTip Forever {version}", "gameVersions": matches, "releaseType": "alpha", + "changelog": notes, "changelogType": "markdown"} + + +def wago_payload(wago_game: dict, version: str, notes: str) -> dict: patches = wago_game.get("patches", {}).get("forever", []) if not isinstance(patches, list) or PATCH not in patches: raise ValueError("Wago must explicitly support the exact Forever patch") - label = f"KwikTip Forever {version}" - return ( - {"displayName": label, "gameVersions": matches, "releaseType": "alpha", - "changelog": notes, "changelogType": "markdown"}, - {"label": label, "supported_forever_patches": [PATCH], - "stability": "alpha", "changelog": notes}, - ) + return {"label": f"KwikTip Forever {version}", "supported_forever_patches": [PATCH], + "stability": "alpha", "changelog": notes} + + +def payloads(cf_versions: list, wago_game: dict, version: str, notes: str) -> tuple[dict, dict]: + return curseforge_payload(cf_versions, version, notes), wago_payload(wago_game, version, notes) def verified_inputs(directory: Path, tag: str) -> tuple[str, Path, str]: @@ -79,7 +87,7 @@ def fetch_json(url: str, headers: dict) -> dict | list: return json.load(response) -def upload(url: str, headers: dict, metadata: dict, archive: Path) -> None: +def upload(url: str, headers: dict, metadata: dict, archive: Path) -> str | None: boundary = "kwiktip-" + uuid.uuid4().hex body = ( f"--{boundary}\r\nContent-Disposition: form-data; name=\"metadata\"\r\n" @@ -92,24 +100,51 @@ def upload(url: str, headers: dict, metadata: dict, archive: Path) -> None: with open_request(request) as response: if response.status not in (200, 201): raise ValueError(f"Upload returned HTTP {response.status}") + # Receipt IDs help reconcile a later provider failure. Do not dump the + # response body, and never turn a successful POST into a retry on JSON. + try: + result = json.load(response) + except (ValueError, UnicodeError, OSError): + result = {} + file_id = result.get("id") if isinstance(result, dict) else None + if isinstance(file_id, (str, int)) and not isinstance(file_id, bool): + if re.fullmatch(r"[A-Za-z0-9_-]{1,128}", str(file_id)): + return str(file_id) + return None -def publish(directory: Path, tag: str) -> None: +def publish(directory: Path, tag: str, provider: str = "all", preflight_only: bool = False) -> None: + if provider not in ("all", "curseforge", "wago"): + raise ValueError("Unknown marketplace") version, archive, notes = verified_inputs(directory, tag) cf_token, wago_token = os.environ.get("CF_API_KEY"), os.environ.get("WAGO_API_TOKEN") - if not cf_token or not wago_token: - raise ValueError("CF_API_KEY and WAGO_API_TOKEN must both be available; nothing uploaded") + use_cf, use_wago = provider != "wago", provider != "curseforge" + if (use_cf and not cf_token) or (use_wago and not wago_token): + raise ValueError("Selected marketplace token must be available; nothing uploaded") cf_headers = {"x-api-token": cf_token} wago_headers = {"authorization": f"Bearer {wago_token}", "accept": "application/json"} - cf_versions = fetch_json("https://wow.curseforge.com/api/game/wow/versions", cf_headers) - wago_game = fetch_json("https://addons.wago.io/api/data/game", {}) - cf_payload, wago_payload = payloads(cf_versions, wago_game, version, notes) + selected_cf_payload, selected_wago_payload = None, None + if use_cf: + print("CurseForge: GET exact Forever patch metadata (no upload yet)", flush=True) + cf_versions = fetch_json("https://wow.curseforge.com/api/game/wow/versions", cf_headers) + selected_cf_payload = curseforge_payload(cf_versions, version, notes) + if use_wago: + print("Wago: GET exact Forever patch metadata (no upload yet)", flush=True) + wago_game = fetch_json("https://addons.wago.io/api/data/game", {}) + selected_wago_payload = wago_payload(wago_game, version, notes) + print("Selected marketplace metadata verified; no files uploaded yet", flush=True) + if preflight_only: + return # Complete all validation before the first POST. A later failure can still # leave a partial publication; do not automatically retry either upload. - upload(f"https://wow.curseforge.com/api/projects/{CF_PROJECT}/upload-file", cf_headers, cf_payload, archive) - print(f"CurseForge project {CF_PROJECT}: Forever alpha upload succeeded", flush=True) - upload(f"https://addons.wago.io/api/projects/{WAGO_PROJECT}/version", wago_headers, wago_payload, archive) - print(f"Wago project {WAGO_PROJECT}: Forever alpha upload succeeded", flush=True) + if use_cf: + print(f"CurseForge project {CF_PROJECT}: POST verified Forever alpha", flush=True) + file_id = upload(f"https://wow.curseforge.com/api/projects/{CF_PROJECT}/upload-file", cf_headers, selected_cf_payload, archive) + print(f"CurseForge project {CF_PROJECT}: Forever alpha upload succeeded; file ID {file_id or 'not supplied'}", flush=True) + if use_wago: + print(f"Wago project {WAGO_PROJECT}: POST verified Forever alpha", flush=True) + file_id = upload(f"https://addons.wago.io/api/projects/{WAGO_PROJECT}/version", wago_headers, selected_wago_payload, archive) + print(f"Wago project {WAGO_PROJECT}: Forever alpha upload succeeded; file ID {file_id or 'not supplied'}", flush=True) def main() -> None: @@ -117,10 +152,14 @@ def main() -> None: parser.add_argument("directory", type=Path) parser.add_argument("--tag", required=True) parser.add_argument("--publish", action="store_true", help="perform actual uploads; omit for verified no-network plan") + parser.add_argument("--provider", choices=("all", "curseforge", "wago"), default="all") + parser.add_argument("--preflight", action="store_true", help="check live provider metadata using GET only; never upload") args = parser.parse_args() try: - if args.publish: - publish(args.directory, args.tag) + if args.publish and args.preflight: + parser.error("--publish and --preflight are mutually exclusive") + if args.publish or args.preflight: + publish(args.directory, args.tag, args.provider, preflight_only=args.preflight) else: version, _, _ = verified_inputs(args.directory, args.tag) print(json.dumps({"version": version, "flavor": "forever", "curseforge": CF_PROJECT,