Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 29 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,15 @@ small set of /vouch commands from maintainers to manage the allowlist.
## How it works

Each run sweeps the repository: it fetches the allowlist and blocklist,
enumerates all open pull requests through the API, and comments on and closes
every one whose author is neither on the list nor has write (or admin, or
enumerates open pull requests opened within the last 24 hours, and comments
on and closes every one whose author is neither on the list nor has write (or admin, or
maintain) access to the repository. Write access is checked with the
[collaborator permission
API](https://docs.github.com/en/rest/collaborators/collaborators#get-repository-permissions-for-a-user),
which reflects grants from teams and organization base permissions, so
maintainers never need to be listed.
maintainers never need to be listed. Pull requests older than 24 hours are
never closed, so enabling the action (or revoking/blocking someone) does not
close long-standing PRs.

An optional blocklist, in the same repository as the allowlist, names
accounts that are unwelcome to contribute. Their PRs are closed with a
Expand All @@ -40,8 +42,8 @@ commenting on a pull request:
| Comment | Effect |
|-----------------------------------------|--------|
| `/vouch allow` or just `/vouch` | Add the PR author to the allowlist, and reopen the PR if it was closed before the comment. |
| `/vouch revoke` | Remove the PR author from the allowlist. The next sweep closes their open PRs. |
| `/vouch block` | Add the PR author to the blocklist (requires `blocklist-path`). The next sweep closes their open PRs with `blocked-message`. |
| `/vouch revoke` | Remove the PR author from the allowlist. The next sweep closes their open PRs opened in the last 24 hours. |
| `/vouch block` | Add the PR author to the blocklist (requires `blocklist-path`). The next sweep closes their open PRs opened in the last 24 hours with `blocked-message`. |

Revoking means the author needs a new vouch; blocking is a stronger judgment
that the account is unwelcome. There is no command to unblock: maintainers
Expand Down Expand Up @@ -97,12 +99,33 @@ into `.github/workflows/`.
| `allowlist-path` | yes | Path to the allowlist within `permissions-repo`. |
| `blocklist-path` | no | Path to the blocklist within `permissions-repo`. The blocklist is off when empty. |
| `vouch-team` | no | `org/team-slug` whose members can `/vouch`. Vouching is off when empty. |
| `message` | yes | Comment posted before closing. `{author}` is replaced with the PR author's login. |
| `message` | yes | Comment posted before closing. `{author}` is replaced with the PR author's login. Hard-wrapped lines in a paragraph are joined, so wrap freely and separate paragraphs with a blank line. |
| `blocked-message` | if `blocklist-path` | Comment posted before closing a blocked author's PR. `{author}` is substituted as in `message`. |
| `token` | no | Token used to list, comment on, and close PRs. Defaults to `github.token`. |
| `dry-run` | no | `true` to change nothing (no comments, closes, reopens, or list commits) and only print the audit log of what would be done. Defaults to `false`. |

Output `closed` is a JSON array of the PR numbers closed by this run.

Each run ends its log with an audit log of every write it made, one line per
action, printed even if the run fails partway:

```text
Audit log: 4 action(s) taken.
2026-11-20T10:00:01.123Z commit file=org/gov:approved.txt sha=3f9c... pr=https://github.com/org/proj/pull/7 message="allow newbie by maint"
2026-11-20T10:00:01.456Z reopen pr=https://github.com/org/proj/pull/7 via=https://github.com/org/proj/pull/7#issuecomment-1
2026-11-20T10:00:02.789Z comment pr=https://github.com/org/proj/pull/9 author=mallory url=https://github.com/org/proj/pull/9#issuecomment-2
2026-11-20T10:00:03.012Z close pr=https://github.com/org/proj/pull/9 author=mallory reason=not-approved
```

`reason` is `not-approved` or `blocked`. For a `commit`, `pr` is the PR
carrying the `/vouch` comment.

With `dry-run: true`, the header reads `Audit log (dry run): N action(s)
would be taken.` and entries omit `sha` and the comment `url`, which only
exist once the write is made. Within a dry run, list changes from vouches
are applied in memory, so the PRs it reports it would close are those a
real run would close. The `closed` output is always `[]`.

If the allowlist cannot be fetched or is empty, or `blocklist-path` is set
but cannot be fetched, the action fails rather than closing anything. An
empty blocklist is fine.
Expand Down
10 changes: 9 additions & 1 deletion action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@ inputs:
message:
description: >
Comment posted on each pull request before closing it. "{author}" is
replaced with the PR author's login.
replaced with the PR author's login. Hard-wrapped lines within a
paragraph are joined; separate paragraphs with a blank line.
required: true
blocked-message:
description: >
Expand All @@ -63,6 +64,13 @@ inputs:
required: false
default: ${{ github.token }}

dry-run:
description: >
When "true", make no changes to pull requests, the allowlist, or the
blocklist; only print the audit log of actions a real run would take.
required: false
default: "false"

outputs:
closed:
description: JSON array of the pull request numbers that were closed.
Expand Down
24 changes: 23 additions & 1 deletion src/lib.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,30 @@ export function isApproved(logins, author) {
return logins.has(author.toLowerCase());
}

// Lines that must keep their own line: blank, indented (code), lists,
// headings, quotes, tables, fences, and rules.
const STANDALONE = /^(\s*$|\s|[-*+>#|]|\d+[.)]\s|```|~~~)/;

// GitHub renders every newline in a comment as a line break, so lines
// hard-wrapped in YAML are joined back into flowing paragraphs.
export function unwrap(text) {
const out = [];
let fenced = false;
for (const line of text.replace(/\r\n/g, "\n").split("\n")) {
const fence = /^(```|~~~)/.test(line);
const prev = out.length ? out[out.length - 1] : null;
if (!fenced && !fence && prev !== null && !STANDALONE.test(prev) && !STANDALONE.test(line)) {
out[out.length - 1] = `${prev} ${line.trim()}`;
} else {
out.push(line);
}
if (fence) fenced = !fenced;
}
return out.join("\n");
}

export function renderMessage(template, author) {
return template.replaceAll("{author}", author);
return unwrap(template).replaceAll("{author}", author);
}

export function appendLogin(text, login) {
Expand Down
125 changes: 103 additions & 22 deletions src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ import {
// skipped scheduled runs don't miss any.
const VOUCH_LOOKBACK_MS = 24 * 60 * 60 * 1000;

// Only PRs opened this recently are closed; older ones are left alone.
const CLOSE_MAX_AGE_MS = 24 * 60 * 60 * 1000;

function input(name, { required = false } = {}) {
const value = (process.env[`INPUT_${name.toUpperCase()}`] ?? "").trim();
if (required && !value) throw new Error(`Input required and not supplied: ${name}`);
Expand All @@ -27,6 +30,24 @@ function setOutput(name, value) {
}
}

// Records a write the run made, for the audit log printed at exit.
function audit(ctx, action, details) {
ctx.audit.push({ time: new Date().toISOString(), action, ...details });
}

function printAudit(ctx) {
const entries = ctx.audit;
console.log(
ctx.dryRun
? `Audit log (dry run): ${entries.length} action(s) would be taken.`
: `Audit log: ${entries.length} action(s) taken.`,
);
for (const { time, action, ...details } of entries) {
const fields = Object.entries(details).map(([k, v]) => `${k}=${v}`);
console.log(` ${time} ${action} ${fields.join(" ")}`);
}
}

async function github(token, url, { method = "GET", body, allow404 = false } = {}) {
const res = await fetch(url, {
method,
Expand Down Expand Up @@ -78,29 +99,46 @@ async function readList(ctx, path) {
return { path, text, sha: file.sha, logins: parseList(text) };
}

async function writeList(ctx, list, text, message) {
const res = await github(ctx.permsToken, contentsUrl(ctx.apiUrl, ctx.permsRepo, list.path), {
method: "PUT",
body: {
message,
content: Buffer.from(text).toString("base64"),
sha: list.sha,
...(ctx.permsRef && { branch: ctx.permsRef }),
},
});
function prUrl(ctx, number) {
return `${ctx.serverUrl}/${ctx.repo}/pull/${number}`;
}

// In dry-run, only the in-memory list changes, so later decisions in the
// run match what a real run would do.
async function writeList(ctx, list, text, message, pr) {
if (!ctx.dryRun) {
const res = await github(ctx.permsToken, contentsUrl(ctx.apiUrl, ctx.permsRepo, list.path), {
method: "PUT",
body: {
message,
content: Buffer.from(text).toString("base64"),
sha: list.sha,
...(ctx.permsRef && { branch: ctx.permsRef }),
},
});
list.sha = (await res.json()).content.sha;
}
list.text = text;
list.sha = (await res.json()).content.sha;
list.logins = parseList(text);
audit(ctx, "commit", {
file: `${ctx.permsRepo}:${list.path}`,
...(!ctx.dryRun && { sha: list.sha }),
pr: prUrl(ctx, pr),
message: JSON.stringify(message.split("\n")[0]),
});
}


async function reopen(ctx, number) {
console.log(`Reopening #${number}.`);
async function reopen(ctx, number, via) {
console.log(`${ctx.dryRun ? "Would reopen" : "Reopening"} #${number}.`);
try {
await github(ctx.token, `${ctx.repoUrl}/pulls/${number}`, {
method: "PATCH",
body: { state: "open" },
});
if (!ctx.dryRun) {
await github(ctx.token, `${ctx.repoUrl}/pulls/${number}`, {
method: "PATCH",
body: { state: "open" },
});
}
audit(ctx, "reopen", { pr: prUrl(ctx, number), via });
} catch (err) {
// e.g. the head branch was deleted; don't let one PR block the sweep.
console.log(`::warning::Could not reopen #${number}: ${err.message}`);
Expand Down Expand Up @@ -188,6 +226,7 @@ async function processVouches(ctx, allow, block) {
block,
appendLogin(block.text, author),
`block ${author} by ${blockVouch.c.user.login}\n\nVia: ${blockVouch.c.html_url}`,
blockVouch.pr.number,
);
}
if (!last) continue;
Expand All @@ -204,6 +243,7 @@ async function processVouches(ctx, allow, block) {
allow,
removeLogin(allow.text, author),
`revoke ${author} by ${last.c.user.login}\n\nVia: ${last.c.html_url}`,
last.pr.number,
);
continue;
}
Expand All @@ -214,14 +254,15 @@ async function processVouches(ctx, allow, block) {
allow,
appendLogin(allow.text, author),
`allow ${author} by ${last.c.user.login}\n\nVia: ${last.c.html_url}`,
last.pr.number,
);
}
const reopened = new Set();
for (const { c, pr } of allows) {
if (reopened.has(pr.number)) continue;
if (pr.state === "closed" && !pr.merged && Date.parse(pr.closed_at) < Date.parse(c.created_at)) {
reopened.add(pr.number);
await reopen(ctx, pr.number);
await reopen(ctx, pr.number, c.html_url);
}
}
}
Expand All @@ -231,23 +272,44 @@ async function processVouches(ctx, allow, block) {
async function closeUnapproved(ctx, allow, block) {
const writers = new Map();
const closed = [];
for (const pr of await paginate(ctx.token, `${ctx.repoUrl}/pulls?state=open&per_page=100`)) {
const cutoff = Date.now() - CLOSE_MAX_AGE_MS;
let url = `${ctx.repoUrl}/pulls?state=open&sort=created&direction=desc&per_page=100`;
const recent = [];
while (url) {
const res = await github(ctx.token, url);
const page = await res.json();
const fresh = page.filter((pr) => Date.parse(pr.created_at) >= cutoff);
recent.push(...fresh);
// Newest first, so a page with any old PR is the last one we need.
url = fresh.length === page.length ? nextLink(res.headers.get("link")) : null;
}
for (const pr of recent) {
const author = pr.user.login;
const blocked = block !== null && isApproved(block.logins, author);
if (!blocked && isApproved(allow.logins, author)) continue;
if (!writers.has(author)) writers.set(author, await hasWriteAccess(ctx, author));
if (writers.get(author)) continue;
console.log(
`Closing #${pr.number}: ${author} is ${blocked ? "blocked" : "not an approved contributor"}.`,
`${ctx.dryRun ? "Would close" : "Closing"} #${pr.number}: ` +
`${author} is ${blocked ? "blocked" : "not an approved contributor"}.`,
);
await github(ctx.token, `${ctx.repoUrl}/issues/${pr.number}/comments`, {
const reason = blocked ? "blocked" : "not-approved";
const url = prUrl(ctx, pr.number);
if (ctx.dryRun) {
audit(ctx, "comment", { pr: url, author });
audit(ctx, "close", { pr: url, author, reason });
continue;
}
const res = await github(ctx.token, `${ctx.repoUrl}/issues/${pr.number}/comments`, {
method: "POST",
body: { body: renderMessage(blocked ? ctx.blockedMessage : ctx.message, author) },
});
audit(ctx, "comment", { pr: url, author, url: (await res.json()).html_url });
await github(ctx.token, `${ctx.repoUrl}/pulls/${pr.number}`, {
method: "PATCH",
body: { state: "closed" },
});
audit(ctx, "close", { pr: url, author, reason });
closed.push(pr.number);
}
return closed;
Expand All @@ -258,9 +320,16 @@ async function closeUnapproved(ctx, allow, block) {
async function run() {
const apiUrl = process.env.GITHUB_API_URL ?? "https://api.github.com";
const token = input("token", { required: true });
const dryRun = input("dry-run") || "false";
if (dryRun !== "true" && dryRun !== "false") {
throw new Error(`dry-run must be "true" or "false", got "${dryRun}"`);
}
const ctx = {
apiUrl,
serverUrl: process.env.GITHUB_SERVER_URL ?? "https://github.com",
repo: process.env.GITHUB_REPOSITORY,
repoUrl: `${apiUrl}/repos/${process.env.GITHUB_REPOSITORY}`,
dryRun: dryRun === "true",
token,
message: input("message", { required: true }),
permsRepo: input("permissions-repo", { required: true }),
Expand All @@ -269,7 +338,17 @@ async function run() {
allowPath: input("allowlist-path", { required: true }),
blockPath: input("blocklist-path"),
vouchTeam: input("vouch-team"),
audit: [],
};
try {
await sweep(ctx);
} finally {
// Also on failure, so partial runs are accounted for.
printAudit(ctx);
}
}

async function sweep(ctx) {
if (ctx.blockPath) ctx.blockedMessage = input("blocked-message", { required: true });
parsePair(ctx.permsRepo, "permissions-repo");

Expand All @@ -283,7 +362,9 @@ async function run() {
if (ctx.vouchTeam) await processVouches(ctx, allow, block);

const closed = await closeUnapproved(ctx, allow, block);
console.log(closed.length ? `Closed ${closed.length} pull request(s).` : "Nothing to close.");
if (!ctx.dryRun) {
console.log(closed.length ? `Closed ${closed.length} pull request(s).` : "Nothing to close.");
}
setOutput("closed", JSON.stringify(closed));
}

Expand Down
36 changes: 36 additions & 0 deletions test/lib.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,42 @@ test("renderMessage substitutes every {author}", () => {
assert.equal(renderMessage("Hi @{author}, {author}!", "bob"), "Hi @bob, bob!");
});

test("renderMessage joins hard-wrapped paragraphs", () => {
const template =
"Thanks @{author} for your contribution, but\nthis bot is closing this PR.\n\n" +
"See [the contributing\ndocs](https://example.com).\n";
assert.equal(
renderMessage(template, "bob"),
"Thanks @bob for your contribution, but this bot is closing this PR.\n\n" +
"See [the contributing docs](https://example.com).\n",
);
});

test("renderMessage keeps block markdown on its own lines", () => {
const template = [
"# Closed",
"Intro line one",
"line two:",
"- item one",
"- item two",
"1. first",
"> quoted",
"| a | b |",
"|---|---|",
"```",
"code line",
"more code",
"```",
" indented code",
"after",
"",
].join("\n");
assert.equal(
renderMessage(template, "bob"),
template.replace("Intro line one\nline two:", "Intro line one line two:"),
);
});

test("parsePair", () => {
assert.deepEqual(parsePair("org/repo.name", "x"), ["org", "repo.name"]);
assert.throws(() => parsePair("org", "x"), /x must be/);
Expand Down
Loading