external-pr-scope.js 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  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. module.exports = { normalizeRepo, liveReposOf, analyze, readPlugins, evaluate, MARKETPLACE };