@jakobm/peacekeeper 0.21.0 → 0.22.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
@@ -85,9 +85,21 @@ peacekeeper generate-github-setup \
85
85
  ```
86
86
 
87
87
  Repeat `--repository` to configure any number of repositories in one script.
88
- The command writes the setup to stdout, so it can be inspected, pasted into a
89
- shell, or redirected to a file. Repository and owner values are inlined in the
90
- output; the command does not require npm publication information.
88
+ At generation time the command reads and validates each repository's
89
+ `peacekeeper.config.json` from its GitHub default branch, then embeds that
90
+ repository's `git.releaseRequiredChecks` in the output. A repository without the
91
+ file uses Peacekeeper's bundled defaults; an invalid file or unreadable repository
92
+ stops generation. The command writes this configuration snapshot to stdout, so it
93
+ can be inspected, pasted into a shell, or redirected to a file and run immediately.
94
+ Repository and owner values are also inlined; the command does not require npm
95
+ publication information.
96
+
97
+ The generator and `verify-release-protection` consume one internal GitHub policy
98
+ model. The generator materializes its canonical repository settings and ruleset
99
+ JSON into the shell script; the script itself does not read configuration or
100
+ interpret policy at runtime. Verification normalizes GitHub's response and checks
101
+ it against the same model, while continuing to accept documented semantic
102
+ alternatives such as equivalent classic branch protection.
91
103
 
92
104
  When moving an existing project to Peacekeeper, update its dependency and lockfile,
93
105
  package scripts, and configuration filename together. Replace previous lifecycle
@@ -493,16 +505,17 @@ after new pushes, and contain no rule except that pull-request approval rule. It
493
505
  only bypass actor must be the personal repository owner from `git.requiredApprover`,
494
506
  with `bypass_mode: pull_request`. This lets the owner merge their own PR without
495
507
  approval while the separate base policy still requires a PR and successful CI.
496
- No other user, team, role, or app may bypass either policy. Peacekeeper does not
497
- verify bypass actors because GitHub hides them from read-only administration
498
- tokens; inspect them manually instead.
508
+ No other user, team, role, or app may bypass either policy. Peacekeeper verifies
509
+ bypass actors when GitHub returns them. GitHub hides them from read-only
510
+ administration tokens, in which case Peacekeeper warns that this part remains
511
+ unknown instead of reporting a false success or failure.
499
512
 
500
513
  Only merge commits may be used. Either disable squash and rebase
501
514
  in repository settings, or restrict the default branch's pull-request ruleset to
502
515
  `allowed_merge_methods: ["merge"]`. Other branches are outside this policy.
503
516
  Required linear history and any applicable PR rule excluding merge commits fail
504
- verification. Bypass actors for base PR and strict-check rules also require
505
- manual inspection.
517
+ verification. Bypass actors for base PR and strict-check rules require manual
518
+ inspection only when GitHub omits them from its response.
506
519
  Enable `allow_auto_merge` in repository settings: this permits opting in per PR;
507
520
  Peacekeeper never enables auto-merge on individual PRs.
508
521
 
@@ -512,7 +525,8 @@ PR workflow uses only `pull_request`, with `branches` set to exactly
512
525
  `[git.defaultBranch]`, and runs `verify-release-protection` with `GH_TOKEN` after `npm ci` and
513
526
  before tests in a job listed in `git.releaseRequiredChecks`. The job and step must
514
527
  not skip verification or ignore failures. The online verifier then checks that
515
- all those configured check names are mandatory on GitHub, including its own job.
528
+ exactly those configured check names are mandatory on GitHub, including its own
529
+ job; missing and additional checks are both configuration drift.
516
530
  Push, manual, scheduled, and other triggers are rejected in this workflow. Keep
517
531
  publishing, deployment, reports, and benchmarks in separate workflows.
518
532
  For example, in a required `test` job:
@@ -541,15 +555,18 @@ jobs in its latest PR workflow run. Manual tags without that PR are rejected.
541
555
  `verify-release-version` remains available for local version checks alone.
542
556
 
543
557
  API failures, missing permissions, and unverifiable rules stop the commands.
544
- Bypass actors are the exception: each policy verification prints `Cannot verify
545
- bypass users unless given write access. Run a manual check instead; available as
546
- a gist.` and continues without inspecting them.
558
+ Bypass actors are the exception when GitHub omits them: policy verification then
559
+ prints `Cannot verify bypass users unless given write access. Run a manual check
560
+ instead; available as a gist.` and continues with that part marked unknown. When
561
+ the API returns bypass actors, Peacekeeper compares them with the same policy used
562
+ to generate the setup script and rejects drift.
547
563
  The workflow expects a `RELEASE_POLICY_TOKEN` Actions secret, exposed to the
548
564
  commands as `GH_TOKEN`. Use a fine-grained PAT or GitHub App token with access to
549
565
  this repository and Administration read, Contents read/write, Pull requests read and
550
566
  Actions read permissions. Contents write is required even to read merge-related
551
- settings such as `delete_branch_on_merge`. Administration read is sufficient
552
- because bypass actors are checked manually.
567
+ settings such as `delete_branch_on_merge`. Administration read is sufficient for
568
+ the remaining checks; ruleset write access is required for GitHub to reveal
569
+ bypass actors.
553
570
  The normal workflow `GITHUB_TOKEN` cannot be granted Administration permission
554
571
  through workflow YAML. After correcting access or rules, rerun the failed job.
555
572
  Fork PRs do not receive this secret and fail the policy check; do not expose it
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jakobm/peacekeeper",
3
- "version": "0.21.0",
3
+ "version": "0.22.0",
4
4
  "description": "Shared repository test, Git worktree, and Codex hook commands",
5
5
  "license": "MIT",
6
6
  "author": "Jakob Mattsson",
@@ -2,5 +2,6 @@ export default ({ projectConfig, updateConfig }) => ({
2
2
  projectConfig: projectConfig.projectConfig,
3
3
  repositoryRoot: projectConfig.repositoryRoot,
4
4
  requireTestCommands: projectConfig.requireTestCommands,
5
+ validateConfig: projectConfig.validateConfig,
5
6
  updateConfig: updateConfig.run,
6
7
  });
@@ -11,6 +11,6 @@ allowed-external:
11
11
  configuration: [execFileSync, fs, isDeepStrictEqual, output, path, projectConfigDefaults, runtime]
12
12
  lifecycle: [buffer, clock, executablePath, fs, output, path, runtime, spawn, spawnSync]
13
13
  maintenance: [execFileSync, fs, output, path, runtime, spawnSync]
14
- projects: [fs, isDeepStrictEqual, modulesRoot, output, packageVersion, path, projectConfigDefaults, runtime, semver, spawnSync, TOML, url, YAML]
14
+ projects: [buffer, fs, isDeepStrictEqual, modulesRoot, output, packageVersion, path, projectConfigDefaults, runtime, semver, spawnSync, TOML, url, YAML]
15
15
  releases: [assessReleaseSchema, clock, execFileSync, fs, modulesRoot, os, output, path, runtime, semver, spawnSync, url, YAML]
16
16
  testing: [clock, crypto, execFileSync, fs, modulesRoot, os, output, path, runtime, spawnSync]
@@ -253,11 +253,12 @@ Online release policy and GitHub token setup
253
253
  Enable "Automatically delete head branches" (delete_branch_on_merge=true) in
254
254
  the repository settings. The online release policy commands require it.
255
255
 
256
- Configure the default branch from git.defaultBranch with every exact job name
256
+ Configure the default branch from git.defaultBranch with exactly the job names
257
257
  in git.releaseRequiredChecks mandatory and "Require branches to be up to date
258
258
  before merging" enabled. The base policy may use either classic branch
259
259
  protection with strict status checks or active branch rulesets requiring
260
- strict status checks. Its bypass configuration must be inspected manually.
260
+ strict status checks. Its bypass configuration is compared when GitHub exposes
261
+ it and otherwise must be inspected manually.
261
262
  Merge queues are not currently an alternative to this strict policy. For the
262
263
  matrix example, also require its matrix checks as described above.
263
264
 
@@ -267,8 +268,8 @@ Online release policy and GitHub token setup
267
268
  git.requiredApprover, with actor_type User and bypass_mode pull_request. The
268
269
  configured account must be the personal repository owner. This approval-only
269
270
  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.
271
+ still prevents direct pushes and requires strict CI. Any other visible bypass
272
+ violates the policy; inspect it manually when GitHub omits the actors.
272
273
 
273
274
  Create a fine-grained GitHub PAT or GitHub App installation token with access
274
275
  to this repository and these repository permissions:
@@ -277,7 +278,7 @@ Online release policy and GitHub token setup
277
278
  Pull requests: read
278
279
  Actions: read
279
280
  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
+ Peacekeeper verifies them when exposed and otherwise prints this warning:
281
282
  Cannot verify bypass users unless given write access. Run a manual check
282
283
  instead; available as a gist.
283
284
 
@@ -402,16 +403,17 @@ Default-branch GitHub policy chain
402
403
  This applies to private projects too; configure nonempty releaseRequiredChecks.
403
404
 
404
405
  Online verification reads the actual GitHub default branch and requires PRs,
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
406
+ exactly the configured strict mandatory checks, and merge commits only. It also
407
+ verifies the separate owner-approval ruleset described above. Bypass actors are
408
+ compared when GitHub returns them; otherwise verification warns that they are
409
+ unknown. Enable
408
410
  repository allow_auto_merge; this only offers per-PR opt-in and does not
409
411
  activate auto-merge for any PR.
410
412
  Restrict merge methods either repository-wide (merge enabled, squash and rebase
411
413
  disabled) or with a default-branch PR ruleset allowing only merge. Other branches
412
414
  are not checked. Linear-history rules or PR rules excluding merge are errors.
413
- Base PR requirements, like status checks, require active rules. Inspect all
414
- bypass actors manually.
415
+ Base PR requirements, like status checks, require active rules. Inspect bypass
416
+ actors manually only when GitHub omits them from the response.
415
417
  Existing automatic head-branch deletion requirements still apply.
416
418
 
417
419
  Missing CI is detected on the next local npm test. GitHub settings are checked
@@ -1,5 +1,6 @@
1
- export default ({ installHooks, external: { fs, modulesRoot, packageVersion, path, projectConfigDefaults, runtime, spawnSync, url: Url, } }) => {
1
+ export default ({ installHooks, releases, external: { fs, modulesRoot, packageVersion, path, projectConfigDefaults, runtime, spawnSync, url: Url, } }) => {
2
2
  const { planHooks } = installHooks;
3
+ const { createGithubPolicy, githubSetupPlan } = releases;
3
4
  const TOOLCHAIN = Object.freeze({
4
5
  node: '22.14.0',
5
6
  npm: '11.21.0',
@@ -70,20 +71,37 @@ export default ({ installHooks, external: { fs, modulesRoot, packageVersion, pat
70
71
  }
71
72
  function renderTemplate(filename, replacements) {
72
73
  let template = fs.readFileSync(path.join(modulesRoot, `projects/${filename}`), 'utf8');
74
+ const placeholders = [...template.matchAll(/\{\{([A-Z_]+)\}\}/gu)].map(match => match[1]);
75
+ const unknown = placeholders.find(name => !Object.hasOwn(replacements, name));
76
+ if (unknown)
77
+ throw new Error(`Unknown GitHub setup template placeholder: {{${unknown}}}`);
73
78
  for (const [name, value] of Object.entries(replacements)) {
74
79
  template = template.replaceAll(`{{${name}}}`, value);
75
80
  }
76
- const unresolved = template.match(/\{\{[A-Z_]+\}\}/u);
77
- if (unresolved)
78
- throw new Error(`Unknown GitHub setup template placeholder: ${unresolved[0]}`);
79
81
  return template.trim();
80
82
  }
81
83
  function githubSetup(repositories) {
82
84
  const prefix = renderTemplate('github-setup-prefix.sh', {});
83
- const configured = repositories.map(({ owner, repositoryName }) => renderTemplate('github-setup-repository-template.sh', {
84
- OWNER: shellSingleQuotedContent(owner),
85
- REPOSITORY_NAME: shellSingleQuotedContent(repositoryName),
86
- }));
85
+ const configured = repositories.map(({ owner, repositoryName, requiredChecks, requiredApprover = owner, defaultBranch = 'main' }) => {
86
+ let plan;
87
+ try {
88
+ plan = githubSetupPlan(createGithubPolicy({ branch: defaultBranch,
89
+ checks: requiredChecks, requiredApprover }));
90
+ }
91
+ catch (error) {
92
+ throw new Error(`GitHub setup for ${owner}/${repositoryName}: ${error instanceof Error ? error.message : String(error)}`);
93
+ }
94
+ return renderTemplate('github-setup-repository-template.sh', {
95
+ OWNER: shellSingleQuotedContent(owner),
96
+ REPOSITORY_NAME: shellSingleQuotedContent(repositoryName),
97
+ DEFAULT_BRANCH: shellSingleQuotedContent(plan.branchPath),
98
+ REPOSITORY_PATCH_ARGUMENTS: plan.repositoryPatchArguments,
99
+ BASE_RULESET: plan.baseRuleset,
100
+ APPROVAL_RULESET: plan.approvalRuleset,
101
+ REQUIRED_APPROVER: shellSingleQuotedContent(requiredApprover),
102
+ REQUIRED_APPROVER_LOWER: shellSingleQuotedContent(requiredApprover.toLowerCase()),
103
+ });
104
+ });
87
105
  const argumentsValue = repositories
88
106
  .map(({ owner, repositoryName }) => `--new-repo ${shellLiteral(`${owner}/${repositoryName}`)}`)
89
107
  .join(' ');
@@ -135,7 +153,10 @@ export default ({ installHooks, external: { fs, modulesRoot, packageVersion, pat
135
153
  write(root, '.gitignore', 'node_modules/\n*.tgz\ntmp/\n');
136
154
  write(root, 'README.md', `# ${options.repositoryName}\n\nA TypeScript library generated by Peacekeeper.\n\n## API\n\n\`hello()\` returns \`"hello world"\`.\n`);
137
155
  write(root, 'LICENSE', `MIT License\n\nCopyright (c) ${options.authorName}\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n`);
138
- write(root, 'setup-github-config.sh', githubSetup([options]), 0o755);
156
+ write(root, 'setup-github-config.sh', githubSetup([{
157
+ ...options, requiredChecks: defaults.git.releaseRequiredChecks,
158
+ requiredApprover: defaults.git.requiredApprover, defaultBranch: defaults.git.defaultBranch,
159
+ }]), 0o755);
139
160
  }
140
161
  function createProject(options, dependencies = {}) {
141
162
  const run = dependencies.run || commandRunner;
@@ -1,8 +1,55 @@
1
- export default ({ createProjectCore, external: { runtime } }) => {
1
+ export default ({ configuration, createProjectCore, external: { buffer: Buffer, projectConfigDefaults, runtime, spawnSync, } }) => {
2
+ const { validateConfig } = configuration;
2
3
  const { githubSetup, repositoryIdentity } = createProjectCore;
4
+ function api(endpoint, missingAllowed = false) {
5
+ const response = spawnSync('gh', ['api', '--hostname', 'github.com', '--method', 'GET', endpoint], {
6
+ encoding: 'utf8',
7
+ });
8
+ if (response.status === 0) {
9
+ try {
10
+ return JSON.parse(response.stdout);
11
+ }
12
+ catch {
13
+ throw new Error(`GitHub returned invalid JSON for ${endpoint}.`);
14
+ }
15
+ }
16
+ if (missingAllowed && /HTTP 404\b/u.test(response.stderr || ''))
17
+ return undefined;
18
+ throw new Error(`Cannot read GitHub configuration (${endpoint}): ${response.error?.message
19
+ || response.stderr?.trim() || `exit ${response.status}`}`);
20
+ }
21
+ function loadRepositorySetup(repository) {
22
+ const identity = repositoryIdentity(repository);
23
+ const slug = `${identity.owner}/${identity.repositoryName}`;
24
+ const metadata = api(`repos/${slug}`);
25
+ if (typeof metadata?.default_branch !== 'string' || !metadata.default_branch) {
26
+ throw new Error(`GitHub did not return a default branch for ${slug}.`);
27
+ }
28
+ const endpoint = `repos/${slug}/contents/peacekeeper.config.json?ref=${encodeURIComponent(metadata.default_branch)}`;
29
+ const file = api(endpoint, true);
30
+ let config;
31
+ if (file === undefined) {
32
+ config = structuredClone(projectConfigDefaults);
33
+ }
34
+ else {
35
+ if (file.type !== 'file' || file.encoding !== 'base64' || typeof file.content !== 'string') {
36
+ throw new Error(`${slug}/peacekeeper.config.json: GitHub returned invalid file contents.`);
37
+ }
38
+ try {
39
+ config = JSON.parse(Buffer.from(file.content, 'base64').toString('utf8'));
40
+ }
41
+ catch (error) {
42
+ throw new Error(`${slug}/peacekeeper.config.json: ${error instanceof Error ? error.message : String(error)}`);
43
+ }
44
+ }
45
+ validateConfig(config, `${slug}/peacekeeper.config.json`);
46
+ return { ...identity, requiredChecks: config.git.releaseRequiredChecks,
47
+ requiredApprover: config.git.requiredApprover || identity.owner,
48
+ defaultBranch: metadata.default_branch };
49
+ }
3
50
  function run({ repository: repositories }) {
4
51
  try {
5
- runtime.stdout.write(githubSetup(repositories.map(repositoryIdentity)));
52
+ runtime.stdout.write(githubSetup(repositories.map(loadRepositorySetup)));
6
53
  }
7
54
  catch (error) {
8
55
  runtime.stderr.write(`Error: ${error instanceof Error ? error.message : String(error)}\n`);
@@ -1,12 +1,12 @@
1
1
  # Verify repository access and personal ownership for {{OWNER}}/{{REPOSITORY_NAME}}.
2
2
  gh repo view '{{OWNER}}/{{REPOSITORY_NAME}}' >/dev/null
3
- if [[ "$(gh api 'repos/{{OWNER}}/{{REPOSITORY_NAME}}' --jq .owner.login)" != '{{OWNER}}' ]]; then
4
- printf 'Expected %s/%s to be owned by the personal account %s.\n' '{{OWNER}}' '{{REPOSITORY_NAME}}' '{{OWNER}}' >&2
3
+ if [[ "$(gh api 'repos/{{OWNER}}/{{REPOSITORY_NAME}}' --jq '.owner.login | ascii_downcase')" != '{{REQUIRED_APPROVER_LOWER}}' ]]; then
4
+ printf 'Expected %s/%s to be owned by the personal account %s.\n' '{{OWNER}}' '{{REPOSITORY_NAME}}' '{{REQUIRED_APPROVER}}' >&2
5
5
  exit 1
6
6
  fi
7
7
 
8
8
  # Configure repository-wide branch cleanup, auto-merge, and merge methods.
9
- gh api --method PATCH 'repos/{{OWNER}}/{{REPOSITORY_NAME}}' -F delete_branch_on_merge=true -F allow_auto_merge=true -F allow_merge_commit=true -F allow_squash_merge=false -F allow_rebase_merge=false >/dev/null
9
+ gh api --method PATCH 'repos/{{OWNER}}/{{REPOSITORY_NAME}}' {{REPOSITORY_PATCH_ARGUMENTS}} >/dev/null
10
10
 
11
11
  # Create or update one named ruleset without changing unrelated rulesets.
12
12
  upsert_ruleset() {
@@ -26,65 +26,15 @@ upsert_ruleset() {
26
26
 
27
27
  # Protect the default branch with pull requests, merge commits, and strict CI.
28
28
  upsert_ruleset 'Peacekeeper base protection' <<'JSON'
29
- {
30
- "name": "Peacekeeper base protection",
31
- "target": "branch",
32
- "enforcement": "active",
33
- "bypass_actors": [],
34
- "conditions": { "ref_name": { "include": ["~DEFAULT_BRANCH"], "exclude": [] } },
35
- "rules": [
36
- { "type": "deletion" },
37
- { "type": "non_fast_forward" },
38
- {
39
- "type": "pull_request",
40
- "parameters": {
41
- "required_approving_review_count": 0,
42
- "dismiss_stale_reviews_on_push": false,
43
- "require_code_owner_review": false,
44
- "require_last_push_approval": false,
45
- "required_review_thread_resolution": false,
46
- "allowed_merge_methods": ["merge"]
47
- }
48
- },
49
- {
50
- "type": "required_status_checks",
51
- "parameters": {
52
- "strict_required_status_checks_policy": true,
53
- "do_not_enforce_on_create": false,
54
- "required_status_checks": [{ "context": "test" }]
55
- }
56
- }
57
- ]
58
- }
29
+ {{BASE_RULESET}}
59
30
  JSON
60
31
 
61
32
  # Require fresh code-owner approval while allowing the owner to bypass this rule.
62
33
  upsert_ruleset 'Peacekeeper owner approval' <<JSON
63
- {
64
- "name": "Peacekeeper owner approval",
65
- "target": "branch",
66
- "enforcement": "active",
67
- "bypass_actors": [
68
- { "actor_id": $(gh api 'users/{{OWNER}}' --jq .id), "actor_type": "User", "bypass_mode": "pull_request" }
69
- ],
70
- "conditions": { "ref_name": { "include": ["~DEFAULT_BRANCH"], "exclude": [] } },
71
- "rules": [
72
- {
73
- "type": "pull_request",
74
- "parameters": {
75
- "required_approving_review_count": 1,
76
- "dismiss_stale_reviews_on_push": true,
77
- "require_code_owner_review": true,
78
- "require_last_push_approval": false,
79
- "required_review_thread_resolution": false,
80
- "allowed_merge_methods": ["merge"]
81
- }
82
- }
83
- ]
84
- }
34
+ {{APPROVAL_RULESET}}
85
35
  JSON
86
36
 
87
37
  # Remove legacy branch protection now superseded by the rulesets above.
88
- if gh api 'repos/{{OWNER}}/{{REPOSITORY_NAME}}/branches/main/protection' >/dev/null 2>&1; then
89
- gh api --method DELETE 'repos/{{OWNER}}/{{REPOSITORY_NAME}}/branches/main/protection' >/dev/null
38
+ if gh api 'repos/{{OWNER}}/{{REPOSITORY_NAME}}/branches/{{DEFAULT_BRANCH}}/protection' >/dev/null 2>&1; then
39
+ gh api --method DELETE 'repos/{{OWNER}}/{{REPOSITORY_NAME}}/branches/{{DEFAULT_BRANCH}}/protection' >/dev/null
90
40
  fi
@@ -0,0 +1,46 @@
1
+ {
2
+ "repository": {
3
+ "delete_branch_on_merge": true,
4
+ "allow_auto_merge": true,
5
+ "allow_merge_commit": true,
6
+ "allow_squash_merge": false,
7
+ "allow_rebase_merge": false
8
+ },
9
+ "ruleset": {
10
+ "name": "Peacekeeper base protection",
11
+ "target": "branch",
12
+ "enforcement": "active",
13
+ "bypass_actors": [],
14
+ "conditions": {
15
+ "ref_name": {
16
+ "include": ["~DEFAULT_BRANCH"],
17
+ "exclude": []
18
+ }
19
+ },
20
+ "rules": [
21
+ { "type": "deletion" },
22
+ { "type": "non_fast_forward" },
23
+ {
24
+ "type": "pull_request",
25
+ "parameters": {
26
+ "required_approving_review_count": 0,
27
+ "dismiss_stale_reviews_on_push": false,
28
+ "require_code_owner_review": false,
29
+ "require_last_push_approval": false,
30
+ "required_review_thread_resolution": false,
31
+ "allowed_merge_methods": ["merge"]
32
+ }
33
+ },
34
+ {
35
+ "type": "required_status_checks",
36
+ "parameters": {
37
+ "strict_required_status_checks_policy": true,
38
+ "do_not_enforce_on_create": false,
39
+ "required_status_checks": {
40
+ "$peacekeeper": "releaseRequiredChecks"
41
+ }
42
+ }
43
+ }
44
+ ]
45
+ }
46
+ }
@@ -0,0 +1,35 @@
1
+ {
2
+ "ruleset": {
3
+ "name": "Peacekeeper owner approval",
4
+ "target": "branch",
5
+ "enforcement": "active",
6
+ "conditions": {
7
+ "ref_name": {
8
+ "include": ["~DEFAULT_BRANCH"],
9
+ "exclude": []
10
+ }
11
+ },
12
+ "bypass_actors": [
13
+ {
14
+ "actor_id": {
15
+ "$peacekeeper": "requiredApproverId"
16
+ },
17
+ "actor_type": "User",
18
+ "bypass_mode": "pull_request"
19
+ }
20
+ ],
21
+ "rules": [
22
+ {
23
+ "type": "pull_request",
24
+ "parameters": {
25
+ "required_approving_review_count": 1,
26
+ "dismiss_stale_reviews_on_push": true,
27
+ "require_code_owner_review": true,
28
+ "require_last_push_approval": false,
29
+ "required_review_thread_resolution": false,
30
+ "allowed_merge_methods": ["merge"]
31
+ }
32
+ }
33
+ ]
34
+ }
35
+ }
@@ -0,0 +1,127 @@
1
+ export default ({ external: { fs, modulesRoot, path } }) => {
2
+ const ownerIdMarker = '__PEACEKEEPER_OWNER_ID__';
3
+ const directive = '$peacekeeper';
4
+ function readDocument(filename) {
5
+ const file = path.join(modulesRoot, `releases/${filename}`);
6
+ try {
7
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
8
+ }
9
+ catch (error) {
10
+ throw new Error(`Cannot read bundled GitHub policy ${filename}: ${error instanceof Error ? error.message : String(error)}`);
11
+ }
12
+ }
13
+ const baseDocument = readDocument('github-base-protection-policy.json');
14
+ const approvalDocument = readDocument('github-owner-approval-policy.json');
15
+ function materialize(value, variables, filename) {
16
+ if (Array.isArray(value))
17
+ return value.map(item => materialize(item, variables, filename));
18
+ if (!value || typeof value !== 'object')
19
+ return value;
20
+ if (Object.hasOwn(value, directive)) {
21
+ if (Object.keys(value).length !== 1 || typeof value[directive] !== 'string'
22
+ || !Object.hasOwn(variables, value[directive])) {
23
+ throw new Error(`${filename}: invalid Peacekeeper policy directive`);
24
+ }
25
+ return structuredClone(variables[value[directive]]);
26
+ }
27
+ return Object.fromEntries(Object.entries(value)
28
+ .map(([key, item]) => [key, materialize(item, variables, filename)]));
29
+ }
30
+ function policyDocument(document, filename, variables) {
31
+ const policy = materialize(document, variables, filename);
32
+ if (!policy.ruleset || typeof policy.ruleset !== 'object' || !Array.isArray(policy.ruleset.rules)) {
33
+ throw new Error(`${filename}: bundled GitHub policy must contain a ruleset with rules`);
34
+ }
35
+ return policy;
36
+ }
37
+ function uniqueChecks(checks) {
38
+ return Array.isArray(checks) && checks.length > 0
39
+ && checks.every(check => typeof check === 'string' && check.trim() === check && check.length > 0)
40
+ && new Set(checks).size === checks.length;
41
+ }
42
+ function createGithubPolicy({ branch = 'main', checks, requiredApprover }) {
43
+ if (!uniqueChecks(checks))
44
+ throw new Error('GitHub policy requires unique nonempty status check names.');
45
+ if (typeof requiredApprover !== 'string' || !requiredApprover.trim()) {
46
+ throw new Error('A required GitHub approver must be provided.');
47
+ }
48
+ if (typeof branch !== 'string' || !branch)
49
+ throw new Error('GitHub policy requires a default branch.');
50
+ const base = policyDocument(baseDocument, 'github-base-protection-policy.json', {
51
+ releaseRequiredChecks: checks.map(context => ({ context })),
52
+ });
53
+ const ownerApproval = policyDocument(approvalDocument, 'github-owner-approval-policy.json', {
54
+ requiredApproverId: ownerIdMarker,
55
+ });
56
+ if (!base.repository || typeof base.repository !== 'object') {
57
+ throw new Error('github-base-protection-policy.json: bundled GitHub policy must contain repository settings');
58
+ }
59
+ return {
60
+ branch,
61
+ checks: [...checks],
62
+ requiredApprover,
63
+ repository: base.repository,
64
+ baseRuleset: base.ruleset,
65
+ approvalRuleset: ownerApproval.ruleset,
66
+ };
67
+ }
68
+ function setupPlan(policy) {
69
+ return {
70
+ branch: policy.branch,
71
+ branchPath: encodeURIComponent(policy.branch),
72
+ repositoryPatchArguments: Object.entries(policy.repository)
73
+ .map(([name, value]) => `-F ${name}=${value}`).join(' '),
74
+ baseRuleset: JSON.stringify(policy.baseRuleset, null, 2),
75
+ approvalRuleset: JSON.stringify(policy.approvalRuleset, null, 2)
76
+ .replace(JSON.stringify(ownerIdMarker), "$(gh api 'users/{{REQUIRED_APPROVER}}' --jq .id)"),
77
+ };
78
+ }
79
+ function sameMembers(actual, expected) {
80
+ return actual.length === expected.length
81
+ && actual.every(value => expected.includes(value));
82
+ }
83
+ function approvalParameters(policy, parameters) {
84
+ const expected = policy.approvalRuleset.rules[0].parameters;
85
+ return parameters?.required_approving_review_count === expected.required_approving_review_count
86
+ && parameters.dismiss_stale_reviews_on_push === expected.dismiss_stale_reviews_on_push
87
+ && parameters.require_code_owner_review === expected.require_code_owner_review;
88
+ }
89
+ function requiredCheckContexts(policy) {
90
+ return policy.baseRuleset.rules
91
+ .find(rule => rule.type === 'required_status_checks').parameters.required_status_checks
92
+ .map(check => check.context);
93
+ }
94
+ function managedRulesetMatches(policy, actual) {
95
+ const expected = [policy.baseRuleset, policy.approvalRuleset]
96
+ .find(ruleset => ruleset.name === actual?.name);
97
+ if (!expected)
98
+ return true;
99
+ function matchesShape(wanted, observed) {
100
+ if (Array.isArray(wanted))
101
+ return Array.isArray(observed)
102
+ && wanted.length === observed.length
103
+ && (() => {
104
+ const unmatched = [...observed];
105
+ return wanted.every(value => {
106
+ const index = unmatched.findIndex(candidate => matchesShape(value, candidate));
107
+ if (index < 0)
108
+ return false;
109
+ unmatched.splice(index, 1);
110
+ return true;
111
+ });
112
+ })();
113
+ if (wanted && typeof wanted === 'object')
114
+ return observed && typeof observed === 'object'
115
+ && Object.entries(wanted).every(([key, value]) => matchesShape(value, observed[key]));
116
+ return wanted === observed;
117
+ }
118
+ const withoutBypass = ruleset => {
119
+ const { bypass_actors: _bypass, ...rest } = ruleset;
120
+ return rest;
121
+ };
122
+ return matchesShape(withoutBypass(expected), actual);
123
+ }
124
+ const api = { approvalParameters, createGithubPolicy, managedRulesetMatches,
125
+ requiredCheckContexts, sameMembers, setupPlan };
126
+ return api;
127
+ };
@@ -1,6 +1,8 @@
1
- export default ({ assessRelease, release, releaseCore, verifyRelease, verifyReleaseProtection, verifyReleaseVersion }) => ({
1
+ export default ({ assessRelease, githubPolicy, release, releaseCore, verifyRelease, verifyReleaseProtection, verifyReleaseVersion }) => ({
2
2
  assessRelease: assessRelease.run,
3
+ createGithubPolicy: githubPolicy.createGithubPolicy,
3
4
  ensureLockfilesMatch: releaseCore.ensureLockfilesMatch,
5
+ githubSetupPlan: githubPolicy.setupPlan,
4
6
  inspectWorkflow: releaseCore.inspectWorkflow,
5
7
  release: release.run,
6
8
  verifyRelease: verifyRelease.run,
@@ -1,4 +1,5 @@
1
- export default ({ configuration }) => {
1
+ export default ({ configuration, githubPolicy }) => {
2
+ const { approvalParameters, createGithubPolicy, managedRulesetMatches, requiredCheckContexts, sameMembers } = githubPolicy;
2
3
  function requiredPolicy(cwd) {
3
4
  const { projectConfig } = configuration;
4
5
  const config = projectConfig(cwd).git;
@@ -10,32 +11,24 @@ export default ({ configuration }) => {
10
11
  }
11
12
  return { checks: config.releaseRequiredChecks, requiredApprover: config.requiredApprover };
12
13
  }
13
- function approvalParameters(parameters) {
14
- return parameters?.required_approving_review_count === 1
15
- && parameters.dismiss_stale_reviews_on_push === true
16
- && parameters.require_code_owner_review === true;
17
- }
18
14
  const bypassWarning = 'Cannot verify bypass users unless given write access. Run a manual check instead; available as a gist.';
19
15
  // A missing classic protection is expected for ruleset-only repositories. All
20
16
  // other API failures, including permission failures, must propagate.
21
17
  function verifyProtection({ api, slug, branch, checks, requiredApprover: approver, warn }) {
22
- if (warn)
23
- warn(bypassWarning);
24
- if (!approver)
25
- throw new Error('A required GitHub approver must be provided.');
18
+ const policy = createGithubPolicy({ branch, checks, requiredApprover: approver });
26
19
  const base = `repos/${slug}`;
27
20
  const repository = api(base);
28
- if (repository?.delete_branch_on_merge !== true) {
21
+ if (repository?.delete_branch_on_merge !== policy.repository.delete_branch_on_merge) {
29
22
  throw new Error(`Repository ${slug} must enable delete_branch_on_merge. Run gh api --method PATCH ${base} -F delete_branch_on_merge=true, then rerun.`);
30
23
  }
31
- if (repository.allow_auto_merge !== true)
24
+ if (repository.allow_auto_merge !== policy.repository.allow_auto_merge)
32
25
  throw new Error('Repository must enable allow_auto_merge; this only makes auto-merge available per PR.');
33
26
  if (repository.default_branch !== branch)
34
27
  throw new Error(`Verify the actual default branch (${repository.default_branch}), not ${branch}.`);
35
28
  if (repository.owner?.type !== 'User'
36
- || repository.owner.login?.toLowerCase() !== approver.toLowerCase()
29
+ || repository.owner.login?.toLowerCase() !== policy.requiredApprover.toLowerCase()
37
30
  || !Number.isInteger(repository.owner.id)) {
38
- throw new Error(`git.requiredApprover (${approver}) must be the personal owner of repository ${slug}.`);
31
+ throw new Error(`git.requiredApprover (${policy.requiredApprover}) must be the personal owner of repository ${slug}.`);
39
32
  }
40
33
  let protection;
41
34
  try {
@@ -57,6 +50,20 @@ export default ({ configuration }) => {
57
50
  if (protection?.required_linear_history?.enabled || rules.some(rule => rule.type === 'required_linear_history')) {
58
51
  throw new Error('Default branch must allow merge commits; disable required linear history.');
59
52
  }
53
+ if (protection) {
54
+ if (protection.allow_deletions?.enabled === true)
55
+ throw new Error('Default branch must prevent deletion.');
56
+ if (protection.allow_force_pushes?.enabled === true)
57
+ throw new Error('Default branch must prevent force pushes.');
58
+ if (protection.enforce_admins?.enabled !== true)
59
+ throw new Error('Classic branch protection must include administrators.');
60
+ }
61
+ else {
62
+ if (!rules.some(rule => rule.type === 'deletion'))
63
+ throw new Error('Default branch rulesets must prevent deletion.');
64
+ if (!rules.some(rule => rule.type === 'non_fast_forward'))
65
+ throw new Error('Default branch rulesets must prevent force pushes.');
66
+ }
60
67
  const rulesets = new Map();
61
68
  function rulesetFor(rule) {
62
69
  if (!Number.isInteger(rule.ruleset_id))
@@ -68,26 +75,39 @@ export default ({ configuration }) => {
68
75
  if (!Array.isArray(ruleset.rules)) {
69
76
  throw new Error('Cannot verify all rules in a policy ruleset; grant access to the complete ruleset, then rerun.');
70
77
  }
78
+ if (!managedRulesetMatches(policy, ruleset)) {
79
+ throw new Error(`Managed ruleset ${ruleset.name} differs from Peacekeeper's generated policy. Regenerate and run the GitHub setup script.`);
80
+ }
71
81
  rulesets.set(rule.ruleset_id, ruleset);
72
82
  }
73
83
  return rulesets.get(rule.ruleset_id);
74
84
  }
75
85
  for (const rule of rules.filter(rule => Number.isInteger(rule.ruleset_id)))
76
86
  rulesetFor(rule);
87
+ for (const name of [policy.baseRuleset.name, policy.approvalRuleset.name]) {
88
+ if ([...rulesets.values()].filter(ruleset => ruleset.name === name).length > 1) {
89
+ throw new Error(`Default branch has multiple managed rulesets named ${name}. Remove duplicates, then rerun.`);
90
+ }
91
+ }
77
92
  const approvalRulesets = new Set();
78
93
  for (const [id, ruleset] of rulesets) {
79
94
  if (ruleset.rules.length === 1 && ruleset.rules[0].type === 'pull_request'
80
- && approvalParameters(ruleset.rules[0].parameters))
95
+ && approvalParameters(policy, ruleset.rules[0].parameters))
81
96
  approvalRulesets.add(id);
82
97
  }
83
98
  const classicReviews = protection?.required_pull_request_reviews;
99
+ const classicBypasses = classicReviews?.bypass_pull_request_allowances;
100
+ if (classicBypasses && ['users', 'teams', 'apps']
101
+ .some(kind => Array.isArray(classicBypasses[kind]) && classicBypasses[kind].length > 0)) {
102
+ throw new Error('Classic branch protection must not allow pull-request bypass actors.');
103
+ }
84
104
  let requiresPullRequest = Boolean(classicReviews);
85
105
  let branchMergeOnly = false;
86
106
  let approvalPolicyCount = 0;
87
107
  for (const rule of rules.filter(rule => rule.type === 'pull_request')) {
88
108
  const ruleset = rulesetFor(rule);
89
109
  if (approvalRulesets.has(rule.ruleset_id)) {
90
- if (!approvalParameters(rule.parameters)) {
110
+ if (!approvalParameters(policy, rule.parameters)) {
91
111
  throw new Error('The effective owner approval rule must require one code-owner approval and dismiss stale approvals.');
92
112
  }
93
113
  approvalPolicyCount += 1;
@@ -105,6 +125,27 @@ export default ({ configuration }) => {
105
125
  if (approvalPolicyCount !== 1 || approvalRulesets.size !== 1) {
106
126
  throw new Error('Default branch must have exactly one owner approval ruleset requiring one code-owner approval and stale approval dismissal.');
107
127
  }
128
+ let bypassUnknown = Boolean(protection);
129
+ for (const [id, ruleset] of rulesets) {
130
+ const protectsRelease = approvalRulesets.has(id)
131
+ || ruleset.rules.some(rule => ['pull_request', 'required_status_checks'].includes(rule.type || ''));
132
+ if (!protectsRelease)
133
+ continue;
134
+ if (!Array.isArray(ruleset.bypass_actors)) {
135
+ bypassUnknown = true;
136
+ continue;
137
+ }
138
+ const expected = approvalRulesets.has(id)
139
+ ? [{ actor_id: repository.owner.id, actor_type: 'User', bypass_mode: 'pull_request' }]
140
+ : [];
141
+ const actual = ruleset.bypass_actors.map(actor => ({ actor_id: actor.actor_id,
142
+ actor_type: actor.actor_type, bypass_mode: actor.bypass_mode }));
143
+ if (JSON.stringify(actual) !== JSON.stringify(expected)) {
144
+ throw new Error('Ruleset bypass actors do not match the generated Peacekeeper policy.');
145
+ }
146
+ }
147
+ if (bypassUnknown && warn)
148
+ warn(bypassWarning);
108
149
  const strictChecks = new Set();
109
150
  const classic = protection?.required_status_checks;
110
151
  if (classic?.strict === true) {
@@ -120,14 +161,20 @@ export default ({ configuration }) => {
120
161
  for (const check of rule.parameters.required_status_checks || [])
121
162
  strictChecks.add(check.context);
122
163
  }
123
- const missing = checks.filter(check => !strictChecks.has(check));
124
- if (!checks.length || missing.length) {
125
- throw new Error(`Branch ${branch} must require strict status checks for: ${missing.join(', ') || '(no checks configured)'}. Enable strict checks, then rerun.`);
164
+ const expectedChecks = requiredCheckContexts(policy);
165
+ const actualChecks = [...strictChecks];
166
+ const missing = expectedChecks.filter(check => !strictChecks.has(check));
167
+ const extra = actualChecks.filter(check => !expectedChecks.includes(check));
168
+ if (!sameMembers(actualChecks, expectedChecks)) {
169
+ const detail = [missing.length ? `missing: ${missing.join(', ')}` : '',
170
+ extra.length ? `extra: ${extra.join(', ')}` : ''].filter(Boolean).join('; ');
171
+ throw new Error(`Branch ${branch} must require exactly these strict status checks: ${expectedChecks.join(', ')}${detail ? ` (${detail})` : ''}. Enable strict checks, then rerun.`);
126
172
  }
127
173
  if (!requiresPullRequest)
128
174
  throw new Error('Default branch must require pull requests.');
129
- if (repository.allow_merge_commit !== true || (!branchMergeOnly
130
- && (repository.allow_squash_merge !== false || repository.allow_rebase_merge !== false))) {
175
+ if (repository.allow_merge_commit !== policy.repository.allow_merge_commit || (!branchMergeOnly
176
+ && (repository.allow_squash_merge !== policy.repository.allow_squash_merge
177
+ || repository.allow_rebase_merge !== policy.repository.allow_rebase_merge))) {
131
178
  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.');
132
179
  }
133
180
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jakobm/peacekeeper",
3
- "version": "0.21.0",
3
+ "version": "0.22.0",
4
4
  "description": "Shared repository test, Git worktree, and Codex hook commands",
5
5
  "license": "MIT",
6
6
  "author": "Jakob Mattsson",