external-pr-scope.js 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. 'use strict';
  2. // Shared logic for letting a NON-MEMBER pull request stay open and be reviewed, scoped to
  3. // the contributor's own already-listed plugin repo. No maintained allowlist, no individuals.
  4. //
  5. // Trust model: we do NOT verify the submitter's identity. We trust the SOURCE REPO. A PR is
  6. // in scope only if it ADDS marketplace.json entries whose source.url is a repo that ALREADY
  7. // backs a live entry in this marketplace (derived from the base marketplace.json), pinned to
  8. // a commit in that repo. Because the repo is org-controlled and the SHA pins to a real commit
  9. // there, the shipped code is the org's code regardless of who opened the PR. Merge still
  10. // requires CI + a maintainer approval.
  11. //
  12. // Used by:
  13. // - close-external-prs.yml (skip the auto-close when in scope)
  14. // - external-pr-scope-guard.yml (required status check: fail a non-member PR that is out of scope)
  15. //
  16. // Security: evaluate() reads base + head marketplace.json as DATA via the API and parses them;
  17. // it never checks out or executes head code.
  18. const MARKETPLACE = '.claude-plugin/marketplace.json';
  19. function normalizeRepo(u) {
  20. return String(u || '').trim().toLowerCase()
  21. .replace(/^git\+/, '')
  22. .replace(/^https?:\/\//, '')
  23. .replace(/\.git$/, '')
  24. .replace(/\/+$/, '');
  25. }
  26. function pluginsByName(json) {
  27. const map = {};
  28. for (const p of (json && json.plugins) || []) { if (p && p.name) map[p.name] = p; }
  29. return map;
  30. }
  31. // Repos that already back a live entry, derived from the base marketplace.json.
  32. function liveReposOf(base) {
  33. const s = new Set();
  34. for (const name of Object.keys(base)) {
  35. const u = base[name] && base[name].source && base[name].source.url;
  36. if (!u) continue;
  37. const r = normalizeRepo(u);
  38. if (r.split('/').length >= 3) s.add(r); // host/org/repo
  39. }
  40. return s;
  41. }
  42. // Pure decision over an already-computed diff. Returns { ok, problems, added, removed, modified }.
  43. // before = plugins at the MERGE-BASE (what head forked from), after = plugins at HEAD,
  44. // liveRepos = repos already live on the current base branch. Diffing before->after (not
  45. // base-tip->head) isolates THIS PR's changes; a stale fork no longer shows main's later
  46. // additions as phantom removals.
  47. function analyze({ changedFiles, before, after, liveRepos }) {
  48. const problems = [];
  49. const off = changedFiles.filter(n => n !== MARKETPLACE);
  50. if (off.length) problems.push(`changes files other than ${MARKETPLACE}: ${off.join(', ')}`);
  51. const baseNames = new Set(Object.keys(before));
  52. const headNames = new Set(Object.keys(after));
  53. const removed = [...baseNames].filter(n => !headNames.has(n));
  54. const added = [...headNames].filter(n => !baseNames.has(n));
  55. const modified = [...headNames].filter(
  56. n => baseNames.has(n) && JSON.stringify(before[n]) !== JSON.stringify(after[n])
  57. );
  58. if (removed.length) problems.push(`removes existing entr${removed.length > 1 ? 'ies' : 'y'}: ${removed.join(', ')}`);
  59. if (modified.length) problems.push(`modifies existing entr${modified.length > 1 ? 'ies' : 'y'}: ${modified.join(', ')}`);
  60. if (!off.length && !added.length && !removed.length && !modified.length) {
  61. problems.push('makes no in-scope change (expected additions to marketplace.json)');
  62. }
  63. for (const name of added) {
  64. const u = after[name] && after[name].source && after[name].source.url;
  65. if (!u) { problems.push(`added "${name}" has no source.url to validate`); continue; }
  66. const r = normalizeRepo(u);
  67. if (r.split('/').length < 3) { problems.push(`added "${name}" source.url ${u} is not a valid repo URL`); continue; }
  68. if (!liveRepos.has(r)) {
  69. problems.push(`added "${name}" points at ${u}, a repo with no existing live plugin in this marketplace`);
  70. }
  71. }
  72. return { ok: problems.length === 0, problems, added, removed, modified, liveRepoCount: liveRepos.size };
  73. }
  74. async function readPlugins(github, owner, repo, ref) {
  75. try {
  76. const { data } = await github.rest.repos.getContent({ owner, repo, ref, path: MARKETPLACE });
  77. return pluginsByName(JSON.parse(Buffer.from(data.content, 'base64').toString('utf8')));
  78. } catch (e) {
  79. return null;
  80. }
  81. }
  82. // API wrapper used by both workflows. Fetches the diff + base/head marketplace.json, delegates to analyze().
  83. async function evaluate({ github, context }) {
  84. const pr = context.payload.pull_request;
  85. const owner = context.repo.owner, repo = context.repo.repo;
  86. const files = await github.paginate(github.rest.pulls.listFiles, {
  87. owner, repo, pull_number: pr.number, per_page: 100,
  88. });
  89. const changedFiles = files.map(f => f.filename);
  90. // Diff THIS PR's changes (merge-base -> head), not base-tip -> head, so a fork that is
  91. // behind main doesn't show main's later additions as phantom removals.
  92. let mergeBaseSha = pr.base.sha;
  93. try {
  94. const cmp = await github.rest.repos.compareCommits({ owner, repo, base: pr.base.sha, head: pr.head.sha });
  95. if (cmp && cmp.data && cmp.data.merge_base_commit && cmp.data.merge_base_commit.sha) {
  96. mergeBaseSha = cmp.data.merge_base_commit.sha;
  97. }
  98. } catch (e) { /* fall back to base.sha */ }
  99. const liveBase = await readPlugins(github, owner, repo, pr.base.sha); // current base branch (for "already live")
  100. const before = await readPlugins(github, owner, repo, mergeBaseSha); // what head forked from
  101. const after = await readPlugins(github, pr.head.repo.owner.login, pr.head.repo.name, pr.head.sha);
  102. if (liveBase === null || before === null || after === null) {
  103. return { ok: false, problems: ['could not read marketplace.json at base, merge-base, and/or head'], added: [], removed: [], modified: [] };
  104. }
  105. return analyze({ changedFiles, before, after, liveRepos: liveReposOf(liveBase) });
  106. }
  107. // Authors that are NOT subject to the external-contributor scope rules:
  108. // - the repo's own automation bot — its bump PRs legitimately MODIFY existing entries
  109. // (SHA bumps), which the additions-only external-contributor rule forbids; AND
  110. // - org members (write/admin).
  111. // Safe under pull_request_target: a fork PR cannot set its author to github-actions[bot]
  112. // (that login is only ever the org's own GITHUB_TOKEN workflow), and the member path is a
  113. // real permission lookup. Wrapped in try/catch because getCollaboratorPermissionLevel throws
  114. // for a non-collaborator/unknown user — without this, both callers would error the job rather
  115. // than fall through to scope evaluation.
  116. const EXEMPT_BOTS = new Set(['github-actions[bot]']);
  117. async function isExemptAuthor({ github, context }) {
  118. const author = context.payload.pull_request.user.login;
  119. if (EXEMPT_BOTS.has(author)) {
  120. return { exempt: true, reason: `${author} is the trusted automation bot` };
  121. }
  122. try {
  123. const { data } = await github.rest.repos.getCollaboratorPermissionLevel({
  124. owner: context.repo.owner, repo: context.repo.repo, username: author,
  125. });
  126. if (['admin', 'write'].includes(data.permission)) {
  127. return { exempt: true, reason: `${author} is ${data.permission} (member)` };
  128. }
  129. } catch (e) {
  130. // not a collaborator / lookup failed → not exempt; fall through to scope evaluation
  131. }
  132. return { exempt: false };
  133. }
  134. module.exports = { normalizeRepo, liveReposOf, analyze, readPlugins, evaluate, isExemptAuthor, MARKETPLACE };