From d90a74c3076e51d5aec4af3c01b16e20b4f0d7b8 Mon Sep 17 00:00:00 2001 From: rdlabo Date: Wed, 11 Nov 2026 09:09:40 +0900 Subject: [PATCH 1/4] fix(ci): restore npm beta publishing --- .github/scripts/npm-release.mjs | 26 ++++++-- .github/scripts/npm-release.test.mjs | 24 +++++++ .github/workflows/release.yml | 97 +++++++++++++++++++++++++--- 3 files changed, 135 insertions(+), 12 deletions(-) diff --git a/.github/scripts/npm-release.mjs b/.github/scripts/npm-release.mjs index b02af36..6411bc2 100644 --- a/.github/scripts/npm-release.mjs +++ b/.github/scripts/npm-release.mjs @@ -19,7 +19,25 @@ export function releaseVersion(version, tag, pr, sha) { export async function resolveRelease(github, context) { if (context.eventName === "issue_comment") - return resolveCommentBeta(github, context); + return resolveCommentBeta(github, context.payload, context.repo); + if (context.eventName === "workflow_dispatch") { + const inputs = context.payload.inputs; + if (!/^[1-9]\d*$/.test(inputs?.["comment-id"]) || + !/^[a-f0-9]{40}$/.test(inputs?.["head-sha"])) { + throw new Error("Invalid beta dispatch inputs"); + } + const { data: comment } = await github.rest.issues.getComment({ + ...context.repo, + comment_id: Number(inputs["comment-id"]), + }); + const number = Number(comment.issue_url.match(/\/issues\/([1-9]\d*)$/)?.[1]); + if (!number || comment.updated_at !== comment.created_at) { + throw new Error("The original /beta comment is no longer valid"); + } + return resolveCommentBeta(github, { + action: "created", issue: { number, pull_request: {} }, comment, + }, context.repo, inputs["head-sha"]); + } const repo = context.repo; const { data: main } = await github.rest.repos.getBranch({ ...repo, @@ -102,11 +120,10 @@ export async function resolveRelease(github, context) { return { sha, ...releaseVersion(pkg.version, tag, pr, sha) }; } -async function resolveCommentBeta(github, context) { - const { action, issue, comment } = context.payload; +async function resolveCommentBeta(github, payload, repo, expectedSha) { + const { action, issue, comment } = payload; if (action !== "created" || !issue.pull_request || comment.body !== "/beta") return null; - const repo = context.repo; const { data: permission } = await github.rest.repos.getCollaboratorPermissionLevel({ ...repo, @@ -129,6 +146,7 @@ async function resolveCommentBeta(github, context) { !pr.head.repo ) return null; + if (expectedSha && pr.head.sha !== expectedSha) return null; // A queued comment must not authorize code pushed after that comment. if (Date.parse(pr.updated_at) > Date.parse(comment.created_at)) { throw new Error( diff --git a/.github/scripts/npm-release.test.mjs b/.github/scripts/npm-release.test.mjs index c6346cc..86ba9e7 100644 --- a/.github/scripts/npm-release.test.mjs +++ b/.github/scripts/npm-release.test.mjs @@ -249,3 +249,27 @@ test("GitHub maintain role is accepted even when the legacy permission is write" f.state.role = "maintain"; assert.equal((await resolveRelease(f.github, f.context)).channel, "beta"); }); + +test("dispatch keeps the original authorized PR head", async () => { + const f = commentFixture(); + const comment = { + ...f.context.payload.comment, + updated_at: f.context.payload.comment.created_at, + issue_url: "https://api.github.com/repos/rdlabo-dev/cf-workers-native/issues/43", + }; + f.github.rest.issues = { + getComment: async ({ comment_id }) => { + assert.equal(comment_id, 123); + return { data: comment }; + }, + }; + const original = await resolveRelease(f.github, f.context); + f.context.eventName = "workflow_dispatch"; + f.context.payload = { inputs: { "comment-id": "123", "head-sha": sha } }; + assert.deepEqual(await resolveRelease(f.github, f.context), original); + f.state.pr.head.sha = "b".repeat(40); + assert.equal(await isReleaseCurrent(f.github, f.context, original), false); + f.state.pr.head.sha = sha; + comment.updated_at = "2026-10-20"; + await assert.rejects(resolveRelease(f.github, f.context), /no longer valid/); +}); diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 56d8f2f..0a082e6 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -5,6 +5,16 @@ on: tags: ["v*"] issue_comment: types: [created] + workflow_dispatch: + inputs: + comment-id: + description: ID of the authorized /beta comment + required: true + type: string + head-sha: + description: PR head authorized by the comment workflow + required: true + type: string workflow_run: workflows: [Compatibility] types: [completed] @@ -15,12 +25,18 @@ permissions: jobs: prepare: - if: github.event_name != 'issue_comment' || (github.event.issue.pull_request && github.event.comment.body == '/beta') + if: >- + (github.event_name == 'issue_comment' && github.event.issue.pull_request && + github.event.comment.body == '/beta' && github.run_attempt == '1') || + (github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' && + github.actor == 'github-actions[bot]') || + github.event_name == 'push' || github.event_name == 'workflow_run' runs-on: ubuntu-24.04 timeout-minutes: 70 permissions: contents: read actions: read + issues: read pull-requests: read outputs: plan: ${{ steps.plan.outputs.result }} @@ -43,18 +59,18 @@ jobs: const { resolveRelease } = await import(`${process.env.GITHUB_WORKSPACE}/.github/scripts/npm-release.mjs`); return await resolveRelease(github, context); - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - if: steps.plan.outputs.result != 'null' + if: github.event_name != 'issue_comment' && steps.plan.outputs.result != 'null' with: repository: ${{ fromJSON(steps.plan.outputs.result).repository || github.repository }} ref: ${{ fromJSON(steps.plan.outputs.result).sha }} persist-credentials: false - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 - if: steps.plan.outputs.result != 'null' + if: github.event_name != 'issue_comment' && steps.plan.outputs.result != 'null' with: node-version: 24 package-manager-cache: false - name: Build the exact release candidate - if: steps.plan.outputs.result != 'null' + if: github.event_name != 'issue_comment' && steps.plan.outputs.result != 'null' env: VERSION: ${{ fromJSON(steps.plan.outputs.result).version }} DIST_TAG: ${{ fromJSON(steps.plan.outputs.result).channel }} @@ -65,26 +81,49 @@ jobs: mkdir -p "$RUNNER_TEMP/npm-release" npm pack --pack-destination "$RUNNER_TEMP/npm-release" - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 - if: steps.plan.outputs.result != 'null' + if: github.event_name != 'issue_comment' && steps.plan.outputs.result != 'null' with: name: npm-release path: ${{ runner.temp }}/npm-release/*.tgz if-no-files-found: error retention-days: 7 + dispatch-comment-beta: + needs: prepare + if: github.event_name == 'issue_comment' && needs.prepare.outputs.plan != 'null' + runs-on: ubuntu-24.04 + permissions: + actions: write + steps: + - uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8 + env: + PLAN: ${{ needs.prepare.outputs.plan }} + with: + script: | + await github.rest.actions.createWorkflowDispatch({ + ...context.repo, + workflow_id: 'release.yml', + ref: 'main', + inputs: { + 'comment-id': String(context.payload.comment.id), + 'head-sha': JSON.parse(process.env.PLAN).sha, + }, + }); + publish: # Only authorized candidates enter the publication queue. concurrency: group: npm-release cancel-in-progress: false needs: prepare - if: needs.prepare.outputs.plan != 'null' + if: github.event_name != 'issue_comment' && needs.prepare.outputs.plan != 'null' runs-on: ubuntu-24.04 timeout-minutes: 5 permissions: contents: read id-token: write actions: read + issues: read pull-requests: read steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -131,5 +170,47 @@ jobs: assert.equal(pkg.publishConfig.access, 'public'); assert.ok(!pkg.publishConfig.registry || pkg.publishConfig.registry === 'https://registry.npmjs.org'); JS - DIST_TAG=$(node -p 'JSON.parse(process.env.PLAN).channel') - npm publish "${archives[0]}" --ignore-scripts --provenance --access public --tag "$DIST_TAG" --registry https://registry.npmjs.org + PACKAGE_ARCHIVE="${archives[0]}" node --input-type=module <<'JS' + import assert from 'node:assert/strict'; + import { readFileSync } from 'node:fs'; + import { createHash } from 'node:crypto'; + import { spawnSync } from 'node:child_process'; + const { version: EXPECTED_VERSION, channel: DIST_TAG } = JSON.parse(process.env.PLAN); + const archives = new Map([['cf-workers-native', process.env.PACKAGE_ARCHIVE]]); + const isPublished = (spec, archive) => { + const existing = spawnSync('npm', ['view', spec, 'dist.integrity', '--json', '--prefer-online', + '--registry=https://registry.npmjs.org'], { encoding: 'utf8' }); + if (existing.status === 0) { + const integrity = 'sha512-' + createHash('sha512').update(readFileSync(archive)).digest('base64'); + assert.equal(JSON.parse(existing.stdout), integrity, `${spec} already exists with different contents`); + return true; + } + let error; + try { error = JSON.parse(existing.stdout).error; } catch {} + assert.equal(error?.code, 'E404', `Cannot check ${spec}: ${existing.stderr}`); + return false; + }; + for (const [name, archive] of archives) { + const spec = `${name}@${EXPECTED_VERSION}`; + if (!isPublished(spec, archive)) { + const result = spawnSync('npm', ['publish', archive, '--ignore-scripts', '--provenance', '--access', 'public', + '--json', '--registry=https://registry.npmjs.org', '--tag', DIST_TAG], { encoding: 'utf8' }); + process.stdout.write(result.stdout ?? ''); + process.stderr.write(result.stderr ?? ''); + if (result.status === 0) continue; + let code; + try { code = JSON.parse(result.stdout).error?.code; } catch {} + assert.equal(code, 'E409', `Publish failed for ${spec}`); + // Another release run can finish before the version is visible to npm view. + for (const delay of [0, 2000, 4000, 8000, 16000]) { + if (delay) await new Promise(resolve => setTimeout(resolve, delay)); + if (isPublished(spec, archive)) { + code = undefined; + break; + } + } + assert.equal(code, undefined, `Publish conflict for ${spec}: no matching public version became visible`); + } + console.log(`${spec} already published with matching contents; skipping.`); + } + JS From 4613a80cc2c89e2bf414a19b8f647c34203c263b Mon Sep 17 00:00:00 2001 From: rdlabo Date: Wed, 11 Nov 2026 09:24:33 +0900 Subject: [PATCH 2/4] fix(ci): harden beta authorization and artifact validation --- .github/scripts/npm-release.mjs | 90 +++++++++++++++++++++++++--- .github/scripts/npm-release.test.mjs | 59 +++++++++++++++--- .github/workflows/ci.yml | 53 ++++++++++++++++ .github/workflows/release.yml | 65 +++++++++++--------- 4 files changed, 225 insertions(+), 42 deletions(-) diff --git a/.github/scripts/npm-release.mjs b/.github/scripts/npm-release.mjs index 6411bc2..35fc3e9 100644 --- a/.github/scripts/npm-release.mjs +++ b/.github/scripts/npm-release.mjs @@ -22,21 +22,32 @@ export async function resolveRelease(github, context) { return resolveCommentBeta(github, context.payload, context.repo); if (context.eventName === "workflow_dispatch") { const inputs = context.payload.inputs; - if (!/^[1-9]\d*$/.test(inputs?.["comment-id"]) || - !/^[a-f0-9]{40}$/.test(inputs?.["head-sha"])) { + if ( + !/^[1-9]\d*$/.test(inputs?.["comment-id"]) || + !/^[a-f0-9]{40}$/.test(inputs?.["head-sha"]) + ) { throw new Error("Invalid beta dispatch inputs"); } const { data: comment } = await github.rest.issues.getComment({ ...context.repo, comment_id: Number(inputs["comment-id"]), }); - const number = Number(comment.issue_url.match(/\/issues\/([1-9]\d*)$/)?.[1]); + const number = Number( + comment.issue_url.match(/\/issues\/([1-9]\d*)$/)?.[1], + ); if (!number || comment.updated_at !== comment.created_at) { throw new Error("The original /beta comment is no longer valid"); } - return resolveCommentBeta(github, { - action: "created", issue: { number, pull_request: {} }, comment, - }, context.repo, inputs["head-sha"]); + return resolveCommentBeta( + github, + { + action: "created", + issue: { number, pull_request: {} }, + comment, + }, + context.repo, + inputs["head-sha"], + ); } const repo = context.repo; const { data: main } = await github.rest.repos.getBranch({ @@ -153,6 +164,36 @@ async function resolveCommentBeta(github, payload, repo, expectedSha) { "PR changed after /beta; post a fresh comment after CI passes", ); } + let lastForcePush; + if (!expectedSha) { + const { repository } = await github.graphql( + ` + query($owner: String!, $repo: String!, $number: Int!) { + repository(owner: $owner, name: $repo) { + pullRequest(number: $number) { + headRefOid + timelineItems(last: 1, itemTypes: [HEAD_REF_FORCE_PUSHED_EVENT]) { + nodes { ... on HeadRefForcePushedEvent { createdAt afterCommit { oid } } } + } + } + } + } + `, + { ...repo, number: issue.number }, + ); + const current = repository?.pullRequest; + if ( + current?.headRefOid !== pr.head.sha || + current.timelineItems.nodes.some( + (node) => Date.parse(node.createdAt) >= Date.parse(comment.created_at), + ) + ) { + throw new Error( + "The PR head changed at or after /beta; post a fresh comment.", + ); + } + [lastForcePush] = current.timelineItems.nodes; + } const files = await github.paginate(github.rest.pulls.listFiles, { ...repo, pull_number: issue.number, @@ -180,7 +221,12 @@ async function resolveCommentBeta(github, payload, repo, expectedSha) { per_page: 100, }); const latest = runs - .filter((run) => run.pull_requests.some((p) => p.number === pr.number)) + .filter((run) => + run.pull_requests?.length + ? run.pull_requests.some((p) => p.number === pr.number) + : run.head_repository?.full_name === pr.head.repo?.full_name && + run.head_branch === pr.head.ref, + ) .sort((a, b) => b.run_number - a.run_number)[0]; if ( !latest || @@ -197,9 +243,37 @@ async function resolveCommentBeta(github, payload, repo, expectedSha) { const pkg = JSON.parse(Buffer.from(file.content, "base64").toString("utf8")); if (pkg.name !== "cf-workers-native") throw new Error("Unexpected trusted package name"); + if ( + lastForcePush && + lastForcePush.afterCommit?.oid !== sha && + Date.parse(latest.created_at) <= Date.parse(lastForcePush.createdAt) + ) { + throw new Error( + "The candidate predates the last head rewind; post /beta after fresh CI", + ); + } + const artifactName = `npm-beta-pr${pr.number}-${sha}-${latest.run_attempt}`; + const artifacts = await github.paginate( + github.rest.actions.listWorkflowRunArtifacts, + { + ...repo, + run_id: latest.id, + per_page: 100, + }, + ); + if ( + !artifacts.some( + (artifact) => artifact.name === artifactName && !artifact.expired, + ) + ) { + throw new Error( + "The immutable beta candidate is missing or expired; select Re-run all jobs in Compatibility, then post /beta again", + ); + } return { sha, - repository: pr.head.repo.full_name, + candidateRunId: latest.id, + candidateArtifact: artifactName, pr: pr.number, ...releaseVersion(pkg.version, undefined, pr.number, sha), }; diff --git a/.github/scripts/npm-release.test.mjs b/.github/scripts/npm-release.test.mjs index 86ba9e7..901d326 100644 --- a/.github/scripts/npm-release.test.mjs +++ b/.github/scripts/npm-release.test.mjs @@ -157,14 +157,31 @@ function commentFixture() { state: "open", draft: false, base: { ref: "main" }, - head: { sha, repo: { full_name: "contributor/fork" } }, + head: { sha, ref: "feature", repo: { full_name: "contributor/fork" } }, updated_at: "2026-10-19T07:00:00Z", }; f.state.files = []; - f.state.runs[0].pull_requests = [{ number: 43 }]; + Object.assign(f.state.runs[0], { + id: 12, + run_attempt: 1, + created_at: "2026-10-18", + head_branch: "feature", + head_repository: { full_name: "contributor/fork" }, + pull_requests: [], + }); + f.github.rest.actions.listWorkflowRunArtifacts = "artifacts"; + f.state.artifacts = [{ name: `npm-beta-pr43-${sha}-1`, expired: false }]; f.github.rest.repos.getCollaboratorPermissionLevel = async () => ({ data: { permission: f.state.permission, role_name: f.state.role }, }); + f.github.graphql = async () => ({ + repository: { + pullRequest: { + headRefOid: f.state.pr.head.sha, + timelineItems: { nodes: f.state.forcePushes ?? [] }, + }, + }, + }); f.github.rest.pulls = { get: async () => ({ data: f.state.pr }), listFiles: "files", @@ -181,7 +198,8 @@ test("/beta supports an authorized fork head without changing latest", async () const plan = await resolveRelease(f.github, f.context); assert.deepEqual(plan, { sha, - repository: "contributor/fork", + candidateRunId: 12, + candidateArtifact: `npm-beta-pr43-${sha}-1`, pr: 43, version: "0.1.1-beta.pr43.shaaaaaaaaaaaaa", channel: "beta", @@ -217,8 +235,18 @@ test("/beta refuses workflow changes, unmatched PR CI and updates after the comm ]), (f) => (f.state.files = [{ filename: ".github/scripts/npm-release.mjs" }]), (f) => (f.state.runs[0].pull_requests = [{ number: 99 }]), + (f) => (f.state.runs[0].head_branch = "unrelated"), + (f) => (f.state.artifacts[0].name = `npm-beta-pr99-${sha}-1`), (f) => (f.state.runs[0].conclusion = "failure"), (f) => (f.state.pr.updated_at = "2026-10-19T07:00:01Z"), + (f) => (f.state.forcePushes = [{ createdAt: "2026-10-19T07:00:00Z" }]), + (f) => + (f.state.forcePushes = [ + { + createdAt: "2026-10-19T06:00:00Z", + afterCommit: { oid: "b".repeat(40) }, + }, + ]), ]) { const f = commentFixture(); change(f); @@ -234,11 +262,13 @@ test("publication rechecks current permission, head and CI after building", asyn ]) { const f = commentFixture(); const plan = await resolveRelease(f.github, f.context); + dispatchComment(f); change(f); assert.equal(await isReleaseCurrent(f.github, f.context, plan), false); } const f = commentFixture(); const plan = await resolveRelease(f.github, f.context); + dispatchComment(f); f.state.runs[0].conclusion = "failure"; await assert.rejects(isReleaseCurrent(f.github, f.context, plan)); }); @@ -250,12 +280,12 @@ test("GitHub maintain role is accepted even when the legacy permission is write" assert.equal((await resolveRelease(f.github, f.context)).channel, "beta"); }); -test("dispatch keeps the original authorized PR head", async () => { - const f = commentFixture(); +function dispatchComment(f) { const comment = { ...f.context.payload.comment, updated_at: f.context.payload.comment.created_at, - issue_url: "https://api.github.com/repos/rdlabo-dev/cf-workers-native/issues/43", + issue_url: + "https://api.github.com/repos/rdlabo-dev/cf-workers-native/issues/43", }; f.github.rest.issues = { getComment: async ({ comment_id }) => { @@ -263,9 +293,15 @@ test("dispatch keeps the original authorized PR head", async () => { return { data: comment }; }, }; - const original = await resolveRelease(f.github, f.context); f.context.eventName = "workflow_dispatch"; f.context.payload = { inputs: { "comment-id": "123", "head-sha": sha } }; + return comment; +} + +test("dispatch keeps the original authorized PR head", async () => { + const f = commentFixture(); + const original = await resolveRelease(f.github, f.context); + const comment = dispatchComment(f); assert.deepEqual(await resolveRelease(f.github, f.context), original); f.state.pr.head.sha = "b".repeat(40); assert.equal(await isReleaseCurrent(f.github, f.context, original), false); @@ -273,3 +309,12 @@ test("dispatch keeps the original authorized PR head", async () => { comment.updated_at = "2026-10-20"; await assert.rejects(resolveRelease(f.github, f.context), /no longer valid/); }); + +test("comment beta requires the artifact from the successful run attempt", async () => { + const f = commentFixture(); + f.state.runs[0].run_attempt = 2; + await assert.rejects( + resolveRelease(f.github, f.context), + /candidate is missing or expired/, + ); +}); diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e7b1840..0d8f632 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,6 +2,7 @@ name: Compatibility on: pull_request: + types: [opened, synchronize, reopened, ready_for_review] push: branches: [main] merge_group: @@ -414,6 +415,54 @@ jobs: demo/artifacts/upstream/playwright/ retention-days: 7 + beta-candidate: + if: github.event_name == 'pull_request' && github.base_ref == 'main' && github.event.pull_request.draft == false + runs-on: ubuntu-24.04 + timeout-minutes: 15 + permissions: + contents: read + steps: + - name: Read the base package version + id: base-version + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8 + with: + script: | + const { data: manifest } = await github.rest.repos.getContent({ + ...context.repo, + path: 'package.json', + ref: context.payload.pull_request.base.sha, + }); + const pkg = JSON.parse(Buffer.from(manifest.content, 'base64').toString('utf8')); + const version = pkg.version.split('-')[0]; + if (!/^\d+\.\d+\.\d+$/.test(version)) throw new Error('Invalid beta base version'); + core.setOutput('version', version); + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: ${{ github.event.pull_request.head.repo.full_name }} + ref: ${{ github.event.pull_request.head.sha }} + persist-credentials: false + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 24 + package-manager-cache: false + - name: Pack the exact PR candidate + env: + BASE_VERSION: ${{ steps.base-version.outputs.version }} + PR_NUMBER: ${{ github.event.pull_request.number }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + run: | + npm install + VERSION="${BASE_VERSION}-beta.pr${PR_NUMBER}.sha${HEAD_SHA:0:12}" + npm version "$VERSION" --no-git-tag-version --ignore-scripts --allow-same-version + npm pkg set publishConfig.tag=beta + npm pack --pack-destination "$RUNNER_TEMP" + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: npm-beta-pr${{ github.event.pull_request.number }}-${{ github.event.pull_request.head.sha }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/cf-workers-native-*.tgz + if-no-files-found: error + retention-days: 7 + required: name: CI if: ${{ always() }} @@ -426,6 +475,7 @@ jobs: streams-fallback, package, upstream, + beta-candidate, ] runs-on: ubuntu-24.04 timeout-minutes: 1 @@ -439,9 +489,12 @@ jobs: BINDINGS: ${{ needs.bindings.result }} STREAMS: ${{ needs['streams-fallback'].result }} PACKAGE: ${{ needs.package.result }} + BETA_CANDIDATE: ${{ needs['beta-candidate'].result }} + BETA_EXPECTED: ${{ github.event_name == 'pull_request' && github.base_ref == 'main' && github.event.pull_request.draft == false && 'success' || 'skipped' }} UPSTREAM: ${{ needs.upstream.result }} run: | test "$CHECKOUT" = success + test "$BETA_CANDIDATE" = "$BETA_EXPECTED" expected=success if [ "$REUSE" = true ]; then expected=skipped; fi for result in "$LIBRARY" "$COMPATIBILITY" "$BINDINGS" "$STREAMS" "$PACKAGE" "$UPSTREAM"; do diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 0a082e6..35aff4b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -58,30 +58,26 @@ jobs: script: | const { resolveRelease } = await import(`${process.env.GITHUB_WORKSPACE}/.github/scripts/npm-release.mjs`); return await resolveRelease(github, context); - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - if: github.event_name != 'issue_comment' && steps.plan.outputs.result != 'null' - with: - repository: ${{ fromJSON(steps.plan.outputs.result).repository || github.repository }} - ref: ${{ fromJSON(steps.plan.outputs.result).sha }} - persist-credentials: false - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 - if: github.event_name != 'issue_comment' && steps.plan.outputs.result != 'null' + if: (github.event_name == 'push' || github.event_name == 'workflow_run') && steps.plan.outputs.result != 'null' with: node-version: 24 package-manager-cache: false - name: Build the exact release candidate - if: github.event_name != 'issue_comment' && steps.plan.outputs.result != 'null' + if: (github.event_name == 'push' || github.event_name == 'workflow_run') && steps.plan.outputs.result != 'null' env: + SHA: ${{ fromJSON(steps.plan.outputs.result).sha }} VERSION: ${{ fromJSON(steps.plan.outputs.result).version }} DIST_TAG: ${{ fromJSON(steps.plan.outputs.result).channel }} run: | + test "$(git rev-parse HEAD)" = "$SHA" npm install npm version "$VERSION" --no-git-tag-version --ignore-scripts --allow-same-version npm pkg set "publishConfig.tag=$DIST_TAG" mkdir -p "$RUNNER_TEMP/npm-release" npm pack --pack-destination "$RUNNER_TEMP/npm-release" - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 - if: github.event_name != 'issue_comment' && steps.plan.outputs.result != 'null' + if: (github.event_name == 'push' || github.event_name == 'workflow_run') && steps.plan.outputs.result != 'null' with: name: npm-release path: ${{ runner.temp }}/npm-release/*.tgz @@ -137,9 +133,19 @@ jobs: - name: Update npm for trusted publishing run: npm install -g npm@latest - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 + if: github.event_name != 'workflow_dispatch' with: name: npm-release path: ${{ runner.temp }}/npm-release + - name: Download the immutable PR candidate + if: github.event_name == 'workflow_dispatch' + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 + with: + name: ${{ fromJSON(needs.prepare.outputs.plan).candidateArtifact }} + run-id: ${{ fromJSON(needs.prepare.outputs.plan).candidateRunId }} + github-token: ${{ github.token }} + repository: ${{ github.repository }} + path: ${{ runner.temp }}/npm-release - name: Revalidate authorization and candidate id: current uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8 @@ -158,24 +164,29 @@ jobs: shopt -s nullglob archives=("$RUNNER_TEMP"/npm-release/*.tgz) test "${#archives[@]}" -eq 1 - tar -xOf "${archives[0]}" package/package.json > "$RUNNER_TEMP/release-package.json" - node --input-type=module <<'JS' - import { readFileSync } from 'node:fs'; - import assert from 'node:assert/strict'; - const plan = JSON.parse(process.env.PLAN); - const pkg = JSON.parse(readFileSync(`${process.env.RUNNER_TEMP}/release-package.json`, 'utf8')); - assert.equal(pkg.name, 'cf-workers-native'); - assert.equal(pkg.version, plan.version); - assert.equal(pkg.publishConfig.tag, plan.channel); - assert.equal(pkg.publishConfig.access, 'public'); - assert.ok(!pkg.publishConfig.registry || pkg.publishConfig.registry === 'https://registry.npmjs.org'); - JS PACKAGE_ARCHIVE="${archives[0]}" node --input-type=module <<'JS' import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; import { createHash } from 'node:crypto'; - import { spawnSync } from 'node:child_process'; + import { execFileSync, spawnSync } from 'node:child_process'; + import { createRequire } from 'node:module'; + const require = createRequire(import.meta.url); + const npmRoot = execFileSync('npm', ['root', '-g'], { encoding: 'utf8' }).trim(); + const pacote = require(`${npmRoot}/npm/node_modules/pacote`); + const readManifest = archive => pacote.manifest(archive, { + cache: `${process.env.RUNNER_TEMP}/npm-manifest-cache`, ignoreScripts: true, offline: true, + }); const { version: EXPECTED_VERSION, channel: DIST_TAG } = JSON.parse(process.env.PLAN); + const pkg = await readManifest(process.env.PACKAGE_ARCHIVE); + assert.equal(pkg.name, 'cf-workers-native'); + assert.equal(pkg.version, EXPECTED_VERSION, "Unexpected candidate version. Update the PR from main, wait for fresh CI, then post /beta again."); + const config = pkg.publishConfig; + assert(config && typeof config === 'object' && !Array.isArray(config) && + Object.keys(config).every(key => ['access', 'registry', 'tag'].includes(key)), 'Unexpected publishConfig key'); + assert.equal(config.tag, DIST_TAG); + assert.equal(config.access, 'public'); + assert([undefined, 'https://registry.npmjs.org', 'https://registry.npmjs.org/'].includes(config.registry), + 'Unexpected publish registry'); const archives = new Map([['cf-workers-native', process.env.PACKAGE_ARCHIVE]]); const isPublished = (spec, archive) => { const existing = spawnSync('npm', ['view', spec, 'dist.integrity', '--json', '--prefer-online', @@ -200,16 +211,16 @@ jobs: if (result.status === 0) continue; let code; try { code = JSON.parse(result.stdout).error?.code; } catch {} - assert.equal(code, 'E409', `Publish failed for ${spec}`); - // Another release run can finish before the version is visible to npm view. - for (const delay of [0, 2000, 4000, 8000, 16000]) { + // A concurrent publish may fail in npm's version check or during the PUT. + let matched = false; + for (const delay of code === 'E409' ? [0, 2000, 4000, 8000, 16000] : [0]) { if (delay) await new Promise(resolve => setTimeout(resolve, delay)); if (isPublished(spec, archive)) { - code = undefined; + matched = true; break; } } - assert.equal(code, undefined, `Publish conflict for ${spec}: no matching public version became visible`); + assert(matched, `Publish failed for ${spec}: no matching public version became visible`); } console.log(`${spec} already published with matching contents; skipping.`); } From 95934c643ee5bc7cc16c5544621f0e913643ae45 Mon Sep 17 00:00:00 2001 From: rdlabo Date: Wed, 11 Nov 2026 09:25:37 +0900 Subject: [PATCH 3/4] fix(ci): harden beta authorization and artifact validation --- .github/scripts/npm-release.mjs | 3 +++ .github/scripts/npm-release.test.mjs | 1 + 2 files changed, 4 insertions(+) diff --git a/.github/scripts/npm-release.mjs b/.github/scripts/npm-release.mjs index 35fc3e9..288928a 100644 --- a/.github/scripts/npm-release.mjs +++ b/.github/scripts/npm-release.mjs @@ -235,6 +235,9 @@ async function resolveCommentBeta(github, payload, repo, expectedSha) { ) { throw new Error("The PR head must pass Compatibility before /beta"); } + if (Date.parse(latest.created_at) >= Date.parse(comment.created_at)) { + throw new Error("The candidate CI must start before the /beta comment"); + } const { data: file } = await github.rest.repos.getContent({ ...repo, path: "package.json", diff --git a/.github/scripts/npm-release.test.mjs b/.github/scripts/npm-release.test.mjs index 901d326..4183191 100644 --- a/.github/scripts/npm-release.test.mjs +++ b/.github/scripts/npm-release.test.mjs @@ -238,6 +238,7 @@ test("/beta refuses workflow changes, unmatched PR CI and updates after the comm (f) => (f.state.runs[0].head_branch = "unrelated"), (f) => (f.state.artifacts[0].name = `npm-beta-pr99-${sha}-1`), (f) => (f.state.runs[0].conclusion = "failure"), + (f) => (f.state.runs[0].created_at = f.context.payload.comment.created_at), (f) => (f.state.pr.updated_at = "2026-10-19T07:00:01Z"), (f) => (f.state.forcePushes = [{ createdAt: "2026-10-19T07:00:00Z" }]), (f) => From 5d8cac685d202aeed53b6393c46e6d56574a28de Mon Sep 17 00:00:00 2001 From: rdlabo Date: Wed, 11 Nov 2026 10:08:48 +0900 Subject: [PATCH 4/4] fix(ci): pin the Wrangler compatibility test runtime --- demo/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/demo/package.json b/demo/package.json index 9f55a14..5ac9922 100644 --- a/demo/package.json +++ b/demo/package.json @@ -75,7 +75,7 @@ "typescript": "^7.0.2", "vite": "^7.3.7", "vitest": "^5.0.5", - "wrangler": "^4.151.0", + "wrangler": "4.151.0", "ws": "8.21.0" } }