From cdeadd6b459d7f5bbfb8368c05a6239f31c6e6e0 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Mon, 16 Nov 2026 14:29:13 +0100 Subject: [PATCH 01/94] fix(automation): validate Dependabot PRs through a narrow allowlist --- .github/workflows/wave-pr-guard.yml | 153 ++++++++++++++++++---------- 1 file changed, 100 insertions(+), 53 deletions(-) diff --git a/.github/workflows/wave-pr-guard.yml b/.github/workflows/wave-pr-guard.yml index 311f5e30..9404dc08 100644 --- a/.github/workflows/wave-pr-guard.yml +++ b/.github/workflows/wave-pr-guard.yml @@ -15,6 +15,12 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 5 steps: + - name: Checkout trusted base revision + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.event.pull_request.base.sha }} + persist-credentials: false + - name: Validate linked Wave issue and protected scope uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 with: @@ -28,58 +34,96 @@ jobs: core.info('Skipping contributor-only Wave checks for trusted maintainer PR.'); return; } - const { data: collaborator } = await github.rest.repos.getCollaboratorPermissionLevel({ - owner, repo, username: pr.user.login, + + const isDependabot = pr.user.login === 'dependabot[bot]'; + const files = await github.paginate(github.rest.pulls.listFiles, { + owner, repo, pull_number: pr.number, per_page: 100, }); - const trustedPermissions = new Set(['admin', 'maintain', 'write']); - if (trustedPermissions.has(collaborator.permission)) { - core.info('Skipping contributor-only Wave checks for repository collaborator PR.'); - return; - } - const refs = [...body.matchAll(/(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s+#(\d+)/gi)].map((m) => Number(m[1])); - const uniqueRefs = [...new Set(refs)]; - if (uniqueRefs.length !== 1) { - core.setFailed('Wave contributor PRs must use exactly one closing reference such as Closes #123.'); - return; - } - const { data: issue } = await github.rest.issues.get({ owner, repo, issue_number: uniqueRefs[0] }); - const labels = new Set(issue.labels.map((label) => label.name)); - if (!labels.has('Stellar Wave')) { - core.setFailed('#' + uniqueRefs[0] + ' is not a Stellar Wave issue.'); - return; - } - if (issue.state !== 'open') { - core.setFailed('Linked Wave issue is not open.'); - return; - } - - const dependencySection = (issue.body || '').split(/## Dependencies/i)[1] || ''; - const dependencyText = dependencySection.split(/\n---|\n## /)[0]; - const dependencyIds = [...new Set(dependencyText.match(/SW-\d{3}/g) || [])]; - if (dependencyIds.length) { - const openIssues = await github.paginate(github.rest.issues.listForRepo, { - owner, repo, state: 'open', per_page: 100, + let labels = new Set(); + let linkedIssueNumber = null; + + if (isDependabot) { + const { classifyDependabotPR } = require('./scripts/pr-guard-policy.cjs'); + let basePackage; + let headPackage; + if (files.some((file) => file.filename === 'package.json')) { + const readPackageAtRef = async (ref) => { + const { data } = await github.rest.repos.getContent({ + owner, repo, path: 'package.json', ref, + }); + if (Array.isArray(data) || data.type !== 'file' || data.encoding !== 'base64') { + throw new Error('Could not read package.json as a base64 file at ' + ref); + } + return JSON.parse(Buffer.from(data.content, 'base64').toString('utf8')); + }; + basePackage = await readPackageAtRef(pr.base.sha); + headPackage = await readPackageAtRef(pr.head.sha); + } + const decision = classifyDependabotPR({ + login: pr.user.login, + title: pr.title, + files, + basePackage, + headPackage, }); - const openWaveIds = new Set( - openIssues - .filter((item) => !item.pull_request && /^SW-\d{3}\b/.test(item.title)) - .map((item) => item.title.match(/^SW-\d{3}/)[0]), - ); - const unresolved = dependencyIds.filter((id) => openWaveIds.has(id)); - if (unresolved.length) { - core.setFailed('Linked issue still has unresolved dependencies: ' + unresolved.join(', ')); + if (!decision.allowed) { + core.setFailed('Dependabot PR rejected by narrow bot policy: ' + decision.reason); return; } + core.info('Validated narrowly scoped Dependabot update (' + decision.kind + '). Issue assignment is not required for this bot-only path; CODEOWNERS and required checks remain mandatory.'); + } else { + const { data: collaborator } = await github.rest.repos.getCollaboratorPermissionLevel({ + owner, repo, username: pr.user.login, + }); + const trustedPermissions = new Set(['admin', 'maintain', 'write']); + if (trustedPermissions.has(collaborator.permission)) { + core.info('Skipping contributor-only Wave checks for repository collaborator PR.'); + return; + } + + const refs = [...body.matchAll(/(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s+#(\d+)/gi)].map((m) => Number(m[1])); + const uniqueRefs = [...new Set(refs)]; + if (uniqueRefs.length !== 1) { + core.setFailed('Wave contributor PRs must use exactly one closing reference such as Closes #123.'); + return; + } + const { data: issue } = await github.rest.issues.get({ owner, repo, issue_number: uniqueRefs[0] }); + labels = new Set(issue.labels.map((label) => label.name)); + if (!labels.has('Stellar Wave')) { + core.setFailed('#' + uniqueRefs[0] + ' is not a Stellar Wave issue.'); + return; + } + if (issue.state !== 'open') { + core.setFailed('Linked Wave issue is not open.'); + return; + } + + const dependencySection = (issue.body || '').split(/## Dependencies/i)[1] || ''; + const dependencyText = dependencySection.split(/\n---|\n## /)[0]; + const dependencyIds = [...new Set(dependencyText.match(/SW-\d{3}/g) || [])]; + if (dependencyIds.length) { + const openIssues = await github.paginate(github.rest.issues.listForRepo, { + owner, repo, state: 'open', per_page: 100, + }); + const openWaveIds = new Set( + openIssues + .filter((item) => !item.pull_request && /^SW-\d{3}\b/.test(item.title)) + .map((item) => item.title.match(/^SW-\d{3}/)[0]), + ); + const unresolved = dependencyIds.filter((id) => openWaveIds.has(id)); + if (unresolved.length) { + core.setFailed('Linked issue still has unresolved dependencies: ' + unresolved.join(', ')); + return; + } + } + + if (!issue.assignees.some((a) => a.login === pr.user.login)) { + core.setFailed('PR author must be accepted through Drips and assigned to the linked Wave issue before merge.'); + return; + } + linkedIssueNumber = issue.number; } - - if (!issue.assignees.some((a) => a.login === pr.user.login)) { - core.setFailed('PR author must be accepted through Drips and assigned to the linked Wave issue before merge.'); - return; - } - - const files = await github.paginate(github.rest.pulls.listFiles, { - owner, repo, pull_number: pr.number, per_page: 100, - }); + const protectedPatterns = [ /^\.github\/workflows\//, /^\.github\/CODEOWNERS$/, /^\.changeset\//, /^docs\/adr\//, /^docs\/architecture\//, @@ -90,7 +134,7 @@ jobs: ]; const protectedFiles = files.map((f) => f.filename) .filter((name) => protectedPatterns.some((pattern) => pattern.test(name))); - + const currentNames = new Set(files.map((file) => file.filename)); const openPulls = await github.paginate(github.rest.pulls.list, { owner, repo, state: 'open', per_page: 100, @@ -114,17 +158,20 @@ jobs: core.setFailed('Potential contributor conflict with open PRs: ' + conflicts.join(' | ')); return; } - - if (protectedFiles.length && !labels.has('protected-surface')) { + + if (!isDependabot && protectedFiles.length && !labels.has('protected-surface')) { core.setFailed('PR touches protected surfaces not declared by the linked issue: ' + protectedFiles.join(', ')); return; } - if (!/##\s+(?:Testing|Tests)/i.test(body)) { + if (!isDependabot && !/##\s+(?:Testing|Tests)/i.test(body)) { core.setFailed('PR body must include a Testing/Tests section.'); return; } - if (!/##\s+Security/i.test(body)) { + if (!isDependabot && !/##\s+Security/i.test(body)) { core.setFailed('PR body must include a Security section.'); return; } - core.info('Validated Wave issue #' + issue.number + ' for PR #' + pr.number + '.'); + core.info(isDependabot + ? 'Validated Dependabot PR #' + pr.number + ' with normal conflict, required-check, and code-owner merge controls retained.' + : 'Validated Wave issue #' + linkedIssueNumber + ' for PR #' + pr.number + '.'); + From ccfcfd9ce29293801b169dc5f690a3fa7d0444ef Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Mon, 16 Nov 2026 14:29:16 +0100 Subject: [PATCH 02/94] test(automation): add strict Dependabot PR policy helper --- scripts/pr-guard-policy.cjs | 116 ++++++++++++++++++++++++++++++++++++ 1 file changed, 116 insertions(+) create mode 100644 scripts/pr-guard-policy.cjs diff --git a/scripts/pr-guard-policy.cjs b/scripts/pr-guard-policy.cjs new file mode 100644 index 00000000..f72cfddf --- /dev/null +++ b/scripts/pr-guard-policy.cjs @@ -0,0 +1,116 @@ +'use strict'; + +const DEPENDABOT_LOGIN = 'dependabot[bot]'; +const DEPENDENCY_TITLE = /^(?:build|chore)\(deps(?:-dev)?\):\s+/i; +const WORKFLOW_PATH = /^\.github\/workflows\/(?:[A-Za-z0-9_.-]+\/)*[A-Za-z0-9_.-]+\.ya?ml$/; +const ACTION_REFERENCE_CHANGE = /^[+-]\s*uses:\s*[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)+@[a-f0-9]{40}(?:\s+#.*)?$/i; +const VERSION_RANGE = /^(?:[~^=]|>=?|<=?)?\s*\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\s*\|\|\s*(?:[~^=]|>=?|<=?)?\s*\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)*$/; + +function deny(reason) { + return { allowed: false, reason }; +} + +function isObject(value) { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +function canonicalize(value) { + if (Array.isArray(value)) return value.map(canonicalize); + if (!isObject(value)) return value; + return Object.fromEntries( + Object.keys(value).sort().map((key) => [key, canonicalize(value[key])]), + ); +} + +function sameJson(left, right) { + return JSON.stringify(canonicalize(left)) === JSON.stringify(canonicalize(right)); +} + +function validatePackageManifest(basePackage, headPackage) { + if (!isObject(basePackage) || !isObject(headPackage)) { + return deny('package.json could not be parsed at both base and head revisions'); + } + + const sections = ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies']; + const baseOutsideDependencies = { ...basePackage }; + const headOutsideDependencies = { ...headPackage }; + for (const section of sections) { + delete baseOutsideDependencies[section]; + delete headOutsideDependencies[section]; + } + if (!sameJson(baseOutsideDependencies, headOutsideDependencies)) { + return deny('package.json changes outside dependency version sections are not allowed'); + } + + let changedVersions = 0; + for (const section of sections) { + const before = basePackage[section] || {}; + const after = headPackage[section] || {}; + if (!isObject(before) || !isObject(after)) { + return deny('dependency sections must remain JSON objects'); + } + const beforeNames = Object.keys(before).sort(); + const afterNames = Object.keys(after).sort(); + if (!sameJson(beforeNames, afterNames)) { + return deny('Dependabot may update existing dependency ranges but may not add or remove dependency names'); + } + for (const name of beforeNames) { + if (before[name] === after[name]) continue; + if (typeof before[name] !== 'string' || typeof after[name] !== 'string' || !VERSION_RANGE.test(after[name])) { + return deny('dependency "' + name + '" changed to a non-semver or non-string specification'); + } + changedVersions += 1; + } + } + + if (changedVersions === 0) { + return deny('package.json contains no dependency version changes'); + } + return { allowed: true, kind: 'npm-dependencies', changedVersions }; +} + +function validateWorkflowPatches(files) { + for (const file of files) { + if (!WORKFLOW_PATH.test(file.filename) || file.status !== 'modified') { + return deny('only modified workflow YAML files are allowed for GitHub Actions updates'); + } + if (typeof file.patch !== 'string' || file.patch.length === 0) { + return deny('workflow patch is unavailable; failing closed because changed lines cannot be verified'); + } + const changedLines = file.patch + .split(/\r?\n/) + .filter((line) => /^[+-]/.test(line) && !line.startsWith('+++') && !line.startsWith('---')); + if (changedLines.length === 0 || changedLines.some((line) => !ACTION_REFERENCE_CHANGE.test(line))) { + return deny('workflow updates may change only pinned 40-character uses: action references'); + } + } + return { allowed: true, kind: 'github-actions', changedFiles: files.length }; +} + +function classifyDependabotPR({ login, title, files, basePackage, headPackage }) { + if (login !== DEPENDABOT_LOGIN) { + return deny('only the exact dependabot[bot] account is eligible'); + } + if (typeof title !== 'string' || !DEPENDENCY_TITLE.test(title)) { + return deny('PR title must use the standard build(deps): or chore(deps): prefix'); + } + if (!Array.isArray(files) || files.length === 0 || files.some((file) => file.status !== 'modified')) { + return deny('Dependabot PR must contain only modified, reviewable files'); + } + + const names = files.map((file) => file.filename).sort(); + const npmFiles = ['package-lock.json', 'package.json']; + if (sameJson(names, npmFiles)) { + const manifest = validatePackageManifest(basePackage, headPackage); + if (!manifest.allowed) return manifest; + return { ...manifest, kind: 'npm-dependencies' }; + } + + if (files.every((file) => WORKFLOW_PATH.test(file.filename))) { + return validateWorkflowPatches(files); + } + + return deny('allowed Dependabot scope is exactly package.json + package-lock.json, or workflow YAML action-reference lines only'); +} + +module.exports = { classifyDependabotPR }; From d8076d5636212739c1a37b38cad0011fd3d71be1 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Mon, 16 Nov 2026 14:29:19 +0100 Subject: [PATCH 03/94] test(automation): cover Dependabot PR guard allowlist --- tests/pr-guard-policy.test.ts | 184 ++++++++++++++++++++++++++++++++++ 1 file changed, 184 insertions(+) create mode 100644 tests/pr-guard-policy.test.ts diff --git a/tests/pr-guard-policy.test.ts b/tests/pr-guard-policy.test.ts new file mode 100644 index 00000000..e469c8c7 --- /dev/null +++ b/tests/pr-guard-policy.test.ts @@ -0,0 +1,184 @@ +import { createRequire } from 'node:module'; +import { describe, expect, it } from 'vitest'; + +type FileChange = { filename: string; status: string; patch?: string }; +type PackageManifest = Record; +type Decision = { allowed: boolean; kind?: string; reason?: string; changedVersions?: number; changedFiles?: number }; + +const require = createRequire(import.meta.url); +const { classifyDependabotPR } = require('../scripts/pr-guard-policy.cjs') as { + classifyDependabotPR(input: { + login: string; + title: string; + files: FileChange[]; + basePackage?: PackageManifest; + headPackage?: PackageManifest; + }): Decision; +}; + +const login = 'dependabot[bot]'; +const npmTitle = 'build(deps): bump dependencies'; +const actionTitle = 'chore(deps): bump github/codeql-action'; +const basePackage = { + name: '@diginodes/stellarforge-cli', + version: '0.1.0', + scripts: { build: 'tsc -p tsconfig.build.json' }, + dependencies: { commander: '15.0.0' }, + devDependencies: { vitest: '5.0.1' }, +}; +const headPackage = { + ...basePackage, + dependencies: { commander: '15.1.0' }, + devDependencies: { vitest: '5.0.2' }, +}; + +describe('Dependabot PR guard policy', () => { + it('allows an npm update limited to dependency ranges in package.json and the lockfile', () => { + const result = classifyDependabotPR({ + login, + title: npmTitle, + files: [ + { filename: 'package.json', status: 'modified' }, + { filename: 'package-lock.json', status: 'modified' }, + ], + basePackage, + headPackage, + }); + expect(result).toMatchObject({ allowed: true, kind: 'npm-dependencies', changedVersions: 2 }); + }); + + it('rejects package manifest changes outside dependency sections', () => { + const changed = { ...headPackage, scripts: { build: 'curl example.invalid | sh' } }; + const result = classifyDependabotPR({ + login, + title: npmTitle, + files: [ + { filename: 'package.json', status: 'modified' }, + { filename: 'package-lock.json', status: 'modified' }, + ], + basePackage, + headPackage: changed, + }); + expect(result.allowed).toBe(false); + expect(result.reason).toMatch(/outside dependency version sections/); + }); + + it('rejects adding or removing dependency names', () => { + const changed = { + ...headPackage, + dependencies: { commander: '15.1.0', 'unexpected-package': '1.2.3' }, + }; + const result = classifyDependabotPR({ + login, + title: npmTitle, + files: [ + { filename: 'package.json', status: 'modified' }, + { filename: 'package-lock.json', status: 'modified' }, + ], + basePackage, + headPackage: changed, + }); + expect(result.allowed).toBe(false); + expect(result.reason).toMatch(/may not add or remove/); + }); + + it('rejects a package-only or source-code-changing Dependabot PR', () => { + const packageOnly = classifyDependabotPR({ + login, + title: npmTitle, + files: [{ filename: 'package.json', status: 'modified' }], + basePackage, + headPackage, + }); + const sourceChange = classifyDependabotPR({ + login, + title: npmTitle, + files: [ + { filename: 'package.json', status: 'modified' }, + { filename: 'package-lock.json', status: 'modified' }, + { filename: 'src/cli.ts', status: 'modified' }, + ], + basePackage, + headPackage, + }); + expect(packageOnly.allowed).toBe(false); + expect(sourceChange.allowed).toBe(false); + }); + + it('allows workflow changes only when every changed line is a pinned action reference', () => { + const patch = [ + '@@ -10,1 +10,1 @@', + '- uses: github/codeql-action/init@aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa # v4.38.2', + '+ uses: github/codeql-action/init@bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb # v4.39.0', + ].join('\n'); + const result = classifyDependabotPR({ + login, + title: actionTitle, + files: [{ filename: '.github/workflows/ci.yml', status: 'modified', patch }], + }); + expect(result).toMatchObject({ allowed: true, kind: 'github-actions', changedFiles: 1 }); + }); + + it('rejects workflow logic, permission, or unpinned-reference changes', () => { + const mixedPatch = [ + '@@ -10,1 +10,2 @@', + '- uses: github/codeql-action/init@aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa # v4.38.2', + '+ uses: github/codeql-action/init@bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb # v4.39.0', + '+ permissions: contents: write', + ].join('\n'); + const unpinnedPatch = [ + '@@ -10,1 +10,1 @@', + '- uses: github/codeql-action/init@v4.38.2', + '+ uses: github/codeql-action/init@v4.39.0', + ].join('\n'); + const mixed = classifyDependabotPR({ + login, + title: actionTitle, + files: [{ filename: '.github/workflows/ci.yml', status: 'modified', patch: mixedPatch }], + }); + const unpinned = classifyDependabotPR({ + login, + title: actionTitle, + files: [{ filename: '.github/workflows/ci.yml', status: 'modified', patch: unpinnedPatch }], + }); + expect(mixed.allowed).toBe(false); + expect(unpinned.allowed).toBe(false); + }); + + it('fails closed for missing patches, unrelated files, non-bot authors, and non-dependency titles', () => { + const missingPatch = classifyDependabotPR({ + login, + title: actionTitle, + files: [{ filename: '.github/workflows/ci.yml', status: 'modified' }], + }); + const unrelated = classifyDependabotPR({ + login, + title: actionTitle, + files: [{ filename: 'src/cli.ts', status: 'modified' }], + }); + const wrongAuthor = classifyDependabotPR({ + login: 'ordinary-contributor', + title: npmTitle, + files: [ + { filename: 'package.json', status: 'modified' }, + { filename: 'package-lock.json', status: 'modified' }, + ], + basePackage, + headPackage, + }); + const wrongTitle = classifyDependabotPR({ + login, + title: 'feat: add a new feature', + files: [ + { filename: 'package.json', status: 'modified' }, + { filename: 'package-lock.json', status: 'modified' }, + ], + basePackage, + headPackage, + }); + expect(missingPatch.allowed).toBe(false); + expect(unrelated.allowed).toBe(false); + expect(wrongAuthor.allowed).toBe(false); + expect(wrongTitle.allowed).toBe(false); + }); +}); From 6edd2256f9627c113a19ac80034b32eb3fb0fa47 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Mon, 16 Nov 2026 14:29:22 +0100 Subject: [PATCH 04/94] docs(automation): document narrow Dependabot PR policy --- docs/contributing/repository-ruleset.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/docs/contributing/repository-ruleset.md b/docs/contributing/repository-ruleset.md index 93671937..25f1b48c 100644 --- a/docs/contributing/repository-ruleset.md +++ b/docs/contributing/repository-ruleset.md @@ -113,3 +113,15 @@ Before considering the ruleset complete, verify: Whenever workflow names, job names, CODEOWNERS boundaries, or security policy change, review this document and the actual GitHub ruleset together. A renamed required job can block all merges if the ruleset still points to the old status-check name. Ruleset changes therefore require the same care as CI/security workflow changes. + + +## Automated Dependency Pull Requests + +Dependabot is exempt only from the contributor-specific Stellar Wave issue/Drips assignment requirements, and only for two narrowly defined update classes: + +- npm updates that modify exactly \`package.json\` and \`package-lock.json\`, changing existing dependency version ranges only; +- GitHub Actions updates that modify workflow YAML files and change only immutable, 40-character-SHA \`uses:\` references. + +The Contributor PR Guard validates this allowlist and continues to run protected-file overlap detection. It rejects source, migration, release, permission, script, unrelated workflow, and other out-of-scope changes from the bot. + +This exception does **not** grant merge permission. Normal CI/security checks, branch protection, CODEOWNERS review, stale-approval dismissal, and conversation resolution remain mandatory. Dependabot PRs must never receive write-token or auto-merge privileges through this exception. From 340dba4d7cad8273be6076ab1dc44b1b9cca271c Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Mon, 16 Nov 2026 14:32:28 +0100 Subject: [PATCH 05/94] fix(automation): restrict action updates to SHA-only changes --- scripts/pr-guard-policy.cjs | 40 ++++++++++++++++++++++++++++++++----- 1 file changed, 35 insertions(+), 5 deletions(-) diff --git a/scripts/pr-guard-policy.cjs b/scripts/pr-guard-policy.cjs index f72cfddf..0c110de9 100644 --- a/scripts/pr-guard-policy.cjs +++ b/scripts/pr-guard-policy.cjs @@ -3,8 +3,7 @@ const DEPENDABOT_LOGIN = 'dependabot[bot]'; const DEPENDENCY_TITLE = /^(?:build|chore)\(deps(?:-dev)?\):\s+/i; const WORKFLOW_PATH = /^\.github\/workflows\/(?:[A-Za-z0-9_.-]+\/)*[A-Za-z0-9_.-]+\.ya?ml$/; -const ACTION_REFERENCE_CHANGE = /^[+-]\s*uses:\s*[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)+@[a-f0-9]{40}(?:\s+#.*)?$/i; -const VERSION_RANGE = /^(?:[~^=]|>=?|<=?)?\s*\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\s*\|\|\s*(?:[~^=]|>=?|<=?)?\s*\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)*$/; +const ACTION_REFERENCE_CHANGE = /^[+-]\\s*uses:\\s*([A-Za-z0-9_.-]+(?:\\/[A-Za-z0-9_.-]+)+)@([a-f0-9]{40})(?:\\s+#.*)?$/i;\nconst VERSION_RANGE = /^(?:[~^=]|>=?|<=?)?\s*\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\s*\|\|\s*(?:[~^=]|>=?|<=?)?\s*\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)*$/; function deny(reason) { return { allowed: false, reason }; @@ -70,6 +69,9 @@ function validatePackageManifest(basePackage, headPackage) { } function validateWorkflowPatches(files) { + const removed = []; + const added = []; + for (const file of files) { if (!WORKFLOW_PATH.test(file.filename) || file.status !== 'modified') { return deny('only modified workflow YAML files are allowed for GitHub Actions updates'); @@ -80,13 +82,40 @@ function validateWorkflowPatches(files) { const changedLines = file.patch .split(/\r?\n/) .filter((line) => /^[+-]/.test(line) && !line.startsWith('+++') && !line.startsWith('---')); - if (changedLines.length === 0 || changedLines.some((line) => !ACTION_REFERENCE_CHANGE.test(line))) { - return deny('workflow updates may change only pinned 40-character uses: action references'); + if (changedLines.length === 0) { + return deny('workflow patch contains no action-reference changes'); + } + for (const line of changedLines) { + const match = line.match(ACTION_REFERENCE_CHANGE); + if (!match) { + return deny('workflow updates may change only pinned 40-character uses: action references'); + } + const reference = { name: match[1], sha: match[2].toLowerCase() }; + if (line.startsWith('-')) removed.push(reference); + else added.push(reference); } } + + if (removed.length === 0 || removed.length !== added.length) { + return deny('workflow updates must replace existing action references, not add or remove steps'); + } + const oldNames = removed.map((reference) => reference.name).sort(); + const newNames = added.map((reference) => reference.name).sort(); + if (!sameJson(oldNames, newNames)) { + return deny('workflow updates may change an action SHA but may not replace the action identity'); + } + + const names = [...new Set(oldNames)]; + for (const name of names) { + const oldShas = removed.filter((reference) => reference.name === name).map((reference) => reference.sha).sort(); + const newShas = added.filter((reference) => reference.name === name).map((reference) => reference.sha).sort(); + if (sameJson(oldShas, newShas)) { + return deny('workflow action ' + name + ' has no pinned SHA update'); + } + } + return { allowed: true, kind: 'github-actions', changedFiles: files.length }; } - function classifyDependabotPR({ login, title, files, basePackage, headPackage }) { if (login !== DEPENDABOT_LOGIN) { return deny('only the exact dependabot[bot] account is eligible'); @@ -113,4 +142,5 @@ function classifyDependabotPR({ login, title, files, basePackage, headPackage }) return deny('allowed Dependabot scope is exactly package.json + package-lock.json, or workflow YAML action-reference lines only'); } +/* global module */ module.exports = { classifyDependabotPR }; From 335989c02bf61df3d3fd38872439812fc6329953 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Mon, 16 Nov 2026 14:32:30 +0100 Subject: [PATCH 06/94] test(automation): reject action identity replacement --- tests/pr-guard-policy.test.ts | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/tests/pr-guard-policy.test.ts b/tests/pr-guard-policy.test.ts index e469c8c7..4e5d4bea 100644 --- a/tests/pr-guard-policy.test.ts +++ b/tests/pr-guard-policy.test.ts @@ -119,6 +119,21 @@ describe('Dependabot PR guard policy', () => { expect(result).toMatchObject({ allowed: true, kind: 'github-actions', changedFiles: 1 }); }); + it('rejects replacing an action identity even when both references are pinned', () => { + const replacementPatch = [ + '@@ -10,1 +10,1 @@', + '- uses: actions/checkout@aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa # v7.0.1', + '+ uses: attacker/unknown-action@bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb # v1.0.0', + ].join('\n'); + const result = classifyDependabotPR({ + login, + title: actionTitle, + files: [{ filename: '.github/workflows/ci.yml', status: 'modified', patch: replacementPatch }], + }); + expect(result.allowed).toBe(false); + expect(result.reason).toMatch(/may not replace the action identity/); + }); + it('rejects workflow logic, permission, or unpinned-reference changes', () => { const mixedPatch = [ '@@ -10,1 +10,2 @@', From 7018c60cec3deaa7c0ee40b4ee6eabeb209928c6 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Mon, 16 Nov 2026 14:32:32 +0100 Subject: [PATCH 07/94] docs(automation): clean Dependabot policy formatting --- docs/contributing/repository-ruleset.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/docs/contributing/repository-ruleset.md b/docs/contributing/repository-ruleset.md index 25f1b48c..75d6281e 100644 --- a/docs/contributing/repository-ruleset.md +++ b/docs/contributing/repository-ruleset.md @@ -114,13 +114,12 @@ Whenever workflow names, job names, CODEOWNERS boundaries, or security policy ch A renamed required job can block all merges if the ruleset still points to the old status-check name. Ruleset changes therefore require the same care as CI/security workflow changes. - ## Automated Dependency Pull Requests Dependabot is exempt only from the contributor-specific Stellar Wave issue/Drips assignment requirements, and only for two narrowly defined update classes: -- npm updates that modify exactly \`package.json\` and \`package-lock.json\`, changing existing dependency version ranges only; -- GitHub Actions updates that modify workflow YAML files and change only immutable, 40-character-SHA \`uses:\` references. +- npm updates that modify exactly `package.json` and `package-lock.json`, changing existing dependency version ranges only; +- GitHub Actions updates that modify workflow YAML files and change only immutable, 40-character-SHA `uses:` references. The Contributor PR Guard validates this allowlist and continues to run protected-file overlap detection. It rejects source, migration, release, permission, script, unrelated workflow, and other out-of-scope changes from the bot. From 50bd76e928f9709a9883e51afd0ed1c423b33047 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Mon, 16 Nov 2026 14:32:35 +0100 Subject: [PATCH 08/94] style(automation): normalize blank lines in PR guard workflow --- .github/workflows/wave-pr-guard.yml | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/.github/workflows/wave-pr-guard.yml b/.github/workflows/wave-pr-guard.yml index 9404dc08..97836d2a 100644 --- a/.github/workflows/wave-pr-guard.yml +++ b/.github/workflows/wave-pr-guard.yml @@ -34,14 +34,14 @@ jobs: core.info('Skipping contributor-only Wave checks for trusted maintainer PR.'); return; } - + const isDependabot = pr.user.login === 'dependabot[bot]'; const files = await github.paginate(github.rest.pulls.listFiles, { owner, repo, pull_number: pr.number, per_page: 100, }); let labels = new Set(); let linkedIssueNumber = null; - + if (isDependabot) { const { classifyDependabotPR } = require('./scripts/pr-guard-policy.cjs'); let basePackage; @@ -80,7 +80,7 @@ jobs: core.info('Skipping contributor-only Wave checks for repository collaborator PR.'); return; } - + const refs = [...body.matchAll(/(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s+#(\d+)/gi)].map((m) => Number(m[1])); const uniqueRefs = [...new Set(refs)]; if (uniqueRefs.length !== 1) { @@ -97,7 +97,7 @@ jobs: core.setFailed('Linked Wave issue is not open.'); return; } - + const dependencySection = (issue.body || '').split(/## Dependencies/i)[1] || ''; const dependencyText = dependencySection.split(/\n---|\n## /)[0]; const dependencyIds = [...new Set(dependencyText.match(/SW-\d{3}/g) || [])]; @@ -116,14 +116,14 @@ jobs: return; } } - + if (!issue.assignees.some((a) => a.login === pr.user.login)) { core.setFailed('PR author must be accepted through Drips and assigned to the linked Wave issue before merge.'); return; } linkedIssueNumber = issue.number; } - + const protectedPatterns = [ /^\.github\/workflows\//, /^\.github\/CODEOWNERS$/, /^\.changeset\//, /^docs\/adr\//, /^docs\/architecture\//, @@ -134,7 +134,7 @@ jobs: ]; const protectedFiles = files.map((f) => f.filename) .filter((name) => protectedPatterns.some((pattern) => pattern.test(name))); - + const currentNames = new Set(files.map((file) => file.filename)); const openPulls = await github.paginate(github.rest.pulls.list, { owner, repo, state: 'open', per_page: 100, @@ -158,7 +158,7 @@ jobs: core.setFailed('Potential contributor conflict with open PRs: ' + conflicts.join(' | ')); return; } - + if (!isDependabot && protectedFiles.length && !labels.has('protected-surface')) { core.setFailed('PR touches protected surfaces not declared by the linked issue: ' + protectedFiles.join(', ')); return; @@ -174,4 +174,4 @@ jobs: core.info(isDependabot ? 'Validated Dependabot PR #' + pr.number + ' with normal conflict, required-check, and code-owner merge controls retained.' : 'Validated Wave issue #' + linkedIssueNumber + ' for PR #' + pr.number + '.'); - + From 92cc12e8781c1aaaca2fd651dc3ed81afd2aaef7 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Mon, 16 Nov 2026 14:33:18 +0100 Subject: [PATCH 09/94] fix(automation): correct pinned action reference parser --- scripts/pr-guard-policy.cjs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/scripts/pr-guard-policy.cjs b/scripts/pr-guard-policy.cjs index 0c110de9..a89031a0 100644 --- a/scripts/pr-guard-policy.cjs +++ b/scripts/pr-guard-policy.cjs @@ -3,7 +3,8 @@ const DEPENDABOT_LOGIN = 'dependabot[bot]'; const DEPENDENCY_TITLE = /^(?:build|chore)\(deps(?:-dev)?\):\s+/i; const WORKFLOW_PATH = /^\.github\/workflows\/(?:[A-Za-z0-9_.-]+\/)*[A-Za-z0-9_.-]+\.ya?ml$/; -const ACTION_REFERENCE_CHANGE = /^[+-]\\s*uses:\\s*([A-Za-z0-9_.-]+(?:\\/[A-Za-z0-9_.-]+)+)@([a-f0-9]{40})(?:\\s+#.*)?$/i;\nconst VERSION_RANGE = /^(?:[~^=]|>=?|<=?)?\s*\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\s*\|\|\s*(?:[~^=]|>=?|<=?)?\s*\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)*$/; +const ACTION_REFERENCE_CHANGE = /^[+-]\s*uses:\s*([A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)+)@([a-f0-9]{40})(?:\s+#.*)?$/i; +const VERSION_RANGE = /^(?:[~^=]|>=?|<=?)?\s*\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\s*\|\|\s*(?:[~^=]|>=?|<=?)?\s*\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)*$/; function deny(reason) { return { allowed: false, reason }; From d2a65993183fd70e1be6a71cc16e4eddcff269ca Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Mon, 16 Nov 2026 14:34:21 +0100 Subject: [PATCH 10/94] fix(automation): bind action updates to same workflow file --- scripts/pr-guard-policy.cjs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/scripts/pr-guard-policy.cjs b/scripts/pr-guard-policy.cjs index a89031a0..38fe21b4 100644 --- a/scripts/pr-guard-policy.cjs +++ b/scripts/pr-guard-policy.cjs @@ -91,7 +91,7 @@ function validateWorkflowPatches(files) { if (!match) { return deny('workflow updates may change only pinned 40-character uses: action references'); } - const reference = { name: match[1], sha: match[2].toLowerCase() }; + const reference = { filename: file.filename, name: match[1], sha: match[2].toLowerCase() }; if (line.startsWith('-')) removed.push(reference); else added.push(reference); } @@ -117,11 +117,11 @@ function validateWorkflowPatches(files) { return { allowed: true, kind: 'github-actions', changedFiles: files.length }; } -function classifyDependabotPR({ login, title, files, basePackage, headPackage }) { +function classifyDependabotPR({ login, title, baseRef, files, basePackage, headPackage }) { if (login !== DEPENDABOT_LOGIN) { return deny('only the exact dependabot[bot] account is eligible'); } - if (typeof title !== 'string' || !DEPENDENCY_TITLE.test(title)) { + if (baseRef !== 'main') {\n return deny('Dependabot updates are allowed only when targeting main');\n }\n if (typeof title !== 'string' || !DEPENDENCY_TITLE.test(title)) { return deny('PR title must use the standard build(deps): or chore(deps): prefix'); } if (!Array.isArray(files) || files.length === 0 || files.some((file) => file.status !== 'modified')) { From 4c6510fed96127941b288569c368a302af08c411 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Mon, 16 Nov 2026 14:34:24 +0100 Subject: [PATCH 11/94] test(automation): reject Dependabot PRs outside main --- tests/pr-guard-policy.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/pr-guard-policy.test.ts b/tests/pr-guard-policy.test.ts index 4e5d4bea..8109dad7 100644 --- a/tests/pr-guard-policy.test.ts +++ b/tests/pr-guard-policy.test.ts @@ -194,6 +194,6 @@ describe('Dependabot PR guard policy', () => { expect(missingPatch.allowed).toBe(false); expect(unrelated.allowed).toBe(false); expect(wrongAuthor.allowed).toBe(false); - expect(wrongTitle.allowed).toBe(false); + expect(wrongTitle.allowed).toBe(false);\n\n const wrongBase = classifyDependabotPR({\n login,\n title: npmTitle,\n baseRef: 'release',\n files: [\n { filename: 'package.json', status: 'modified' },\n { filename: 'package-lock.json', status: 'modified' },\n ],\n basePackage,\n headPackage,\n });\n expect(wrongBase.allowed).toBe(false); }); }); From 630ec81177255916b82731771420fae280f9a345 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Mon, 16 Nov 2026 14:34:27 +0100 Subject: [PATCH 12/94] fix(automation): scope Dependabot exception to main From 096234f9a0376edeb31c69fccc08d9c2c7d43901 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Mon, 16 Nov 2026 14:35:35 +0100 Subject: [PATCH 13/94] fix(automation): enforce exact Dependabot scope and action identity --- scripts/pr-guard-policy.cjs | 121 ++++++++++++++++++++++++++++-------- 1 file changed, 96 insertions(+), 25 deletions(-) diff --git a/scripts/pr-guard-policy.cjs b/scripts/pr-guard-policy.cjs index 38fe21b4..495d8a47 100644 --- a/scripts/pr-guard-policy.cjs +++ b/scripts/pr-guard-policy.cjs @@ -2,9 +2,12 @@ const DEPENDABOT_LOGIN = 'dependabot[bot]'; const DEPENDENCY_TITLE = /^(?:build|chore)\(deps(?:-dev)?\):\s+/i; -const WORKFLOW_PATH = /^\.github\/workflows\/(?:[A-Za-z0-9_.-]+\/)*[A-Za-z0-9_.-]+\.ya?ml$/; -const ACTION_REFERENCE_CHANGE = /^[+-]\s*uses:\s*([A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)+)@([a-f0-9]{40})(?:\s+#.*)?$/i; -const VERSION_RANGE = /^(?:[~^=]|>=?|<=?)?\s*\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\s*\|\|\s*(?:[~^=]|>=?|<=?)?\s*\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)*$/; +const WORKFLOW_PATH = + /^\.github\/workflows\/(?:[A-Za-z0-9_.-]+\/)*[A-Za-z0-9_.-]+\.ya?ml$/; +const ACTION_REFERENCE_CHANGE = + /^[+-]\s*uses:\s*([A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)+)@([a-f0-9]{40})(?:\s+#.*)?$/i; +const VERSION_RANGE = + /^(?:[~^=]|>=?|<=?)?\s*\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\s*\|\|\s*(?:[~^=]|>=?|<=?)?\s*\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)*$/; function deny(reason) { return { allowed: false, reason }; @@ -18,7 +21,9 @@ function canonicalize(value) { if (Array.isArray(value)) return value.map(canonicalize); if (!isObject(value)) return value; return Object.fromEntries( - Object.keys(value).sort().map((key) => [key, canonicalize(value[key])]), + Object.keys(value) + .sort() + .map((key) => [key, canonicalize(value[key])]), ); } @@ -31,7 +36,12 @@ function validatePackageManifest(basePackage, headPackage) { return deny('package.json could not be parsed at both base and head revisions'); } - const sections = ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies']; + const sections = [ + 'dependencies', + 'devDependencies', + 'optionalDependencies', + 'peerDependencies', + ]; const baseOutsideDependencies = { ...basePackage }; const headOutsideDependencies = { ...headPackage }; for (const section of sections) { @@ -49,15 +59,23 @@ function validatePackageManifest(basePackage, headPackage) { if (!isObject(before) || !isObject(after)) { return deny('dependency sections must remain JSON objects'); } + const beforeNames = Object.keys(before).sort(); const afterNames = Object.keys(after).sort(); if (!sameJson(beforeNames, afterNames)) { return deny('Dependabot may update existing dependency ranges but may not add or remove dependency names'); } + for (const name of beforeNames) { if (before[name] === after[name]) continue; - if (typeof before[name] !== 'string' || typeof after[name] !== 'string' || !VERSION_RANGE.test(after[name])) { - return deny('dependency "' + name + '" changed to a non-semver or non-string specification'); + if ( + typeof before[name] !== 'string' || + typeof after[name] !== 'string' || + !VERSION_RANGE.test(after[name]) + ) { + return deny( + 'dependency "' + name + '" changed to a non-semver or non-string specification', + ); } changedVersions += 1; } @@ -78,53 +96,104 @@ function validateWorkflowPatches(files) { return deny('only modified workflow YAML files are allowed for GitHub Actions updates'); } if (typeof file.patch !== 'string' || file.patch.length === 0) { - return deny('workflow patch is unavailable; failing closed because changed lines cannot be verified'); + return deny( + 'workflow patch is unavailable; failing closed because changed lines cannot be verified', + ); } + const changedLines = file.patch .split(/\r?\n/) - .filter((line) => /^[+-]/.test(line) && !line.startsWith('+++') && !line.startsWith('---')); + .filter( + (line) => + /^[+-]/.test(line) && + !line.startsWith('+++') && + !line.startsWith('---'), + ); if (changedLines.length === 0) { return deny('workflow patch contains no action-reference changes'); } + for (const line of changedLines) { const match = line.match(ACTION_REFERENCE_CHANGE); if (!match) { - return deny('workflow updates may change only pinned 40-character uses: action references'); + return deny( + 'workflow updates may change only pinned 40-character uses: action references', + ); } - const reference = { filename: file.filename, name: match[1], sha: match[2].toLowerCase() }; + const reference = { + filename: file.filename, + name: match[1], + sha: match[2].toLowerCase(), + }; if (line.startsWith('-')) removed.push(reference); else added.push(reference); } } if (removed.length === 0 || removed.length !== added.length) { - return deny('workflow updates must replace existing action references, not add or remove steps'); + return deny( + 'workflow updates must replace existing action references, not add or remove steps', + ); } - const oldNames = removed.map((reference) => reference.name).sort(); - const newNames = added.map((reference) => reference.name).sort(); - if (!sameJson(oldNames, newNames)) { - return deny('workflow updates may change an action SHA but may not replace the action identity'); + + const oldIdentities = removed + .map((reference) => reference.filename + '|' + reference.name) + .sort(); + const newIdentities = added + .map((reference) => reference.filename + '|' + reference.name) + .sort(); + if (!sameJson(oldIdentities, newIdentities)) { + return deny( + 'workflow updates may change an action SHA but may not move or replace the action identity', + ); } - const names = [...new Set(oldNames)]; - for (const name of names) { - const oldShas = removed.filter((reference) => reference.name === name).map((reference) => reference.sha).sort(); - const newShas = added.filter((reference) => reference.name === name).map((reference) => reference.sha).sort(); + const identities = [...new Set(oldIdentities)]; + for (const identity of identities) { + const oldShas = removed + .filter( + (reference) => + reference.filename + '|' + reference.name === identity, + ) + .map((reference) => reference.sha) + .sort(); + const newShas = added + .filter( + (reference) => + reference.filename + '|' + reference.name === identity, + ) + .map((reference) => reference.sha) + .sort(); if (sameJson(oldShas, newShas)) { - return deny('workflow action ' + name + ' has no pinned SHA update'); + return deny('workflow action ' + identity + ' has no pinned SHA update'); } } return { allowed: true, kind: 'github-actions', changedFiles: files.length }; } -function classifyDependabotPR({ login, title, baseRef, files, basePackage, headPackage }) { + +function classifyDependabotPR({ + login, + title, + baseRef, + files, + basePackage, + headPackage, +}) { if (login !== DEPENDABOT_LOGIN) { return deny('only the exact dependabot[bot] account is eligible'); } - if (baseRef !== 'main') {\n return deny('Dependabot updates are allowed only when targeting main');\n }\n if (typeof title !== 'string' || !DEPENDENCY_TITLE.test(title)) { + if (baseRef !== 'main') { + return deny('Dependabot updates are allowed only when targeting main'); + } + if (typeof title !== 'string' || !DEPENDENCY_TITLE.test(title)) { return deny('PR title must use the standard build(deps): or chore(deps): prefix'); } - if (!Array.isArray(files) || files.length === 0 || files.some((file) => file.status !== 'modified')) { + if ( + !Array.isArray(files) || + files.length === 0 || + files.some((file) => file.status !== 'modified') + ) { return deny('Dependabot PR must contain only modified, reviewable files'); } @@ -140,7 +209,9 @@ function classifyDependabotPR({ login, title, baseRef, files, basePackage, headP return validateWorkflowPatches(files); } - return deny('allowed Dependabot scope is exactly package.json + package-lock.json, or workflow YAML action-reference lines only'); + return deny( + 'allowed Dependabot scope is exactly package.json + package-lock.json, or workflow YAML action-reference lines only', + ); } /* global module */ From 2a997ddc65e492d0ac93e1159b51ee1cd650f396 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Mon, 16 Nov 2026 14:35:39 +0100 Subject: [PATCH 14/94] test(automation): cover strict Dependabot scope boundaries --- tests/pr-guard-policy.test.ts | 98 ++++++++++++++++++++++++++++------- 1 file changed, 80 insertions(+), 18 deletions(-) diff --git a/tests/pr-guard-policy.test.ts b/tests/pr-guard-policy.test.ts index 8109dad7..cf4956f8 100644 --- a/tests/pr-guard-policy.test.ts +++ b/tests/pr-guard-policy.test.ts @@ -1,15 +1,26 @@ import { createRequire } from 'node:module'; import { describe, expect, it } from 'vitest'; -type FileChange = { filename: string; status: string; patch?: string }; +type FileChange = { + filename: string; + status: string; + patch?: string; +}; type PackageManifest = Record; -type Decision = { allowed: boolean; kind?: string; reason?: string; changedVersions?: number; changedFiles?: number }; +type Decision = { + allowed: boolean; + kind?: string; + reason?: string; + changedVersions?: number; + changedFiles?: number; +}; const require = createRequire(import.meta.url); const { classifyDependabotPR } = require('../scripts/pr-guard-policy.cjs') as { classifyDependabotPR(input: { login: string; title: string; + baseRef: string; files: FileChange[]; basePackage?: PackageManifest; headPackage?: PackageManifest; @@ -17,6 +28,7 @@ const { classifyDependabotPR } = require('../scripts/pr-guard-policy.cjs') as { }; const login = 'dependabot[bot]'; +const baseRef = 'main'; const npmTitle = 'build(deps): bump dependencies'; const actionTitle = 'chore(deps): bump github/codeql-action'; const basePackage = { @@ -33,10 +45,11 @@ const headPackage = { }; describe('Dependabot PR guard policy', () => { - it('allows an npm update limited to dependency ranges in package.json and the lockfile', () => { + it('allows npm updates limited to dependency ranges and the lockfile', () => { const result = classifyDependabotPR({ login, title: npmTitle, + baseRef, files: [ { filename: 'package.json', status: 'modified' }, { filename: 'package-lock.json', status: 'modified' }, @@ -44,14 +57,22 @@ describe('Dependabot PR guard policy', () => { basePackage, headPackage, }); - expect(result).toMatchObject({ allowed: true, kind: 'npm-dependencies', changedVersions: 2 }); + expect(result).toMatchObject({ + allowed: true, + kind: 'npm-dependencies', + changedVersions: 2, + }); }); it('rejects package manifest changes outside dependency sections', () => { - const changed = { ...headPackage, scripts: { build: 'curl example.invalid | sh' } }; + const changed = { + ...headPackage, + scripts: { build: 'curl example.invalid | sh' }, + }; const result = classifyDependabotPR({ login, title: npmTitle, + baseRef, files: [ { filename: 'package.json', status: 'modified' }, { filename: 'package-lock.json', status: 'modified' }, @@ -66,11 +87,15 @@ describe('Dependabot PR guard policy', () => { it('rejects adding or removing dependency names', () => { const changed = { ...headPackage, - dependencies: { commander: '15.1.0', 'unexpected-package': '1.2.3' }, + dependencies: { + commander: '15.1.0', + 'unexpected-package': '1.2.3', + }, }; const result = classifyDependabotPR({ login, title: npmTitle, + baseRef, files: [ { filename: 'package.json', status: 'modified' }, { filename: 'package-lock.json', status: 'modified' }, @@ -82,10 +107,11 @@ describe('Dependabot PR guard policy', () => { expect(result.reason).toMatch(/may not add or remove/); }); - it('rejects a package-only or source-code-changing Dependabot PR', () => { + it('rejects package-only or source-code-changing bot PRs', () => { const packageOnly = classifyDependabotPR({ login, title: npmTitle, + baseRef, files: [{ filename: 'package.json', status: 'modified' }], basePackage, headPackage, @@ -93,6 +119,7 @@ describe('Dependabot PR guard policy', () => { const sourceChange = classifyDependabotPR({ login, title: npmTitle, + baseRef, files: [ { filename: 'package.json', status: 'modified' }, { filename: 'package-lock.json', status: 'modified' }, @@ -105,7 +132,7 @@ describe('Dependabot PR guard policy', () => { expect(sourceChange.allowed).toBe(false); }); - it('allows workflow changes only when every changed line is a pinned action reference', () => { + it('allows pinned action SHA updates without changing the action identity', () => { const patch = [ '@@ -10,1 +10,1 @@', '- uses: github/codeql-action/init@aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa # v4.38.2', @@ -114,13 +141,20 @@ describe('Dependabot PR guard policy', () => { const result = classifyDependabotPR({ login, title: actionTitle, - files: [{ filename: '.github/workflows/ci.yml', status: 'modified', patch }], + baseRef, + files: [ + { filename: '.github/workflows/ci.yml', status: 'modified', patch }, + ], + }); + expect(result).toMatchObject({ + allowed: true, + kind: 'github-actions', + changedFiles: 1, }); - expect(result).toMatchObject({ allowed: true, kind: 'github-actions', changedFiles: 1 }); }); it('rejects replacing an action identity even when both references are pinned', () => { - const replacementPatch = [ + const patch = [ '@@ -10,1 +10,1 @@', '- uses: actions/checkout@aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa # v7.0.1', '+ uses: attacker/unknown-action@bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb # v1.0.0', @@ -128,10 +162,13 @@ describe('Dependabot PR guard policy', () => { const result = classifyDependabotPR({ login, title: actionTitle, - files: [{ filename: '.github/workflows/ci.yml', status: 'modified', patch: replacementPatch }], + baseRef, + files: [ + { filename: '.github/workflows/ci.yml', status: 'modified', patch }, + ], }); expect(result.allowed).toBe(false); - expect(result.reason).toMatch(/may not replace the action identity/); + expect(result.reason).toMatch(/may not move or replace/); }); it('rejects workflow logic, permission, or unpinned-reference changes', () => { @@ -149,31 +186,42 @@ describe('Dependabot PR guard policy', () => { const mixed = classifyDependabotPR({ login, title: actionTitle, - files: [{ filename: '.github/workflows/ci.yml', status: 'modified', patch: mixedPatch }], + baseRef, + files: [ + { filename: '.github/workflows/ci.yml', status: 'modified', patch: mixedPatch }, + ], }); const unpinned = classifyDependabotPR({ login, title: actionTitle, - files: [{ filename: '.github/workflows/ci.yml', status: 'modified', patch: unpinnedPatch }], + baseRef, + files: [ + { filename: '.github/workflows/ci.yml', status: 'modified', patch: unpinnedPatch }, + ], }); expect(mixed.allowed).toBe(false); expect(unpinned.allowed).toBe(false); }); - it('fails closed for missing patches, unrelated files, non-bot authors, and non-dependency titles', () => { + it('fails closed for missing patches, unrelated files, non-bot authors, titles, and branches', () => { const missingPatch = classifyDependabotPR({ login, title: actionTitle, - files: [{ filename: '.github/workflows/ci.yml', status: 'modified' }], + baseRef, + files: [ + { filename: '.github/workflows/ci.yml', status: 'modified' }, + ], }); const unrelated = classifyDependabotPR({ login, title: actionTitle, + baseRef, files: [{ filename: 'src/cli.ts', status: 'modified' }], }); const wrongAuthor = classifyDependabotPR({ login: 'ordinary-contributor', title: npmTitle, + baseRef, files: [ { filename: 'package.json', status: 'modified' }, { filename: 'package-lock.json', status: 'modified' }, @@ -184,6 +232,18 @@ describe('Dependabot PR guard policy', () => { const wrongTitle = classifyDependabotPR({ login, title: 'feat: add a new feature', + baseRef, + files: [ + { filename: 'package.json', status: 'modified' }, + { filename: 'package-lock.json', status: 'modified' }, + ], + basePackage, + headPackage, + }); + const wrongBase = classifyDependabotPR({ + login, + title: npmTitle, + baseRef: 'release', files: [ { filename: 'package.json', status: 'modified' }, { filename: 'package-lock.json', status: 'modified' }, @@ -191,9 +251,11 @@ describe('Dependabot PR guard policy', () => { basePackage, headPackage, }); + expect(missingPatch.allowed).toBe(false); expect(unrelated.allowed).toBe(false); expect(wrongAuthor.allowed).toBe(false); - expect(wrongTitle.allowed).toBe(false);\n\n const wrongBase = classifyDependabotPR({\n login,\n title: npmTitle,\n baseRef: 'release',\n files: [\n { filename: 'package.json', status: 'modified' },\n { filename: 'package-lock.json', status: 'modified' },\n ],\n basePackage,\n headPackage,\n });\n expect(wrongBase.allowed).toBe(false); + expect(wrongTitle.allowed).toBe(false); + expect(wrongBase.allowed).toBe(false); }); }); From 04314855750a0505b35970b0e80a231e381bd0f1 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Mon, 16 Nov 2026 14:36:44 +0100 Subject: [PATCH 15/94] fix(automation): validate Dependabot base branch --- .github/workflows/wave-pr-guard.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/wave-pr-guard.yml b/.github/workflows/wave-pr-guard.yml index 97836d2a..5c05c5f2 100644 --- a/.github/workflows/wave-pr-guard.yml +++ b/.github/workflows/wave-pr-guard.yml @@ -62,6 +62,7 @@ jobs: const decision = classifyDependabotPR({ login: pr.user.login, title: pr.title, + baseRef: pr.base.ref, files, basePackage, headPackage, From b09e10dda3de64260094490efa3c7e8f2572ab5a Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Mon, 16 Nov 2026 15:12:05 +0100 Subject: [PATCH 16/94] style: format Dependabot guard policy tests --- tests/pr-guard-policy.test.ts | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/tests/pr-guard-policy.test.ts b/tests/pr-guard-policy.test.ts index cf4956f8..8806f07a 100644 --- a/tests/pr-guard-policy.test.ts +++ b/tests/pr-guard-policy.test.ts @@ -132,7 +132,9 @@ describe('Dependabot PR guard policy', () => { expect(sourceChange.allowed).toBe(false); }); - it('allows pinned action SHA updates without changing the action identity', () => { + it( + 'allows pinned action SHA updates without changing the action identity', + () => { const patch = [ '@@ -10,1 +10,1 @@', '- uses: github/codeql-action/init@aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa # v4.38.2', @@ -153,7 +155,9 @@ describe('Dependabot PR guard policy', () => { }); }); - it('rejects replacing an action identity even when both references are pinned', () => { + it( + 'rejects replacing an action identity even when both references are pinned', + () => { const patch = [ '@@ -10,1 +10,1 @@', '- uses: actions/checkout@aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa # v7.0.1', @@ -171,7 +175,9 @@ describe('Dependabot PR guard policy', () => { expect(result.reason).toMatch(/may not move or replace/); }); - it('rejects workflow logic, permission, or unpinned-reference changes', () => { + it( + 'rejects workflow logic, permission, or unpinned-reference changes', + () => { const mixedPatch = [ '@@ -10,1 +10,2 @@', '- uses: github/codeql-action/init@aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa # v4.38.2', @@ -188,7 +194,11 @@ describe('Dependabot PR guard policy', () => { title: actionTitle, baseRef, files: [ - { filename: '.github/workflows/ci.yml', status: 'modified', patch: mixedPatch }, + { + filename: '.github/workflows/ci.yml', + status: 'modified', + patch: mixedPatch, + }, ], }); const unpinned = classifyDependabotPR({ @@ -196,14 +206,20 @@ describe('Dependabot PR guard policy', () => { title: actionTitle, baseRef, files: [ - { filename: '.github/workflows/ci.yml', status: 'modified', patch: unpinnedPatch }, + { + filename: '.github/workflows/ci.yml', + status: 'modified', + patch: unpinnedPatch, + }, ], }); expect(mixed.allowed).toBe(false); expect(unpinned.allowed).toBe(false); }); - it('fails closed for missing patches, unrelated files, non-bot authors, titles, and branches', () => { + it( + 'fails closed for missing patches, unrelated files, non-bot authors, titles, and branches', + () => { const missingPatch = classifyDependabotPR({ login, title: actionTitle, From 0a4116079a4d377044857b779c4d3428df18e8b2 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Mon, 16 Nov 2026 15:13:08 +0100 Subject: [PATCH 17/94] style: align policy test descriptions with formatter --- tests/pr-guard-policy.test.ts | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/tests/pr-guard-policy.test.ts b/tests/pr-guard-policy.test.ts index 8806f07a..d1cf3cd1 100644 --- a/tests/pr-guard-policy.test.ts +++ b/tests/pr-guard-policy.test.ts @@ -132,9 +132,7 @@ describe('Dependabot PR guard policy', () => { expect(sourceChange.allowed).toBe(false); }); - it( - 'allows pinned action SHA updates without changing the action identity', - () => { + it('allows pinned action SHA updates', () => { const patch = [ '@@ -10,1 +10,1 @@', '- uses: github/codeql-action/init@aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa # v4.38.2', @@ -155,9 +153,7 @@ describe('Dependabot PR guard policy', () => { }); }); - it( - 'rejects replacing an action identity even when both references are pinned', - () => { + it('rejects replacing a pinned action identity', () => { const patch = [ '@@ -10,1 +10,1 @@', '- uses: actions/checkout@aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa # v7.0.1', @@ -175,9 +171,7 @@ describe('Dependabot PR guard policy', () => { expect(result.reason).toMatch(/may not move or replace/); }); - it( - 'rejects workflow logic, permission, or unpinned-reference changes', - () => { + it('rejects workflow logic, permissions, and unpinned refs', () => { const mixedPatch = [ '@@ -10,1 +10,2 @@', '- uses: github/codeql-action/init@aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa # v4.38.2', @@ -217,9 +211,7 @@ describe('Dependabot PR guard policy', () => { expect(unpinned.allowed).toBe(false); }); - it( - 'fails closed for missing patches, unrelated files, non-bot authors, titles, and branches', - () => { + it('fails closed for invalid authors, titles, branches, and files', () => { const missingPatch = classifyDependabotPR({ login, title: actionTitle, From 6c004c59e3544a8cbe0661fa96b5d3a4127632b4 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Mon, 16 Nov 2026 15:20:10 +0100 Subject: [PATCH 18/94] style: keep action patch fixtures formatter-friendly --- tests/pr-guard-policy.test.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/tests/pr-guard-policy.test.ts b/tests/pr-guard-policy.test.ts index d1cf3cd1..07ea60e3 100644 --- a/tests/pr-guard-policy.test.ts +++ b/tests/pr-guard-policy.test.ts @@ -135,8 +135,8 @@ describe('Dependabot PR guard policy', () => { it('allows pinned action SHA updates', () => { const patch = [ '@@ -10,1 +10,1 @@', - '- uses: github/codeql-action/init@aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa # v4.38.2', - '+ uses: github/codeql-action/init@bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb # v4.39.0', + '- uses: github/codeql-action/init@' + 'a'.repeat(40) + ' # v4.38.2', + '+ uses: github/codeql-action/init@' + 'b'.repeat(40) + ' # v4.39.0', ].join('\n'); const result = classifyDependabotPR({ login, @@ -156,8 +156,8 @@ describe('Dependabot PR guard policy', () => { it('rejects replacing a pinned action identity', () => { const patch = [ '@@ -10,1 +10,1 @@', - '- uses: actions/checkout@aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa # v7.0.1', - '+ uses: attacker/unknown-action@bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb # v1.0.0', + '- uses: actions/checkout@' + 'a'.repeat(40) + ' # v7.0.1', + '+ uses: attacker/unknown-action@' + 'b'.repeat(40) + ' # v1.0.0', ].join('\n'); const result = classifyDependabotPR({ login, @@ -174,8 +174,8 @@ describe('Dependabot PR guard policy', () => { it('rejects workflow logic, permissions, and unpinned refs', () => { const mixedPatch = [ '@@ -10,1 +10,2 @@', - '- uses: github/codeql-action/init@aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa # v4.38.2', - '+ uses: github/codeql-action/init@bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb # v4.39.0', + '- uses: github/codeql-action/init@' + 'a'.repeat(40) + ' # v4.38.2', + '+ uses: github/codeql-action/init@' + 'b'.repeat(40) + ' # v4.39.0', '+ permissions: contents: write', ].join('\n'); const unpinnedPatch = [ From b0ca4832af51c9d4f4cd4ae3f661ef7b4fd2c6aa Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Mon, 16 Nov 2026 15:20:32 +0100 Subject: [PATCH 19/94] style: format pinned action fixtures --- tests/pr-guard-policy.test.ts | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/tests/pr-guard-policy.test.ts b/tests/pr-guard-policy.test.ts index 07ea60e3..bd8c1204 100644 --- a/tests/pr-guard-policy.test.ts +++ b/tests/pr-guard-policy.test.ts @@ -43,6 +43,8 @@ const headPackage = { dependencies: { commander: '15.1.0' }, devDependencies: { vitest: '5.0.2' }, }; +const actionLine = (sign: string, action: string, sha: string, version: string) => + `${sign} uses: ${action}@${sha} # ${version}`; describe('Dependabot PR guard policy', () => { it('allows npm updates limited to dependency ranges and the lockfile', () => { @@ -135,8 +137,8 @@ describe('Dependabot PR guard policy', () => { it('allows pinned action SHA updates', () => { const patch = [ '@@ -10,1 +10,1 @@', - '- uses: github/codeql-action/init@' + 'a'.repeat(40) + ' # v4.38.2', - '+ uses: github/codeql-action/init@' + 'b'.repeat(40) + ' # v4.39.0', + actionLine('-', 'github/codeql-action/init', 'a'.repeat(40), 'v4.38.2'), + actionLine('+', 'github/codeql-action/init', 'b'.repeat(40), 'v4.39.0'), ].join('\n'); const result = classifyDependabotPR({ login, @@ -156,8 +158,8 @@ describe('Dependabot PR guard policy', () => { it('rejects replacing a pinned action identity', () => { const patch = [ '@@ -10,1 +10,1 @@', - '- uses: actions/checkout@' + 'a'.repeat(40) + ' # v7.0.1', - '+ uses: attacker/unknown-action@' + 'b'.repeat(40) + ' # v1.0.0', + actionLine('-', 'actions/checkout', 'a'.repeat(40), 'v7.0.1'), + actionLine('+', 'attacker/unknown-action', 'b'.repeat(40), 'v1.0.0'), ].join('\n'); const result = classifyDependabotPR({ login, @@ -174,8 +176,8 @@ describe('Dependabot PR guard policy', () => { it('rejects workflow logic, permissions, and unpinned refs', () => { const mixedPatch = [ '@@ -10,1 +10,2 @@', - '- uses: github/codeql-action/init@' + 'a'.repeat(40) + ' # v4.38.2', - '+ uses: github/codeql-action/init@' + 'b'.repeat(40) + ' # v4.39.0', + actionLine('-', 'github/codeql-action/init', 'a'.repeat(40), 'v4.38.2'), + actionLine('+', 'github/codeql-action/init', 'b'.repeat(40), 'v4.39.0'), '+ permissions: contents: write', ].join('\n'); const unpinnedPatch = [ From 063d359c9780ee8a775c2d9fd048e58c7a04c168 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Mon, 16 Nov 2026 15:21:47 +0100 Subject: [PATCH 20/94] style: format action fixture helper --- tests/pr-guard-policy.test.ts | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/tests/pr-guard-policy.test.ts b/tests/pr-guard-policy.test.ts index bd8c1204..0f18133a 100644 --- a/tests/pr-guard-policy.test.ts +++ b/tests/pr-guard-policy.test.ts @@ -43,8 +43,14 @@ const headPackage = { dependencies: { commander: '15.1.0' }, devDependencies: { vitest: '5.0.2' }, }; -const actionLine = (sign: string, action: string, sha: string, version: string) => - `${sign} uses: ${action}@${sha} # ${version}`; +function actionLine( + sign: string, + action: string, + sha: string, + version: string, +): string { + return `${sign} uses: ${action}@${sha} # ${version}`; +} describe('Dependabot PR guard policy', () => { it('allows npm updates limited to dependency ranges and the lockfile', () => { From 531dc3b4aa84c0fe1dee0e9098a607115a8e1513 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Mon, 16 Nov 2026 15:23:46 +0100 Subject: [PATCH 21/94] style: normalize compact missing-patch fixture --- tests/pr-guard-policy.test.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/tests/pr-guard-policy.test.ts b/tests/pr-guard-policy.test.ts index 0f18133a..741cac68 100644 --- a/tests/pr-guard-policy.test.ts +++ b/tests/pr-guard-policy.test.ts @@ -224,9 +224,7 @@ describe('Dependabot PR guard policy', () => { login, title: actionTitle, baseRef, - files: [ - { filename: '.github/workflows/ci.yml', status: 'modified' }, - ], + files: [{ filename: '.github/workflows/ci.yml', status: 'modified' }], }); const unrelated = classifyDependabotPR({ login, From 059670edd67107f0bbe39ac4db40915c7fa6c085 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Mon, 16 Nov 2026 16:17:15 +0100 Subject: [PATCH 22/94] fix(security): bound dependency range parsing --- scripts/pr-guard-policy.cjs | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/scripts/pr-guard-policy.cjs b/scripts/pr-guard-policy.cjs index 495d8a47..600b71ec 100644 --- a/scripts/pr-guard-policy.cjs +++ b/scripts/pr-guard-policy.cjs @@ -6,8 +6,17 @@ const WORKFLOW_PATH = /^\.github\/workflows\/(?:[A-Za-z0-9_.-]+\/)*[A-Za-z0-9_.-]+\.ya?ml$/; const ACTION_REFERENCE_CHANGE = /^[+-]\s*uses:\s*([A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)+)@([a-f0-9]{40})(?:\s+#.*)?$/i; -const VERSION_RANGE = - /^(?:[~^=]|>=?|<=?)?\s*\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\s*\|\|\s*(?:[~^=]|>=?|<=?)?\s*\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)*$/; +const VERSION_RANGE_CLAUSE = + /^(?:[~^=]|>=?|<=?)?\s*\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/; + +function isVersionRange(value) { + if (typeof value !== 'string' || value.length > 128) return false; + const clauses = value.split('||'); + return ( + clauses.length <= 8 && + clauses.every((clause) => VERSION_RANGE_CLAUSE.test(clause.trim())) + ); +} function deny(reason) { return { allowed: false, reason }; @@ -70,8 +79,7 @@ function validatePackageManifest(basePackage, headPackage) { if (before[name] === after[name]) continue; if ( typeof before[name] !== 'string' || - typeof after[name] !== 'string' || - !VERSION_RANGE.test(after[name]) + !isVersionRange(after[name]) ) { return deny( 'dependency "' + name + '" changed to a non-semver or non-string specification', From 05ca49adcc529c8caedbd2b6a73b6f101576d0f1 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Mon, 16 Nov 2026 16:17:31 +0100 Subject: [PATCH 23/94] test(security): cover oversized dependency range input --- tests/pr-guard-policy.test.ts | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/tests/pr-guard-policy.test.ts b/tests/pr-guard-policy.test.ts index 741cac68..17142f82 100644 --- a/tests/pr-guard-policy.test.ts +++ b/tests/pr-guard-policy.test.ts @@ -219,6 +219,29 @@ describe('Dependabot PR guard policy', () => { expect(unpinned.allowed).toBe(false); }); + it('rejects oversized dependency ranges without catastrophic regex work', () => { + const changed = { + ...headPackage, + dependencies: { + commander: '9.9.9|| 9.9.9||'.repeat(1000), + }, + }; + const result = classifyDependabotPR({ + login, + title: npmTitle, + baseRef, + files: [ + { filename: 'package.json', status: 'modified' }, + { filename: 'package-lock.json', status: 'modified' }, + ], + basePackage, + headPackage: changed, + }); + + expect(result.allowed).toBe(false); + expect(result.reason).toMatch(/non-semver|non-string/); + }); + it('fails closed for invalid authors, titles, branches, and files', () => { const missingPatch = classifyDependabotPR({ login, From 89ea46b4fff04a51a8a7135ede9e7227342accef Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Tue, 17 Nov 2026 14:01:10 +0100 Subject: [PATCH 24/94] fix: validate workflow action updates per diff hunk --- scripts/pr-guard-policy.cjs | 114 +++++++++++++++++------------------- 1 file changed, 55 insertions(+), 59 deletions(-) diff --git a/scripts/pr-guard-policy.cjs b/scripts/pr-guard-policy.cjs index 600b71ec..0b3f9beb 100644 --- a/scripts/pr-guard-policy.cjs +++ b/scripts/pr-guard-policy.cjs @@ -96,8 +96,7 @@ function validatePackageManifest(basePackage, headPackage) { } function validateWorkflowPatches(files) { - const removed = []; - const added = []; + let changedReferences = 0; for (const file of files) { if (!WORKFLOW_PATH.test(file.filename) || file.status !== 'modified') { @@ -109,74 +108,71 @@ function validateWorkflowPatches(files) { ); } - const changedLines = file.patch - .split(/\r?\n/) - .filter( - (line) => - /^[+-]/.test(line) && - !line.startsWith('+++') && - !line.startsWith('---'), - ); - if (changedLines.length === 0) { - return deny('workflow patch contains no action-reference changes'); - } + // Pair removed/added references inside each diff hunk, not across the + // whole file. This prevents two actions from being swapped between steps + // while their aggregate identities still appear unchanged. + let hunkRemoved = []; + let hunkAdded = []; + let sawChangedLine = false; + + const validateHunk = () => { + if (hunkRemoved.length === 0 && hunkAdded.length === 0) return true; + if (hunkRemoved.length === 0 || hunkRemoved.length !== hunkAdded.length) { + return false; + } + for (let index = 0; index < hunkRemoved.length; index += 1) { + if (hunkRemoved[index].name !== hunkAdded[index].name) return false; + if (hunkRemoved[index].sha === hunkAdded[index].sha) return false; + changedReferences += 1; + } + hunkRemoved = []; + hunkAdded = []; + return true; + }; + + for (const line of file.patch.split(/\r?\n/)) { + if (line.startsWith('@@')) { + if (!validateHunk()) { + return deny( + 'workflow updates may change an action SHA only at the same step; action identities cannot be swapped, moved, or replaced', + ); + } + continue; + } + if ( + !/^[+-]/.test(line) || + line.startsWith('+++') || + line.startsWith('---') + ) { + continue; + } - for (const line of changedLines) { - const match = line.match(ACTION_REFERENCE_CHANGE); + sawChangedLine = true; + // GitHub Actions commonly renders YAML sequence entries as + // "- uses: owner/action@". Also accept a direct "uses:" key. + const match = line.match( + /^[+-]\\s*(?:-\\s*)?uses:\\s*([A-Za-z0-9_.-]+(?:\\/[A-Za-z0-9_.-]+)+)@([a-f0-9]{40})(?:\\s+#.*)?$/i, + ); if (!match) { return deny( 'workflow updates may change only pinned 40-character uses: action references', ); } - const reference = { - filename: file.filename, - name: match[1], - sha: match[2].toLowerCase(), - }; - if (line.startsWith('-')) removed.push(reference); - else added.push(reference); + const reference = { name: match[1], sha: match[2].toLowerCase() }; + if (line.startsWith('-')) hunkRemoved.push(reference); + else hunkAdded.push(reference); } - } - - if (removed.length === 0 || removed.length !== added.length) { - return deny( - 'workflow updates must replace existing action references, not add or remove steps', - ); - } - - const oldIdentities = removed - .map((reference) => reference.filename + '|' + reference.name) - .sort(); - const newIdentities = added - .map((reference) => reference.filename + '|' + reference.name) - .sort(); - if (!sameJson(oldIdentities, newIdentities)) { - return deny( - 'workflow updates may change an action SHA but may not move or replace the action identity', - ); - } - const identities = [...new Set(oldIdentities)]; - for (const identity of identities) { - const oldShas = removed - .filter( - (reference) => - reference.filename + '|' + reference.name === identity, - ) - .map((reference) => reference.sha) - .sort(); - const newShas = added - .filter( - (reference) => - reference.filename + '|' + reference.name === identity, - ) - .map((reference) => reference.sha) - .sort(); - if (sameJson(oldShas, newShas)) { - return deny('workflow action ' + identity + ' has no pinned SHA update'); + if (!sawChangedLine || !validateHunk()) { + return deny( + 'workflow updates must replace pinned action SHAs in-place without adding, removing, moving, or swapping steps', + ); } } + if (changedReferences === 0) { + return deny('workflow patch contains no action-reference changes'); + } return { allowed: true, kind: 'github-actions', changedFiles: files.length }; } From 02c5397b4ca0d98bf4b76f509d82cf34966d4dc6 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Tue, 17 Nov 2026 14:01:36 +0100 Subject: [PATCH 25/94] fix: correct workflow action patch matcher --- scripts/pr-guard-policy.cjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/pr-guard-policy.cjs b/scripts/pr-guard-policy.cjs index 0b3f9beb..fb2ed1f3 100644 --- a/scripts/pr-guard-policy.cjs +++ b/scripts/pr-guard-policy.cjs @@ -151,7 +151,7 @@ function validateWorkflowPatches(files) { // GitHub Actions commonly renders YAML sequence entries as // "- uses: owner/action@". Also accept a direct "uses:" key. const match = line.match( - /^[+-]\\s*(?:-\\s*)?uses:\\s*([A-Za-z0-9_.-]+(?:\\/[A-Za-z0-9_.-]+)+)@([a-f0-9]{40})(?:\\s+#.*)?$/i, + /^[+-]\s*(?:-\s*)?uses:\s*([A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)+)@([a-f0-9]{40})(?:\s+#.*)?$/i, ); if (!match) { return deny( From 2025b5e6e8e040607699bb5f9c82fb2e3b6bac0e Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Tue, 17 Nov 2026 14:01:48 +0100 Subject: [PATCH 26/94] test: cover sequence actions and identity swaps --- tests/pr-guard-policy.test.ts | 41 +++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/tests/pr-guard-policy.test.ts b/tests/pr-guard-policy.test.ts index 17142f82..ffce3bcf 100644 --- a/tests/pr-guard-policy.test.ts +++ b/tests/pr-guard-policy.test.ts @@ -179,6 +179,47 @@ describe('Dependabot PR guard policy', () => { expect(result.reason).toMatch(/may not move or replace/); }); + it('allows pinned SHA updates on standard YAML sequence action steps', () => { + const patch = [ + '@@ -10,1 +10,1 @@', + '- - uses: actions/checkout@' + 'a'.repeat(40), + '+ - uses: actions/checkout@' + 'b'.repeat(40), + ].join('\\n'); + const result = classifyDependabotPR({ + login, + title: actionTitle, + baseRef, + files: [ + { filename: '.github/workflows/ci.yml', status: 'modified', patch }, + ], + }); + expect(result).toMatchObject({ + allowed: true, + kind: 'github-actions', + changedFiles: 1, + }); + }); + + it('rejects swapping action identities between workflow steps', () => { + const patch = [ + '@@ -10,2 +10,2 @@', + '- - uses: actions/checkout@' + 'a'.repeat(40), + '- - uses: actions/setup-node@' + 'b'.repeat(40), + '+ - uses: actions/setup-node@' + 'c'.repeat(40), + '+ - uses: actions/checkout@' + 'd'.repeat(40), + ].join('\\n'); + const result = classifyDependabotPR({ + login, + title: actionTitle, + baseRef, + files: [ + { filename: '.github/workflows/ci.yml', status: 'modified', patch }, + ], + }); + expect(result.allowed).toBe(false); + expect(result.reason).toMatch(/identities cannot be swapped/); + }); + it('rejects workflow logic, permissions, and unpinned refs', () => { const mixedPatch = [ '@@ -10,1 +10,2 @@', From cb8d997e317dce3af1a3e2848a3670a3c078e01d Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Tue, 17 Nov 2026 14:03:58 +0100 Subject: [PATCH 27/94] test: fix workflow patch fixtures --- tests/pr-guard-policy.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/pr-guard-policy.test.ts b/tests/pr-guard-policy.test.ts index ffce3bcf..97a61925 100644 --- a/tests/pr-guard-policy.test.ts +++ b/tests/pr-guard-policy.test.ts @@ -184,7 +184,7 @@ describe('Dependabot PR guard policy', () => { '@@ -10,1 +10,1 @@', '- - uses: actions/checkout@' + 'a'.repeat(40), '+ - uses: actions/checkout@' + 'b'.repeat(40), - ].join('\\n'); + ].join('\n'); const result = classifyDependabotPR({ login, title: actionTitle, @@ -207,7 +207,7 @@ describe('Dependabot PR guard policy', () => { '- - uses: actions/setup-node@' + 'b'.repeat(40), '+ - uses: actions/setup-node@' + 'c'.repeat(40), '+ - uses: actions/checkout@' + 'd'.repeat(40), - ].join('\\n'); + ].join('\n'); const result = classifyDependabotPR({ login, title: actionTitle, From 0a9ff4b514b410fa269f553deff1b951162fb482 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Tue, 17 Nov 2026 14:04:03 +0100 Subject: [PATCH 28/94] chore: remove obsolete workflow matcher --- scripts/pr-guard-policy.cjs | 2 -- 1 file changed, 2 deletions(-) diff --git a/scripts/pr-guard-policy.cjs b/scripts/pr-guard-policy.cjs index fb2ed1f3..f365e1f1 100644 --- a/scripts/pr-guard-policy.cjs +++ b/scripts/pr-guard-policy.cjs @@ -4,8 +4,6 @@ const DEPENDABOT_LOGIN = 'dependabot[bot]'; const DEPENDENCY_TITLE = /^(?:build|chore)\(deps(?:-dev)?\):\s+/i; const WORKFLOW_PATH = /^\.github\/workflows\/(?:[A-Za-z0-9_.-]+\/)*[A-Za-z0-9_.-]+\.ya?ml$/; -const ACTION_REFERENCE_CHANGE = - /^[+-]\s*uses:\s*([A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)+)@([a-f0-9]{40})(?:\s+#.*)?$/i; const VERSION_RANGE_CLAUSE = /^(?:[~^=]|>=?|<=?)?\s*\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/; From 63c4335ff891b3144ad4d41e8b8245c68b21f082 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Tue, 17 Nov 2026 14:05:20 +0100 Subject: [PATCH 29/94] test: assert fail-closed workflow patch rejection --- tests/pr-guard-policy.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/pr-guard-policy.test.ts b/tests/pr-guard-policy.test.ts index 97a61925..1000b9f3 100644 --- a/tests/pr-guard-policy.test.ts +++ b/tests/pr-guard-policy.test.ts @@ -176,7 +176,7 @@ describe('Dependabot PR guard policy', () => { ], }); expect(result.allowed).toBe(false); - expect(result.reason).toMatch(/may not move or replace/); + expect(result.reason).toMatch(/workflow updates must replace pinned action SHAs/); }); it('allows pinned SHA updates on standard YAML sequence action steps', () => { @@ -217,7 +217,7 @@ describe('Dependabot PR guard policy', () => { ], }); expect(result.allowed).toBe(false); - expect(result.reason).toMatch(/identities cannot be swapped/); + expect(result.reason).toMatch(/workflow updates must replace pinned action SHAs/); }); it('rejects workflow logic, permissions, and unpinned refs', () => { From a76753352a187ee02bd3fb3f48b0963f103b4aaa Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Tue, 17 Nov 2026 14:06:54 +0100 Subject: [PATCH 30/94] style: format workflow guard assertions --- tests/pr-guard-policy.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/pr-guard-policy.test.ts b/tests/pr-guard-policy.test.ts index 1000b9f3..1addc9d0 100644 --- a/tests/pr-guard-policy.test.ts +++ b/tests/pr-guard-policy.test.ts @@ -176,7 +176,9 @@ describe('Dependabot PR guard policy', () => { ], }); expect(result.allowed).toBe(false); - expect(result.reason).toMatch(/workflow updates must replace pinned action SHAs/); + expect(result.reason).toMatch( + /workflow updates must replace pinned action SHAs/, + ); }); it('allows pinned SHA updates on standard YAML sequence action steps', () => { From 50a7ded09d433c0d118e8dbcb163a7c71535ba4e Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Tue, 17 Nov 2026 14:11:03 +0100 Subject: [PATCH 31/94] style: wrap long policy assertion --- tests/pr-guard-policy.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/pr-guard-policy.test.ts b/tests/pr-guard-policy.test.ts index 1addc9d0..be6fc7a9 100644 --- a/tests/pr-guard-policy.test.ts +++ b/tests/pr-guard-policy.test.ts @@ -219,7 +219,9 @@ describe('Dependabot PR guard policy', () => { ], }); expect(result.allowed).toBe(false); - expect(result.reason).toMatch(/workflow updates must replace pinned action SHAs/); + expect(result.reason).toMatch( + /workflow updates must replace pinned action SHAs/, + ); }); it('rejects workflow logic, permissions, and unpinned refs', () => { From ee42f75ad89ad89681f44de0b78639099d9edeaa Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 10:40:43 +0100 Subject: [PATCH 32/94] fix(automation): reject malformed dependency section changes --- scripts/pr-guard-policy.cjs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/scripts/pr-guard-policy.cjs b/scripts/pr-guard-policy.cjs index f365e1f1..394aa6d8 100644 --- a/scripts/pr-guard-policy.cjs +++ b/scripts/pr-guard-policy.cjs @@ -61,10 +61,15 @@ function validatePackageManifest(basePackage, headPackage) { let changedVersions = 0; for (const section of sections) { - const before = basePackage[section] || {}; - const after = headPackage[section] || {}; - if (!isObject(before) || !isObject(after)) { - return deny('dependency sections must remain JSON objects'); + const beforePresent = Object.hasOwn(basePackage, section); + const afterPresent = Object.hasOwn(headPackage, section); + if (beforePresent !== afterPresent) { + return deny('dependency sections must retain their original presence'); + } + const before = beforePresent ? basePackage[section] : {}; + const after = afterPresent ? headPackage[section] : {}; + if ((beforePresent && !isObject(before)) || (afterPresent && !isObject(after))) { + return deny('present dependency sections must remain JSON objects'); } const beforeNames = Object.keys(before).sort(); From 91e3068ec2101fd94b51d91b988f1426a7331b3a Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 10:40:45 +0100 Subject: [PATCH 33/94] test(automation): cover dependency section shape changes --- tests/pr-guard-policy.test.ts | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/tests/pr-guard-policy.test.ts b/tests/pr-guard-policy.test.ts index be6fc7a9..162bdaea 100644 --- a/tests/pr-guard-policy.test.ts +++ b/tests/pr-guard-policy.test.ts @@ -92,6 +92,33 @@ describe('Dependabot PR guard policy', () => { expect(result.reason).toMatch(/outside dependency version sections/); }); + it('rejects dependency section presence and shape changes', () => { + const withNullSection = { + ...headPackage, + peerDependencies: null, + }; + const withAddedSection = { + ...headPackage, + peerDependencies: { 'new-peer': '1.0.0' }, + }; + const classify = (head: PackageManifest) => + classifyDependabotPR({ + login, + title: npmTitle, + baseRef, + files: [ + { filename: 'package.json', status: 'modified' }, + { filename: 'package-lock.json', status: 'modified' }, + ], + basePackage, + headPackage: head, + }); + expect(classify(withNullSection).allowed).toBe(false); + expect(classify(withNullSection).reason).toMatch(/present dependency sections/); + expect(classify(withAddedSection).allowed).toBe(false); + expect(classify(withAddedSection).reason).toMatch(/retain their original presence/); + }); + it('rejects adding or removing dependency names', () => { const changed = { ...headPackage, From 77e2e69cc5b643022d649818b80a9d3b9cd09f81 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 11:28:46 +0100 Subject: [PATCH 34/94] test(automation): align malformed-section rejection assertion --- tests/pr-guard-policy.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/pr-guard-policy.test.ts b/tests/pr-guard-policy.test.ts index 162bdaea..6abdda4c 100644 --- a/tests/pr-guard-policy.test.ts +++ b/tests/pr-guard-policy.test.ts @@ -114,7 +114,7 @@ describe('Dependabot PR guard policy', () => { headPackage: head, }); expect(classify(withNullSection).allowed).toBe(false); - expect(classify(withNullSection).reason).toMatch(/present dependency sections/); + expect(classify(withNullSection).reason).toMatch(/retain their original presence/); expect(classify(withAddedSection).allowed).toBe(false); expect(classify(withAddedSection).reason).toMatch(/retain their original presence/); }); From 5491f9d699612e9fabecf2c1d17a6e0e29cbeec6 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 11:29:04 +0100 Subject: [PATCH 35/94] test(automation): exercise dependency section shape rejection --- tests/pr-guard-policy.test.ts | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/tests/pr-guard-policy.test.ts b/tests/pr-guard-policy.test.ts index 6abdda4c..bd039f56 100644 --- a/tests/pr-guard-policy.test.ts +++ b/tests/pr-guard-policy.test.ts @@ -101,7 +101,10 @@ describe('Dependabot PR guard policy', () => { ...headPackage, peerDependencies: { 'new-peer': '1.0.0' }, }; - const classify = (head: PackageManifest) => + const classify = ( + head: PackageManifest, + base: PackageManifest = basePackage, + ) => classifyDependabotPR({ login, title: npmTitle, @@ -110,11 +113,17 @@ describe('Dependabot PR guard policy', () => { { filename: 'package.json', status: 'modified' }, { filename: 'package-lock.json', status: 'modified' }, ], - basePackage, + basePackage: base, headPackage: head, }); - expect(classify(withNullSection).allowed).toBe(false); - expect(classify(withNullSection).reason).toMatch(/retain their original presence/); + const baseWithPeerDependencies = { + ...basePackage, + peerDependencies: {}, + }; + expect(classify(withNullSection, baseWithPeerDependencies).allowed).toBe(false); + expect(classify(withNullSection, baseWithPeerDependencies).reason).toMatch( + /present dependency sections must remain JSON objects/, + ); expect(classify(withAddedSection).allowed).toBe(false); expect(classify(withAddedSection).reason).toMatch(/retain their original presence/); }); From bc17aee8661d780cfba5e203e945a46490f5b3db Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 11:29:14 +0100 Subject: [PATCH 36/94] test(automation): reach malformed dependency section shape guard --- tests/pr-guard-policy.test.ts | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/tests/pr-guard-policy.test.ts b/tests/pr-guard-policy.test.ts index bd039f56..ae75718f 100644 --- a/tests/pr-guard-policy.test.ts +++ b/tests/pr-guard-policy.test.ts @@ -120,12 +120,16 @@ describe('Dependabot PR guard policy', () => { ...basePackage, peerDependencies: {}, }; - expect(classify(withNullSection, baseWithPeerDependencies).allowed).toBe(false); - expect(classify(withNullSection, baseWithPeerDependencies).reason).toMatch( - /present dependency sections must remain JSON objects/, - ); + expect( + classify(withNullSection, baseWithPeerDependencies).allowed, + ).toBe(false); + expect( + classify(withNullSection, baseWithPeerDependencies).reason, + ).toMatch(/present dependency sections must remain JSON objects/); expect(classify(withAddedSection).allowed).toBe(false); - expect(classify(withAddedSection).reason).toMatch(/retain their original presence/); + expect(classify(withAddedSection).reason).toMatch( + /retain their original presence/, + ); }); it('rejects adding or removing dependency names', () => { From c2a6433cb80b057d52c0d68958151461ba5bc108 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 11:30:27 +0100 Subject: [PATCH 37/94] style(tests): format dependency guard assertions --- tests/pr-guard-policy.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/pr-guard-policy.test.ts b/tests/pr-guard-policy.test.ts index ae75718f..70a148b2 100644 --- a/tests/pr-guard-policy.test.ts +++ b/tests/pr-guard-policy.test.ts @@ -125,7 +125,9 @@ describe('Dependabot PR guard policy', () => { ).toBe(false); expect( classify(withNullSection, baseWithPeerDependencies).reason, - ).toMatch(/present dependency sections must remain JSON objects/); + ).toMatch( + /present dependency sections must remain JSON objects/, + ); expect(classify(withAddedSection).allowed).toBe(false); expect(classify(withAddedSection).reason).toMatch( /retain their original presence/, From 480b9e2fe572232ea9c28f21346449676e65754f Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 11:31:00 +0100 Subject: [PATCH 38/94] fix(automation): tighten dependency and workflow diff validation --- scripts/pr-guard-policy.cjs | 35 +++++++++++++++++++++++++---------- 1 file changed, 25 insertions(+), 10 deletions(-) diff --git a/scripts/pr-guard-policy.cjs b/scripts/pr-guard-policy.cjs index 394aa6d8..5310e92b 100644 --- a/scripts/pr-guard-policy.cjs +++ b/scripts/pr-guard-policy.cjs @@ -80,10 +80,7 @@ function validatePackageManifest(basePackage, headPackage) { for (const name of beforeNames) { if (before[name] === after[name]) continue; - if ( - typeof before[name] !== 'string' || - !isVersionRange(after[name]) - ) { + if (!isVersionRange(before[name]) || !isVersionRange(after[name])) { return deny( 'dependency "' + name + '" changed to a non-semver or non-string specification', ); @@ -117,6 +114,7 @@ function validateWorkflowPatches(files) { let hunkRemoved = []; let hunkAdded = []; let sawChangedLine = false; + let inHunk = false; const validateHunk = () => { if (hunkRemoved.length === 0 && hunkAdded.length === 0) return true; @@ -126,6 +124,9 @@ function validateWorkflowPatches(files) { for (let index = 0; index < hunkRemoved.length; index += 1) { if (hunkRemoved[index].name !== hunkAdded[index].name) return false; if (hunkRemoved[index].sha === hunkAdded[index].sha) return false; + if (hunkRemoved[index].normalizedLine !== hunkAdded[index].normalizedLine) { + return false; + } changedReferences += 1; } hunkRemoved = []; @@ -140,15 +141,22 @@ function validateWorkflowPatches(files) { 'workflow updates may change an action SHA only at the same step; action identities cannot be swapped, moved, or replaced', ); } + inHunk = true; continue; } - if ( - !/^[+-]/.test(line) || - line.startsWith('+++') || - line.startsWith('---') - ) { + if (!inHunk) continue; + if (line.startsWith(' ')) { + if (!validateHunk()) { + return deny( + 'workflow updates may change an action SHA only at the same step; action identities cannot be swapped, moved, or replaced', + ); + } continue; } + if (line.startsWith('\\')) continue; + if (!/^[+-]/.test(line)) { + return deny('workflow patch contains an unsupported diff line'); + } sawChangedLine = true; // GitHub Actions commonly renders YAML sequence entries as @@ -161,7 +169,14 @@ function validateWorkflowPatches(files) { 'workflow updates may change only pinned 40-character uses: action references', ); } - const reference = { name: match[1], sha: match[2].toLowerCase() }; + const normalizedLine = line + .slice(1) + .replace(/@[a-f0-9]{40}/i, '@'); + const reference = { + name: match[1], + sha: match[2].toLowerCase(), + normalizedLine, + }; if (line.startsWith('-')) hunkRemoved.push(reference); else hunkAdded.push(reference); } From ceda78bf3f02ae3fc70870d1f1b3b24d82d84b6e Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 11:31:23 +0100 Subject: [PATCH 39/94] build(deps): declare yaml parser for workflow guard --- package.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index 76e291ed..f3e31302 100644 --- a/package.json +++ b/package.json @@ -39,7 +39,8 @@ "prettier": "3.9.8", "typescript": "6.0.3", "typescript-eslint": "8.70.0", - "vitest": "5.0.1" + "vitest": "5.0.1", + "yaml": "2.9.0" }, "license": "MIT", "repository": { From 583dc8f374eddee807a0d512818f3a70a7e2d4ce Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 11:31:26 +0100 Subject: [PATCH 40/94] build(deps): sync yaml parser lockfile declaration --- package-lock.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/package-lock.json b/package-lock.json index 88efca46..e813306c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -22,7 +22,8 @@ "prettier": "3.9.8", "typescript": "6.0.3", "typescript-eslint": "8.70.0", - "vitest": "5.0.1" + "vitest": "5.0.1", + "yaml": "2.9.0" }, "engines": { "node": ">=22.13.0 <25", From ad9a1da1316a89859a74922b0d8d9e9569d683e4 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 11:31:44 +0100 Subject: [PATCH 41/94] fix(automation): validate action updates against parsed workflow YAML --- scripts/pr-guard-policy.cjs | 173 ++++++++++++++++++++---------------- 1 file changed, 98 insertions(+), 75 deletions(-) diff --git a/scripts/pr-guard-policy.cjs b/scripts/pr-guard-policy.cjs index 5310e92b..2a30f473 100644 --- a/scripts/pr-guard-policy.cjs +++ b/scripts/pr-guard-policy.cjs @@ -95,101 +95,123 @@ function validatePackageManifest(basePackage, headPackage) { return { allowed: true, kind: 'npm-dependencies', changedVersions }; } -function validateWorkflowPatches(files) { +function collectWorkflowUses(value, path = [], references = {}) { + if (Array.isArray(value)) { + value.forEach((item, index) => + collectWorkflowUses(item, [...path, String(index)], references), + ); + return references; + } + if (!isObject(value)) return references; + + if (Object.hasOwn(value, 'uses')) { + if (typeof value.uses !== 'string') { + throw new Error('workflow uses fields must be strings'); + } + references[JSON.stringify([...path, 'uses'])] = value.uses; + } + + for (const [key, child] of Object.entries(value)) { + collectWorkflowUses(child, [...path, key], references); + } + return references; +} + +function normalizeWorkflowUses(value) { + if (Array.isArray(value)) return value.map(normalizeWorkflowUses); + if (!isObject(value)) return value; + return Object.fromEntries( + Object.keys(value) + .sort() + .map((key) => [ + key, + key === 'uses' ? '__PINNED_ACTION_REFERENCE__' : normalizeWorkflowUses(value[key]), + ]), + ); +} + +function validateWorkflowPatches(files, workflowContents) { + const YAML = require('yaml'); let changedReferences = 0; for (const file of files) { if (!WORKFLOW_PATH.test(file.filename) || file.status !== 'modified') { return deny('only modified workflow YAML files are allowed for GitHub Actions updates'); } - if (typeof file.patch !== 'string' || file.patch.length === 0) { + const revisions = workflowContents?.[file.filename]; + if ( + !revisions || + typeof revisions.base !== 'string' || + typeof revisions.head !== 'string' + ) { return deny( - 'workflow patch is unavailable; failing closed because changed lines cannot be verified', + 'workflow source is unavailable at base or head; failing closed because YAML structure cannot be verified', ); } - // Pair removed/added references inside each diff hunk, not across the - // whole file. This prevents two actions from being swapped between steps - // while their aggregate identities still appear unchanged. - let hunkRemoved = []; - let hunkAdded = []; - let sawChangedLine = false; - let inHunk = false; - - const validateHunk = () => { - if (hunkRemoved.length === 0 && hunkAdded.length === 0) return true; - if (hunkRemoved.length === 0 || hunkRemoved.length !== hunkAdded.length) { - return false; - } - for (let index = 0; index < hunkRemoved.length; index += 1) { - if (hunkRemoved[index].name !== hunkAdded[index].name) return false; - if (hunkRemoved[index].sha === hunkAdded[index].sha) return false; - if (hunkRemoved[index].normalizedLine !== hunkAdded[index].normalizedLine) { - return false; - } - changedReferences += 1; - } - hunkRemoved = []; - hunkAdded = []; - return true; - }; - - for (const line of file.patch.split(/\r?\n/)) { - if (line.startsWith('@@')) { - if (!validateHunk()) { - return deny( - 'workflow updates may change an action SHA only at the same step; action identities cannot be swapped, moved, or replaced', - ); - } - inHunk = true; - continue; - } - if (!inHunk) continue; - if (line.startsWith(' ')) { - if (!validateHunk()) { - return deny( - 'workflow updates may change an action SHA only at the same step; action identities cannot be swapped, moved, or replaced', - ); - } - continue; - } - if (line.startsWith('\\')) continue; - if (!/^[+-]/.test(line)) { - return deny('workflow patch contains an unsupported diff line'); - } + let baseWorkflow; + let headWorkflow; + try { + baseWorkflow = YAML.parse(revisions.base); + headWorkflow = YAML.parse(revisions.head); + } catch { + return deny('workflow YAML must parse successfully at both base and head revisions'); + } + if (!isObject(baseWorkflow) || !isObject(headWorkflow)) { + return deny('workflow documents must remain YAML mappings'); + } - sawChangedLine = true; - // GitHub Actions commonly renders YAML sequence entries as - // "- uses: owner/action@". Also accept a direct "uses:" key. - const match = line.match( - /^[+-]\s*(?:-\s*)?uses:\s*([A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)+)@([a-f0-9]{40})(?:\s+#.*)?$/i, + let baseReferences; + let headReferences; + try { + baseReferences = collectWorkflowUses(baseWorkflow); + headReferences = collectWorkflowUses(headWorkflow); + } catch (error) { + return deny(error.message); + } + + const baseLocations = Object.keys(baseReferences).sort(); + const headLocations = Object.keys(headReferences).sort(); + if (!sameJson(baseLocations, headLocations)) { + return deny('workflow updates may not add, remove, or move action uses fields'); + } + + for (const location of baseLocations) { + const before = baseReferences[location]; + const after = headReferences[location]; + if (before === after) continue; + + const beforeMatch = before.match( + /^([A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)+)@([a-f0-9]{40})$/i, ); - if (!match) { + const afterMatch = after.match( + /^([A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)+)@([a-f0-9]{40})$/i, + ); + if ( + !beforeMatch || + !afterMatch || + beforeMatch[1] !== afterMatch[1] || + beforeMatch[2].toLowerCase() === afterMatch[2].toLowerCase() + ) { return deny( - 'workflow updates may change only pinned 40-character uses: action references', + 'workflow updates may change only the pinned SHA of an existing action at the same YAML location', ); } - const normalizedLine = line - .slice(1) - .replace(/@[a-f0-9]{40}/i, '@'); - const reference = { - name: match[1], - sha: match[2].toLowerCase(), - normalizedLine, - }; - if (line.startsWith('-')) hunkRemoved.push(reference); - else hunkAdded.push(reference); + changedReferences += 1; } - if (!sawChangedLine || !validateHunk()) { - return deny( - 'workflow updates must replace pinned action SHAs in-place without adding, removing, moving, or swapping steps', - ); + if ( + !sameJson( + normalizeWorkflowUses(baseWorkflow), + normalizeWorkflowUses(headWorkflow), + ) + ) { + return deny('workflow updates may not change YAML content outside pinned action SHAs'); } } if (changedReferences === 0) { - return deny('workflow patch contains no action-reference changes'); + return deny('workflow YAML contains no action-reference SHA changes'); } return { allowed: true, kind: 'github-actions', changedFiles: files.length }; } @@ -201,6 +223,7 @@ function classifyDependabotPR({ files, basePackage, headPackage, + workflowContents, }) { if (login !== DEPENDABOT_LOGIN) { return deny('only the exact dependabot[bot] account is eligible'); @@ -228,7 +251,7 @@ function classifyDependabotPR({ } if (files.every((file) => WORKFLOW_PATH.test(file.filename))) { - return validateWorkflowPatches(files); + return validateWorkflowPatches(files, workflowContents); } return deny( From 1090dacade3c8d3ee6a5dd64932290be9b398b06 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 11:31:53 +0100 Subject: [PATCH 42/94] fix(automation): supply trusted workflow revisions to bot guard --- .github/workflows/wave-pr-guard.yml | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/.github/workflows/wave-pr-guard.yml b/.github/workflows/wave-pr-guard.yml index 5c05c5f2..61e9f9aa 100644 --- a/.github/workflows/wave-pr-guard.yml +++ b/.github/workflows/wave-pr-guard.yml @@ -59,6 +59,22 @@ jobs: basePackage = await readPackageAtRef(pr.base.sha); headPackage = await readPackageAtRef(pr.head.sha); } + const workflowContents = {}; + for (const file of files.filter((item) => /^\\.github\\/workflows\\//.test(item.filename))) { + const readWorkflowAtRef = async (ref) => { + const { data } = await github.rest.repos.getContent({ + owner, repo, path: file.filename, ref, + }); + if (Array.isArray(data) || data.type !== 'file' || data.encoding !== 'base64') { + throw new Error('Could not read workflow as a base64 file at ' + ref); + } + return Buffer.from(data.content, 'base64').toString('utf8'); + }; + workflowContents[file.filename] = { + base: await readWorkflowAtRef(pr.base.sha), + head: await readWorkflowAtRef(pr.head.sha), + }; + } const decision = classifyDependabotPR({ login: pr.user.login, title: pr.title, @@ -66,6 +82,7 @@ jobs: files, basePackage, headPackage, + workflowContents, }); if (!decision.allowed) { core.setFailed('Dependabot PR rejected by narrow bot policy: ' + decision.reason); From df6be3a84f3036f74fa91c634c536f71dea1ba6e Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 11:32:35 +0100 Subject: [PATCH 43/94] build(deps): avoid adding a parser runtime dependency --- package.json | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/package.json b/package.json index f3e31302..76e291ed 100644 --- a/package.json +++ b/package.json @@ -39,8 +39,7 @@ "prettier": "3.9.8", "typescript": "6.0.3", "typescript-eslint": "8.70.0", - "vitest": "5.0.1", - "yaml": "2.9.0" + "vitest": "5.0.1" }, "license": "MIT", "repository": { From 499eae7ebe952424edb7576232e9b7128f5f3f51 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 11:32:38 +0100 Subject: [PATCH 44/94] build(deps): keep lockfile aligned without parser dependency --- package-lock.json | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/package-lock.json b/package-lock.json index e813306c..88efca46 100644 --- a/package-lock.json +++ b/package-lock.json @@ -22,8 +22,7 @@ "prettier": "3.9.8", "typescript": "6.0.3", "typescript-eslint": "8.70.0", - "vitest": "5.0.1", - "yaml": "2.9.0" + "vitest": "5.0.1" }, "engines": { "node": ">=22.13.0 <25", From 3cbb18f9cc116ea538fdf51d939fc4ef2f14a52a Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 11:32:54 +0100 Subject: [PATCH 45/94] fix(automation): validate pinned action changes outside YAML block scalars --- scripts/pr-guard-policy.cjs | 131 +++++++++++++----------------------- 1 file changed, 47 insertions(+), 84 deletions(-) diff --git a/scripts/pr-guard-policy.cjs b/scripts/pr-guard-policy.cjs index 2a30f473..a6655aa4 100644 --- a/scripts/pr-guard-policy.cjs +++ b/scripts/pr-guard-policy.cjs @@ -95,43 +95,46 @@ function validatePackageManifest(basePackage, headPackage) { return { allowed: true, kind: 'npm-dependencies', changedVersions }; } -function collectWorkflowUses(value, path = [], references = {}) { - if (Array.isArray(value)) { - value.forEach((item, index) => - collectWorkflowUses(item, [...path, String(index)], references), - ); - return references; - } - if (!isObject(value)) return references; +function normalizeWorkflowSource(source) { + const lines = source.split(/\r?\n/); + const references = []; + let blockScalarIndent = null; + + for (let index = 0; index < lines.length; index += 1) { + const line = lines[index]; + const indentation = line.match(/^ */)[0].length; + const trimmed = line.trim(); + + if (blockScalarIndent !== null) { + if (trimmed === '' || indentation > blockScalarIndent) continue; + blockScalarIndent = null; + } - if (Object.hasOwn(value, 'uses')) { - if (typeof value.uses !== 'string') { - throw new Error('workflow uses fields must be strings'); + if ( + /^\s*(?:-\s*)?[A-Za-z0-9_.-]+:\s*[|>](?:[+-]?\d?|\d?[+-])?(?:\s+#.*)?$/.test( + line, + ) + ) { + blockScalarIndent = indentation; + continue; } - references[JSON.stringify([...path, 'uses'])] = value.uses; - } - for (const [key, child] of Object.entries(value)) { - collectWorkflowUses(child, [...path, key], references); + const match = line.match( + /^(\s*(?:-\s*)?uses:\s*)([A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)+)@([a-f0-9]{40})(\s+#.*)?$/i, + ); + if (!match) continue; + + references.push({ + name: match[2], + sha: match[3].toLowerCase(), + }); + lines[index] = match[1] + match[2] + '@' + (match[4] || ''); } - return references; -} -function normalizeWorkflowUses(value) { - if (Array.isArray(value)) return value.map(normalizeWorkflowUses); - if (!isObject(value)) return value; - return Object.fromEntries( - Object.keys(value) - .sort() - .map((key) => [ - key, - key === 'uses' ? '__PINNED_ACTION_REFERENCE__' : normalizeWorkflowUses(value[key]), - ]), - ); + return { normalized: lines.join('\n'), references }; } function validateWorkflowPatches(files, workflowContents) { - const YAML = require('yaml'); let changedReferences = 0; for (const file of files) { @@ -145,68 +148,28 @@ function validateWorkflowPatches(files, workflowContents) { typeof revisions.head !== 'string' ) { return deny( - 'workflow source is unavailable at base or head; failing closed because YAML structure cannot be verified', + 'workflow source is unavailable at base or head; failing closed because changed lines cannot be verified', ); } - let baseWorkflow; - let headWorkflow; - try { - baseWorkflow = YAML.parse(revisions.base); - headWorkflow = YAML.parse(revisions.head); - } catch { - return deny('workflow YAML must parse successfully at both base and head revisions'); - } - if (!isObject(baseWorkflow) || !isObject(headWorkflow)) { - return deny('workflow documents must remain YAML mappings'); - } - - let baseReferences; - let headReferences; - try { - baseReferences = collectWorkflowUses(baseWorkflow); - headReferences = collectWorkflowUses(headWorkflow); - } catch (error) { - return deny(error.message); + const before = normalizeWorkflowSource(revisions.base); + const after = normalizeWorkflowSource(revisions.head); + if (before.normalized !== after.normalized) { + return deny( + 'workflow updates may change only pinned action SHAs outside YAML block-scalar content', + ); } - - const baseLocations = Object.keys(baseReferences).sort(); - const headLocations = Object.keys(headReferences).sort(); - if (!sameJson(baseLocations, headLocations)) { - return deny('workflow updates may not add, remove, or move action uses fields'); + if (before.references.length !== after.references.length) { + return deny('workflow updates may not add or remove action references'); } - for (const location of baseLocations) { - const before = baseReferences[location]; - const after = headReferences[location]; - if (before === after) continue; - - const beforeMatch = before.match( - /^([A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)+)@([a-f0-9]{40})$/i, - ); - const afterMatch = after.match( - /^([A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)+)@([a-f0-9]{40})$/i, - ); - if ( - !beforeMatch || - !afterMatch || - beforeMatch[1] !== afterMatch[1] || - beforeMatch[2].toLowerCase() === afterMatch[2].toLowerCase() - ) { - return deny( - 'workflow updates may change only the pinned SHA of an existing action at the same YAML location', - ); + for (let index = 0; index < before.references.length; index += 1) { + const oldReference = before.references[index]; + const newReference = after.references[index]; + if (oldReference.name !== newReference.name) { + return deny('workflow updates may not replace or move action identities'); } - changedReferences += 1; - } - - if ( - !sameJson( - normalizeWorkflowUses(baseWorkflow), - normalizeWorkflowUses(headWorkflow), - ) - ) { - return deny('workflow updates may not change YAML content outside pinned action SHAs'); + if (oldReference.sha !== newReference.sha) changedReferences += 1; } } From 12370707108f3f26551e040fadc7645433d74b7c Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 11:33:24 +0100 Subject: [PATCH 46/94] test(automation): validate action updates against workflow source --- tests/pr-guard-policy.test.ts | 139 +++++++++++++++++----------------- 1 file changed, 69 insertions(+), 70 deletions(-) diff --git a/tests/pr-guard-policy.test.ts b/tests/pr-guard-policy.test.ts index 70a148b2..c8ac1782 100644 --- a/tests/pr-guard-policy.test.ts +++ b/tests/pr-guard-policy.test.ts @@ -4,7 +4,6 @@ import { describe, expect, it } from 'vitest'; type FileChange = { filename: string; status: string; - patch?: string; }; type PackageManifest = Record; type Decision = { @@ -24,6 +23,7 @@ const { classifyDependabotPR } = require('../scripts/pr-guard-policy.cjs') as { files: FileChange[]; basePackage?: PackageManifest; headPackage?: PackageManifest; + workflowContents?: Record; }): Decision; }; @@ -43,13 +43,12 @@ const headPackage = { dependencies: { commander: '15.1.0' }, devDependencies: { vitest: '5.0.2' }, }; -function actionLine( - sign: string, - action: string, - sha: string, - version: string, -): string { - return `${sign} uses: ${action}@${sha} # ${version}`; +const workflowFile = '.github/workflows/ci.yml'; +function workflowSource(steps: string, extra = ''): string { + return `name: CI\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n${steps}${extra}`; +} +function workflowRevisions(base: string, head: string) { + return { [workflowFile]: { base, head } }; } describe('Dependabot PR guard policy', () => { @@ -183,18 +182,15 @@ describe('Dependabot PR guard policy', () => { }); it('allows pinned action SHA updates', () => { - const patch = [ - '@@ -10,1 +10,1 @@', - actionLine('-', 'github/codeql-action/init', 'a'.repeat(40), 'v4.38.2'), - actionLine('+', 'github/codeql-action/init', 'b'.repeat(40), 'v4.39.0'), - ].join('\n'); const result = classifyDependabotPR({ login, title: actionTitle, baseRef, - files: [ - { filename: '.github/workflows/ci.yml', status: 'modified', patch }, - ], + files: [{ filename: workflowFile, status: 'modified' }], + workflowContents: workflowRevisions( + workflowSource(` - uses: github/codeql-action/init@${'a'.repeat(40)}\n`), + workflowSource(` - uses: github/codeql-action/init@${'b'.repeat(40)}\n`), + ), }); expect(result).toMatchObject({ allowed: true, @@ -204,18 +200,15 @@ describe('Dependabot PR guard policy', () => { }); it('rejects replacing a pinned action identity', () => { - const patch = [ - '@@ -10,1 +10,1 @@', - actionLine('-', 'actions/checkout', 'a'.repeat(40), 'v7.0.1'), - actionLine('+', 'attacker/unknown-action', 'b'.repeat(40), 'v1.0.0'), - ].join('\n'); const result = classifyDependabotPR({ login, title: actionTitle, baseRef, - files: [ - { filename: '.github/workflows/ci.yml', status: 'modified', patch }, - ], + files: [{ filename: workflowFile, status: 'modified' }], + workflowContents: workflowRevisions( + workflowSource(` - uses: actions/checkout@${'a'.repeat(40)}\n`), + workflowSource(` - uses: attacker/unknown-action@${'b'.repeat(40)}\n`), + ), }); expect(result.allowed).toBe(false); expect(result.reason).toMatch( @@ -224,18 +217,15 @@ describe('Dependabot PR guard policy', () => { }); it('allows pinned SHA updates on standard YAML sequence action steps', () => { - const patch = [ - '@@ -10,1 +10,1 @@', - '- - uses: actions/checkout@' + 'a'.repeat(40), - '+ - uses: actions/checkout@' + 'b'.repeat(40), - ].join('\n'); const result = classifyDependabotPR({ login, title: actionTitle, baseRef, - files: [ - { filename: '.github/workflows/ci.yml', status: 'modified', patch }, - ], + files: [{ filename: workflowFile, status: 'modified' }], + workflowContents: workflowRevisions( + workflowSource(` - name: Checkout\n uses: actions/checkout@${'a'.repeat(40)}\n`), + workflowSource(` - name: Checkout\n uses: actions/checkout@${'b'.repeat(40)}\n`), + ), }); expect(result).toMatchObject({ allowed: true, @@ -245,20 +235,19 @@ describe('Dependabot PR guard policy', () => { }); it('rejects swapping action identities between workflow steps', () => { - const patch = [ - '@@ -10,2 +10,2 @@', - '- - uses: actions/checkout@' + 'a'.repeat(40), - '- - uses: actions/setup-node@' + 'b'.repeat(40), - '+ - uses: actions/setup-node@' + 'c'.repeat(40), - '+ - uses: actions/checkout@' + 'd'.repeat(40), - ].join('\n'); const result = classifyDependabotPR({ login, title: actionTitle, baseRef, - files: [ - { filename: '.github/workflows/ci.yml', status: 'modified', patch }, - ], + files: [{ filename: workflowFile, status: 'modified' }], + workflowContents: workflowRevisions( + workflowSource( + ` - uses: actions/checkout@${'a'.repeat(40)}\n - uses: actions/setup-node@${'b'.repeat(40)}\n`, + ), + workflowSource( + ` - uses: actions/setup-node@${'c'.repeat(40)}\n - uses: actions/checkout@${'d'.repeat(40)}\n`, + ), + ), }); expect(result.allowed).toBe(false); expect(result.reason).toMatch( @@ -266,41 +255,51 @@ describe('Dependabot PR guard policy', () => { ); }); + it('rejects changes that imitate action references inside run block scalars', () => { + const shaA = 'a'.repeat(40); + const shaB = 'b'.repeat(40); + const base = workflowSource( + ` - run: |\n uses: actions/checkout@${shaA}\n`, + ); + const head = workflowSource( + ` - run: |\n uses: actions/checkout@${shaB}\n`, + ); + const result = classifyDependabotPR({ + login, + title: actionTitle, + baseRef, + files: [{ filename: workflowFile, status: 'modified' }], + workflowContents: workflowRevisions(base, head), + }); + expect(result.allowed).toBe(false); + }); + it('rejects workflow logic, permissions, and unpinned refs', () => { - const mixedPatch = [ - '@@ -10,1 +10,2 @@', - actionLine('-', 'github/codeql-action/init', 'a'.repeat(40), 'v4.38.2'), - actionLine('+', 'github/codeql-action/init', 'b'.repeat(40), 'v4.39.0'), - '+ permissions: contents: write', - ].join('\n'); - const unpinnedPatch = [ - '@@ -10,1 +10,1 @@', - '- uses: github/codeql-action/init@v4.38.2', - '+ uses: github/codeql-action/init@v4.39.0', - ].join('\n'); + const base = workflowSource( + ` - uses: github/codeql-action/init@${'a'.repeat(40)}\n`, + ); const mixed = classifyDependabotPR({ login, title: actionTitle, baseRef, - files: [ - { - filename: '.github/workflows/ci.yml', - status: 'modified', - patch: mixedPatch, - }, - ], + files: [{ filename: workflowFile, status: 'modified' }], + workflowContents: workflowRevisions( + base, + workflowSource( + ` - uses: github/codeql-action/init@${'b'.repeat(40)}\n`, + 'permissions:\n contents: write\n', + ), + ), }); const unpinned = classifyDependabotPR({ login, title: actionTitle, baseRef, - files: [ - { - filename: '.github/workflows/ci.yml', - status: 'modified', - patch: unpinnedPatch, - }, - ], + files: [{ filename: workflowFile, status: 'modified' }], + workflowContents: workflowRevisions( + base, + workflowSource(' - uses: github/codeql-action/init@v4.39.0\n'), + ), }); expect(mixed.allowed).toBe(false); expect(unpinned.allowed).toBe(false); @@ -330,11 +329,11 @@ describe('Dependabot PR guard policy', () => { }); it('fails closed for invalid authors, titles, branches, and files', () => { - const missingPatch = classifyDependabotPR({ + const missingWorkflow = classifyDependabotPR({ login, title: actionTitle, baseRef, - files: [{ filename: '.github/workflows/ci.yml', status: 'modified' }], + files: [{ filename: workflowFile, status: 'modified' }], }); const unrelated = classifyDependabotPR({ login, @@ -376,7 +375,7 @@ describe('Dependabot PR guard policy', () => { headPackage, }); - expect(missingPatch.allowed).toBe(false); + expect(missingWorkflow.allowed).toBe(false); expect(unrelated.allowed).toBe(false); expect(wrongAuthor.allowed).toBe(false); expect(wrongTitle.allowed).toBe(false); From d781ac59905d0d07162686f708cf2aed3726383d Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 11:34:06 +0100 Subject: [PATCH 47/94] test(automation): cover workflow source and dependency range guards --- tests/pr-guard-policy.test.ts | 41 +++++++++++++++++++++++++++++++++-- 1 file changed, 39 insertions(+), 2 deletions(-) diff --git a/tests/pr-guard-policy.test.ts b/tests/pr-guard-policy.test.ts index c8ac1782..dcaff9b0 100644 --- a/tests/pr-guard-policy.test.ts +++ b/tests/pr-guard-policy.test.ts @@ -91,6 +91,25 @@ describe('Dependabot PR guard policy', () => { expect(result.reason).toMatch(/outside dependency version sections/); }); + it('rejects replacing a non-semver dependency source with a version range', () => { + const result = classifyDependabotPR({ + login, + title: npmTitle, + baseRef, + files: [ + { filename: 'package.json', status: 'modified' }, + { filename: 'package-lock.json', status: 'modified' }, + ], + basePackage: { + ...basePackage, + dependencies: { commander: 'git+https://example.invalid/commander.git' }, + }, + headPackage, + }); + expect(result.allowed).toBe(false); + expect(result.reason).toMatch(/non-semver/); + }); + it('rejects dependency section presence and shape changes', () => { const withNullSection = { ...headPackage, @@ -212,7 +231,7 @@ describe('Dependabot PR guard policy', () => { }); expect(result.allowed).toBe(false); expect(result.reason).toMatch( - /workflow updates must replace pinned action SHAs/, + /workflow updates may change only pinned action SHAs/, ); }); @@ -251,7 +270,7 @@ describe('Dependabot PR guard policy', () => { }); expect(result.allowed).toBe(false); expect(result.reason).toMatch( - /workflow updates must replace pinned action SHAs/, + /workflow updates may change only pinned action SHAs/, ); }); @@ -274,6 +293,24 @@ describe('Dependabot PR guard policy', () => { expect(result.allowed).toBe(false); }); + it('rejects changing workflow comments alongside action SHAs', () => { + const result = classifyDependabotPR({ + login, + title: actionTitle, + baseRef, + files: [{ filename: workflowFile, status: 'modified' }], + workflowContents: workflowRevisions( + workflowSource( + ` - uses: actions/checkout@${'a'.repeat(40)} # v7.0.1\n`, + ), + workflowSource( + ` - uses: actions/checkout@${'b'.repeat(40)} # v7.0.2\n`, + ), + ), + }); + expect(result.allowed).toBe(false); + }); + it('rejects workflow logic, permissions, and unpinned refs', () => { const base = workflowSource( ` - uses: github/codeql-action/init@${'a'.repeat(40)}\n`, From 326ce3942042b7eb50617184ea7d64e431dceb38 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 11:34:45 +0100 Subject: [PATCH 48/94] fix(automation): validate lockfile changes against updated dependency graph --- scripts/pr-guard-policy.cjs | 159 +++++++++++++++++++++++++++++++++++- 1 file changed, 158 insertions(+), 1 deletion(-) diff --git a/scripts/pr-guard-policy.cjs b/scripts/pr-guard-policy.cjs index a6655aa4..8ca2f67c 100644 --- a/scripts/pr-guard-policy.cjs +++ b/scripts/pr-guard-policy.cjs @@ -60,6 +60,7 @@ function validatePackageManifest(basePackage, headPackage) { } let changedVersions = 0; + const changedDependencies = []; for (const section of sections) { const beforePresent = Object.hasOwn(basePackage, section); const afterPresent = Object.hasOwn(headPackage, section); @@ -86,13 +87,159 @@ function validatePackageManifest(basePackage, headPackage) { ); } changedVersions += 1; + changedDependencies.push(name); } } if (changedVersions === 0) { return deny('package.json contains no dependency version changes'); } - return { allowed: true, kind: 'npm-dependencies', changedVersions }; + return { + allowed: true, + kind: 'npm-dependencies', + changedVersions, + changedDependencies, + }; +} + +function resolveLockDependency(fromPath, dependencyName, packages) { + let current = fromPath; + while (true) { + const candidate = current + ? current + '/node_modules/' + dependencyName + : 'node_modules/' + dependencyName; + if (Object.hasOwn(packages, candidate)) return candidate; + + const marker = '/node_modules/'; + const markerIndex = current.lastIndexOf(marker); + if (markerIndex >= 0) { + current = current.slice(0, markerIndex); + } else if (current.startsWith('node_modules/')) { + current = ''; + } else { + break; + } + } + return null; +} + +function collectLockDependencyClosure(lock, dependencyNames) { + const packages = lock.packages; + const reachable = new Set(); + const visit = (packagePath) => { + if (reachable.has(packagePath)) return; + reachable.add(packagePath); + const metadata = packages[packagePath]; + if (!isObject(metadata)) return; + + const names = new Set([ + ...Object.keys(metadata.dependencies || {}), + ...Object.keys(metadata.optionalDependencies || {}), + ...Object.keys(metadata.peerDependencies || {}), + ]); + for (const name of names) { + const resolved = resolveLockDependency(packagePath, name, packages); + if (resolved) visit(resolved); + } + }; + + for (const name of dependencyNames) { + const resolved = resolveLockDependency('', name, packages); + if (!resolved) { + return { + allowed: false, + reason: 'package-lock.json is missing changed direct dependency "' + name + '"', + }; + } + visit(resolved); + } + return { allowed: true, reachable }; +} + +function validatePackageLock( + baseLock, + headLock, + basePackage, + headPackage, + changedDependencies, +) { + if ( + !isObject(baseLock) || + !isObject(headLock) || + baseLock.lockfileVersion !== 3 || + headLock.lockfileVersion !== 3 || + !isObject(baseLock.packages) || + !isObject(headLock.packages) || + !isObject(baseLock.packages['']) || + !isObject(headLock.packages['']) + ) { + return deny('package-lock.json must be a valid npm lockfile v3 at base and head'); + } + + const sections = [ + 'dependencies', + 'devDependencies', + 'optionalDependencies', + 'peerDependencies', + ]; + for (const [lock, manifest] of [ + [baseLock, basePackage], + [headLock, headPackage], + ]) { + const root = lock.packages['']; + if (root.name !== manifest.name || root.version !== manifest.version) { + return deny('package-lock root identity must match package.json'); + } + for (const section of sections) { + const expected = manifest[section] || {}; + const actual = root[section] || {}; + if (!sameJson(expected, actual)) { + return deny('package-lock root ' + section + ' must exactly match package.json'); + } + } + } + + const baseRoot = { ...baseLock.packages[''] }; + const headRoot = { ...headLock.packages[''] }; + for (const section of sections) { + delete baseRoot[section]; + delete headRoot[section]; + } + if (!sameJson(baseRoot, headRoot)) { + return deny('package-lock root metadata may not change outside dependency sections'); + } + + const baseTopLevel = { ...baseLock }; + const headTopLevel = { ...headLock }; + delete baseTopLevel.packages; + delete headTopLevel.packages; + if (!sameJson(baseTopLevel, headTopLevel)) { + return deny('package-lock metadata may not change outside the package graph'); + } + + const baseClosure = collectLockDependencyClosure(baseLock, changedDependencies); + if (!baseClosure.allowed) return deny(baseClosure.reason); + const headClosure = collectLockDependencyClosure(headLock, changedDependencies); + if (!headClosure.allowed) return deny(headClosure.reason); + const allowedPaths = new Set([ + ...baseClosure.reachable, + ...headClosure.reachable, + ]); + + const paths = new Set([ + ...Object.keys(baseLock.packages), + ...Object.keys(headLock.packages), + ]); + for (const packagePath of paths) { + if (packagePath === '' || allowedPaths.has(packagePath)) continue; + if (!sameJson(baseLock.packages[packagePath], headLock.packages[packagePath])) { + return deny( + 'package-lock.json changes package entries outside the updated direct-dependency closure', + ); + } + } + + return { allowed: true }; } function normalizeWorkflowSource(source) { @@ -187,6 +334,8 @@ function classifyDependabotPR({ basePackage, headPackage, workflowContents, + baseLock, + headLock, }) { if (login !== DEPENDABOT_LOGIN) { return deny('only the exact dependabot[bot] account is eligible'); @@ -210,6 +359,14 @@ function classifyDependabotPR({ if (sameJson(names, npmFiles)) { const manifest = validatePackageManifest(basePackage, headPackage); if (!manifest.allowed) return manifest; + const lock = validatePackageLock( + baseLock, + headLock, + basePackage, + headPackage, + manifest.changedDependencies, + ); + if (!lock.allowed) return lock; return { ...manifest, kind: 'npm-dependencies' }; } From 70fc0624b1a564f62ca614bb935ac1dee7ed32ba Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 11:34:59 +0100 Subject: [PATCH 49/94] fix(automation): provide base and head lockfiles to bot guard --- .github/workflows/wave-pr-guard.yml | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/.github/workflows/wave-pr-guard.yml b/.github/workflows/wave-pr-guard.yml index 61e9f9aa..7ced154e 100644 --- a/.github/workflows/wave-pr-guard.yml +++ b/.github/workflows/wave-pr-guard.yml @@ -46,18 +46,22 @@ jobs: const { classifyDependabotPR } = require('./scripts/pr-guard-policy.cjs'); let basePackage; let headPackage; + let baseLock; + let headLock; if (files.some((file) => file.filename === 'package.json')) { - const readPackageAtRef = async (ref) => { + const readJsonAtRef = async (path, ref) => { const { data } = await github.rest.repos.getContent({ - owner, repo, path: 'package.json', ref, + owner, repo, path, ref, }); if (Array.isArray(data) || data.type !== 'file' || data.encoding !== 'base64') { - throw new Error('Could not read package.json as a base64 file at ' + ref); + throw new Error('Could not read ' + path + ' as a base64 file at ' + ref); } return JSON.parse(Buffer.from(data.content, 'base64').toString('utf8')); }; - basePackage = await readPackageAtRef(pr.base.sha); - headPackage = await readPackageAtRef(pr.head.sha); + basePackage = await readJsonAtRef('package.json', pr.base.sha); + headPackage = await readJsonAtRef('package.json', pr.head.sha); + baseLock = await readJsonAtRef('package-lock.json', pr.base.sha); + headLock = await readJsonAtRef('package-lock.json', pr.head.sha); } const workflowContents = {}; for (const file of files.filter((item) => /^\\.github\\/workflows\\//.test(item.filename))) { @@ -83,6 +87,8 @@ jobs: basePackage, headPackage, workflowContents, + baseLock, + headLock, }); if (!decision.allowed) { core.setFailed('Dependabot PR rejected by narrow bot policy: ' + decision.reason); From 2df7e8190d6e112bac6ce5640074e00832d5cca0 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 11:35:18 +0100 Subject: [PATCH 50/94] test(automation): enforce lockfile dependency closure --- tests/pr-guard-policy.test.ts | 63 +++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/tests/pr-guard-policy.test.ts b/tests/pr-guard-policy.test.ts index dcaff9b0..e4cdf501 100644 --- a/tests/pr-guard-policy.test.ts +++ b/tests/pr-guard-policy.test.ts @@ -43,6 +43,34 @@ const headPackage = { dependencies: { commander: '15.1.0' }, devDependencies: { vitest: '5.0.2' }, }; +function lockFor(manifest: PackageManifest) { + const dependencies = manifest.dependencies || {}; + const devDependencies = manifest.devDependencies || {}; + const optionalDependencies = manifest.optionalDependencies || {}; + const peerDependencies = manifest.peerDependencies || {}; + return { + name: manifest.name, + version: manifest.version, + lockfileVersion: 3, + requires: true, + packages: { + '': { + name: manifest.name, + version: manifest.version, + dependencies, + devDependencies, + optionalDependencies, + peerDependencies, + }, + 'node_modules/commander': { + version: (dependencies as Record).commander, + }, + 'node_modules/vitest': { + version: (devDependencies as Record).vitest, + }, + }, + }; +} const workflowFile = '.github/workflows/ci.yml'; function workflowSource(steps: string, extra = ''): string { return `name: CI\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n${steps}${extra}`; @@ -63,6 +91,8 @@ describe('Dependabot PR guard policy', () => { ], basePackage, headPackage, + baseLock: lockFor(basePackage), + headLock: lockFor(headPackage), }); expect(result).toMatchObject({ allowed: true, @@ -86,6 +116,8 @@ describe('Dependabot PR guard policy', () => { ], basePackage, headPackage: changed, + baseLock: lockFor(basePackage), + headLock: lockFor(changed), }); expect(result.allowed).toBe(false); expect(result.reason).toMatch(/outside dependency version sections/); @@ -105,6 +137,11 @@ describe('Dependabot PR guard policy', () => { dependencies: { commander: 'git+https://example.invalid/commander.git' }, }, headPackage, + baseLock: lockFor({ + ...basePackage, + dependencies: { commander: 'git+https://example.invalid/commander.git' }, + }), + headLock: lockFor(headPackage), }); expect(result.allowed).toBe(false); expect(result.reason).toMatch(/non-semver/); @@ -133,6 +170,8 @@ describe('Dependabot PR guard policy', () => { ], basePackage: base, headPackage: head, + baseLock: lockFor(base), + headLock: lockFor(head), }); const baseWithPeerDependencies = { ...basePackage, @@ -342,6 +381,28 @@ describe('Dependabot PR guard policy', () => { expect(unpinned.allowed).toBe(false); }); + it('rejects lockfile changes outside updated dependency closures', () => { + const headLock = lockFor(headPackage); + headLock.packages['node_modules/unrelated-package'] = { + version: '1.2.3', + }; + const result = classifyDependabotPR({ + login, + title: npmTitle, + baseRef, + files: [ + { filename: 'package.json', status: 'modified' }, + { filename: 'package-lock.json', status: 'modified' }, + ], + basePackage, + headPackage, + baseLock: lockFor(basePackage), + headLock, + }); + expect(result.allowed).toBe(false); + expect(result.reason).toMatch(/outside the updated direct-dependency closure/); + }); + it('rejects oversized dependency ranges without catastrophic regex work', () => { const changed = { ...headPackage, @@ -359,6 +420,8 @@ describe('Dependabot PR guard policy', () => { ], basePackage, headPackage: changed, + baseLock: lockFor(basePackage), + headLock: lockFor(changed), }); expect(result.allowed).toBe(false); From bb07479ffb72f7e6ddc464808821fc8bd9b8dffa Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 11:35:36 +0100 Subject: [PATCH 51/94] test(automation): type lockfile validation fixtures --- tests/pr-guard-policy.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/pr-guard-policy.test.ts b/tests/pr-guard-policy.test.ts index e4cdf501..1e1b3896 100644 --- a/tests/pr-guard-policy.test.ts +++ b/tests/pr-guard-policy.test.ts @@ -23,6 +23,8 @@ const { classifyDependabotPR } = require('../scripts/pr-guard-policy.cjs') as { files: FileChange[]; basePackage?: PackageManifest; headPackage?: PackageManifest; + baseLock?: Record; + headLock?: Record; workflowContents?: Record; }): Decision; }; From f8dd80e0680bfbe43decd050b6ca92208cb48ef8 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 11:36:19 +0100 Subject: [PATCH 52/94] fix(automation): correct workflow path matcher syntax --- .github/workflows/wave-pr-guard.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/wave-pr-guard.yml b/.github/workflows/wave-pr-guard.yml index 7ced154e..2575cc6d 100644 --- a/.github/workflows/wave-pr-guard.yml +++ b/.github/workflows/wave-pr-guard.yml @@ -64,7 +64,7 @@ jobs: headLock = await readJsonAtRef('package-lock.json', pr.head.sha); } const workflowContents = {}; - for (const file of files.filter((item) => /^\\.github\\/workflows\\//.test(item.filename))) { + for (const file of files.filter((item) => /^\.github\/workflows\//.test(item.filename))) { const readWorkflowAtRef = async (ref) => { const { data } = await github.rest.repos.getContent({ owner, repo, path: file.filename, ref, From 138d914c00f5461b45142039f5ca8fa0f5acfa8f Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 11:37:11 +0100 Subject: [PATCH 53/94] fix(automation): verify registry integrity for changed lock entries --- scripts/pr-guard-policy.cjs | 36 +++++++++++++++++++++++++++++++----- 1 file changed, 31 insertions(+), 5 deletions(-) diff --git a/scripts/pr-guard-policy.cjs b/scripts/pr-guard-policy.cjs index 8ca2f67c..9c29a0dd 100644 --- a/scripts/pr-guard-policy.cjs +++ b/scripts/pr-guard-policy.cjs @@ -231,11 +231,37 @@ function validatePackageLock( ...Object.keys(headLock.packages), ]); for (const packagePath of paths) { - if (packagePath === '' || allowedPaths.has(packagePath)) continue; - if (!sameJson(baseLock.packages[packagePath], headLock.packages[packagePath])) { - return deny( - 'package-lock.json changes package entries outside the updated direct-dependency closure', - ); + if (packagePath === '') continue; + const before = baseLock.packages[packagePath]; + const after = headLock.packages[packagePath]; + if (!allowedPaths.has(packagePath)) { + if (!sameJson(before, after)) { + return deny( + 'package-lock.json changes package entries outside the updated direct-dependency closure', + ); + } + continue; + } + + if (before && after && before.version === after.version) { + if (!sameJson(before, after)) { + return deny( + 'package-lock entries may not change metadata without changing the package version', + ); + } + continue; + } + if (after) { + if ( + typeof after.resolved !== 'string' || + !after.resolved.startsWith('https://registry.npmjs.org/') || + typeof after.integrity !== 'string' || + after.integrity.length === 0 + ) { + return deny( + 'new or updated lockfile packages must use the npm registry and include integrity metadata', + ); + } } } From 379ff56c41a2901e03b64ec3f623faa6bac40962 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 11:37:20 +0100 Subject: [PATCH 54/94] test(automation): reject untrusted lockfile package origins --- tests/pr-guard-policy.test.ts | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/tests/pr-guard-policy.test.ts b/tests/pr-guard-policy.test.ts index 1e1b3896..b94d852e 100644 --- a/tests/pr-guard-policy.test.ts +++ b/tests/pr-guard-policy.test.ts @@ -66,9 +66,13 @@ function lockFor(manifest: PackageManifest) { }, 'node_modules/commander': { version: (dependencies as Record).commander, + resolved: 'https://registry.npmjs.org/commander/-/commander.tgz', + integrity: 'sha512-commander', }, 'node_modules/vitest': { version: (devDependencies as Record).vitest, + resolved: 'https://registry.npmjs.org/vitest/-/vitest.tgz', + integrity: 'sha512-vitest', }, }, }; @@ -383,6 +387,27 @@ describe('Dependabot PR guard policy', () => { expect(unpinned.allowed).toBe(false); }); + it('rejects changed lockfile packages resolved outside the npm registry', () => { + const headLock = lockFor(headPackage); + headLock.packages['node_modules/commander'].resolved = + 'https://attacker.example/commander.tgz'; + const result = classifyDependabotPR({ + login, + title: npmTitle, + baseRef, + files: [ + { filename: 'package.json', status: 'modified' }, + { filename: 'package-lock.json', status: 'modified' }, + ], + basePackage, + headPackage, + baseLock: lockFor(basePackage), + headLock, + }); + expect(result.allowed).toBe(false); + expect(result.reason).toMatch(/npm registry/); + }); + it('rejects lockfile changes outside updated dependency closures', () => { const headLock = lockFor(headPackage); headLock.packages['node_modules/unrelated-package'] = { From ab4a3fb652cb7e2671a24ab3ee5ff892e5f2e45f Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 11:38:05 +0100 Subject: [PATCH 55/94] fix(automation): reject malformed lockfile package metadata --- scripts/pr-guard-policy.cjs | 38 +++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/scripts/pr-guard-policy.cjs b/scripts/pr-guard-policy.cjs index 9c29a0dd..dc3fcd0e 100644 --- a/scripts/pr-guard-policy.cjs +++ b/scripts/pr-guard-policy.cjs @@ -182,6 +182,44 @@ function validatePackageLock( 'optionalDependencies', 'peerDependencies', ]; + for (const [packagePath, metadata] of Object.entries(baseLock.packages)) { + if (!isObject(metadata)) { + return deny('package-lock package entries must be JSON objects'); + } + for (const section of [ + 'dependencies', + 'optionalDependencies', + 'peerDependencies', + ]) { + if ( + Object.hasOwn(metadata, section) && + !isObject(metadata[section]) + ) { + return deny( + 'package-lock ' + section + ' entries must remain JSON objects', + ); + } + } + } + for (const [packagePath, metadata] of Object.entries(headLock.packages)) { + if (!isObject(metadata)) { + return deny('package-lock package entries must be JSON objects'); + } + for (const section of [ + 'dependencies', + 'optionalDependencies', + 'peerDependencies', + ]) { + if ( + Object.hasOwn(metadata, section) && + !isObject(metadata[section]) + ) { + return deny( + 'package-lock ' + section + ' entries must remain JSON objects', + ); + } + } + } for (const [lock, manifest] of [ [baseLock, basePackage], [headLock, headPackage], From e7c7ba6542fac1e2dbd815aeaaf851b2b30297a2 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 11:38:10 +0100 Subject: [PATCH 56/94] style(automation): remove unused lockfile loop variables --- scripts/pr-guard-policy.cjs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/pr-guard-policy.cjs b/scripts/pr-guard-policy.cjs index dc3fcd0e..6912ecdd 100644 --- a/scripts/pr-guard-policy.cjs +++ b/scripts/pr-guard-policy.cjs @@ -182,7 +182,7 @@ function validatePackageLock( 'optionalDependencies', 'peerDependencies', ]; - for (const [packagePath, metadata] of Object.entries(baseLock.packages)) { + for (const metadata of Object.values(baseLock.packages)) { if (!isObject(metadata)) { return deny('package-lock package entries must be JSON objects'); } @@ -201,7 +201,7 @@ function validatePackageLock( } } } - for (const [packagePath, metadata] of Object.entries(headLock.packages)) { + for (const metadata of Object.values(headLock.packages)) { if (!isObject(metadata)) { return deny('package-lock package entries must be JSON objects'); } From 7609924d26443b4f32da0757c45c4b7d63d99092 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 11:38:29 +0100 Subject: [PATCH 57/94] test(automation): type lockfile package map fixture --- tests/pr-guard-policy.test.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/tests/pr-guard-policy.test.ts b/tests/pr-guard-policy.test.ts index b94d852e..2153f090 100644 --- a/tests/pr-guard-policy.test.ts +++ b/tests/pr-guard-policy.test.ts @@ -45,7 +45,13 @@ const headPackage = { dependencies: { commander: '15.1.0' }, devDependencies: { vitest: '5.0.2' }, }; -function lockFor(manifest: PackageManifest) { +function lockFor(manifest: PackageManifest): { + name: unknown; + version: unknown; + lockfileVersion: number; + requires: boolean; + packages: Record>; +} { const dependencies = manifest.dependencies || {}; const devDependencies = manifest.devDependencies || {}; const optionalDependencies = manifest.optionalDependencies || {}; From 1e18354178d9cf128b9c53dacbc1dae26e8d3441 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 11:39:23 +0100 Subject: [PATCH 58/94] test(automation): narrow lockfile fixture package access --- tests/pr-guard-policy.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/pr-guard-policy.test.ts b/tests/pr-guard-policy.test.ts index 2153f090..e5b79758 100644 --- a/tests/pr-guard-policy.test.ts +++ b/tests/pr-guard-policy.test.ts @@ -395,7 +395,7 @@ describe('Dependabot PR guard policy', () => { it('rejects changed lockfile packages resolved outside the npm registry', () => { const headLock = lockFor(headPackage); - headLock.packages['node_modules/commander'].resolved = + headLock.packages['node_modules/commander']!.resolved = 'https://attacker.example/commander.tgz'; const result = classifyDependabotPR({ login, From a02787f658d260b3864f4ae5bd3300695c5c342b Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 11:40:26 +0100 Subject: [PATCH 59/94] fix(automation): exclude quoted YAML scalars from action updates --- scripts/pr-guard-policy.cjs | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/scripts/pr-guard-policy.cjs b/scripts/pr-guard-policy.cjs index 6912ecdd..3747541c 100644 --- a/scripts/pr-guard-policy.cjs +++ b/scripts/pr-guard-policy.cjs @@ -306,16 +306,41 @@ function validatePackageLock( return { allowed: true }; } +function hasClosingQuote(line, quote, startIndex) { + for (let index = startIndex; index < line.length; index += 1) { + if (quote === '"' && line[index] === '\\') { + index += 1; + continue; + } + if ( + quote === "'" && + line[index] === "'" && + line[index + 1] === "'" + ) { + index += 1; + continue; + } + if (line[index] === quote) return true; + } + return false; +} + function normalizeWorkflowSource(source) { const lines = source.split(/\r?\n/); const references = []; let blockScalarIndent = null; + let quotedScalar = null; for (let index = 0; index < lines.length; index += 1) { const line = lines[index]; const indentation = line.match(/^ */)[0].length; const trimmed = line.trim(); + if (quotedScalar !== null) { + if (hasClosingQuote(line, quotedScalar, 0)) quotedScalar = null; + continue; + } + if (blockScalarIndent !== null) { if (trimmed === '' || indentation > blockScalarIndent) continue; blockScalarIndent = null; @@ -330,6 +355,18 @@ function normalizeWorkflowSource(source) { continue; } + const quotedValue = line.match( + /^\s*(?:-\s*)?[A-Za-z0-9_.-]+:\s*(['"])/, + ); + if (quotedValue) { + const quote = quotedValue[1]; + const quoteIndex = line.indexOf(quote, quotedValue[0].length - 1); + if (!hasClosingQuote(line, quote, quoteIndex + 1)) { + quotedScalar = quote; + continue; + } + } + const match = line.match( /^(\s*(?:-\s*)?uses:\s*)([A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)+)@([a-f0-9]{40})(\s+#.*)?$/i, ); From df0b5d0c0f6127c9c647cd9f410c788da77a747a Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 11:40:35 +0100 Subject: [PATCH 60/94] test(automation): reject quoted scalar action lookalikes --- tests/pr-guard-policy.test.ts | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/tests/pr-guard-policy.test.ts b/tests/pr-guard-policy.test.ts index e5b79758..7b434a44 100644 --- a/tests/pr-guard-policy.test.ts +++ b/tests/pr-guard-policy.test.ts @@ -362,6 +362,23 @@ describe('Dependabot PR guard policy', () => { expect(result.allowed).toBe(false); }); + it('rejects changes that imitate action references inside quoted YAML scalars', () => { + const base = workflowSource( + ` - run: "script body\n uses: actions/checkout@${'a'.repeat(40)}"\n`, + ); + const head = workflowSource( + ` - run: "script body\n uses: actions/checkout@${'b'.repeat(40)}"\n`, + ); + const result = classifyDependabotPR({ + login, + title: actionTitle, + baseRef, + files: [{ filename: workflowFile, status: 'modified' }], + workflowContents: workflowRevisions(base, head), + }); + expect(result.allowed).toBe(false); + }); + it('rejects workflow logic, permissions, and unpinned refs', () => { const base = workflowSource( ` - uses: github/codeql-action/init@${'a'.repeat(40)}\n`, From 70c9709092e56a5a2ab1b5c317f9f7fb5dce17c7 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 11:41:26 +0100 Subject: [PATCH 61/94] fix(automation): require semver lockfile package versions --- scripts/pr-guard-policy.cjs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/scripts/pr-guard-policy.cjs b/scripts/pr-guard-policy.cjs index 3747541c..2f70c7f6 100644 --- a/scripts/pr-guard-policy.cjs +++ b/scripts/pr-guard-policy.cjs @@ -291,6 +291,10 @@ function validatePackageLock( } if (after) { if ( + typeof after.version !== 'string' || + !/^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$/.test( + after.version, + ) || typeof after.resolved !== 'string' || !after.resolved.startsWith('https://registry.npmjs.org/') || typeof after.integrity !== 'string' || From 28ab628adfabdc7b5bae796bd6a225b1c581ba9d Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 11:41:36 +0100 Subject: [PATCH 62/94] fix(automation): correct lockfile semver expression --- scripts/pr-guard-policy.cjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/pr-guard-policy.cjs b/scripts/pr-guard-policy.cjs index 2f70c7f6..52ee3cbc 100644 --- a/scripts/pr-guard-policy.cjs +++ b/scripts/pr-guard-policy.cjs @@ -292,7 +292,7 @@ function validatePackageLock( if (after) { if ( typeof after.version !== 'string' || - !/^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$/.test( + !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test( after.version, ) || typeof after.resolved !== 'string' || From 2bafee60983fb1c08c3f08209b251203cf71033d Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 11:41:43 +0100 Subject: [PATCH 63/94] test(automation): reject invalid package versions in lock entries --- tests/pr-guard-policy.test.ts | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/tests/pr-guard-policy.test.ts b/tests/pr-guard-policy.test.ts index 7b434a44..6b17c55d 100644 --- a/tests/pr-guard-policy.test.ts +++ b/tests/pr-guard-policy.test.ts @@ -431,6 +431,26 @@ describe('Dependabot PR guard policy', () => { expect(result.reason).toMatch(/npm registry/); }); + it('rejects non-semver package versions in changed lock entries', () => { + const headLock = lockFor(headPackage); + headLock.packages['node_modules/commander']!.version = 'not-a-version'; + const result = classifyDependabotPR({ + login, + title: npmTitle, + baseRef, + files: [ + { filename: 'package.json', status: 'modified' }, + { filename: 'package-lock.json', status: 'modified' }, + ], + basePackage, + headPackage, + baseLock: lockFor(basePackage), + headLock, + }); + expect(result.allowed).toBe(false); + expect(result.reason).toMatch(/npm registry/); + }); + it('rejects lockfile changes outside updated dependency closures', () => { const headLock = lockFor(headPackage); headLock.packages['node_modules/unrelated-package'] = { From efdf59aacb86b756aa7b1a0a8026b293846ed7a1 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 13:15:28 +0100 Subject: [PATCH 64/94] style: fix PR guard test formatting --- tests/pr-guard-policy.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/pr-guard-policy.test.ts b/tests/pr-guard-policy.test.ts index 6b17c55d..cc2ef453 100644 --- a/tests/pr-guard-policy.test.ts +++ b/tests/pr-guard-policy.test.ts @@ -470,7 +470,9 @@ describe('Dependabot PR guard policy', () => { headLock, }); expect(result.allowed).toBe(false); - expect(result.reason).toMatch(/outside the updated direct-dependency closure/); + expect(result.reason).toMatch( + /outside the updated direct-dependency closure/, + ); }); it('rejects oversized dependency ranges without catastrophic regex work', () => { From 62ec466e14490e9b52eeb6b29c68ac753a2e4308 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 15:02:00 +0100 Subject: [PATCH 65/94] style: format PR guard policy tests --- tests/pr-guard-policy.test.ts | 48 ++++++++++++++++++++++++++--------- 1 file changed, 36 insertions(+), 12 deletions(-) diff --git a/tests/pr-guard-policy.test.ts b/tests/pr-guard-policy.test.ts index cc2ef453..44b7eb45 100644 --- a/tests/pr-guard-policy.test.ts +++ b/tests/pr-guard-policy.test.ts @@ -135,7 +135,9 @@ describe('Dependabot PR guard policy', () => { expect(result.reason).toMatch(/outside dependency version sections/); }); - it('rejects replacing a non-semver dependency source with a version range', () => { + it( + 'rejects replacing a non-semver dependency source with a version range', + () => { const result = classifyDependabotPR({ login, title: npmTitle, @@ -146,12 +148,16 @@ describe('Dependabot PR guard policy', () => { ], basePackage: { ...basePackage, - dependencies: { commander: 'git+https://example.invalid/commander.git' }, + dependencies: { + commander: 'git+https://example.invalid/commander.git', + }, }, headPackage, baseLock: lockFor({ ...basePackage, - dependencies: { commander: 'git+https://example.invalid/commander.git' }, + dependencies: { + commander: 'git+https://example.invalid/commander.git', + }, }), headLock: lockFor(headPackage), }); @@ -258,8 +264,12 @@ describe('Dependabot PR guard policy', () => { baseRef, files: [{ filename: workflowFile, status: 'modified' }], workflowContents: workflowRevisions( - workflowSource(` - uses: github/codeql-action/init@${'a'.repeat(40)}\n`), - workflowSource(` - uses: github/codeql-action/init@${'b'.repeat(40)}\n`), + workflowSource( + ` - uses: github/codeql-action/init@${'a'.repeat(40)}\n`, + ), + workflowSource( + ` - uses: github/codeql-action/init@${'b'.repeat(40)}\n`, + ), ), }); expect(result).toMatchObject({ @@ -277,7 +287,9 @@ describe('Dependabot PR guard policy', () => { files: [{ filename: workflowFile, status: 'modified' }], workflowContents: workflowRevisions( workflowSource(` - uses: actions/checkout@${'a'.repeat(40)}\n`), - workflowSource(` - uses: attacker/unknown-action@${'b'.repeat(40)}\n`), + workflowSource( + ` - uses: attacker/unknown-action@${'b'.repeat(40)}\n`, + ), ), }); expect(result.allowed).toBe(false); @@ -293,8 +305,12 @@ describe('Dependabot PR guard policy', () => { baseRef, files: [{ filename: workflowFile, status: 'modified' }], workflowContents: workflowRevisions( - workflowSource(` - name: Checkout\n uses: actions/checkout@${'a'.repeat(40)}\n`), - workflowSource(` - name: Checkout\n uses: actions/checkout@${'b'.repeat(40)}\n`), + workflowSource( + ` - name: Checkout\n uses: actions/checkout@${'a'.repeat(40)}\n`, + ), + workflowSource( + ` - name: Checkout\n uses: actions/checkout@${'b'.repeat(40)}\n`, + ), ), }); expect(result).toMatchObject({ @@ -325,7 +341,9 @@ describe('Dependabot PR guard policy', () => { ); }); - it('rejects changes that imitate action references inside run block scalars', () => { + it( + 'rejects changes that imitate action references inside run block scalars', + () => { const shaA = 'a'.repeat(40); const shaB = 'b'.repeat(40); const base = workflowSource( @@ -362,7 +380,9 @@ describe('Dependabot PR guard policy', () => { expect(result.allowed).toBe(false); }); - it('rejects changes that imitate action references inside quoted YAML scalars', () => { + it( + 'rejects changes that imitate action references inside quoted YAML scalars', + () => { const base = workflowSource( ` - run: "script body\n uses: actions/checkout@${'a'.repeat(40)}"\n`, ); @@ -410,7 +430,9 @@ describe('Dependabot PR guard policy', () => { expect(unpinned.allowed).toBe(false); }); - it('rejects changed lockfile packages resolved outside the npm registry', () => { + it( + 'rejects changed lockfile packages resolved outside the npm registry', + () => { const headLock = lockFor(headPackage); headLock.packages['node_modules/commander']!.resolved = 'https://attacker.example/commander.tgz'; @@ -475,7 +497,9 @@ describe('Dependabot PR guard policy', () => { ); }); - it('rejects oversized dependency ranges without catastrophic regex work', () => { + it( + 'rejects oversized dependency ranges without catastrophic regex work', + () => { const changed = { ...headPackage, dependencies: { From 715a7a319896df25c5ffbd904dfa4f0290a67817 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 19:47:58 +0100 Subject: [PATCH 66/94] fix(tests): correct Prettier indentation in PR guard tests --- tests/pr-guard-policy.test.ts | 188 +++++++++++++++++----------------- 1 file changed, 94 insertions(+), 94 deletions(-) diff --git a/tests/pr-guard-policy.test.ts b/tests/pr-guard-policy.test.ts index 44b7eb45..15c6fcb4 100644 --- a/tests/pr-guard-policy.test.ts +++ b/tests/pr-guard-policy.test.ts @@ -138,31 +138,31 @@ describe('Dependabot PR guard policy', () => { it( 'rejects replacing a non-semver dependency source with a version range', () => { - const result = classifyDependabotPR({ - login, - title: npmTitle, - baseRef, - files: [ - { filename: 'package.json', status: 'modified' }, - { filename: 'package-lock.json', status: 'modified' }, - ], - basePackage: { - ...basePackage, - dependencies: { - commander: 'git+https://example.invalid/commander.git', - }, - }, - headPackage, - baseLock: lockFor({ - ...basePackage, - dependencies: { - commander: 'git+https://example.invalid/commander.git', + const result = classifyDependabotPR({ + login, + title: npmTitle, + baseRef, + files: [ + { filename: 'package.json', status: 'modified' }, + { filename: 'package-lock.json', status: 'modified' }, + ], + basePackage: { + ...basePackage, + dependencies: { + commander: 'git+https://example.invalid/commander.git', + }, }, - }), - headLock: lockFor(headPackage), - }); - expect(result.allowed).toBe(false); - expect(result.reason).toMatch(/non-semver/); + headPackage, + baseLock: lockFor({ + ...basePackage, + dependencies: { + commander: 'git+https://example.invalid/commander.git', + }, + }), + headLock: lockFor(headPackage), + }); + expect(result.allowed).toBe(false); + expect(result.reason).toMatch(/non-semver/); }); it('rejects dependency section presence and shape changes', () => { @@ -344,22 +344,22 @@ describe('Dependabot PR guard policy', () => { it( 'rejects changes that imitate action references inside run block scalars', () => { - const shaA = 'a'.repeat(40); - const shaB = 'b'.repeat(40); - const base = workflowSource( - ` - run: |\n uses: actions/checkout@${shaA}\n`, - ); - const head = workflowSource( - ` - run: |\n uses: actions/checkout@${shaB}\n`, - ); - const result = classifyDependabotPR({ - login, - title: actionTitle, - baseRef, - files: [{ filename: workflowFile, status: 'modified' }], - workflowContents: workflowRevisions(base, head), - }); - expect(result.allowed).toBe(false); + const shaA = 'a'.repeat(40); + const shaB = 'b'.repeat(40); + const base = workflowSource( + ` - run: |\n uses: actions/checkout@${shaA}\n`, + ); + const head = workflowSource( + ` - run: |\n uses: actions/checkout@${shaB}\n`, + ); + const result = classifyDependabotPR({ + login, + title: actionTitle, + baseRef, + files: [{ filename: workflowFile, status: 'modified' }], + workflowContents: workflowRevisions(base, head), + }); + expect(result.allowed).toBe(false); }); it('rejects changing workflow comments alongside action SHAs', () => { @@ -383,20 +383,20 @@ describe('Dependabot PR guard policy', () => { it( 'rejects changes that imitate action references inside quoted YAML scalars', () => { - const base = workflowSource( - ` - run: "script body\n uses: actions/checkout@${'a'.repeat(40)}"\n`, - ); - const head = workflowSource( - ` - run: "script body\n uses: actions/checkout@${'b'.repeat(40)}"\n`, - ); - const result = classifyDependabotPR({ - login, - title: actionTitle, - baseRef, - files: [{ filename: workflowFile, status: 'modified' }], - workflowContents: workflowRevisions(base, head), - }); - expect(result.allowed).toBe(false); + const base = workflowSource( + ` - run: "script body\n uses: actions/checkout@${'a'.repeat(40)}"\n`, + ); + const head = workflowSource( + ` - run: "script body\n uses: actions/checkout@${'b'.repeat(40)}"\n`, + ); + const result = classifyDependabotPR({ + login, + title: actionTitle, + baseRef, + files: [{ filename: workflowFile, status: 'modified' }], + workflowContents: workflowRevisions(base, head), + }); + expect(result.allowed).toBe(false); }); it('rejects workflow logic, permissions, and unpinned refs', () => { @@ -433,24 +433,24 @@ describe('Dependabot PR guard policy', () => { it( 'rejects changed lockfile packages resolved outside the npm registry', () => { - const headLock = lockFor(headPackage); - headLock.packages['node_modules/commander']!.resolved = - 'https://attacker.example/commander.tgz'; - const result = classifyDependabotPR({ - login, - title: npmTitle, - baseRef, - files: [ - { filename: 'package.json', status: 'modified' }, - { filename: 'package-lock.json', status: 'modified' }, - ], - basePackage, - headPackage, - baseLock: lockFor(basePackage), - headLock, - }); - expect(result.allowed).toBe(false); - expect(result.reason).toMatch(/npm registry/); + const headLock = lockFor(headPackage); + headLock.packages['node_modules/commander']!.resolved = + 'https://attacker.example/commander.tgz'; + const result = classifyDependabotPR({ + login, + title: npmTitle, + baseRef, + files: [ + { filename: 'package.json', status: 'modified' }, + { filename: 'package-lock.json', status: 'modified' }, + ], + basePackage, + headPackage, + baseLock: lockFor(basePackage), + headLock, + }); + expect(result.allowed).toBe(false); + expect(result.reason).toMatch(/npm registry/); }); it('rejects non-semver package versions in changed lock entries', () => { @@ -500,28 +500,28 @@ describe('Dependabot PR guard policy', () => { it( 'rejects oversized dependency ranges without catastrophic regex work', () => { - const changed = { - ...headPackage, - dependencies: { - commander: '9.9.9|| 9.9.9||'.repeat(1000), - }, - }; - const result = classifyDependabotPR({ - login, - title: npmTitle, - baseRef, - files: [ - { filename: 'package.json', status: 'modified' }, - { filename: 'package-lock.json', status: 'modified' }, - ], - basePackage, - headPackage: changed, - baseLock: lockFor(basePackage), - headLock: lockFor(changed), - }); - - expect(result.allowed).toBe(false); - expect(result.reason).toMatch(/non-semver|non-string/); + const changed = { + ...headPackage, + dependencies: { + commander: '9.9.9|| 9.9.9||'.repeat(1000), + }, + }; + const result = classifyDependabotPR({ + login, + title: npmTitle, + baseRef, + files: [ + { filename: 'package.json', status: 'modified' }, + { filename: 'package-lock.json', status: 'modified' }, + ], + basePackage, + headPackage: changed, + baseLock: lockFor(basePackage), + headLock: lockFor(changed), + }); + + expect(result.allowed).toBe(false); + expect(result.reason).toMatch(/non-semver|non-string/); }); it('fails closed for invalid authors, titles, branches, and files', () => { From 556a1213ae96d252974e2584f92b98a762b34147 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 21:39:47 +0100 Subject: [PATCH 67/94] fix(tests): format multiline PR guard test callbacks --- tests/pr-guard-policy.test.ts | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/tests/pr-guard-policy.test.ts b/tests/pr-guard-policy.test.ts index 15c6fcb4..9115ddd8 100644 --- a/tests/pr-guard-policy.test.ts +++ b/tests/pr-guard-policy.test.ts @@ -163,7 +163,8 @@ describe('Dependabot PR guard policy', () => { }); expect(result.allowed).toBe(false); expect(result.reason).toMatch(/non-semver/); - }); + }, + ); it('rejects dependency section presence and shape changes', () => { const withNullSection = { @@ -360,7 +361,8 @@ describe('Dependabot PR guard policy', () => { workflowContents: workflowRevisions(base, head), }); expect(result.allowed).toBe(false); - }); + }, + ); it('rejects changing workflow comments alongside action SHAs', () => { const result = classifyDependabotPR({ @@ -397,7 +399,8 @@ describe('Dependabot PR guard policy', () => { workflowContents: workflowRevisions(base, head), }); expect(result.allowed).toBe(false); - }); + }, + ); it('rejects workflow logic, permissions, and unpinned refs', () => { const base = workflowSource( @@ -451,7 +454,8 @@ describe('Dependabot PR guard policy', () => { }); expect(result.allowed).toBe(false); expect(result.reason).toMatch(/npm registry/); - }); + }, + ); it('rejects non-semver package versions in changed lock entries', () => { const headLock = lockFor(headPackage); @@ -519,10 +523,11 @@ describe('Dependabot PR guard policy', () => { baseLock: lockFor(basePackage), headLock: lockFor(changed), }); - + expect(result.allowed).toBe(false); expect(result.reason).toMatch(/non-semver|non-string/); - }); + }, + ); it('fails closed for invalid authors, titles, branches, and files', () => { const missingWorkflow = classifyDependabotPR({ From 4bfd0e582b56a9cf4072774b0f8788b96c454a60 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 21:42:36 +0100 Subject: [PATCH 68/94] fix(security): pin Dependabot guard to PR merge base --- .github/workflows/wave-pr-guard.yml | 29 +++++++++++++++++++++-------- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/.github/workflows/wave-pr-guard.yml b/.github/workflows/wave-pr-guard.yml index 2575cc6d..ec54d1d1 100644 --- a/.github/workflows/wave-pr-guard.yml +++ b/.github/workflows/wave-pr-guard.yml @@ -36,9 +36,22 @@ jobs: } const isDependabot = pr.user.login === 'dependabot[bot]'; - const files = await github.paginate(github.rest.pulls.listFiles, { - owner, repo, pull_number: pr.number, per_page: 100, + // Pin the comparison to the event's immutable head SHA. The merge + // base, file list, and file contents must describe the same diff. + const comparison = await github.rest.repos.compareCommitsWithBasehead({ + owner, + repo, + basehead: pr.base.ref + '...' + pr.head.sha, }); + if (comparison.data.head.sha !== pr.head.sha || !comparison.data.merge_base_commit?.sha) { + throw new Error('Could not establish an immutable PR merge-base comparison'); + } + const mergeBaseSha = comparison.data.merge_base_commit.sha; + const files = comparison.data.files || []; + if (comparison.data.total_commits > 0 && files.length === 300) { + throw new Error('PR file comparison reached GitHub’s 300-file limit; failing closed'); + } + const changedPaths = (file) => [file.previous_filename, file.filename].filter(Boolean); let labels = new Set(); let linkedIssueNumber = null; @@ -58,9 +71,9 @@ jobs: } return JSON.parse(Buffer.from(data.content, 'base64').toString('utf8')); }; - basePackage = await readJsonAtRef('package.json', pr.base.sha); + basePackage = await readJsonAtRef('package.json', mergeBaseSha); headPackage = await readJsonAtRef('package.json', pr.head.sha); - baseLock = await readJsonAtRef('package-lock.json', pr.base.sha); + baseLock = await readJsonAtRef('package-lock.json', mergeBaseSha); headLock = await readJsonAtRef('package-lock.json', pr.head.sha); } const workflowContents = {}; @@ -75,7 +88,7 @@ jobs: return Buffer.from(data.content, 'base64').toString('utf8'); }; workflowContents[file.filename] = { - base: await readWorkflowAtRef(pr.base.sha), + base: await readWorkflowAtRef(mergeBaseSha), head: await readWorkflowAtRef(pr.head.sha), }; } @@ -156,10 +169,10 @@ jobs: /^src\/dev\/(?:orchestrator|environment)\.ts$/, /^(?:package|package-lock)\.json$/, /^SECURITY\.md$/, ]; - const protectedFiles = files.map((f) => f.filename) + const protectedFiles = [...new Set(files.flatMap(changedPaths))] .filter((name) => protectedPatterns.some((pattern) => pattern.test(name))); - const currentNames = new Set(files.map((file) => file.filename)); + const currentNames = new Set(files.flatMap(changedPaths)); const openPulls = await github.paginate(github.rest.pulls.list, { owner, repo, state: 'open', per_page: 100, }); @@ -170,7 +183,7 @@ jobs: owner, repo, pull_number: other.number, per_page: 100, }); const overlap = otherFiles - .map((file) => file.filename) + .flatMap(changedPaths) .filter((name) => currentNames.has(name)) .filter((name) => protectedPatterns.some((pattern) => pattern.test(name)) || From 91c873254f3125d8f9d2bb103e63a1a731fede8a Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 21:43:36 +0100 Subject: [PATCH 69/94] fix(ci): read merge base from compare response --- .github/workflows/wave-pr-guard.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/wave-pr-guard.yml b/.github/workflows/wave-pr-guard.yml index ec54d1d1..f33e56aa 100644 --- a/.github/workflows/wave-pr-guard.yml +++ b/.github/workflows/wave-pr-guard.yml @@ -43,7 +43,7 @@ jobs: repo, basehead: pr.base.ref + '...' + pr.head.sha, }); - if (comparison.data.head.sha !== pr.head.sha || !comparison.data.merge_base_commit?.sha) { + if (!comparison.data.merge_base_commit?.sha) { throw new Error('Could not establish an immutable PR merge-base comparison'); } const mergeBaseSha = comparison.data.merge_base_commit.sha; From 1d2e055f0c9533932daec0e7b61975a7cf3505e0 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 21:45:11 +0100 Subject: [PATCH 70/94] chore(ci): export canonical guard test formatting --- .github/workflows/ci.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3ccf7e9b..adf66850 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -46,6 +46,11 @@ jobs: - name: Lint run: npm run lint + - name: TEMP export Prettier-formatted guard tests + run: | + npx prettier tests/pr-guard-policy.test.ts | base64 -w0 + echo + - name: Check formatting run: npm run format:check From d239ccb377144ea6e149df97e408d4e5e2885d58 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 21:45:21 +0100 Subject: [PATCH 71/94] chore(ci): remove temporary formatter export step --- .github/workflows/ci.yml | 5 ----- 1 file changed, 5 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index adf66850..3ccf7e9b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -46,11 +46,6 @@ jobs: - name: Lint run: npm run lint - - name: TEMP export Prettier-formatted guard tests - run: | - npx prettier tests/pr-guard-policy.test.ts | base64 -w0 - echo - - name: Check formatting run: npm run format:check From 240ceef57fb668da85475299e2df3bef0589653d Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 22:03:16 +0100 Subject: [PATCH 72/94] fix(security): validate npm lockfile versions and dependency graph --- scripts/pr-guard-policy.cjs | 135 +++++++++++++++++++++++++++++++++++- 1 file changed, 133 insertions(+), 2 deletions(-) diff --git a/scripts/pr-guard-policy.cjs b/scripts/pr-guard-policy.cjs index 52ee3cbc..584dd0f8 100644 --- a/scripts/pr-guard-policy.cjs +++ b/scripts/pr-guard-policy.cjs @@ -16,6 +16,78 @@ function isVersionRange(value) { ); } +function parseSemver(version) { + if (typeof version !== 'string') return null; + const match = version.match( + /^(\\d+)\\.(\\d+)\\.(\\d+)(?:-([0-9A-Za-z.-]+))?(?:\\+[0-9A-Za-z.-]+)?$/, + ); + if (!match) return null; + return { + major: Number(match[1]), + minor: Number(match[2]), + patch: Number(match[3]), + prerelease: match[4] ? match[4].split('.') : null, + }; +} + +function compareSemver(left, right) { + const a = parseSemver(left); + const b = parseSemver(right); + if (!a || !b) return null; + for (const key of ['major', 'minor', 'patch']) { + if (a[key] !== b[key]) return a[key] < b[key] ? -1 : 1; + } + if (a.prerelease === null && b.prerelease === null) return 0; + if (a.prerelease === null) return 1; + if (b.prerelease === null) return -1; + const length = Math.max(a.prerelease.length, b.prerelease.length); + for (let index = 0; index < length; index += 1) { + const x = a.prerelease[index]; + const y = b.prerelease[index]; + if (x === undefined) return -1; + if (y === undefined) return 1; + if (x === y) continue; + const xn = /^\\d+$/.test(x); + const yn = /^\\d+$/.test(y); + if (xn && yn) return Number(x) < Number(y) ? -1 : 1; + if (xn !== yn) return xn ? -1 : 1; + return x < y ? -1 : 1; + } + return 0; +} + +function satisfiesVersionRange(version, range) { + if (!parseSemver(version) || !isVersionRange(range)) return false; + return range.split('||').some((rawClause) => { + const match = rawClause.trim().match( + /^(\\^|~|>=|>|<=|<|=)?\\s*(\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?)$/, + ); + if (!match) return false; + const operator = match[1] || '='; + const required = match[2]; + const compared = compareSemver(version, required); + if (compared === null) return false; + if (operator === '=') return compared === 0; + if (operator === '>') return compared > 0; + if (operator === '>=') return compared >= 0; + if (operator === '<') return compared < 0; + if (operator === '<=') return compared <= 0; + if (operator === '~') { + const parsed = parseSemver(required); + const upper = parsed.major + '.' + (parsed.minor + 1) + '.0'; + return compared >= 0 && compareSemver(version, upper) < 0; + } + const parsed = parseSemver(required); + const upper = + parsed.major > 0 + ? parsed.major + 1 + '.0.0' + : parsed.minor > 0 + ? '0.' + (parsed.minor + 1) + '.0' + : '0.0.' + (parsed.patch + 1); + return compared >= 0 && compareSemver(version, upper) < 0; + }); +} + function deny(reason) { return { allowed: false, reason }; } @@ -237,6 +309,23 @@ function validatePackageLock( } } + // npm may keep a different resolved package version than the manifest + // range appears to request. Verify the root's actual install target. + for (const section of sections) { + const requirements = headPackage[section] || {}; + for (const [name, range] of Object.entries(requirements)) { + const packagePath = resolveLockDependency('', name, headLock.packages); + const resolvedVersion = packagePath + ? headLock.packages[packagePath]?.version + : null; + if (!packagePath || !satisfiesVersionRange(resolvedVersion, range)) { + return deny( + 'package-lock resolved version for "' + name + '" does not satisfy package.json ' + section + ' range', + ); + } + } + } + const baseRoot = { ...baseLock.packages[''] }; const headRoot = { ...headLock.packages[''] }; for (const section of sections) { @@ -264,6 +353,19 @@ function validatePackageLock( ...headClosure.reachable, ]); + const productionReachable = collectLockDependencyClosure(headLock, [ + ...Object.keys(headPackage.dependencies || {}), + ...Object.keys(headPackage.optionalDependencies || {}), + ...Object.keys(headPackage.peerDependencies || {}), + ]); + const developmentReachable = collectLockDependencyClosure( + headLock, + Object.keys(headPackage.devDependencies || {}), + ); + if (!productionReachable.allowed || !developmentReachable.allowed) { + return deny('package-lock dependency graph could not be resolved'); + } + const paths = new Set([ ...Object.keys(baseLock.packages), ...Object.keys(headLock.packages), @@ -282,9 +384,21 @@ function validatePackageLock( } if (before && after && before.version === after.version) { - if (!sameJson(before, after)) { + const beforeWithoutDev = { ...before }; + const afterWithoutDev = { ...after }; + delete beforeWithoutDev.dev; + delete afterWithoutDev.dev; + if (!sameJson(beforeWithoutDev, afterWithoutDev)) { return deny( - 'package-lock entries may not change metadata without changing the package version', + 'package-lock entries may not change artifact metadata without changing the package version', + ); + } + const expectedDev = + developmentReachable.reachable.has(packagePath) && + !productionReachable.reachable.has(packagePath); + if ((after.dev === true) !== expectedDev) { + return deny( + 'package-lock dev flag does not match the updated dependency graph', ); } continue; @@ -307,6 +421,23 @@ function validatePackageLock( } } + // Every retained package must keep its required dependency edges intact. + // Missing optional or peer dependencies can be valid; regular dependencies + // cannot be left unresolved by deleting a shared lockfile entry. + for (const [packagePath, metadata] of Object.entries(headLock.packages)) { + if (!packagePath || metadata.link === true) continue; + for (const dependencyName of Object.keys(metadata.dependencies || {})) { + if (!resolveLockDependency(packagePath, dependencyName, headLock.packages)) { + return deny( + 'package-lock deletion leaves required dependency "' + + dependencyName + + '" unresolved for ' + + packagePath, + ); + } + } + } + return { allowed: true }; } From 832aa63d5436cfe6d7ebc1eb2449f083fa11a2b1 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 22:03:33 +0100 Subject: [PATCH 73/94] test(security): cover npm lockfile graph invariants --- tests/pr-guard-policy.test.ts | 87 +++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) diff --git a/tests/pr-guard-policy.test.ts b/tests/pr-guard-policy.test.ts index 9115ddd8..d0094d93 100644 --- a/tests/pr-guard-policy.test.ts +++ b/tests/pr-guard-policy.test.ts @@ -477,6 +477,93 @@ describe('Dependabot PR guard policy', () => { expect(result.reason).toMatch(/npm registry/); }); + it('rejects a resolved direct dependency version outside its manifest range', () => { + const headLock = lockFor(headPackage); + headLock.packages['node_modules/commander']!.version = '15.0.0'; + const result = classifyDependabotPR({ + login, + title: npmTitle, + baseRef, + files: [ + { filename: 'package.json', status: 'modified' }, + { filename: 'package-lock.json', status: 'modified' }, + ], + basePackage, + headPackage, + baseLock: lockFor(basePackage), + headLock, + }); + + expect(result.allowed).toBe(false); + expect(result.reason).toMatch(/does not satisfy package.json/); + }); + + it('rejects deleting a lock entry required by a retained package', () => { + const headLock = lockFor(headPackage); + headLock.packages['node_modules/commander']!.dependencies = { + 'shared-runtime': '1.0.0', + }; + const result = classifyDependabotPR({ + login, + title: npmTitle, + baseRef, + files: [ + { filename: 'package.json', status: 'modified' }, + { filename: 'package-lock.json', status: 'modified' }, + ], + basePackage, + headPackage, + baseLock: lockFor(basePackage), + headLock, + }); + + expect(result.allowed).toBe(false); + expect(result.reason).toMatch(/required dependency.*unresolved/); + }); + + it('allows a dev flag change only when the updated graph requires it', () => { + const baseLock = lockFor(basePackage); + const headLock = lockFor(headPackage); + baseLock.packages['node_modules/vitest']!.dependencies = { + shared: '1.0.0', + }; + headLock.packages['node_modules/vitest']!.dependencies = { + shared: '1.0.0', + }; + headLock.packages['node_modules/commander']!.dependencies = { + shared: '1.0.0', + }; + baseLock.packages['node_modules/shared'] = { + version: '1.0.0', + resolved: 'https://registry.npmjs.org/shared/-/shared-1.0.0.tgz', + integrity: 'sha512-shared', + dev: true, + }; + headLock.packages['node_modules/shared'] = { + version: '1.0.0', + resolved: 'https://registry.npmjs.org/shared/-/shared-1.0.0.tgz', + integrity: 'sha512-shared', + }; + baseLock.packages['node_modules/vitest']!.dev = true; + headLock.packages['node_modules/vitest']!.dev = true; + + const result = classifyDependabotPR({ + login, + title: npmTitle, + baseRef, + files: [ + { filename: 'package.json', status: 'modified' }, + { filename: 'package-lock.json', status: 'modified' }, + ], + basePackage, + headPackage, + baseLock, + headLock, + }); + + expect(result.allowed).toBe(true); + }); + it('rejects lockfile changes outside updated dependency closures', () => { const headLock = lockFor(headPackage); headLock.packages['node_modules/unrelated-package'] = { From 1b57f71219b72fec6b5aced736432771a3f79570 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 22:03:57 +0100 Subject: [PATCH 74/94] fix(security): verify lockfile artifacts against npm registry metadata --- scripts/pr-guard-policy.cjs | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/scripts/pr-guard-policy.cjs b/scripts/pr-guard-policy.cjs index 584dd0f8..442e14f1 100644 --- a/scripts/pr-guard-policy.cjs +++ b/scripts/pr-guard-policy.cjs @@ -195,6 +195,13 @@ function resolveLockDependency(fromPath, dependencyName, packages) { return null; } +function packageNameFromLockPath(packagePath) { + const segments = packagePath.split('/node_modules/').pop().split('/'); + return segments[0].startsWith('@') + ? segments[0] + '/' + (segments[1] || '') + : segments[0]; +} + function collectLockDependencyClosure(lock, dependencyNames) { const packages = lock.packages; const reachable = new Set(); @@ -234,6 +241,7 @@ function validatePackageLock( basePackage, headPackage, changedDependencies, + registryMetadata, ) { if ( !isObject(baseLock) || @@ -404,18 +412,23 @@ function validatePackageLock( continue; } if (after) { + const packageName = packageNameFromLockPath(packagePath); + const trusted = registryMetadata?.[packageName + '@' + after.version]; if ( typeof after.version !== 'string' || - !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test( + !/^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$/.test( after.version, ) || typeof after.resolved !== 'string' || !after.resolved.startsWith('https://registry.npmjs.org/') || typeof after.integrity !== 'string' || - after.integrity.length === 0 + after.integrity.length === 0 || + !trusted || + trusted.resolved !== after.resolved || + trusted.integrity !== after.integrity ) { return deny( - 'new or updated lockfile packages must use the npm registry and include integrity metadata', + 'new or updated lockfile package tarball and integrity must match trusted npm registry metadata', ); } } @@ -572,6 +585,7 @@ function classifyDependabotPR({ workflowContents, baseLock, headLock, + registryMetadata, }) { if (login !== DEPENDABOT_LOGIN) { return deny('only the exact dependabot[bot] account is eligible'); @@ -601,6 +615,7 @@ function classifyDependabotPR({ basePackage, headPackage, manifest.changedDependencies, + registryMetadata, ); if (!lock.allowed) return lock; return { ...manifest, kind: 'npm-dependencies' }; From 4ae9b458e957bd97d330ee5d1f7563c840a2da67 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 22:04:10 +0100 Subject: [PATCH 75/94] fix(security): verify Dependabot artifacts against npm registry --- .github/workflows/wave-pr-guard.yml | 39 +++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/.github/workflows/wave-pr-guard.yml b/.github/workflows/wave-pr-guard.yml index f33e56aa..e0ca71b7 100644 --- a/.github/workflows/wave-pr-guard.yml +++ b/.github/workflows/wave-pr-guard.yml @@ -76,6 +76,44 @@ jobs: baseLock = await readJsonAtRef('package-lock.json', mergeBaseSha); headLock = await readJsonAtRef('package-lock.json', pr.head.sha); } + const registryMetadata = {}; + if (headLock?.packages && baseLock?.packages) { + const changedLockEntries = Object.entries(headLock.packages) + .filter(([path, after]) => path && after && ( + !baseLock.packages[path] || + baseLock.packages[path].version !== after.version + )); + if (changedLockEntries.length > 200) { + throw new Error('Too many changed lockfile artifacts to verify safely'); + } + for (const [packagePath, entry] of changedLockEntries) { + const segments = packagePath.split('/node_modules/').pop().split('/'); + const packageName = segments[0].startsWith('@') + ? segments[0] + '/' + (segments[1] || '') + : segments[0]; + const version = entry.version; + if (typeof version !== 'string') { + throw new Error('Changed lockfile package has no resolved version'); + } + const registryUrl = 'https://registry.npmjs.org/' + + encodeURIComponent(packageName) + '/' + encodeURIComponent(version); + const response = await fetch(registryUrl, { + headers: { accept: 'application/vnd.npm.install-v1+json' }, + signal: AbortSignal.timeout(10000), + }); + if (!response.ok) { + throw new Error('Could not verify ' + packageName + '@' + version + ' against npm registry'); + } + const metadata = await response.json(); + if (metadata.name !== packageName || metadata.version !== version) { + throw new Error('npm registry returned mismatched package identity'); + } + registryMetadata[packageName + '@' + version] = { + resolved: metadata.dist?.tarball, + integrity: metadata.dist?.integrity, + }; + } + } const workflowContents = {}; for (const file of files.filter((item) => /^\.github\/workflows\//.test(item.filename))) { const readWorkflowAtRef = async (ref) => { @@ -102,6 +140,7 @@ jobs: workflowContents, baseLock, headLock, + registryMetadata, }); if (!decision.allowed) { core.setFailed('Dependabot PR rejected by narrow bot policy: ' + decision.reason); From 0284109c4ef11b6eb98f5308b12f51ef2cee35d8 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 22:04:32 +0100 Subject: [PATCH 76/94] build(security): declare YAML parser for guard validation --- package.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index 76e291ed..f3e31302 100644 --- a/package.json +++ b/package.json @@ -39,7 +39,8 @@ "prettier": "3.9.8", "typescript": "6.0.3", "typescript-eslint": "8.70.0", - "vitest": "5.0.1" + "vitest": "5.0.1", + "yaml": "2.9.0" }, "license": "MIT", "repository": { From ee02d1dc2daf9ce0627ab8a75d63bd12962e4f05 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 22:04:35 +0100 Subject: [PATCH 77/94] build(security): lock YAML parser dependency --- package-lock.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/package-lock.json b/package-lock.json index 88efca46..e813306c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -22,7 +22,8 @@ "prettier": "3.9.8", "typescript": "6.0.3", "typescript-eslint": "8.70.0", - "vitest": "5.0.1" + "vitest": "5.0.1", + "yaml": "2.9.0" }, "engines": { "node": ">=22.13.0 <25", From 32da8474853ed70a0fb1448bf5909b5f370ee60f Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 22:05:04 +0100 Subject: [PATCH 78/94] fix(security): parse workflow YAML and mask only action references --- scripts/pr-guard-policy.cjs | 138 +++++++++++++++++++++++------------- 1 file changed, 90 insertions(+), 48 deletions(-) diff --git a/scripts/pr-guard-policy.cjs b/scripts/pr-guard-policy.cjs index 442e14f1..1db26d5c 100644 --- a/scripts/pr-guard-policy.cjs +++ b/scripts/pr-guard-policy.cjs @@ -474,60 +474,93 @@ function hasClosingQuote(line, quote, startIndex) { } function normalizeWorkflowSource(source) { - const lines = source.split(/\r?\n/); - const references = []; - let blockScalarIndent = null; - let quotedScalar = null; - - for (let index = 0; index < lines.length; index += 1) { - const line = lines[index]; - const indentation = line.match(/^ */)[0].length; - const trimmed = line.trim(); - - if (quotedScalar !== null) { - if (hasClosingQuote(line, quotedScalar, 0)) quotedScalar = null; - continue; - } - - if (blockScalarIndent !== null) { - if (trimmed === '' || indentation > blockScalarIndent) continue; - blockScalarIndent = null; - } - - if ( - /^\s*(?:-\s*)?[A-Za-z0-9_.-]+:\s*[|>](?:[+-]?\d?|\d?[+-])?(?:\s+#.*)?$/.test( - line, - ) - ) { - blockScalarIndent = indentation; - continue; - } + const { parseDocument, isMap, isSeq, isScalar } = require('yaml'); + const document = parseDocument(source, { uniqueKeys: true }); + if (document.errors.length || !isMap(document.contents)) { + return { normalized: null, references: [] }; + } - const quotedValue = line.match( - /^\s*(?:-\s*)?[A-Za-z0-9_.-]+:\s*(['"])/, + let normalized = source; + const references = []; + const valueFor = (mapping, key) => { + if (!isMap(mapping)) return undefined; + const pair = mapping.items.find( + (item) => isScalar(item.key) && item.key.value === key, ); - if (quotedValue) { - const quote = quotedValue[1]; - const quoteIndex = line.indexOf(quote, quotedValue[0].length - 1); - if (!hasClosingQuote(line, quote, quoteIndex + 1)) { - quotedScalar = quote; - continue; - } - } - - const match = line.match( - /^(\s*(?:-\s*)?uses:\s*)([A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)+)@([a-f0-9]{40})(\s+#.*)?$/i, + return pair?.value; + }; + const maskReference = (node, location) => { + if (!isScalar(node) || typeof node.value !== 'string') return; + const match = node.value.match( + /^([A-Za-z0-9_.-]+(?:\\/[A-Za-z0-9_.-]+)+)@([a-f0-9]{40})$/i, ); - if (!match) continue; + if (!match || !Array.isArray(node.range)) return; + const [valueStart, valueEnd] = node.range; + const rawValue = source.slice(valueStart, valueEnd); + const shaToken = '@' + match[2]; + const shaOffset = rawValue.lastIndexOf(shaToken); + if (shaOffset < 0) return; + + const shaStart = valueStart + shaOffset + 1; + const shaEnd = shaStart + match[2].length; + normalized = + normalized.slice(0, shaStart) + + '' + + normalized.slice(shaEnd); + + // Dependabot updates the adjacent version annotation with the SHA. Permit + // only a canonical "# vX.Y.Z[-prerelease]" comment on this exact uses line. + const lineEnd = source.indexOf('\\n', valueEnd) < 0 + ? source.length + : source.indexOf('\\n', valueEnd); + const trailing = source.slice(valueEnd, lineEnd); + const comment = trailing.match( + /^(\\s+#\\s*v)(\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?)(\\s*)$/, + ); + if (comment) { + const versionStart = valueEnd + comment[1].length; + const versionEnd = versionStart + comment[2].length; + normalized = + normalized.slice(0, versionStart) + + '' + + normalized.slice(versionEnd); + } references.push({ - name: match[2], - sha: match[3].toLowerCase(), + location, + name: match[1], + sha: match[2].toLowerCase(), }); - lines[index] = match[1] + match[2] + '@' + (match[4] || ''); + }; + + const jobs = valueFor(document.contents, 'jobs'); + if (!isMap(jobs)) return { normalized: null, references: [] }; + + for (const jobPair of jobs.items) { + if (!isScalar(jobPair.key) || typeof jobPair.key.value !== 'string') { + return { normalized: null, references: [] }; + } + const jobName = jobPair.key.value; + const job = jobPair.value; + if (!isMap(job)) continue; + + // Reusable workflow reference: jobs..uses + maskReference(valueFor(job, 'uses'), 'jobs.' + jobName + '.uses'); + + // Action step reference: jobs..steps[*].uses + const steps = valueFor(job, 'steps'); + if (!isSeq(steps)) continue; + for (let index = 0; index < steps.items.length; index += 1) { + const step = steps.items[index]; + if (!isMap(step)) continue; + maskReference( + valueFor(step, 'uses'), + 'jobs.' + jobName + '.steps[' + index + '].uses', + ); + } } - return { normalized: lines.join('\n'), references }; + return { normalized, references }; } function validateWorkflowPatches(files, workflowContents) { @@ -550,9 +583,15 @@ function validateWorkflowPatches(files, workflowContents) { const before = normalizeWorkflowSource(revisions.base); const after = normalizeWorkflowSource(revisions.head); + if ( + before.normalized === null || + after.normalized === null + ) { + return deny('workflow YAML could not be parsed safely'); + } if (before.normalized !== after.normalized) { return deny( - 'workflow updates may change only pinned action SHAs outside YAML block-scalar content', + 'workflow updates may change only pinned action SHAs and canonical version comments at eligible YAML action paths', ); } if (before.references.length !== after.references.length) { @@ -562,7 +601,10 @@ function validateWorkflowPatches(files, workflowContents) { for (let index = 0; index < before.references.length; index += 1) { const oldReference = before.references[index]; const newReference = after.references[index]; - if (oldReference.name !== newReference.name) { + if ( + oldReference.location !== newReference.location || + oldReference.name !== newReference.name + ) { return deny('workflow updates may not replace or move action identities'); } if (oldReference.sha !== newReference.sha) changedReferences += 1; From 6f92f106543f0447072a55e2a4933648a547a412 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 22:05:25 +0100 Subject: [PATCH 79/94] fix(security): preserve source offsets when masking YAML action pins --- scripts/pr-guard-policy.cjs | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/scripts/pr-guard-policy.cjs b/scripts/pr-guard-policy.cjs index 1db26d5c..4ce4121e 100644 --- a/scripts/pr-guard-policy.cjs +++ b/scripts/pr-guard-policy.cjs @@ -480,7 +480,7 @@ function normalizeWorkflowSource(source) { return { normalized: null, references: [] }; } - let normalized = source; + const edits = []; const references = []; const valueFor = (mapping, key) => { if (!isMap(mapping)) return undefined; @@ -492,7 +492,7 @@ function normalizeWorkflowSource(source) { const maskReference = (node, location) => { if (!isScalar(node) || typeof node.value !== 'string') return; const match = node.value.match( - /^([A-Za-z0-9_.-]+(?:\\/[A-Za-z0-9_.-]+)+)@([a-f0-9]{40})$/i, + /^([A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)+)@([a-f0-9]{40})$/i, ); if (!match || !Array.isArray(node.range)) return; const [valueStart, valueEnd] = node.range; @@ -503,27 +503,20 @@ function normalizeWorkflowSource(source) { const shaStart = valueStart + shaOffset + 1; const shaEnd = shaStart + match[2].length; - normalized = - normalized.slice(0, shaStart) + - '' + - normalized.slice(shaEnd); + edits.push({ start: shaStart, end: shaEnd, value: '' }); // Dependabot updates the adjacent version annotation with the SHA. Permit // only a canonical "# vX.Y.Z[-prerelease]" comment on this exact uses line. - const lineEnd = source.indexOf('\\n', valueEnd) < 0 - ? source.length - : source.indexOf('\\n', valueEnd); + const nextLine = source.indexOf('\n', valueEnd); + const lineEnd = nextLine < 0 ? source.length : nextLine; const trailing = source.slice(valueEnd, lineEnd); const comment = trailing.match( - /^(\\s+#\\s*v)(\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?)(\\s*)$/, + /^(\s+#\s*v)(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)(\s*)$/, ); if (comment) { const versionStart = valueEnd + comment[1].length; const versionEnd = versionStart + comment[2].length; - normalized = - normalized.slice(0, versionStart) + - '' + - normalized.slice(versionEnd); + edits.push({ start: versionStart, end: versionEnd, value: '' }); } references.push({ @@ -560,6 +553,13 @@ function normalizeWorkflowSource(source) { } } + let normalized = source; + for (const edit of edits.sort((left, right) => right.start - left.start)) { + normalized = + normalized.slice(0, edit.start) + + edit.value + + normalized.slice(edit.end); + } return { normalized, references }; } From f08bf509f418146ffb0ebdf8e81ccfabcbc67edd Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 22:05:48 +0100 Subject: [PATCH 80/94] test(security): cover YAML action paths and version comments --- tests/pr-guard-policy.test.ts | 77 +++++++++++++++++++++++++++++++---- 1 file changed, 69 insertions(+), 8 deletions(-) diff --git a/tests/pr-guard-policy.test.ts b/tests/pr-guard-policy.test.ts index d0094d93..d314c0e9 100644 --- a/tests/pr-guard-policy.test.ts +++ b/tests/pr-guard-policy.test.ts @@ -15,7 +15,7 @@ type Decision = { }; const require = createRequire(import.meta.url); -const { classifyDependabotPR } = require('../scripts/pr-guard-policy.cjs') as { +const { classifyDependabotPR: classifyDependabotPRInternal } = require('../scripts/pr-guard-policy.cjs') as { classifyDependabotPR(input: { login: string; title: string; @@ -25,9 +25,28 @@ const { classifyDependabotPR } = require('../scripts/pr-guard-policy.cjs') as { headPackage?: PackageManifest; baseLock?: Record; headLock?: Record; + registryMetadata?: Record; workflowContents?: Record; }): Decision; }; +const defaultRegistryMetadata = { + 'commander@15.1.0': { + resolved: 'https://registry.npmjs.org/commander/-/commander-15.1.0.tgz', + integrity: 'sha512-commander', + }, + 'vitest@5.0.2': { + resolved: 'https://registry.npmjs.org/vitest/-/vitest-5.0.2.tgz', + integrity: 'sha512-vitest', + }, +}; +function classifyDependabotPR( + input: Parameters[0], +): Decision { + return classifyDependabotPRInternal({ + ...input, + registryMetadata: input.registryMetadata ?? defaultRegistryMetadata, + }); +} const login = 'dependabot[bot]'; const baseRef = 'main'; @@ -299,19 +318,15 @@ describe('Dependabot PR guard policy', () => { ); }); - it('allows pinned SHA updates on standard YAML sequence action steps', () => { + it('allows pinned SHA updates on unnamed YAML sequence action steps', () => { const result = classifyDependabotPR({ login, title: actionTitle, baseRef, files: [{ filename: workflowFile, status: 'modified' }], workflowContents: workflowRevisions( - workflowSource( - ` - name: Checkout\n uses: actions/checkout@${'a'.repeat(40)}\n`, - ), - workflowSource( - ` - name: Checkout\n uses: actions/checkout@${'b'.repeat(40)}\n`, - ), + workflowSource(` - uses: actions/checkout@${'a'.repeat(40)}\\n`), + workflowSource(` - uses: actions/checkout@${'b'.repeat(40)}\\n`), ), }); expect(result).toMatchObject({ @@ -364,6 +379,52 @@ describe('Dependabot PR guard policy', () => { }, ); + it('allows only the canonical version comment to change with an action SHA', () => { + const result = classifyDependabotPR({ + login, + title: actionTitle, + baseRef, + files: [{ filename: workflowFile, status: 'modified' }], + workflowContents: workflowRevisions( + workflowSource(` - uses: actions/checkout@${'a'.repeat(40)} # v7.0.1\\n`), + workflowSource(` - uses: actions/checkout@${'b'.repeat(40)} # v7.0.2\\n`), + ), + }); + expect(result.allowed).toBe(true); + }); + + it('does not mask uses-like values outside eligible YAML action paths', () => { + const result = classifyDependabotPR({ + login, + title: actionTitle, + baseRef, + files: [{ filename: workflowFile, status: 'modified' }], + workflowContents: workflowRevisions( + workflowSource( + ` - run: echo safe\\n env:\\n uses: actions/checkout@${'a'.repeat(40)}\\n`, + ), + workflowSource( + ` - run: echo safe\\n env:\\n uses: actions/checkout@${'b'.repeat(40)}\\n`, + ), + ), + }); + expect(result.allowed).toBe(false); + }); + + it('allows a pinned reusable workflow SHA update at the jobs path', () => { + const result = classifyDependabotPR({ + login, + title: actionTitle, + baseRef, + files: [{ filename: workflowFile, status: 'modified' }], + workflowContents: workflowRevisions( + `name: CI\\njobs:\\n build:\\n uses: org/workflows/.github/workflows/build.yml@${'a'.repeat(40)}\\n`, + `name: CI\\njobs:\\n build:\\n uses: org/workflows/.github/workflows/build.yml@${'b'.repeat(40)}\\n`, + ), + }); + expect(result.allowed).toBe(true); + }); + it('rejects changing workflow comments alongside action SHAs', () => { const result = classifyDependabotPR({ login, From 1bea79ca15ac46f65fc82165e3fb5a91beed3989 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 22:06:00 +0100 Subject: [PATCH 81/94] test(security): correct YAML source fixtures --- tests/pr-guard-policy.test.ts | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/tests/pr-guard-policy.test.ts b/tests/pr-guard-policy.test.ts index d314c0e9..3efbedfe 100644 --- a/tests/pr-guard-policy.test.ts +++ b/tests/pr-guard-policy.test.ts @@ -325,8 +325,8 @@ describe('Dependabot PR guard policy', () => { baseRef, files: [{ filename: workflowFile, status: 'modified' }], workflowContents: workflowRevisions( - workflowSource(` - uses: actions/checkout@${'a'.repeat(40)}\\n`), - workflowSource(` - uses: actions/checkout@${'b'.repeat(40)}\\n`), + workflowSource(` - uses: actions/checkout@${'a'.repeat(40)}\n`), + workflowSource(` - uses: actions/checkout@${'b'.repeat(40)}\n`), ), }); expect(result).toMatchObject({ @@ -386,8 +386,8 @@ describe('Dependabot PR guard policy', () => { baseRef, files: [{ filename: workflowFile, status: 'modified' }], workflowContents: workflowRevisions( - workflowSource(` - uses: actions/checkout@${'a'.repeat(40)} # v7.0.1\\n`), - workflowSource(` - uses: actions/checkout@${'b'.repeat(40)} # v7.0.2\\n`), + workflowSource(` - uses: actions/checkout@${'a'.repeat(40)} # v7.0.1\n`), + workflowSource(` - uses: actions/checkout@${'b'.repeat(40)} # v7.0.2\n`), ), }); expect(result.allowed).toBe(true); @@ -401,10 +401,10 @@ describe('Dependabot PR guard policy', () => { files: [{ filename: workflowFile, status: 'modified' }], workflowContents: workflowRevisions( workflowSource( - ` - run: echo safe\\n env:\\n uses: actions/checkout@${'a'.repeat(40)}\\n`, + ` - run: echo safe\n env:\n uses: actions/checkout@${'a'.repeat(40)}\n`, ), workflowSource( - ` - run: echo safe\\n env:\\n uses: actions/checkout@${'b'.repeat(40)}\\n`, + ` - run: echo safe\n env:\n uses: actions/checkout@${'b'.repeat(40)}\n`, ), ), }); @@ -418,8 +418,8 @@ describe('Dependabot PR guard policy', () => { baseRef, files: [{ filename: workflowFile, status: 'modified' }], workflowContents: workflowRevisions( - `name: CI\\njobs:\\n build:\\n uses: org/workflows/.github/workflows/build.yml@${'a'.repeat(40)}\\n`, - `name: CI\\njobs:\\n build:\\n uses: org/workflows/.github/workflows/build.yml@${'b'.repeat(40)}\\n`, + `name: CI\njobs:\n build:\n uses: org/workflows/.github/workflows/build.yml@${'a'.repeat(40)}\n`, + `name: CI\njobs:\n build:\n uses: org/workflows/.github/workflows/build.yml@${'b'.repeat(40)}\n`, ), }); expect(result.allowed).toBe(true); From 25bbcf41632da645475477113c190f5d30409748 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 22:06:07 +0100 Subject: [PATCH 82/94] build(security): install trusted YAML parser for guard --- .github/workflows/wave-pr-guard.yml | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/.github/workflows/wave-pr-guard.yml b/.github/workflows/wave-pr-guard.yml index e0ca71b7..706f784f 100644 --- a/.github/workflows/wave-pr-guard.yml +++ b/.github/workflows/wave-pr-guard.yml @@ -13,7 +13,7 @@ jobs: guard: name: Wave PR scope and ownership runs-on: ubuntu-latest - timeout-minutes: 5 + timeout-minutes: 10 steps: - name: Checkout trusted base revision uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -21,6 +21,15 @@ jobs: ref: ${{ github.event.pull_request.base.sha }} persist-credentials: false + - name: Setup trusted Node.js toolchain + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: '22.13.0' + package-manager-cache: false + + - name: Install dependencies from trusted base lockfile + run: npm ci --ignore-scripts --no-audit --no-fund + - name: Validate linked Wave issue and protected scope uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 with: From 51ac9d11e76d58a735ea2ef7c02684e14a190bc0 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 22:06:27 +0100 Subject: [PATCH 83/94] fix(security): correct semver range parser escapes --- scripts/pr-guard-policy.cjs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/scripts/pr-guard-policy.cjs b/scripts/pr-guard-policy.cjs index 4ce4121e..c05a8881 100644 --- a/scripts/pr-guard-policy.cjs +++ b/scripts/pr-guard-policy.cjs @@ -19,7 +19,7 @@ function isVersionRange(value) { function parseSemver(version) { if (typeof version !== 'string') return null; const match = version.match( - /^(\\d+)\\.(\\d+)\\.(\\d+)(?:-([0-9A-Za-z.-]+))?(?:\\+[0-9A-Za-z.-]+)?$/, + /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/, ); if (!match) return null; return { @@ -47,8 +47,8 @@ function compareSemver(left, right) { if (x === undefined) return -1; if (y === undefined) return 1; if (x === y) continue; - const xn = /^\\d+$/.test(x); - const yn = /^\\d+$/.test(y); + const xn = /^\d+$/.test(x); + const yn = /^\d+$/.test(y); if (xn && yn) return Number(x) < Number(y) ? -1 : 1; if (xn !== yn) return xn ? -1 : 1; return x < y ? -1 : 1; @@ -60,7 +60,7 @@ function satisfiesVersionRange(version, range) { if (!parseSemver(version) || !isVersionRange(range)) return false; return range.split('||').some((rawClause) => { const match = rawClause.trim().match( - /^(\\^|~|>=|>|<=|<|=)?\\s*(\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?)$/, + /^(\^|~|>=|>|<=|<|=)?\s*(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)$/, ); if (!match) return false; const operator = match[1] || '='; @@ -416,7 +416,7 @@ function validatePackageLock( const trusted = registryMetadata?.[packageName + '@' + after.version]; if ( typeof after.version !== 'string' || - !/^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$/.test( + !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test( after.version, ) || typeof after.resolved !== 'string' || From fa8f8c8f65f200ec9efc8df594139088d8d9fac0 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 22:06:44 +0100 Subject: [PATCH 84/94] test(security): assert direct dependency range failure --- tests/pr-guard-policy.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/pr-guard-policy.test.ts b/tests/pr-guard-policy.test.ts index 3efbedfe..8002c4f7 100644 --- a/tests/pr-guard-policy.test.ts +++ b/tests/pr-guard-policy.test.ts @@ -514,7 +514,7 @@ describe('Dependabot PR guard policy', () => { headLock, }); expect(result.allowed).toBe(false); - expect(result.reason).toMatch(/npm registry/); + expect(result.reason).toMatch(/does not satisfy package.json/); }, ); From ed390083753d5fe15ff7e027e278d6f7d08635fa Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 22:07:01 +0100 Subject: [PATCH 85/94] test(security): align lockfile rejection assertions --- tests/pr-guard-policy.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/pr-guard-policy.test.ts b/tests/pr-guard-policy.test.ts index 8002c4f7..79dc67c1 100644 --- a/tests/pr-guard-policy.test.ts +++ b/tests/pr-guard-policy.test.ts @@ -514,7 +514,7 @@ describe('Dependabot PR guard policy', () => { headLock, }); expect(result.allowed).toBe(false); - expect(result.reason).toMatch(/does not satisfy package.json/); + expect(result.reason).toMatch(/trusted npm registry metadata/); }, ); @@ -535,7 +535,7 @@ describe('Dependabot PR guard policy', () => { headLock, }); expect(result.allowed).toBe(false); - expect(result.reason).toMatch(/npm registry/); + expect(result.reason).toMatch(/does not satisfy package.json/); }); it('rejects a resolved direct dependency version outside its manifest range', () => { From de960668607481c0a0a5893dcbceae5d473eadde Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 22:07:16 +0100 Subject: [PATCH 86/94] fix(security): validate dev flags for all changed lock entries --- scripts/pr-guard-policy.cjs | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/scripts/pr-guard-policy.cjs b/scripts/pr-guard-policy.cjs index c05a8881..eb1280bd 100644 --- a/scripts/pr-guard-policy.cjs +++ b/scripts/pr-guard-policy.cjs @@ -391,6 +391,17 @@ function validatePackageLock( continue; } + if (after) { + const expectedDev = + developmentReachable.reachable.has(packagePath) && + !productionReachable.reachable.has(packagePath); + if ((after.dev === true) !== expectedDev) { + return deny( + 'package-lock dev flag does not match the updated dependency graph', + ); + } + } + if (before && after && before.version === after.version) { const beforeWithoutDev = { ...before }; const afterWithoutDev = { ...after }; @@ -401,14 +412,6 @@ function validatePackageLock( 'package-lock entries may not change artifact metadata without changing the package version', ); } - const expectedDev = - developmentReachable.reachable.has(packagePath) && - !productionReachable.reachable.has(packagePath); - if ((after.dev === true) !== expectedDev) { - return deny( - 'package-lock dev flag does not match the updated dependency graph', - ); - } continue; } if (after) { From 831c7c00a924996727c21b40d016f017aeb172c3 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 22:07:22 +0100 Subject: [PATCH 87/94] test(security): model npm dev graph flags in fixtures --- tests/pr-guard-policy.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/pr-guard-policy.test.ts b/tests/pr-guard-policy.test.ts index 79dc67c1..c83dfe39 100644 --- a/tests/pr-guard-policy.test.ts +++ b/tests/pr-guard-policy.test.ts @@ -98,6 +98,7 @@ function lockFor(manifest: PackageManifest): { version: (devDependencies as Record).vitest, resolved: 'https://registry.npmjs.org/vitest/-/vitest.tgz', integrity: 'sha512-vitest', + dev: true, }, }, }; From 1b24231c4145103a133b9ad268ffd84a251e3569 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 22:07:44 +0100 Subject: [PATCH 88/94] test(security): align lock fixture tarballs with package versions --- tests/pr-guard-policy.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/pr-guard-policy.test.ts b/tests/pr-guard-policy.test.ts index c83dfe39..b2bc0091 100644 --- a/tests/pr-guard-policy.test.ts +++ b/tests/pr-guard-policy.test.ts @@ -91,12 +91,12 @@ function lockFor(manifest: PackageManifest): { }, 'node_modules/commander': { version: (dependencies as Record).commander, - resolved: 'https://registry.npmjs.org/commander/-/commander.tgz', + resolved: 'https://registry.npmjs.org/commander/-/commander-' + (dependencies as Record).commander + '.tgz', integrity: 'sha512-commander', }, 'node_modules/vitest': { version: (devDependencies as Record).vitest, - resolved: 'https://registry.npmjs.org/vitest/-/vitest.tgz', + resolved: 'https://registry.npmjs.org/vitest/-/vitest-' + (devDependencies as Record).vitest + '.tgz', integrity: 'sha512-vitest', dev: true, }, From 85fae8615f0288d1d0bf3135f2d33ae79133d549 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 22:07:58 +0100 Subject: [PATCH 89/94] fix(security): tolerate absent optional and peer lock edges --- scripts/pr-guard-policy.cjs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/scripts/pr-guard-policy.cjs b/scripts/pr-guard-policy.cjs index eb1280bd..d7ccbd0f 100644 --- a/scripts/pr-guard-policy.cjs +++ b/scripts/pr-guard-policy.cjs @@ -323,6 +323,9 @@ function validatePackageLock( const requirements = headPackage[section] || {}; for (const [name, range] of Object.entries(requirements)) { const packagePath = resolveLockDependency('', name, headLock.packages); + if (!packagePath && ['optionalDependencies', 'peerDependencies'].includes(section)) { + continue; + } const resolvedVersion = packagePath ? headLock.packages[packagePath]?.version : null; @@ -361,11 +364,15 @@ function validatePackageLock( ...headClosure.reachable, ]); - const productionReachable = collectLockDependencyClosure(headLock, [ + const productionRoots = [ ...Object.keys(headPackage.dependencies || {}), ...Object.keys(headPackage.optionalDependencies || {}), ...Object.keys(headPackage.peerDependencies || {}), - ]); + ].filter((name) => resolveLockDependency('', name, headLock.packages)); + const productionReachable = collectLockDependencyClosure( + headLock, + productionRoots, + ); const developmentReachable = collectLockDependencyClosure( headLock, Object.keys(headPackage.devDependencies || {}), From 39fe2cc91977fd698509fffe10287c1a4197cc5a Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 22:09:58 +0100 Subject: [PATCH 90/94] fix(security): resolve npm package names from lock paths --- scripts/pr-guard-policy.cjs | 28 +++++++--------------------- 1 file changed, 7 insertions(+), 21 deletions(-) diff --git a/scripts/pr-guard-policy.cjs b/scripts/pr-guard-policy.cjs index d7ccbd0f..5179b1a0 100644 --- a/scripts/pr-guard-policy.cjs +++ b/scripts/pr-guard-policy.cjs @@ -196,7 +196,12 @@ function resolveLockDependency(fromPath, dependencyName, packages) { } function packageNameFromLockPath(packagePath) { - const segments = packagePath.split('/node_modules/').pop().split('/'); + const withoutNodeModules = packagePath.includes('/node_modules/') + ? packagePath.split('/node_modules/').pop() + : packagePath.startsWith('node_modules/') + ? packagePath.slice('node_modules/'.length) + : packagePath; + const segments = withoutNodeModules.split('/'); return segments[0].startsWith('@') ? segments[0] + '/' + (segments[1] || '') : segments[0]; @@ -464,27 +469,8 @@ function validatePackageLock( return { allowed: true }; } -function hasClosingQuote(line, quote, startIndex) { - for (let index = startIndex; index < line.length; index += 1) { - if (quote === '"' && line[index] === '\\') { - index += 1; - continue; - } - if ( - quote === "'" && - line[index] === "'" && - line[index + 1] === "'" - ) { - index += 1; - continue; - } - if (line[index] === quote) return true; - } - return false; -} - function normalizeWorkflowSource(source) { - const { parseDocument, isMap, isSeq, isScalar } = require('yaml'); + const { parseDocument, isMap, isSeq, isScalar } = module.require('yaml'); const document = parseDocument(source, { uniqueKeys: true }); if (document.errors.length || !isMap(document.contents)) { return { normalized: null, references: [] }; From 84aae1010dc87704d3e39913ffd52138aab96ef5 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 22:10:05 +0100 Subject: [PATCH 91/94] test(security): reject arbitrary workflow comment changes --- tests/pr-guard-policy.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/pr-guard-policy.test.ts b/tests/pr-guard-policy.test.ts index b2bc0091..733fa6e8 100644 --- a/tests/pr-guard-policy.test.ts +++ b/tests/pr-guard-policy.test.ts @@ -434,10 +434,10 @@ describe('Dependabot PR guard policy', () => { files: [{ filename: workflowFile, status: 'modified' }], workflowContents: workflowRevisions( workflowSource( - ` - uses: actions/checkout@${'a'.repeat(40)} # v7.0.1\n`, + ` - uses: actions/checkout@${'a'.repeat(40)} # release-one\n`, ), workflowSource( - ` - uses: actions/checkout@${'b'.repeat(40)} # v7.0.2\n`, + ` - uses: actions/checkout@${'b'.repeat(40)} # release-two\n`, ), ), }); From d0eb2130eddc561a50a31e3fa19a19b8414a4ed1 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 22:13:47 +0100 Subject: [PATCH 92/94] chore(ci): export canonical formatting for guard test --- .github/workflows/ci.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3ccf7e9b..66d89f88 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -31,6 +31,11 @@ jobs: node-version: '22.13.0' package-manager-cache: false + - name: TEMP export Prettier-formatted guard test + run: | + npx prettier tests/pr-guard-policy.test.ts | base64 -w0 + echo + - name: Install from committed lockfile run: npm ci --ignore-scripts --no-audit --no-fund From 9e2ac9acc158a59637759bb2d14e6b962b634d2b Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 22:14:59 +0100 Subject: [PATCH 93/94] style(test): apply canonical Prettier formatting --- tests/pr-guard-policy.test.ts | 281 +++++++++++++++++----------------- 1 file changed, 139 insertions(+), 142 deletions(-) diff --git a/tests/pr-guard-policy.test.ts b/tests/pr-guard-policy.test.ts index 733fa6e8..305a523d 100644 --- a/tests/pr-guard-policy.test.ts +++ b/tests/pr-guard-policy.test.ts @@ -15,20 +15,24 @@ type Decision = { }; const require = createRequire(import.meta.url); -const { classifyDependabotPR: classifyDependabotPRInternal } = require('../scripts/pr-guard-policy.cjs') as { - classifyDependabotPR(input: { - login: string; - title: string; - baseRef: string; - files: FileChange[]; - basePackage?: PackageManifest; - headPackage?: PackageManifest; - baseLock?: Record; - headLock?: Record; - registryMetadata?: Record; - workflowContents?: Record; - }): Decision; -}; +const { classifyDependabotPR: classifyDependabotPRInternal } = + require('../scripts/pr-guard-policy.cjs') as { + classifyDependabotPR(input: { + login: string; + title: string; + baseRef: string; + files: FileChange[]; + basePackage?: PackageManifest; + headPackage?: PackageManifest; + baseLock?: Record; + headLock?: Record; + registryMetadata?: Record< + string, + { resolved: string; integrity: string } + >; + workflowContents?: Record; + }): Decision; + }; const defaultRegistryMetadata = { 'commander@15.1.0': { resolved: 'https://registry.npmjs.org/commander/-/commander-15.1.0.tgz', @@ -91,12 +95,18 @@ function lockFor(manifest: PackageManifest): { }, 'node_modules/commander': { version: (dependencies as Record).commander, - resolved: 'https://registry.npmjs.org/commander/-/commander-' + (dependencies as Record).commander + '.tgz', + resolved: + 'https://registry.npmjs.org/commander/-/commander-' + + (dependencies as Record).commander + + '.tgz', integrity: 'sha512-commander', }, 'node_modules/vitest': { version: (devDependencies as Record).vitest, - resolved: 'https://registry.npmjs.org/vitest/-/vitest-' + (devDependencies as Record).vitest + '.tgz', + resolved: + 'https://registry.npmjs.org/vitest/-/vitest-' + + (devDependencies as Record).vitest + + '.tgz', integrity: 'sha512-vitest', dev: true, }, @@ -155,36 +165,33 @@ describe('Dependabot PR guard policy', () => { expect(result.reason).toMatch(/outside dependency version sections/); }); - it( - 'rejects replacing a non-semver dependency source with a version range', - () => { - const result = classifyDependabotPR({ - login, - title: npmTitle, - baseRef, - files: [ - { filename: 'package.json', status: 'modified' }, - { filename: 'package-lock.json', status: 'modified' }, - ], - basePackage: { - ...basePackage, - dependencies: { - commander: 'git+https://example.invalid/commander.git', - }, + it('rejects replacing a non-semver dependency source with a version range', () => { + const result = classifyDependabotPR({ + login, + title: npmTitle, + baseRef, + files: [ + { filename: 'package.json', status: 'modified' }, + { filename: 'package-lock.json', status: 'modified' }, + ], + basePackage: { + ...basePackage, + dependencies: { + commander: 'git+https://example.invalid/commander.git', }, - headPackage, - baseLock: lockFor({ - ...basePackage, - dependencies: { - commander: 'git+https://example.invalid/commander.git', - }, - }), - headLock: lockFor(headPackage), - }); - expect(result.allowed).toBe(false); - expect(result.reason).toMatch(/non-semver/); - }, - ); + }, + headPackage, + baseLock: lockFor({ + ...basePackage, + dependencies: { + commander: 'git+https://example.invalid/commander.git', + }, + }), + headLock: lockFor(headPackage), + }); + expect(result.allowed).toBe(false); + expect(result.reason).toMatch(/non-semver/); + }); it('rejects dependency section presence and shape changes', () => { const withNullSection = { @@ -216,12 +223,10 @@ describe('Dependabot PR guard policy', () => { ...basePackage, peerDependencies: {}, }; - expect( - classify(withNullSection, baseWithPeerDependencies).allowed, - ).toBe(false); - expect( - classify(withNullSection, baseWithPeerDependencies).reason, - ).toMatch( + expect(classify(withNullSection, baseWithPeerDependencies).allowed).toBe( + false, + ); + expect(classify(withNullSection, baseWithPeerDependencies).reason).toMatch( /present dependency sections must remain JSON objects/, ); expect(classify(withAddedSection).allowed).toBe(false); @@ -358,27 +363,24 @@ describe('Dependabot PR guard policy', () => { ); }); - it( - 'rejects changes that imitate action references inside run block scalars', - () => { - const shaA = 'a'.repeat(40); - const shaB = 'b'.repeat(40); - const base = workflowSource( - ` - run: |\n uses: actions/checkout@${shaA}\n`, - ); - const head = workflowSource( - ` - run: |\n uses: actions/checkout@${shaB}\n`, - ); - const result = classifyDependabotPR({ - login, - title: actionTitle, - baseRef, - files: [{ filename: workflowFile, status: 'modified' }], - workflowContents: workflowRevisions(base, head), - }); - expect(result.allowed).toBe(false); - }, - ); + it('rejects changes that imitate action references inside run block scalars', () => { + const shaA = 'a'.repeat(40); + const shaB = 'b'.repeat(40); + const base = workflowSource( + ` - run: |\n uses: actions/checkout@${shaA}\n`, + ); + const head = workflowSource( + ` - run: |\n uses: actions/checkout@${shaB}\n`, + ); + const result = classifyDependabotPR({ + login, + title: actionTitle, + baseRef, + files: [{ filename: workflowFile, status: 'modified' }], + workflowContents: workflowRevisions(base, head), + }); + expect(result.allowed).toBe(false); + }); it('allows only the canonical version comment to change with an action SHA', () => { const result = classifyDependabotPR({ @@ -387,8 +389,12 @@ describe('Dependabot PR guard policy', () => { baseRef, files: [{ filename: workflowFile, status: 'modified' }], workflowContents: workflowRevisions( - workflowSource(` - uses: actions/checkout@${'a'.repeat(40)} # v7.0.1\n`), - workflowSource(` - uses: actions/checkout@${'b'.repeat(40)} # v7.0.2\n`), + workflowSource( + ` - uses: actions/checkout@${'a'.repeat(40)} # v7.0.1\n`, + ), + workflowSource( + ` - uses: actions/checkout@${'b'.repeat(40)} # v7.0.2\n`, + ), ), }); expect(result.allowed).toBe(true); @@ -444,25 +450,22 @@ describe('Dependabot PR guard policy', () => { expect(result.allowed).toBe(false); }); - it( - 'rejects changes that imitate action references inside quoted YAML scalars', - () => { - const base = workflowSource( - ` - run: "script body\n uses: actions/checkout@${'a'.repeat(40)}"\n`, - ); - const head = workflowSource( - ` - run: "script body\n uses: actions/checkout@${'b'.repeat(40)}"\n`, - ); - const result = classifyDependabotPR({ - login, - title: actionTitle, - baseRef, - files: [{ filename: workflowFile, status: 'modified' }], - workflowContents: workflowRevisions(base, head), - }); - expect(result.allowed).toBe(false); - }, - ); + it('rejects changes that imitate action references inside quoted YAML scalars', () => { + const base = workflowSource( + ` - run: "script body\n uses: actions/checkout@${'a'.repeat(40)}"\n`, + ); + const head = workflowSource( + ` - run: "script body\n uses: actions/checkout@${'b'.repeat(40)}"\n`, + ); + const result = classifyDependabotPR({ + login, + title: actionTitle, + baseRef, + files: [{ filename: workflowFile, status: 'modified' }], + workflowContents: workflowRevisions(base, head), + }); + expect(result.allowed).toBe(false); + }); it('rejects workflow logic, permissions, and unpinned refs', () => { const base = workflowSource( @@ -495,29 +498,26 @@ describe('Dependabot PR guard policy', () => { expect(unpinned.allowed).toBe(false); }); - it( - 'rejects changed lockfile packages resolved outside the npm registry', - () => { - const headLock = lockFor(headPackage); - headLock.packages['node_modules/commander']!.resolved = - 'https://attacker.example/commander.tgz'; - const result = classifyDependabotPR({ - login, - title: npmTitle, - baseRef, - files: [ - { filename: 'package.json', status: 'modified' }, - { filename: 'package-lock.json', status: 'modified' }, - ], - basePackage, - headPackage, - baseLock: lockFor(basePackage), - headLock, - }); - expect(result.allowed).toBe(false); - expect(result.reason).toMatch(/trusted npm registry metadata/); - }, - ); + it('rejects changed lockfile packages resolved outside the npm registry', () => { + const headLock = lockFor(headPackage); + headLock.packages['node_modules/commander']!.resolved = + 'https://attacker.example/commander.tgz'; + const result = classifyDependabotPR({ + login, + title: npmTitle, + baseRef, + files: [ + { filename: 'package.json', status: 'modified' }, + { filename: 'package-lock.json', status: 'modified' }, + ], + basePackage, + headPackage, + baseLock: lockFor(basePackage), + headLock, + }); + expect(result.allowed).toBe(false); + expect(result.reason).toMatch(/trusted npm registry metadata/); + }); it('rejects non-semver package versions in changed lock entries', () => { const headLock = lockFor(headPackage); @@ -650,33 +650,30 @@ describe('Dependabot PR guard policy', () => { ); }); - it( - 'rejects oversized dependency ranges without catastrophic regex work', - () => { - const changed = { - ...headPackage, - dependencies: { - commander: '9.9.9|| 9.9.9||'.repeat(1000), - }, - }; - const result = classifyDependabotPR({ - login, - title: npmTitle, - baseRef, - files: [ - { filename: 'package.json', status: 'modified' }, - { filename: 'package-lock.json', status: 'modified' }, - ], - basePackage, - headPackage: changed, - baseLock: lockFor(basePackage), - headLock: lockFor(changed), - }); + it('rejects oversized dependency ranges without catastrophic regex work', () => { + const changed = { + ...headPackage, + dependencies: { + commander: '9.9.9|| 9.9.9||'.repeat(1000), + }, + }; + const result = classifyDependabotPR({ + login, + title: npmTitle, + baseRef, + files: [ + { filename: 'package.json', status: 'modified' }, + { filename: 'package-lock.json', status: 'modified' }, + ], + basePackage, + headPackage: changed, + baseLock: lockFor(basePackage), + headLock: lockFor(changed), + }); - expect(result.allowed).toBe(false); - expect(result.reason).toMatch(/non-semver|non-string/); - }, - ); + expect(result.allowed).toBe(false); + expect(result.reason).toMatch(/non-semver|non-string/); + }); it('fails closed for invalid authors, titles, branches, and files', () => { const missingWorkflow = classifyDependabotPR({ From 64b48ad7d07b453abff03eb7c6904f04d0ebd823 Mon Sep 17 00:00:00 2001 From: Ahmed Mahmud Date: Wed, 18 Nov 2026 22:15:06 +0100 Subject: [PATCH 94/94] chore(ci): remove temporary Prettier export step --- .github/workflows/ci.yml | 5 ----- 1 file changed, 5 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 66d89f88..3ccf7e9b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -31,11 +31,6 @@ jobs: node-version: '22.13.0' package-manager-cache: false - - name: TEMP export Prettier-formatted guard test - run: | - npx prettier tests/pr-guard-policy.test.ts | base64 -w0 - echo - - name: Install from committed lockfile run: npm ci --ignore-scripts --no-audit --no-fund