From 7526710d5bcbc2f8ea9179829b68015c8c5dedea Mon Sep 17 00:00:00 2001 From: itvi-1234 Date: Mon, 30 Nov 2026 16:05:39 +0530 Subject: [PATCH] Stage the first npm release of a new package instead of refusing it npm accepts a trusted publisher only for a package that already exists, so the first version of a new package could not be published by this workflow, and publish-all stopped any real run that included one. Eight packages are waiting on this: aws-secrets-manager, aws-sqs, cql, file-system, gpu, kafka-service, observability and rabbitmq-service. npm's staged publishing fills that gap. publish-npm.py now asks npm about each package before publishing any: - already on npm: published with trusted publishing, as before - not on npm: staged with the stage-only token in NPM_STAGE_TOKEN; staging needs no 2FA and publishes nothing until a maintainer approves the staged version on npmjs.com with 2FA - only the 0.0.0-stage placeholder: a staged first release is waiting for approval, so it is skipped When a package needs staging and the token is not set, the run stops before building or publishing anything. After approval, a maintainer adds a trusted publisher to the package, and later releases use trusted publishing. The workflow installs npm 11.15.0, which staged publishing needs, and passes the token only to the publish step. publish-all now reports a first npm release as staged instead of blocking the run. --- .github/workflows/binding-publish-npm.yml | 14 ++- tooling/extension-bindings/ci/publish-npm.py | 76 +++++++++++++++- tooling/extension-bindings/ci/publish_all.py | 6 +- .../extension-bindings/ci/test_publish_all.py | 10 +-- .../extension-bindings/ci/test_publish_npm.py | 86 ++++++++++++++++--- 5 files changed, 168 insertions(+), 24 deletions(-) diff --git a/.github/workflows/binding-publish-npm.yml b/.github/workflows/binding-publish-npm.yml index 7075526..494f295 100644 --- a/.github/workflows/binding-publish-npm.yml +++ b/.github/workflows/binding-publish-npm.yml @@ -26,7 +26,8 @@ jobs: timeout-minutes: 20 permissions: contents: read - # Trusted publishing: npm accepts this workflow's OIDC identity, so no npm token is stored. + # Trusted publishing: npm accepts this workflow's OIDC identity for packages + # that are already on npm, so no publishing token is stored for them. id-token: write env: INPUT_TARGETS: ${{ inputs.targets }} @@ -53,6 +54,10 @@ jobs: registry-url: 'https://registry.npmjs.org' package-manager-cache: false + # Node 24.11.0 ships an older npm; staged publishing needs 11.15.0 or later. + - name: Install npm with staged publishing + run: npm install --global npm@11.15.0 + - name: Install the pinned emitter dependencies, which provide the TypeScript compiler working-directory: tooling/extension-bindings/emitters/typescript run: npm ci --ignore-scripts @@ -60,8 +65,13 @@ jobs: - name: Test the publication helper run: python -m unittest discover -s tooling/extension-bindings/ci -p 'test_publish_npm.py' - - name: Build and check the committed packages, then publish them + # A package that is not on npm yet cannot use trusted publishing, so its first + # release is staged with NPM_STAGE_TOKEN, a stage-only token: staging + # publishes nothing until a maintainer approves it on npmjs.com with 2FA. + - name: Build and check the committed packages, then publish or stage them shell: bash + env: + NPM_STAGE_TOKEN: ${{ secrets.NPM_STAGE_TOKEN }} run: | set -euo pipefail args=() diff --git a/tooling/extension-bindings/ci/publish-npm.py b/tooling/extension-bindings/ci/publish-npm.py index c8fae2a..23c763f 100644 --- a/tooling/extension-bindings/ci/publish-npm.py +++ b/tooling/extension-bindings/ci/publish-npm.py @@ -1,4 +1,15 @@ -"""Build the committed TypeScript bindings and publish them to npm with trusted publishing.""" +"""Build the committed TypeScript bindings and publish them to npm. + +A package that is already on npm is published with trusted publishing: npm +accepts this workflow's OIDC identity, so no token is used. + +npm cannot trust a workflow for a package that does not exist yet. So the first +release of a new package is staged instead, with the stage-only token in +NPM_STAGE_TOKEN. Staging needs no 2FA and publishes nothing: npm shows the +package with a 0.0.0-stage placeholder until a maintainer approves the staged +version on npmjs.com with 2FA. The maintainer then adds a trusted publisher to +the package, and later releases use trusted publishing like the others. +""" from __future__ import annotations @@ -17,7 +28,10 @@ LANGUAGE = "typescript" TOOLING = Path("tooling/extension-bindings") EMITTER = TOOLING / "emitters/typescript" -MINIMUM_NPM = (11, 5, 1) +# Staged publishing needs npm 11.15.0; trusted publishing alone needs 11.5.1. +MINIMUM_NPM = (11, 15, 0) +STAGE_TOKEN = "NPM_STAGE_TOKEN" +STAGE_PLACEHOLDER = "0.0.0-stage" def read_package(root: Path, catalog: dict, target: Target) -> dict: @@ -84,7 +98,7 @@ def check_npm_version(version: str) -> None: numbers = tuple(int(part) for part in version.strip().split("-")[0].split(".")[:3]) if numbers < MINIMUM_NPM: raise ValueError( - "trusted publishing needs npm " + "staged and trusted publishing need npm " + ".".join(map(str, MINIMUM_NPM)) + f" or later, but npm {version.strip()} is installed" ) @@ -103,6 +117,23 @@ def already_published(name: str, version: str) -> bool: return result.returncode == 0 and result.stdout.strip() == version +def npm_status(name: str) -> str: + """Whether a package is on npm: "published", "missing", or "staged" when only + the placeholder of a staged first release exists, waiting for approval.""" + result = subprocess.run( + ["npm", "view", name, "versions", "--json"], + capture_output=True, + text=True, + ) + if result.returncode != 0: + if "E404" in result.stderr: + return "missing" + raise ValueError(f"could not read {name} from npm: {result.stderr.strip()}") + versions = json.loads(result.stdout or "[]") + versions = [versions] if isinstance(versions, str) else versions + return "staged" if set(versions) <= {STAGE_PLACEHOLDER} else "published" + + def publish(root: Path, targets: list[Target], execute: bool) -> None: selected = of_language(targets, LANGUAGE) if not selected: @@ -121,7 +152,23 @@ def publish(root: Path, targets: list[Target], execute: bool) -> None: packages[package["name"]] = package directories[package["name"]] = root / target[1] build_only = add_unselected_dependencies(root, catalog, packages, directories) + statuses: dict[str, str] = {} + if execute: + # Decide every package before publishing any, so a missing token stops + # the run before it has published only some of them. + for package_name in packages: + if package_name not in build_only and not already_published( + package_name, packages[package_name]["version"] + ): + statuses[package_name] = npm_status(package_name) + first_releases = sorted(name for name, status in statuses.items() if status == "missing") + if first_releases and not os.environ.get(STAGE_TOKEN): + raise ValueError( + f"{', '.join(first_releases)} not on npm yet. A first release is staged with the " + f"stage-only token in the {STAGE_TOKEN} secret, which is not set." + ) published = [] + staged = [] with tempfile.TemporaryDirectory(prefix="npm-bindings-") as name: # Each package is built where its dependencies resolve, from the same # committed tree a consumer would receive. @@ -141,16 +188,37 @@ def publish(root: Path, targets: list[Target], execute: bool) -> None: ) continue run(["npm", "pack", "--dry-run", "--ignore-scripts"], destination, capture_output=True) + status = statuses.get(package_name) if not execute: summarize(f"Built and checked {package_name}@{version}; dry run, nothing was published.") - elif already_published(package_name, version): + elif status is None: summarize(f"{package_name}@{version} is already on npm; skipped.") + elif status == "staged": + summarize( + f"{package_name} has a staged first release waiting for approval on npmjs.com " + "(Staged Packages); skipped." + ) + elif status == "missing": + run( + ["npm", "stage", "publish", "--access", "public", "--ignore-scripts"], + destination, + env={**os.environ, "NODE_AUTH_TOKEN": os.environ[STAGE_TOKEN]}, + ) + staged.append(f"{package_name}@{version}") + summarize(f"Staged {package_name}@{version} as its first release.") else: run(["npm", "publish", "--access", "public", "--ignore-scripts"], destination) published.append(f"{package_name}@{version}") summarize(f"Published {package_name}@{version}.") if execute: summarize("Published to npm: " + (", ".join(published) if published else "nothing new.")) + if staged: + summarize( + "Staged, waiting for a maintainer: " + ", ".join(staged) + ". Approve each one on " + "npmjs.com under Staged Packages, with 2FA. Before the next release of these " + "packages, add a trusted publisher to each (npm trust github), then publish " + "within two days." + ) def main() -> None: diff --git a/tooling/extension-bindings/ci/publish_all.py b/tooling/extension-bindings/ci/publish_all.py index 4aa763b..d7945dd 100644 --- a/tooling/extension-bindings/ci/publish_all.py +++ b/tooling/extension-bindings/ci/publish_all.py @@ -153,9 +153,9 @@ def inspect(package: Package, versions: set[str] | None, execute: bool) -> Findi if package.language == "typescript": return Finding( package, FIRST_RELEASE, - "not on npm yet. npm only accepts a trusted publisher for a package that exists, so publish this " - "first version once with an npm token, then add binding-publish-npm.yml as its trusted publisher", - blocking=execute, + "not on npm yet, so this first version is staged with the NPM_STAGE_TOKEN secret. Approve it on " + "npmjs.com under Staged Packages with 2FA, and before its next release add binding-publish-npm.yml " + "as its trusted publisher", ) if package.language == "python": return Finding( diff --git a/tooling/extension-bindings/ci/test_publish_all.py b/tooling/extension-bindings/ci/test_publish_all.py index ff43ead..507ea8d 100644 --- a/tooling/extension-bindings/ci/test_publish_all.py +++ b/tooling/extension-bindings/ci/test_publish_all.py @@ -64,9 +64,9 @@ def test_published_new_and_first_release_versions_are_told_apart(self) -> None: self.assertEqual(script.inspect(python, {"0.2.0"}, True).status, script.NEW_VERSION) first_npm = script.inspect(typescript, None, True) self.assertEqual(first_npm.status, script.FIRST_RELEASE) - self.assertTrue(first_npm.blocking, "npm cannot take a first release through trusted publishing") - self.assertIn("npm token", first_npm.note) - self.assertFalse(script.inspect(typescript, None, False).blocking, "a dry run only reports it") + self.assertFalse(first_npm.blocking, "a first npm release is staged, not refused") + self.assertIn("NPM_STAGE_TOKEN", first_npm.note) + self.assertIn("Staged Packages", first_npm.note) first_pypi = script.inspect(python, None, True) self.assertFalse(first_pypi.blocking) self.assertIn("pending trusted publisher", first_pypi.note) @@ -92,12 +92,12 @@ def test_preflight_lists_only_languages_with_something_new(self) -> None: self.assertIn("| example-common | Python | PyPI | 0.3.0 | new version |", table) self.assertIn("| @example/env | TypeScript | npm | 0.4.0 | published |", table) - def test_a_real_run_with_a_first_npm_release_is_blocked(self) -> None: + def test_a_real_run_with_a_first_npm_release_goes_ahead_to_stage_it(self) -> None: _, pending, blocked = script.preflight( self.root, "env", "typescript", True, lookup=lambda item: None ) self.assertEqual(pending, ["typescript"]) - self.assertTrue(blocked) + self.assertFalse(blocked) class FakeGitHub: diff --git a/tooling/extension-bindings/ci/test_publish_npm.py b/tooling/extension-bindings/ci/test_publish_npm.py index d0d176b..dda5a7d 100644 --- a/tooling/extension-bindings/ci/test_publish_npm.py +++ b/tooling/extension-bindings/ci/test_publish_npm.py @@ -3,6 +3,7 @@ from __future__ import annotations import json +import os from pathlib import Path from types import SimpleNamespace from unittest.mock import patch @@ -56,11 +57,11 @@ def test_dependencies_are_published_before_their_dependents(self) -> None: with self.assertRaisesRegex(ValueError, "cycle"): script.publication_order(packages) - def test_trusted_publishing_needs_a_recent_npm(self) -> None: - for version in ("11.5.1\n", "11.6.0", "12.0.0-pre.1"): + def test_staged_publishing_needs_a_recent_npm(self) -> None: + for version in ("11.15.0\n", "11.16.2", "12.0.0-pre.1"): script.check_npm_version(version) - for version in ("10.8.2", "11.5.0"): - with self.assertRaisesRegex(ValueError, "11.5.1 or later"): + for version in ("10.8.2", "11.5.1", "11.14.9"): + with self.assertRaisesRegex(ValueError, "11.15.0 or later"): script.check_npm_version(version) def test_a_package_must_match_its_catalog_entry(self) -> None: @@ -84,11 +85,11 @@ def test_a_dry_run_builds_and_checks_but_never_publishes(self) -> None: def test_publication_skips_versions_that_are_already_on_npm(self) -> None: def run(command, cwd, **options): - return SimpleNamespace(stdout="11.6.0\n") + return SimpleNamespace(stdout="11.15.0\n") with patch.object(script, "run", side_effect=run) as runner, patch.object( script, "already_published", side_effect=lambda name, version: name == "@example/addon" - ): + ), patch.object(script, "npm_status", return_value="published"): script.publish(self.root, self.targets, True) publishes = [ call for call in runner.call_args_list if call.args[0][:2] == ["npm", "publish"] @@ -101,12 +102,12 @@ def run(command, cwd, **options): def test_an_unselected_dependency_is_built_but_not_published(self) -> None: def run(command, cwd, **options): - return SimpleNamespace(stdout="11.6.0\n") + return SimpleNamespace(stdout="11.15.0\n") targets = select_targets(self.catalog, "owner:typescript") with patch.object(script, "run", side_effect=run) as runner, patch.object( script, "already_published", return_value=False - ) as published: + ) as published, patch.object(script, "npm_status", return_value="published"): script.publish(self.root, targets, True) commands = self.commands(runner.call_args_list) builds = [command[3] for command in commands if command[0] == "node"] @@ -129,7 +130,7 @@ def run(command, cwd, **options): if command[0] == "node": directory = Path(command[3]).parent copied.append(sorted(path.name for path in directory.iterdir())) - return SimpleNamespace(stdout="11.6.0\n") + return SimpleNamespace(stdout="11.15.0\n") with patch.object(script, "run", side_effect=run): script.publish(self.root, self.targets, False) @@ -140,9 +141,74 @@ def run(command, cwd, **options): def test_publication_refuses_an_old_npm(self) -> None: with patch.object( script, "run", return_value=SimpleNamespace(stdout="10.8.2\n") - ), self.assertRaisesRegex(ValueError, "npm 11.5.1"): + ), self.assertRaisesRegex(ValueError, "npm 11.15.0"): script.publish(self.root, self.targets, True) + def run_publication(self, statuses: dict[str, str], token: str | None): + def run(command, cwd, **options): + return SimpleNamespace(stdout="11.15.0\n") + + environment = {key: value for key, value in os.environ.items() if key != "NPM_STAGE_TOKEN"} + if token: + environment["NPM_STAGE_TOKEN"] = token + with patch.object(script, "run", side_effect=run) as runner, patch.object( + script, "already_published", return_value=False + ), patch.object(script, "npm_status", side_effect=lambda name: statuses[name]), patch.dict( + "os.environ", environment, clear=True + ): + script.publish(self.root, self.targets, True) + return runner + + def test_a_first_release_is_staged_with_the_stage_token(self) -> None: + runner = self.run_publication({"@example/addon": "missing", "@example/owner": "published"}, "stage-token") + stages = [call for call in runner.call_args_list if call.args[0][:3] == ["npm", "stage", "publish"]] + self.assertEqual(len(stages), 1) + self.assertTrue(str(stages[0].args[1]).endswith("node_modules/@example/addon")) + self.assertEqual(stages[0].kwargs["env"]["NODE_AUTH_TOKEN"], "stage-token") + publishes = [call for call in runner.call_args_list if call.args[0][:2] == ["npm", "publish"]] + self.assertEqual(len(publishes), 1) + self.assertTrue(str(publishes[0].args[1]).endswith("node_modules/@example/owner")) + self.assertNotIn("env", publishes[0].kwargs) + + def test_a_first_release_without_the_token_publishes_nothing(self) -> None: + def run(command, cwd, **options): + return SimpleNamespace(stdout="11.15.0\n") + + environment = {key: value for key, value in os.environ.items() if key != "NPM_STAGE_TOKEN"} + statuses = {"@example/addon": "missing", "@example/owner": "published"} + with patch.object(script, "run", side_effect=run) as runner, patch.object( + script, "already_published", return_value=False + ), patch.object(script, "npm_status", side_effect=lambda name: statuses[name]), patch.dict( + "os.environ", environment, clear=True + ), self.assertRaisesRegex(ValueError, "@example/addon not on npm yet.*NPM_STAGE_TOKEN"): + script.publish(self.root, self.targets, True) + # The check runs before anything is built, staged or published. + self.assertEqual([call.args[0] for call in runner.call_args_list], [["npm", "--version"]]) + + def test_a_staged_first_release_waits_for_approval(self) -> None: + runner = self.run_publication({"@example/addon": "staged", "@example/owner": "published"}, None) + commands = self.commands(runner.call_args_list) + self.assertFalse(any(command[:3] == ["npm", "stage", "publish"] for command in commands)) + self.assertEqual(sum(command[:2] == ["npm", "publish"] for command in commands), 1) + + def test_npm_status_reads_the_registry(self) -> None: + def view(stdout="", stderr="", code=0): + return SimpleNamespace(returncode=code, stdout=stdout, stderr=stderr) + + cases = [ + (view(code=1, stderr="npm error code E404"), "missing"), + (view(stdout='"0.0.0-stage"'), "staged"), + (view(stdout='["0.0.0-stage", "0.1.0"]'), "published"), + (view(stdout='["0.1.0"]'), "published"), + ] + for result, expected in cases: + with self.subTest(expected=expected), patch("subprocess.run", return_value=result): + self.assertEqual(script.npm_status("@example/addon"), expected) + with patch("subprocess.run", return_value=view(code=1, stderr="network down")), self.assertRaisesRegex( + ValueError, "could not read" + ): + script.npm_status("@example/addon") + def test_publication_needs_the_emitter_dependencies(self) -> None: (self.root / "tooling/extension-bindings/emitters/typescript/node_modules/typescript/bin/tsc").unlink() with self.assertRaisesRegex(ValueError, "npm ci"):