From c5a9a7936184d29b5c03bd35ceb543695a953f0f Mon Sep 17 00:00:00 2001 From: rdlabo Date: Wed, 11 Nov 2026 09:09:11 +0900 Subject: [PATCH 1/3] fix(ci): restore npm beta publishing --- .github/workflows/release.yml | 174 +++++++++++++++++++++++++++------- 1 file changed, 142 insertions(+), 32 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c487464..0ea4cea 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -6,6 +6,20 @@ on: - '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 + target-branch: + description: PR base authorized by the comment workflow + required: true + type: string workflow_run: workflows: - Lint @@ -37,7 +51,7 @@ jobs: repo: context.repo.repo, username: context.payload.comment.user.login, }); - return { authorized: ['admin', 'maintain'].includes(data.permission) }; + return { authorized: [data.permission, data.role_name].some((role) => ['admin', 'maintain'].includes(role)) }; } catch (error) { core.warning(`Could not verify beta comment permission: ${error.message}`); return { authorized: false }; @@ -161,7 +175,11 @@ jobs: (github.event_name == 'issue_comment' && github.event.action == 'created' && github.event.issue.pull_request && - github.event.comment.body == '/beta') || + github.event.comment.body == '/beta' && + github.run_attempt == '1') || + (github.event_name == 'workflow_dispatch' && + github.ref_name == github.event.repository.default_branch && + github.actor == 'github-actions[bot]') || (github.event_name == 'workflow_run' && github.event.action == 'completed') runs-on: ubuntu-latest @@ -189,7 +207,8 @@ jobs: script: | const { owner, repo } = context.repo; const defaultBranch = context.payload.repository.default_branch; - const isComment = context.eventName === 'issue_comment'; + const isDispatch = context.eventName === 'workflow_dispatch'; + const isComment = context.eventName === 'issue_comment' || isDispatch; const protectedWorkflows = [ '.github/workflows/lint.yml', '.github/workflows/package-candidate.yml', @@ -263,22 +282,43 @@ jobs: let prNumber = ''; let event; let sourceKind; + let requestedAt; let required; if (isComment) { - const requester = context.payload.comment.user.login; + let comment = context.payload.comment; + if (isDispatch) { + const inputs = context.payload.inputs; + if (!/^[1-9]\d*$/.test(inputs['comment-id']) || + !/^[a-f0-9]{40}$/.test(inputs['head-sha']) || + inputs['target-branch'] !== defaultBranch) { + throw new Error('Invalid beta dispatch inputs.'); + } + ({ data: comment } = await github.rest.issues.getComment({ + owner, repo, comment_id: Number(inputs['comment-id']), + })); + } + if (comment.body !== '/beta' || comment.created_at !== comment.updated_at) { + throw new Error('The original /beta comment is no longer valid.'); + } + requestedAt = Date.parse(comment.created_at); + if (!Number.isFinite(requestedAt)) throw new Error('Invalid /beta comment timestamp.'); + const requester = comment.user.login; const { data: permission } = await github.rest.repos.getCollaboratorPermissionLevel({ owner, repo, username: requester, }); - if (!['admin', 'maintain'].includes(permission.permission)) { + if (![permission.permission, permission.role_name].some((role) => ['admin', 'maintain'].includes(role))) { core.notice(`@${requester} is not a repository owner or maintainer; /beta was ignored.`); core.setOutput('allowed', 'false'); return; } - prNumber = String(context.payload.issue.number); + prNumber = isDispatch + ? comment.issue_url.match(/\/issues\/([1-9]\d*)$/)?.[1] + : String(context.payload.issue.number); + if (!prNumber) throw new Error('The beta comment has no associated pull request.'); const { data: pullRequest } = await github.rest.pulls.get({ owner, repo, @@ -293,6 +333,15 @@ jobs: core.setFailed('The pull request head repository is no longer available.'); return; } + if (pullRequest.base.ref !== defaultBranch) { + core.notice('Beta publishing requires a PR targeting the default branch.'); + core.setOutput('allowed', 'false'); + return; + } + if (isDispatch && (pullRequest.head.sha !== context.payload.inputs['head-sha'] || + pullRequest.base.ref !== context.payload.inputs['target-branch'])) { + throw new Error('The PR head or base changed after /beta; a fresh /beta is required.'); + } const changedWorkflows = []; for (const path of protectedWorkflows) { const [{ data: trusted }, { data: candidate }] = await Promise.all([ @@ -394,6 +443,10 @@ jobs: return; } + if (isComment && Date.parse(runs.get('Package Candidate').created_at) > requestedAt) { + throw new Error('The candidate was built after the /beta request; post a fresh comment.'); + } + const candidateRun = runs.get('Package Candidate'); const artifactName = `npm-candidate-${headSha}`; const artifacts = await github.paginate(github.rest.actions.listWorkflowRunArtifacts, { @@ -422,9 +475,36 @@ jobs: core.setOutput('source-kind', sourceKind); core.setOutput('version', version); + dispatch-comment-beta: + needs: authorize-candidate + if: github.event_name == 'issue_comment' && needs.authorize-candidate.outputs.allowed == 'true' + runs-on: ubuntu-latest + permissions: + actions: write + steps: + - name: Dispatch the authorized beta + uses: actions/github-script@v8 + env: + HEAD_SHA: ${{ needs.authorize-candidate.outputs.head-sha }} + TARGET_BRANCH: ${{ github.event.repository.default_branch }} + with: + script: | + await github.rest.actions.createWorkflowDispatch({ + ...context.repo, + workflow_id: 'release.yml', + ref: context.payload.repository.default_branch, + inputs: { + 'comment-id': String(context.payload.comment.id), + 'head-sha': process.env.HEAD_SHA, + 'target-branch': process.env.TARGET_BRANCH, + }, + }); + publish-candidate: needs: authorize-candidate - if: needs.authorize-candidate.outputs.allowed == 'true' + if: >- + (github.event_name == 'workflow_dispatch' || github.event_name == 'workflow_run') && + needs.authorize-candidate.outputs.allowed == 'true' runs-on: ubuntu-latest concurrency: group: npm-${{ needs.authorize-candidate.outputs.dist-tag }}-${{ needs.authorize-candidate.outputs.head-sha }} @@ -435,6 +515,7 @@ jobs: actions: read contents: read id-token: write + issues: read pull-requests: read steps: @@ -472,17 +553,25 @@ jobs: if (process.env.SOURCE_KIND === 'comment') { const pull_number = Number(process.env.PR_NUMBER); const { data: pullRequest } = await github.rest.pulls.get({ owner, repo, pull_number }); - if (pullRequest.state !== 'open' || pullRequest.head.sha !== process.env.HEAD_SHA) { + if (pullRequest.state !== 'open' || pullRequest.draft || + pullRequest.head.sha !== process.env.HEAD_SHA || pullRequest.base.ref !== defaultBranch) { core.setFailed('The PR head changed after /beta; a fresh owner or maintainer /beta is required.'); return; } - const requester = context.payload.comment.user.login; + const { data: comment } = await github.rest.issues.getComment({ + owner, repo, comment_id: Number(context.payload.inputs['comment-id']), + }); + if (comment.body !== '/beta' || comment.created_at !== comment.updated_at || + comment.issue_url !== pullRequest.issue_url) { + throw new Error('The original /beta comment is no longer valid.'); + } + const requester = comment.user.login; const { data: permission } = await github.rest.repos.getCollaboratorPermissionLevel({ owner, repo, username: requester, }); - if (!['admin', 'maintain'].includes(permission.permission)) { + if (![permission.permission, permission.role_name].some((role) => ['admin', 'maintain'].includes(role))) { core.setFailed(`@${requester} is no longer a repository owner or maintainer.`); return; } @@ -617,32 +706,53 @@ jobs: EXPECTED_VERSION: ${{ needs.authorize-candidate.outputs.version }} run: | node --input-type=module <<'NODE' - import { readdirSync } from 'node:fs'; + import assert from 'node:assert/strict'; + import { readdirSync, readFileSync } from 'node:fs'; + import { createHash } from 'node:crypto'; import { execFileSync, spawnSync } from 'node:child_process'; - + const { EXPECTED_VERSION, DIST_TAG } = process.env; const directory = process.env.RUNNER_TEMP + '/npm-candidate'; - const archives = readdirSync(directory).filter((file) => file.endsWith('.tgz')).sort(); - for (const archive of archives) { - const path = `${directory}/${archive}`; - const packageJson = JSON.parse(execFileSync( - 'tar', - ['-xOf', path, 'package/package.json'], - { encoding: 'utf8' }, - )); - const existing = spawnSync( - 'npm', - ['view', `${packageJson.name}@${process.env.EXPECTED_VERSION}`, 'version', '--registry', process.env.NPM_CONFIG_REGISTRY], - { stdio: 'ignore' }, - ); + const archives = new Map(); + for (const file of readdirSync(directory).filter(file => file.endsWith('.tgz')).sort()) { + const archive = `${directory}/${file}`; + const pkg = JSON.parse(execFileSync('tar', ['-xOf', archive, 'package/package.json'], { encoding: 'utf8' })); + archives.set(pkg.name, 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) { - console.log(`${packageJson.name}@${process.env.EXPECTED_VERSION} already exists; skipping publish.`); - continue; + 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; } - execFileSync( - 'npm', - ['publish', path, '--ignore-scripts', '--provenance', '--access', 'public', '--registry', process.env.NPM_CONFIG_REGISTRY, '--tag', process.env.DIST_TAG], - { stdio: 'inherit' }, - ); + let error; + try { error = JSON.parse(existing.stdout).error; } catch {} + assert.equal(error?.code, 'E404', `Cannot check ${spec}: ${existing.stderr}`); + return false; + }; + // Check the complete package set before publishing any member. + const pending = new Map([...archives].filter(([name, archive]) => !isPublished(`${name}@${EXPECTED_VERSION}`, archive))); + for (const [name, archive] of pending) { + const spec = `${name}@${EXPECTED_VERSION}`; + 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.`); } NODE From f3e2900e120287aca4cb60ceadaa447dfbf263d9 Mon Sep 17 00:00:00 2001 From: rdlabo Date: Wed, 11 Nov 2026 09:24:19 +0900 Subject: [PATCH 2/3] fix(ci): harden beta authorization and artifact validation --- .github/workflows/release.yml | 106 +++++++++++++++++----------------- 1 file changed, 53 insertions(+), 53 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 0ea4cea..f29b7a7 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -178,7 +178,7 @@ jobs: github.event.comment.body == '/beta' && github.run_attempt == '1') || (github.event_name == 'workflow_dispatch' && - github.ref_name == github.event.repository.default_branch && + github.ref == format('refs/heads/{0}', github.event.repository.default_branch) && github.actor == 'github-actions[bot]') || (github.event_name == 'workflow_run' && github.event.action == 'completed') @@ -283,6 +283,7 @@ jobs: let event; let sourceKind; let requestedAt; + let lastForcePush; let required; if (isComment) { @@ -329,6 +330,29 @@ jobs: core.setOutput('allowed', 'false'); return; } + if (!isDispatch && Date.parse(pullRequest.updated_at) > requestedAt) { + throw new Error('The PR was updated after /beta; post a fresh comment after CI passes.'); + } + if (!isDispatch) { + 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 } } } + } + } + } + } + `, { owner, repo, number: Number(prNumber) }); + const current = repository?.pullRequest; + if (current?.headRefOid !== pullRequest.head.sha || + current.timelineItems.nodes.some(node => Date.parse(node.createdAt) >= requestedAt)) { + throw new Error('The PR head changed at or after /beta; post a fresh comment.'); + } + [lastForcePush] = current.timelineItems.nodes; + } if (!pullRequest.head.repo) { core.setFailed('The pull request head repository is no longer available.'); return; @@ -448,6 +472,10 @@ jobs: } const candidateRun = runs.get('Package Candidate'); + if (lastForcePush && lastForcePush.afterCommit?.oid !== headSha && + Date.parse(candidateRun.created_at) <= Date.parse(lastForcePush.createdAt)) { + throw new Error('The candidate predates the last head rewind; post /beta after fresh CI.'); + } const artifactName = `npm-candidate-${headSha}`; const artifacts = await github.paginate(github.rest.actions.listWorkflowRunArtifacts, { owner, @@ -654,70 +682,42 @@ jobs: repository: ${{ github.repository }} run-id: ${{ needs.authorize-candidate.outputs.run-id }} - - name: Validate complete package set + - name: Validate and publish the complete package set env: DIST_TAG: ${{ needs.authorize-candidate.outputs.dist-tag }} EXPECTED_PACKAGES: ${{ needs.authorize-candidate.outputs.packages }} EXPECTED_VERSION: ${{ needs.authorize-candidate.outputs.version }} - run: | - if [ "$DIST_TAG" != "beta" ]; then - echo "::error::Refusing unsupported dist-tag: $DIST_TAG" - exit 1 - fi - node --input-type=module <<'NODE' - import { readdirSync } from 'node:fs'; - import { execFileSync } from 'node:child_process'; - - const directory = process.env.RUNNER_TEMP + '/npm-candidate'; - const archives = readdirSync(directory).filter((file) => file.endsWith('.tgz')).sort(); - const expected = JSON.parse(process.env.EXPECTED_PACKAGES).sort(); - if (archives.length !== expected.length) { - throw new Error(`Expected ${expected.length} package archives, found ${archives.length}.`); - } - const actual = []; - for (const archive of archives) { - const packageJson = JSON.parse(execFileSync( - 'tar', - ['-xOf', `${directory}/${archive}`, 'package/package.json'], - { encoding: 'utf8' }, - )); - const registry = packageJson.publishConfig?.registry || ''; - if ( - registry && - registry !== 'https://registry.npmjs.org' && - registry !== 'https://registry.npmjs.org/' - ) { - throw new Error(`Refusing ${packageJson.name} with unexpected registry ${registry}.`); - } - if (packageJson.version !== process.env.EXPECTED_VERSION) { - throw new Error(`${packageJson.name} has version ${packageJson.version}; expected ${process.env.EXPECTED_VERSION}.`); - } - actual.push(packageJson.name); - } - actual.sort(); - if (new Set(actual).size !== actual.length || JSON.stringify(actual) !== JSON.stringify(expected)) { - throw new Error(`Artifact package set mismatch: ${JSON.stringify(actual)}`); - } - NODE - - - name: Publish all candidates - env: - DIST_TAG: ${{ needs.authorize-candidate.outputs.dist-tag }} - EXPECTED_VERSION: ${{ needs.authorize-candidate.outputs.version }} run: | node --input-type=module <<'NODE' import assert from 'node:assert/strict'; import { readdirSync, readFileSync } from 'node:fs'; import { createHash } from 'node:crypto'; 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 { EXPECTED_VERSION, DIST_TAG } = process.env; + assert.equal(DIST_TAG, 'beta', 'Unexpected dist-tag'); + const expected = JSON.parse(process.env.EXPECTED_PACKAGES).sort(); const directory = process.env.RUNNER_TEMP + '/npm-candidate'; const archives = new Map(); for (const file of readdirSync(directory).filter(file => file.endsWith('.tgz')).sort()) { const archive = `${directory}/${file}`; - const pkg = JSON.parse(execFileSync('tar', ['-xOf', archive, 'package/package.json'], { encoding: 'utf8' })); + const pkg = await readManifest(archive); + assert.equal(pkg.version, EXPECTED_VERSION, 'Artifact version mismatch'); + const config = pkg.publishConfig ?? {}; + assert(typeof config === 'object' && !Array.isArray(config) && + Object.keys(config).every(key => ['access', 'registry', 'tag'].includes(key)), 'Unexpected publishConfig key'); + assert([undefined, 'https://registry.npmjs.org', 'https://registry.npmjs.org/'].includes(config.registry), + 'Unexpected publish registry'); + assert(!archives.has(pkg.name), 'Duplicate package identity'); archives.set(pkg.name, archive); } + assert.deepEqual([...archives.keys()].sort(), expected, 'Artifact package set mismatch'); const isPublished = (spec, archive) => { const existing = spawnSync('npm', ['view', spec, 'dist.integrity', '--json', '--prefer-online', '--registry=https://registry.npmjs.org'], { encoding: 'utf8' }); @@ -742,16 +742,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.`); } NODE From 42fd035ab2ea883f241d88f0b0e53feec52f6d72 Mon Sep 17 00:00:00 2001 From: rdlabo Date: Wed, 11 Nov 2026 09:25:17 +0900 Subject: [PATCH 3/3] fix(ci): harden beta authorization and artifact validation --- .github/workflows/release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f29b7a7..f3184af 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -467,7 +467,7 @@ jobs: return; } - if (isComment && Date.parse(runs.get('Package Candidate').created_at) > requestedAt) { + if (isComment && Date.parse(runs.get('Package Candidate').created_at) >= requestedAt) { throw new Error('The candidate was built after the /beta request; post a fresh comment.'); }