@jakobm/peacekeeper 0.19.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -42,12 +42,16 @@ The generated executable `setup-github-config.sh` is deliberately not run by the
42
42
  generator. Run it afterwards and complete the manual checklist at its top. It
43
43
  configures applicable GitHub policy through `gh`, including automatic head-branch
44
44
  deletion, repository-level **Allow auto-merge**, and merge commits as the only
45
- permitted pull-request merge method, and uses
45
+ permitted pull-request merge method. It creates separate base-protection and
46
+ owner-approval rulesets for the personal account that owns the repository. The
47
+ base ruleset requires a PR and strict CI without bypass; the approval ruleset
48
+ requires the owner configured in `git.requiredApprover` while allowing only that
49
+ user to bypass that ruleset from a PR. It also uses
46
50
  `groundskeeper secrets sync --new-repo` to add the repository when synchronizing
47
51
  `RELEASE_POLICY_TOKEN`. Published projects also document the required initial manual
48
52
  publication with `npm login` and `npm publish`, followed by npm trusted publishing
49
53
  setup. The authenticated `gh` token needs repository **Administration: write**
50
- permission to configure repository settings and branch protection. The generator
54
+ permission to configure repository settings and rulesets. The generator
51
55
  never registers a publisher or publishes a package.
52
56
 
53
57
  When moving an existing project to Peacekeeper, update its dependency and lockfile,
@@ -116,6 +120,7 @@ Complete example:
116
120
  "remote": "origin",
117
121
  "defaultBranch": "main",
118
122
  "branchPrefix": "codex/",
123
+ "requiredApprover": "OWNER",
119
124
  "checkpointPushRemotes": ["origin"],
120
125
  "releaseMergeMethod": "merge",
121
126
  "releaseRequiredChecks": ["test"],
@@ -135,7 +140,7 @@ Complete example:
135
140
  }
136
141
  ```
137
142
 
138
- `git.remote` and `git.defaultBranch` identify the branch used for checkpointing and cleanup. `git.branchPrefix` names new task branches. `run-tests` always runs the local `check-project` validation first, even when reusing a test receipt. Explicit `check-project` invocations in `tests.commands` are rejected as redundant. The configured commands are complete shell commands, run in order from the caller's Git root; install any executables they use. The test runner stops on the first failure and records a receipt only after every command succeeds. `receiptMaxAgeMinutes` controls how long a receipt can be reused. Set `npmTestUsesRunner` to `true` only when the caller's `npm test` script invokes `peacekeeper run-tests`; this makes the rerun hint `npm test -- --force`. Otherwise the hint uses the explicit package path. `loggingDirectory` stores hook invocation logs relative to the primary Git worktree's root.
143
+ `git.remote` and `git.defaultBranch` identify the branch used for checkpointing and cleanup. `git.branchPrefix` names new task branches. `git.requiredApprover` names the personal GitHub repository owner who must approve other users' PRs and may bypass only the approval ruleset from a PR. Set it explicitly after `update-config`; its bundled default is `null`. The root project must contain `.github/CODEOWNERS` with the single non-comment rule `* @OWNER`, matching this value. `run-tests` always runs the local `check-project` validation first, even when reusing a test receipt. Explicit `check-project` invocations in `tests.commands` are rejected as redundant. The configured commands are complete shell commands, run in order from the caller's Git root; install any executables they use. The test runner stops on the first failure and records a receipt only after every command succeeds. `receiptMaxAgeMinutes` controls how long a receipt can be reused. Set `npmTestUsesRunner` to `true` only when the caller's `npm test` script invokes `peacekeeper run-tests`; this makes the rerun hint `npm test -- --force`. Otherwise the hint uses the explicit package path. `loggingDirectory` stores hook invocation logs relative to the primary Git worktree's root.
139
144
 
140
145
  `loggingEnabled` has the bundled default `true`; set it to `false` to disable invocation logs and the background cleanup worker's log file. Existing logs are kept. The setting is read from the primary checkout's configuration, including for linked worktrees. SessionStart and Stop logs include the process and event working directories, event type, primary-checkout classification, and hook response or error. Only selected event fields are logged, never the full incoming payload. These logs require the Peacekeeper script to start; a missing Node.js executable or package must be diagnosed in Codex's own logs.
141
146
 
@@ -438,18 +443,28 @@ artifacts of tested contents. Configure `git.releaseRequiredChecks` in the root
438
443
  `peacekeeper.config.json` with the exact CI job names required for a release
439
444
  (for this repository: `["test", "Test package"]`). These checks must be mandatory
440
445
  with **Require branches to be up to date before merging** enabled. Classic branch
441
- protection must enforce checks for administrators too. Alternatively, active
442
- rulesets must require strict checks and have no bypass actors. Rules inherited
443
- from the organization are included. Merge queues are not currently an alternative
446
+ protection may provide the base PR and check requirements. Active base rulesets
447
+ may provide them instead. Merge
448
+ queues are not currently an alternative
444
449
  to this strict policy. Repositories must also enable **Automatically delete head
445
450
  branches** (`delete_branch_on_merge=true`).
446
451
 
447
- The default branch must require pull requests (zero required reviewer approvals
448
- is allowed), and only merge commits may be used. Either disable squash and rebase
452
+ The default branch must also have exactly one active approval ruleset. It must
453
+ require one approval from the sole global code owner, dismiss stale approvals
454
+ after new pushes, and contain no rule except that pull-request approval rule. Its
455
+ only bypass actor must be the personal repository owner from `git.requiredApprover`,
456
+ with `bypass_mode: pull_request`. This lets the owner merge their own PR without
457
+ approval while the separate base policy still requires a PR and successful CI.
458
+ No other user, team, role, or app may bypass either policy. Peacekeeper does not
459
+ verify bypass actors because GitHub hides them from read-only administration
460
+ tokens; inspect them manually instead.
461
+
462
+ Only merge commits may be used. Either disable squash and rebase
449
463
  in repository settings, or restrict the default branch's pull-request ruleset to
450
464
  `allowed_merge_methods: ["merge"]`. Other branches are outside this policy.
451
465
  Required linear history and any applicable PR rule excluding merge commits fail
452
- verification. PR and strict-check rules must enforce the policy without bypass.
466
+ verification. Bypass actors for base PR and strict-check rules also require
467
+ manual inspection.
453
468
  Enable `allow_auto_merge` in repository settings: this permits opting in per PR;
454
469
  Peacekeeper never enables auto-merge on individual PRs.
455
470
 
@@ -488,15 +503,16 @@ jobs in its latest PR workflow run. Manual tags without that PR are rejected.
488
503
  `verify-release-version` remains available for local version checks alone.
489
504
 
490
505
  API failures, missing permissions, and unverifiable rules stop the commands.
506
+ Bypass actors are the exception: each policy verification prints `Cannot verify
507
+ bypass users unless given write access. Run a manual check instead; available as
508
+ a gist.` and continues without inspecting them.
491
509
  The workflow expects a `RELEASE_POLICY_TOKEN` Actions secret, exposed to the
492
510
  commands as `GH_TOKEN`. Use a fine-grained PAT or GitHub App token with access to
493
511
  this repository and Administration read, Contents read/write, Pull requests read and
494
512
  Actions read permissions. Contents write is required even to read merge-related
495
- settings such as `delete_branch_on_merge`. GitHub only exposes ruleset bypass actors to callers
496
- with write access to the ruleset; ruleset users must additionally grant that
497
- access (Administration write for repository rulesets, or the appropriate access
498
- for inherited organization rulesets). Missing bypass information also fails.
499
- The normal workflow `GITHUB_TOKEN` cannot be granted Administration permissions
513
+ settings such as `delete_branch_on_merge`. Administration read is sufficient
514
+ because bypass actors are checked manually.
515
+ The normal workflow `GITHUB_TOKEN` cannot be granted Administration permission
500
516
  through workflow YAML. After correcting access or rules, rerun the failed job.
501
517
  Fork PRs do not receive this secret and fail the policy check; do not expose it
502
518
  by executing fork code with `pull_request_target`.
@@ -504,8 +520,7 @@ by executing fork code with `pull_request_target`.
504
520
  To set this up for this repository:
505
521
 
506
522
  1. Open the [token creation form with the required permissions prefilled](https://github.com/settings/personal-access-tokens/new?name=peacekeeper-release-policy&target_name=jakobmattsson&expires_in=90&administration=read&contents=write&pull_requests=read&actions=read).
507
- For repository rulesets, use the [form with Administration write instead](https://github.com/settings/personal-access-tokens/new?name=peacekeeper-release-policy&target_name=jakobmattsson&expires_in=90&administration=write&contents=write&pull_requests=read&actions=read)
508
- so GitHub exposes bypass actors. For another repository, change the resource
523
+ For another repository, change the resource
509
524
  owner. Select **Only select repositories**, choose `peacekeeper`, review
510
525
  the permissions and expiration, and generate the token. If the owner requires
511
526
  approval, wait until the token is approved.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jakobm/peacekeeper",
3
- "version": "0.19.0",
3
+ "version": "0.20.0",
4
4
  "description": "Shared repository test, Git worktree, and Codex hook commands",
5
5
  "license": "MIT",
6
6
  "author": "Jakob Mattsson",
@@ -30,6 +30,7 @@ Project configuration
30
30
 
31
31
  Example configuration fields (merge into the full project configuration):
32
32
  "git": {
33
+ "requiredApprover": "OWNER",
33
34
  "releaseTestWorkflow": "package.yml",
34
35
  "releaseRequiredChecks": ["test"]
35
36
  },
@@ -39,6 +40,14 @@ Project configuration
39
40
  }
40
41
  projectChecks and both its fields are mandatory in an existing configuration.
41
42
 
43
+ git.requiredApprover must identify the personal GitHub account that owns the
44
+ repository. Its bundled default is null so migrations must choose explicitly.
45
+ check-project requires .github/CODEOWNERS to contain exactly one non-comment
46
+ rule matching that account:
47
+ * @OWNER
48
+ Additional ownership patterns or owners are rejected because GitHub accepts
49
+ any matching code owner's approval, which would weaken the identity guarantee.
50
+
42
51
  Package metadata: all projects, including private packages
43
52
  package.json must declare author and repository.
44
53
  author must be a nonblank string or an object with a nonblank string name.
@@ -246,30 +255,31 @@ Online release policy and GitHub token setup
246
255
 
247
256
  Configure the default branch from git.defaultBranch with every exact job name
248
257
  in git.releaseRequiredChecks mandatory and "Require branches to be up to date
249
- before merging" enabled. Choose either:
250
- - Classic branch protection with strict status checks and enforcement for
251
- administrators as well (no administrator bypass).
252
- - Active branch rulesets requiring strict status checks, without any bypass
253
- actors. Organization-inherited rulesets are included in verification.
258
+ before merging" enabled. The base policy may use either classic branch
259
+ protection with strict status checks or active branch rulesets requiring
260
+ strict status checks. Its bypass configuration must be inspected manually.
254
261
  Merge queues are not currently an alternative to this strict policy. For the
255
262
  matrix example, also require its matrix checks as described above.
256
263
 
264
+ Add exactly one active owner-approval ruleset. It must contain only one
265
+ pull_request rule requiring exactly one code-owner approval and stale approval
266
+ dismissal. Its only bypass actor must be the numeric user ID corresponding to
267
+ git.requiredApprover, with actor_type User and bypass_mode pull_request. The
268
+ configured account must be the personal repository owner. This approval-only
269
+ bypass lets that owner merge a PR they authored, but the separate base policy
270
+ still prevents direct pushes and requires strict CI. Any other bypass violates
271
+ the policy and must be caught by the manual inspection.
272
+
257
273
  Create a fine-grained GitHub PAT or GitHub App installation token with access
258
274
  to this repository and these repository permissions:
259
275
  Administration: read
260
276
  Contents: read/write
261
277
  Pull requests: read
262
278
  Actions: read
263
- For repository rulesets, Administration: write is additionally needed because
264
- GitHub only exposes bypass actors to callers with write access to the ruleset.
265
- For organization-inherited rulesets, repository Administration permission
266
- alone does not establish write access to the organization-owned ruleset.
267
- Consult GitHub's organization ruleset endpoint documentation for supported
268
- token types and organization permissions (the fine-grained token section):
269
- https://docs.github.com/en/rest/orgs/rules#get-an-organization-repository-ruleset
270
- The token must also have write access to the contributing ruleset for GitHub
271
- to expose bypass actors. Missing bypass information causes verification to
272
- fail; confirm access with verify-release-protection.
279
+ GitHub exposes bypass actors only to callers with write access to the ruleset.
280
+ Peacekeeper therefore does not verify them and prints this warning instead:
281
+ Cannot verify bypass users unless given write access. Run a manual check
282
+ instead; available as a gist.
273
283
 
274
284
  Recommended Actions secret name: RELEASE_POLICY_TOKEN. A maintainer with
275
285
  permission to manage Actions secrets can save it with:
@@ -392,13 +402,16 @@ Default-branch GitHub policy chain
392
402
  This applies to private projects too; configure nonempty releaseRequiredChecks.
393
403
 
394
404
  Online verification reads the actual GitHub default branch and requires PRs,
395
- strict mandatory configured checks without bypass, and merge commits only.
396
- Zero reviewer approvals is allowed. Enable repository allow_auto_merge; this
397
- only offers per-PR opt-in and does not activate auto-merge for any PR.
405
+ strict mandatory configured checks, and merge commits only. It also verifies
406
+ the separate owner-approval ruleset described above, except for its bypass
407
+ actors. Enable
408
+ repository allow_auto_merge; this only offers per-PR opt-in and does not
409
+ activate auto-merge for any PR.
398
410
  Restrict merge methods either repository-wide (merge enabled, squash and rebase
399
411
  disabled) or with a default-branch PR ruleset allowing only merge. Other branches
400
412
  are not checked. Linear-history rules or PR rules excluding merge are errors.
401
- Ruleset PR requirements, like status checks, require active rules without bypass.
413
+ Base PR requirements, like status checks, require active rules. Inspect all
414
+ bypass actors manually.
402
415
  Existing automatic head-branch deletion requirements still apply.
403
416
 
404
417
  Missing CI is detected on the next local npm test. GitHub settings are checked
@@ -56,6 +56,19 @@ function checkProject(cwd = process.cwd()) {
56
56
  'package.json: repository must be a nonblank string or an object with a nonblank url.');
57
57
  });
58
58
 
59
+ check('GitHub policy', () => {
60
+ const approver = config.git.requiredApprover;
61
+ requireThat(typeof approver === 'string',
62
+ 'peacekeeper.config.json: set git.requiredApprover to the personal GitHub repository owner.');
63
+ if (typeof approver !== 'string') return;
64
+ const file = '.github/CODEOWNERS';
65
+ const lines = read(root, file, value => value.split(/\r?\n/u))
66
+ .map(line => line.trim())
67
+ .filter(line => line && !line.startsWith('#'));
68
+ requireThat(isDeepStrictEqual(lines, [`* @${approver}`]),
69
+ `${file}: use exactly one ownership rule, "* @${approver}", so only git.requiredApprover can satisfy required code-owner review.`);
70
+ });
71
+
59
72
  const workflows = new Map();
60
73
  check('CI', () => {
61
74
  const directory = path.join(root, '.github/workflows');
@@ -99,20 +99,101 @@ function githubSetup({ owner, repositoryName, published }) {
99
99
  ${npm}set -euo pipefail
100
100
 
101
101
  repo=${owner}/${repositoryName}
102
+ required_approver=${owner}
102
103
  gh auth status
103
104
  gh repo view "$repo" >/dev/null
105
+ actual_owner=$(gh api "repos/$repo" --jq .owner.login)
106
+ if [[ "$actual_owner" != "$required_approver" ]]; then
107
+ printf 'Expected personal repository owner %s, found %s.\n' "$required_approver" "$actual_owner" >&2
108
+ exit 1
109
+ fi
110
+ approver_id=$(gh api "users/$required_approver" --jq .id)
104
111
  gh api --method PATCH "repos/$repo" \\
105
112
  -F delete_branch_on_merge=true \\
106
113
  -F allow_auto_merge=true \\
107
114
  -F allow_merge_commit=true \\
108
115
  -F allow_squash_merge=false \\
109
116
  -F allow_rebase_merge=false >/dev/null
110
- gh api --method PUT "repos/$repo/branches/main/protection" \\
111
- -F 'required_status_checks[strict]=true' \\
112
- -f 'required_status_checks[contexts][]=test' \\
113
- -F enforce_admins=true \\
114
- -F 'required_pull_request_reviews[required_approving_review_count]=0' \\
115
- -F restrictions=null >/dev/null
117
+ policy_dir=$(mktemp -d)
118
+ trap 'rm -rf -- "$policy_dir"' EXIT
119
+ base_policy="$policy_dir/base.json"
120
+ approval_policy="$policy_dir/approval.json"
121
+ cat >"$base_policy" <<'JSON'
122
+ {
123
+ "name": "Peacekeeper base protection",
124
+ "target": "branch",
125
+ "enforcement": "active",
126
+ "bypass_actors": [],
127
+ "conditions": { "ref_name": { "include": ["~DEFAULT_BRANCH"], "exclude": [] } },
128
+ "rules": [
129
+ { "type": "deletion" },
130
+ { "type": "non_fast_forward" },
131
+ {
132
+ "type": "pull_request",
133
+ "parameters": {
134
+ "required_approving_review_count": 0,
135
+ "dismiss_stale_reviews_on_push": false,
136
+ "require_code_owner_review": false,
137
+ "require_last_push_approval": false,
138
+ "required_review_thread_resolution": false,
139
+ "allowed_merge_methods": ["merge"]
140
+ }
141
+ },
142
+ {
143
+ "type": "required_status_checks",
144
+ "parameters": {
145
+ "strict_required_status_checks_policy": true,
146
+ "do_not_enforce_on_create": false,
147
+ "required_status_checks": [{ "context": "test" }]
148
+ }
149
+ }
150
+ ]
151
+ }
152
+ JSON
153
+ cat >"$approval_policy" <<JSON
154
+ {
155
+ "name": "Peacekeeper owner approval",
156
+ "target": "branch",
157
+ "enforcement": "active",
158
+ "bypass_actors": [
159
+ { "actor_id": $approver_id, "actor_type": "User", "bypass_mode": "pull_request" }
160
+ ],
161
+ "conditions": { "ref_name": { "include": ["~DEFAULT_BRANCH"], "exclude": [] } },
162
+ "rules": [
163
+ {
164
+ "type": "pull_request",
165
+ "parameters": {
166
+ "required_approving_review_count": 1,
167
+ "dismiss_stale_reviews_on_push": true,
168
+ "require_code_owner_review": true,
169
+ "require_last_push_approval": false,
170
+ "required_review_thread_resolution": false,
171
+ "allowed_merge_methods": ["merge"]
172
+ }
173
+ }
174
+ ]
175
+ }
176
+ JSON
177
+
178
+ upsert_ruleset() {
179
+ local name=$1 payload=$2 ids count id
180
+ ids=$(gh api --paginate "repos/$repo/rulesets?includes_parents=false" --jq ".[] | select(.name == \"$name\") | .id")
181
+ count=$(printf '%s\n' "$ids" | sed '/^$/d' | wc -l | tr -d ' ')
182
+ if [[ "$count" == 0 ]]; then
183
+ gh api --method POST "repos/$repo/rulesets" --input "$payload" >/dev/null
184
+ elif [[ "$count" == 1 ]]; then
185
+ id=$ids
186
+ gh api --method PUT "repos/$repo/rulesets/$id" --input "$payload" >/dev/null
187
+ else
188
+ printf 'Multiple rulesets named %s exist; remove duplicates before retrying.\n' "$name" >&2
189
+ exit 1
190
+ fi
191
+ }
192
+ upsert_ruleset 'Peacekeeper base protection' "$base_policy"
193
+ upsert_ruleset 'Peacekeeper owner approval' "$approval_policy"
194
+ if gh api "repos/$repo/branches/main/protection" >/dev/null 2>&1; then
195
+ gh api --method DELETE "repos/$repo/branches/main/protection" >/dev/null
196
+ fi
116
197
  groundskeeper secrets sync --name RELEASE_POLICY_TOKEN --new-repo "$repo"
117
198
  printf 'GitHub configuration completed for %s.\\n' "$repo"
118
199
  `;
@@ -143,6 +224,7 @@ function generate(root, options) {
143
224
  if (options.published) write(root, 'scripts/test-package.cjs', packageTest().replace('${PACKAGE_NAME}', options.packageName));
144
225
  const defaults = structuredClone(require('./project-config-defaults.json'));
145
226
  defaults.publishesToNpm = options.published;
227
+ defaults.git.requiredApprover = options.owner;
146
228
  defaults.tests.commands = ['npm run typecheck', 'npm run build', 'npm run test:unit', ...(options.published ? ['npm run test:package'] : [])];
147
229
  defaults.tests.npmTestUsesRunner = true;
148
230
  write(root, 'peacekeeper.config.json', json(defaults));
@@ -150,6 +232,7 @@ function generate(root, options) {
150
232
  const prefix = fs.readFileSync(path.join(__dirname, 'codex-setup-prefix.sh'), 'utf8');
151
233
  write(root, '.codex/environments/environment.toml', `version = 1\nname = ${JSON.stringify(options.repositoryName)}\n\n[setup]\nscript = '''\n${prefix}'''\n`);
152
234
  write(root, '.github/workflows/test.yml', workflow(options.published));
235
+ write(root, '.github/CODEOWNERS', `* @${options.owner}\n`);
153
236
  if (options.published) write(root, '.github/workflows/publish.yml', publishWorkflow());
154
237
  write(root, '.gitignore', 'node_modules/\n*.tgz\ntmp/\n');
155
238
  write(root, 'README.md', `# ${options.repositoryName}\n\nA TypeScript library generated by Peacekeeper.\n\n## API\n\n\`hello()\` returns \`"hello world"\`.\n`);
@@ -3,6 +3,7 @@
3
3
  "remote": "origin",
4
4
  "defaultBranch": "main",
5
5
  "branchPrefix": "codex/",
6
+ "requiredApprover": null,
6
7
  "checkpointPushRemotes": [
7
8
  "origin"
8
9
  ],
@@ -14,7 +14,7 @@ function repositoryRoot(cwd = process.cwd()) {
14
14
  // Kept independent of the defaults so additions require an explicit default.
15
15
  const CONFIG_SCHEMA = {
16
16
  publishesToNpm: true,
17
- git: { remote: true, defaultBranch: true, branchPrefix: true,
17
+ git: { remote: true, defaultBranch: true, branchPrefix: true, requiredApprover: true,
18
18
  checkpointPushRemotes: true, releaseMergeMethod: true,
19
19
  releaseRequiredChecks: true, releaseTestWorkflow: true },
20
20
  tests: { commands: true, receiptMaxAgeMinutes: true, npmTestUsesRunner: true },
@@ -59,6 +59,11 @@ function validateConfig(config, file) {
59
59
  for (const field of ['remote', 'defaultBranch', 'branchPrefix']) {
60
60
  requireNonemptyString(config.git[field], `git.${field}`, file);
61
61
  }
62
+ if (config.git.requiredApprover !== null
63
+ && (typeof config.git.requiredApprover !== 'string'
64
+ || !/^(?!-)(?!.*--)[A-Za-z0-9-]{1,39}(?<!-)$/u.test(config.git.requiredApprover))) {
65
+ throw new Error(`${file}: git.requiredApprover must be null or a valid GitHub username`);
66
+ }
62
67
  const remotes = config.git.checkpointPushRemotes;
63
68
  if (!Array.isArray(remotes)
64
69
  || remotes.some((remote) => typeof remote !== 'string' || remote.trim() === ''
@@ -3,7 +3,7 @@ const fs = require('node:fs');
3
3
  const os = require('node:os');
4
4
  const path = require('node:path');
5
5
  const yaml = require('yaml');
6
- const { githubApi, requiredChecks, verifyProtection } = require('./release-protection');
6
+ const { bypassWarning, githubApi, requiredPolicy, verifyProtection } = require('./release-protection');
7
7
  const { projectConfig } = require('./project-config');
8
8
  const requiredCondition = "${{ github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') }}";
9
9
  const stableVersion = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/u;
@@ -235,7 +235,7 @@ function prepare(exec, cwd, bump, log) {
235
235
  if (typeof defaultBranch !== 'string' || !defaultBranch) {
236
236
  throw new ReleaseError('GitHub did not provide the default branch.');
237
237
  }
238
- verifyProtection({ api: githubApi(exec, cwd, host), slug, branch: defaultBranch, checks: requiredChecks(cwd) });
238
+ verifyProtection({ api: githubApi(exec, cwd, host), slug, branch: defaultBranch, ...requiredPolicy(cwd) });
239
239
  checked(exec, 'git', ['fetch', 'origin', defaultBranch], cwd);
240
240
  const manifest = JSON.parse(checkedOutput(exec, 'git', ['show', `origin/${defaultBranch}:package.json`], cwd));
241
241
  const packageInfo = { name: manifest.name, version: manifest.version };
@@ -373,7 +373,7 @@ async function mergeRelease(exec, cwd, details, now, sleep, log) {
373
373
  if (pr.mergeable_state === 'dirty')
374
374
  throw new ReleaseError(`Release PR #${details.pr} has conflicts; inspect it before continuing.`);
375
375
  verifyProtection({ api: githubApi(exec, cwd, details.host), slug: details.slug,
376
- branch: details.defaultBranch, checks: requiredChecks(cwd) });
376
+ branch: details.defaultBranch, ...requiredPolicy(cwd) });
377
377
  if (details.mergeMethod && details.mergeMethod !== 'merge') throw new ReleaseError('Release must use merge commits on the default branch; restart this release.');
378
378
  // GitHub enforces required checks, reviews, and branch freshness on this request.
379
379
  const result = exec('gh', ['api', '--hostname', details.host, '--method', 'PUT',
@@ -394,6 +394,7 @@ async function mergeRelease(exec, cwd, details, now, sleep, log) {
394
394
  }
395
395
  async function release(bump, dependencies) {
396
396
  const { cwd, spawnSync, environment, now, sleep, log } = dependencies;
397
+ log(bypassWarning);
397
398
  const exec = (command, args, options) => execute(spawnSync, environment, command, args, options);
398
399
  const common = path.resolve(cwd, checked(exec, 'git', ['rev-parse', '--git-common-dir'], cwd));
399
400
  const statePath = path.join(common, 'peacekeeper-release.json');
@@ -1,15 +1,30 @@
1
1
  'use strict';
2
2
 
3
- function requiredChecks(cwd) {
3
+ function requiredPolicy(cwd) {
4
4
  const { projectConfig } = require('./project-config');
5
- const checks = projectConfig(cwd).git.releaseRequiredChecks;
6
- if (!checks?.length) throw new Error('Configure git.releaseRequiredChecks with the CI jobs required for releases.');
7
- return checks;
5
+ const config = projectConfig(cwd).git;
6
+ if (!config.releaseRequiredChecks?.length) {
7
+ throw new Error('Configure git.releaseRequiredChecks with the CI jobs required for releases.');
8
+ }
9
+ if (!config.requiredApprover) {
10
+ throw new Error('Configure git.requiredApprover with the personal GitHub repository owner.');
11
+ }
12
+ return { checks: config.releaseRequiredChecks, requiredApprover: config.requiredApprover };
13
+ }
14
+
15
+ function approvalParameters(parameters) {
16
+ return parameters?.required_approving_review_count === 1
17
+ && parameters.dismiss_stale_reviews_on_push === true
18
+ && parameters.require_code_owner_review === true;
8
19
  }
9
20
 
21
+ const bypassWarning = 'Cannot verify bypass users unless given write access. Run a manual check instead; available as a gist.';
22
+
10
23
  // A missing classic protection is expected for ruleset-only repositories. All
11
24
  // other API failures, including permission failures, must propagate.
12
- function verifyProtection({ api, slug, branch, checks }) {
25
+ function verifyProtection({ api, slug, branch, checks, requiredApprover: approver, warn }) {
26
+ if (warn) warn(bypassWarning);
27
+ if (!approver) throw new Error('A required GitHub approver must be provided.');
13
28
  const base = `repos/${slug}`;
14
29
  const repository = api(base);
15
30
  if (repository?.delete_branch_on_merge !== true) {
@@ -17,6 +32,11 @@ function verifyProtection({ api, slug, branch, checks }) {
17
32
  }
18
33
  if (repository.allow_auto_merge !== true) throw new Error('Repository must enable allow_auto_merge; this only makes auto-merge available per PR.');
19
34
  if (repository.default_branch !== branch) throw new Error(`Verify the actual default branch (${repository.default_branch}), not ${branch}.`);
35
+ if (repository.owner?.type !== 'User'
36
+ || repository.owner.login?.toLowerCase() !== approver.toLowerCase()
37
+ || !Number.isInteger(repository.owner.id)) {
38
+ throw new Error(`git.requiredApprover (${approver}) must be the personal owner of repository ${slug}.`);
39
+ }
20
40
  let protection;
21
41
  try {
22
42
  protection = api(`${base}/branches/${encodeURIComponent(branch)}/protection`);
@@ -33,51 +53,70 @@ function verifyProtection({ api, slug, branch, checks }) {
33
53
  if (protection?.required_linear_history?.enabled || rules.some(rule => rule.type === 'required_linear_history')) {
34
54
  throw new Error('Default branch must allow merge commits; disable required linear history.');
35
55
  }
36
- const pullRules = rules.filter(rule => rule.type === 'pull_request');
37
- let requiresPullRequest = Boolean(protection?.required_pull_request_reviews && protection.enforce_admins?.enabled === true
38
- && !(protection.required_pull_request_reviews.bypass_pull_request_allowances?.users?.length)
39
- && !(protection.required_pull_request_reviews.bypass_pull_request_allowances?.teams?.length)
40
- && !(protection.required_pull_request_reviews.bypass_pull_request_allowances?.apps?.length));
41
- let branchMergeOnly = false;
42
- const verifiedRulesets = new Set();
43
- function verifyRuleset(rule) {
56
+
57
+ const rulesets = new Map();
58
+ function rulesetFor(rule) {
44
59
  if (!Number.isInteger(rule.ruleset_id)) throw new Error('GitHub did not identify the policy ruleset.');
45
- if (verifiedRulesets.has(rule.ruleset_id)) return;
46
- const ruleset = api(`${base}/rulesets/${rule.ruleset_id}`);
47
- if (ruleset.enforcement !== 'active' || !Array.isArray(ruleset.bypass_actors)) {
48
- throw new Error('Cannot verify active ruleset bypass settings; grant write access to the ruleset so GitHub exposes bypass actors, then rerun.');
60
+ if (!rulesets.has(rule.ruleset_id)) {
61
+ const ruleset = api(`${base}/rulesets/${rule.ruleset_id}`);
62
+ if (ruleset.enforcement !== 'active') throw new Error('Policy rulesets must be active.');
63
+ if (!Array.isArray(ruleset.rules)) {
64
+ throw new Error('Cannot verify all rules in a policy ruleset; grant access to the complete ruleset, then rerun.');
65
+ }
66
+ rulesets.set(rule.ruleset_id, ruleset);
49
67
  }
50
- if (ruleset.bypass_actors.length) throw new Error('Default branch rulesets must not allow bypass actors.');
51
- verifiedRulesets.add(rule.ruleset_id);
68
+ return rulesets.get(rule.ruleset_id);
52
69
  }
53
- for (const rule of pullRules) {
54
- verifyRuleset(rule);
55
- requiresPullRequest = true;
70
+ for (const rule of rules.filter(rule => Number.isInteger(rule.ruleset_id))) rulesetFor(rule);
71
+
72
+ const approvalRulesets = new Set();
73
+ for (const [id, ruleset] of rulesets) {
74
+ if (ruleset.rules.length === 1 && ruleset.rules[0].type === 'pull_request'
75
+ && approvalParameters(ruleset.rules[0].parameters)) approvalRulesets.add(id);
76
+ }
77
+
78
+ const classicReviews = protection?.required_pull_request_reviews;
79
+ let requiresPullRequest = Boolean(classicReviews);
80
+ let branchMergeOnly = false;
81
+ let approvalPolicyCount = 0;
82
+ for (const rule of rules.filter(rule => rule.type === 'pull_request')) {
83
+ const ruleset = rulesetFor(rule);
84
+ if (approvalRulesets.has(rule.ruleset_id)) {
85
+ if (!approvalParameters(rule.parameters)) {
86
+ throw new Error('The effective owner approval rule must require one code-owner approval and dismiss stale approvals.');
87
+ }
88
+ approvalPolicyCount += 1;
89
+ } else {
90
+ requiresPullRequest = true;
91
+ }
56
92
  const methods = rule.parameters?.allowed_merge_methods;
57
93
  if (methods && !methods.includes('merge')) throw new Error('Default branch PR rules must allow merge commits.');
58
- if (Array.isArray(methods) && methods.length === 1 && methods[0] === 'merge') branchMergeOnly = true;
94
+ if (Array.isArray(methods) && methods.length === 1 && methods[0] === 'merge'
95
+ && !approvalRulesets.has(rule.ruleset_id)) branchMergeOnly = true;
96
+ }
97
+ if (approvalPolicyCount !== 1 || approvalRulesets.size !== 1) {
98
+ throw new Error('Default branch must have exactly one owner approval ruleset requiring one code-owner approval and stale approval dismissal.');
59
99
  }
100
+
60
101
  const strictChecks = new Set();
61
102
  const classic = protection?.required_status_checks;
62
- if (classic?.strict === true && protection.enforce_admins?.enabled === true) {
103
+ if (classic?.strict === true) {
63
104
  for (const check of classic.checks || []) strictChecks.add(check.context);
64
105
  for (const context of classic.contexts || []) strictChecks.add(context);
65
106
  }
66
- // Ruleset bypass actors are not included in the effective-rules response.
67
- // Read every contributing ruleset and require that it has no bypass actors.
68
107
  for (const rule of rules.filter(rule => rule.type === 'required_status_checks')) {
108
+ rulesetFor(rule);
69
109
  if (rule.parameters?.strict_required_status_checks_policy !== true) continue;
70
- verifyRuleset(rule);
71
110
  for (const check of rule.parameters.required_status_checks || []) strictChecks.add(check.context);
72
111
  }
73
112
  const missing = checks.filter(check => !strictChecks.has(check));
74
113
  if (!checks.length || missing.length) {
75
- throw new Error(`Branch ${branch} must require strict status checks without bypass for: ${missing.join(', ') || '(no checks configured)'}. Enable strict checks and enforce them for administrators, or use an active ruleset without bypass actors; then rerun.`);
114
+ throw new Error(`Branch ${branch} must require strict status checks for: ${missing.join(', ') || '(no checks configured)'}. Enable strict checks, then rerun.`);
76
115
  }
77
- if (!requiresPullRequest) throw new Error('Default branch must require pull requests without bypass.');
116
+ if (!requiresPullRequest) throw new Error('Default branch must require pull requests.');
78
117
  if (repository.allow_merge_commit !== true || (!branchMergeOnly
79
118
  && (repository.allow_squash_merge !== false || repository.allow_rebase_merge !== false))) {
80
- throw new Error('Default branch must allow only merge commits: restrict its pull request ruleset to merge, or disable repository squash and rebase merging.');
119
+ throw new Error('Default branch must allow only merge commits: restrict its base pull request ruleset to merge, or disable repository squash and rebase merging.');
81
120
  }
82
121
  }
83
122
 
@@ -93,4 +132,4 @@ function githubApi(exec, cwd, host) {
93
132
  };
94
133
  }
95
134
 
96
- module.exports = { githubApi, requiredChecks, verifyProtection };
135
+ module.exports = { bypassWarning, githubApi, requiredPolicy, verifyProtection };
@@ -12,9 +12,9 @@ function list(api, endpoint, member) {
12
12
  }
13
13
  }
14
14
 
15
- function verifyRelease({ api, slug, sha, tag, branch, checks, workflow }) {
15
+ function verifyRelease({ api, slug, sha, tag, branch, checks, requiredApprover, workflow, warn }) {
16
16
  if (!/^v\d+\.\d+\.\d+$/u.test(tag)) throw new Error('Expected a stable release tag');
17
- verifyProtection({ api, slug, branch, checks });
17
+ verifyProtection({ api, slug, branch, checks, requiredApprover, warn });
18
18
  const base = `repos/${slug}`;
19
19
  const commit = api(`${base}/commits/${encodeURIComponent(sha)}`);
20
20
  const comparison = api(`${base}/compare/${commit.sha}...${encodeURIComponent(branch)}`);
@@ -3,7 +3,7 @@
3
3
  const { spawnSync } = require('node:child_process');
4
4
  const { projectConfig } = require('./project-config');
5
5
  const { originRepository } = require('./release-core');
6
- const { githubApi, requiredChecks, verifyProtection } = require('./release-protection');
6
+ const { githubApi, requiredPolicy, verifyProtection } = require('./release-protection');
7
7
 
8
8
  try {
9
9
  const cwd = process.cwd();
@@ -12,7 +12,8 @@ try {
12
12
  if (remote.status !== 0) throw new Error(remote.stderr);
13
13
  const { host, slug } = originRepository(remote.stdout.trim());
14
14
  const api = githubApi((command, args, options) => spawnSync(command, args, { ...options, encoding: 'utf8' }), cwd, host);
15
- verifyProtection({ api, slug, branch: api(`repos/${slug}`).default_branch, checks: requiredChecks(cwd) });
15
+ verifyProtection({ api, slug, branch: api(`repos/${slug}`).default_branch,
16
+ ...requiredPolicy(cwd), warn: message => console.warn(message) });
16
17
  } catch (error) {
17
18
  console.error(error.message);
18
19
  process.exitCode = 1;
@@ -4,7 +4,7 @@ const { spawnSync, execFileSync } = require('node:child_process');
4
4
  const path = require('node:path');
5
5
  const { projectConfig } = require('./project-config');
6
6
  const { originRepository, inspectWorkflow } = require('./release-core');
7
- const { githubApi, requiredChecks } = require('./release-protection');
7
+ const { githubApi, requiredPolicy } = require('./release-protection');
8
8
  const { verifyRelease } = require('./verify-release-core');
9
9
 
10
10
  try {
@@ -19,7 +19,8 @@ try {
19
19
  const sha = execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }).trim();
20
20
  inspectWorkflow(cwd, tag);
21
21
  verifyRelease({ api, slug, sha, tag, branch: config.git.defaultBranch,
22
- checks: requiredChecks(cwd), workflow: config.git.releaseTestWorkflow });
22
+ ...requiredPolicy(cwd), workflow: config.git.releaseTestWorkflow,
23
+ warn: message => console.warn(message) });
23
24
  } catch (error) {
24
25
  console.error(error.message);
25
26
  process.exitCode = 1;