commit
Add Vercel verification rules, one decision per PR, and per-page filters
New rules: - vercelFileName: _vercel.<sub>.<name>.json should be _vercel.<name>.json - vercelTxtRecord: a vc-domain-verify TXT in a domain file belongs in _vercel.<name>.json One Discord message and one dashboard card per pull request, with a single button for every pending finding on it. NS closes the PR and settles the rest; otherwise one review covers every issue, and it is dismissed only once all of them are fixed. Each decision writes one audit row. The repository filter moves from the header into Overview, Pending and History. Co-Authored-By: Sandrone <[email protected]>
diff --git a/README.md b/README.md
index ed51e37..0721f01 100644
--- a/README.md
+++ b/README.md
@@ -3,15 +3,28 @@
A personal moderation assistant for pull requests on `is-a-dev/register` and
`free-domains/is-a.bot`. Set the list in `GITHUB_REPOS` (comma separated, `owner/name`).
-The dashboard combines every repository. Use the **All / is-a.dev / is-a.bot** filter in the
-header to narrow any page to one repository.
-
-It detects two violations, pings you on Discord, and acts **only** when you press a button.
-
-| Violation | Button | What the button does |
-| ------------------------------------------ | --------------- | ---------------------------------------------------- |
-| NS records from a first-time contributor | Close PR | Posts the policy comment, then closes the PR |
-| `owner.email` is a GitHub no-reply address | Request Changes | Submits a review with an inline comment on that line |
+The dashboard combines every repository. Use the **All / is-a.dev / is-a.bot** filter
+on Overview, Pending and History to narrow that page to one repository. Lookup has its own
+repository picker.
+
+It detects the violations below, pings you on Discord, and acts **only** when you press a button.
+
+| Violation | Button | What the button does |
+| -------------------------------------------------------- | --------------- | ---------------------------------------------------- |
+| NS records from a first-time contributor | Close PR | Posts the policy comment, then closes the PR |
+| `CNAME` to an unsupported host | Request Changes | Submits a review with an inline comment on that line |
+| Vercel preview redirects to the Vercel login | Request Changes | Submits a review explaining Deployment Protection |
+| `owner.email` is a GitHub no-reply address | Request Changes | Submits a review with an inline comment on that line |
+| `_vercel.www.alice.json` instead of `_vercel.alice.json` | Request Changes | Asks for the file to be renamed to the right name |
+| `vc-domain-verify=` TXT inside `alice.json` | Request Changes | Asks for it to move to `_vercel.alice.json` |
+
+Each pull request gets **one** Discord message and one dashboard card listing every issue on it,
+with one button for all of them:
+
+- With NS records on the PR, the button closes it, which settles every other issue too.
+- Otherwise it submits one review: an inline comment per issue where GitHub allows one, the
+ rest in the review body. That review is dismissed once every issue in it is fixed.
+- **Ignore** ignores every pending issue on the PR.
One Deno process runs the scanner, the Discord bot, and the SvelteKit dashboard. They share one SQLite file.
diff --git a/config/messages.jp b/config/messages.jp
index 751d019..d5b9462 100644
--- a/config/messages.jp
+++ b/config/messages.jp
@@ -3,6 +3,9 @@
[nsRecords]
closeComment: "Thanks for your interest in {service}!\n\nThis pull request requests `NS` records. We do not grant nameserver records to first-time contributors, so I am closing this pull request.\n\nYou are welcome to open a new pull request using other record types, such as `A`, `AAAA`, `CNAME`, `MX` or `TXT`. Once you have an accepted registration, you can request `NS` records with a clear justification for why they are needed.\n\nPlease see the [Docs](https://docs.is-a.dev/faq/#who-can-use-ns-records) for more information.\n<sub>This comment was sent with an [automated tool](https://doughmination.gay/automated), and approved by a human. I do not see replies.</sub>"
+[combined]
+reviewSummary: "This pull request has a few things to fix. Please see the comments below.\n<sub>This comment was sent with an [automated tool](https://doughmination.gay/automated), and approved by a human. I do not see replies.</sub>"
+
[unsupportedCname]
reviewComment: "Your `CNAME` record points at a host that we do not support. Please point it at a supported host, or use another record type such as `A` or `AAAA`.\n\nIf you have requested a CloudFlare Worker, please use a legacy CloudFlare Pages project."
reviewDismissal: "Thanks, the `CNAME` record is fixed. Dismissing the requested changes."
@@ -17,3 +20,13 @@ reviewSummary: "Please see the inline comment on `owner.email`.\n<sub>This comme
reviewComment: "Your website preview is not live: it redirects to the Vercel login page, so we cannot review it.\n\nTo make it public:\n\n1. Open your project dashboard on Vercel.\n2. Navigate to **Settings > Deployment Protection**.\n3. Toggle off **Vercel Authentication** (Require Login) and click **Save**.\n4. Test your link in an Incognito window to confirm it loads without a login prompt.\n<sub>This comment was sent with an [automated tool](https://doughmination.gay/automated), and approved by a human. I do not see replies.</sub>"
reviewDismissal: "Thanks, your website preview now loads without a login. Dismissing the requested changes."
reviewSummary: "Please see the comment on your website preview.\n<sub>This comment was sent with an [automated tool](https://doughmination.gay/automated), and approved by a human. I do not see replies.</sub>"
+
+[vercelFileName]
+reviewComment: "This file has the wrong name for a Vercel verification record. Vercel checks the `_vercel` record of your registered domain, so please rename this file to `{vercelFile}`."
+reviewDismissal: "Thanks, the Vercel verification file is named correctly now. Dismissing the requested changes."
+reviewSummary: "Please see the inline comment on the Vercel verification file name.\n<sub>This comment was sent with an [automated tool](https://doughmination.gay/automated), and approved by a human. I do not see replies.</sub>"
+
+[vercelTxtRecord]
+reviewComment: "This `TXT` record is a Vercel verification record (`vc-domain-verify=...`). Vercel looks for it on the `_vercel` record, not on your domain, so please remove it from this file and put it in its own file, `{vercelFile}`."
+reviewDismissal: "Thanks, the Vercel verification record has moved out of the domain file. Dismissing the requested changes."
+reviewSummary: "Please see the inline comment on the Vercel `TXT` record.\n<sub>This comment was sent with an [automated tool](https://doughmination.gay/automated), and approved by a human. I do not see replies.</sub>"
diff --git a/src/lib/components/RepoFilter.svelte b/src/lib/components/RepoFilter.svelte
new file mode 100644
index 0000000..9c75535
--- /dev/null
+++ b/src/lib/components/RepoFilter.svelte
@@ -0,0 +1,69 @@
+<!-- src/lib/components/RepoFilter.svelte
+ MIT — (c) Doughmination System®
+-->
+
+<script lang="ts">
+ import { page } from '$app/state';
+ import { repoLabel } from '#lib/labels.ts';
+
+ let { repos, current }: { repos: string[]; current: string | null } = $props();
+
+ // Same page, with the repository filter set (or cleared for null)
+ function filterHref(repo: string | null): string {
+ const next = new URL(page.url.href);
+
+ if (repo === null) {
+ next.searchParams.delete('repo');
+ } else {
+ next.searchParams.set('repo', repo);
+ }
+
+ return `${next.pathname}${next.search}`;
+ }
+
+ const options = $derived([
+ {
+ repo: null,
+ label: 'All'
+ },
+ ...repos.map((repo) => ({
+ repo,
+ label: repoLabel(repo)
+ }))
+ ]);
+</script>
+
+<div class="filter" role="group" aria-label="Repository filter">
+ {#each options as option (option.label)}
+ <a
+ href={filterHref(option.repo)}
+ title={option.repo ?? 'Every repository'}
+ aria-current={current === option.repo ? 'true' : undefined}
+ >
+ {option.label}
+ </a>
+ {/each}
+</div>
+
+<style>
+ .filter {
+ display: inline-flex;
+ margin-bottom: 1rem;
+ border: 1px solid var(--border);
+ border-radius: 999px;
+ overflow: hidden;
+ background: var(--surface-card);
+ }
+
+ .filter a {
+ padding: 0.2rem 0.8rem;
+ color: var(--text-secondary);
+ text-decoration: none;
+ font-size: 0.9rem;
+ }
+
+ .filter a[aria-current='true'] {
+ background: var(--accent);
+ color: var(--accent-text);
+ }
+</style>
diff --git a/src/lib/labels.ts b/src/lib/labels.ts
index e58c73d..ca606cb 100644
--- a/src/lib/labels.ts
+++ b/src/lib/labels.ts
@@ -8,7 +8,9 @@ export const ruleLabels: Record<string, string> = {
nsRecords: 'NS records (first-time contributor)',
unsupportedCname: 'Unsupported CNAME target',
noReplyEmail: 'No-reply owner.email',
- vercelLogin: 'Vercel preview behind a login'
+ vercelLogin: 'Vercel preview behind a login',
+ vercelFileName: 'Misnamed _vercel file',
+ vercelTxtRecord: 'Vercel TXT in the domain file'
};
export const severityLabels: Record<number, string> = {
diff --git a/src/lib/server/discord/bot.ts b/src/lib/server/discord/bot.ts
index c70bb67..66a6f7e 100644
--- a/src/lib/server/discord/bot.ts
+++ b/src/lib/server/discord/bot.ts
@@ -8,13 +8,18 @@ import { readFileSync } from 'node:fs';
import { Client, Events, MessageFlags, type ClientUser, type Interaction } from 'discord.js';
import { getConfig } from '../config.ts';
-import { getFinding, listUnnotifiedFindings, setFindingDiscordMessage } from '../db/findings.ts';
+import {
+ getFinding,
+ listFindingsForPullRequest,
+ listUnnotifiedFindings,
+ setFindingDiscordMessage
+} from '../db/findings.ts';
import { getValue, setValue } from '../db/keyValue.ts';
import { onFindingEvent } from '../events.ts';
import { createLogger, sleep } from '../logger.ts';
import { performModerationAction, type ModerationDecision } from '../moderation/actions.ts';
import { bySeverity } from '../rules/index.ts';
-import { buttonPrefix, renderFinding } from './render.ts';
+import { buttonPrefix, messageGroup, renderPullRequest } from './render.ts';
const logger = createLogger('discord');
@@ -24,24 +29,33 @@ function isReady(): boolean {
return client?.isReady() ?? false;
}
-// Findings with a send in flight, so the event path and the catch-up path never double-post
-const sendsInFlight = new Set<number>();
+// PRs with a send in flight, so the event path and the catch-up path never double-post.
+// A finding skipped here is attached by the send in flight, or by the next catch-up.
+const sendsInFlight = new Set<string>();
async function sendNotification(findingId: number): Promise<void> {
- if (sendsInFlight.has(findingId)) {
+ const finding = getFinding(findingId);
+
+ if (!finding) {
+ return;
+ }
+
+ const pullRequestKey = `${finding.repo}#${finding.prNumber}`;
+
+ if (sendsInFlight.has(pullRequestKey)) {
return;
}
- sendsInFlight.add(findingId);
+ sendsInFlight.add(pullRequestKey);
try {
await deliverNotification(findingId);
} finally {
- sendsInFlight.delete(findingId);
+ sendsInFlight.delete(pullRequestKey);
}
}
-// Sends to the configured channel when set, otherwise as a direct message
+// One message per PR: joins a live message for the PR, or sends a new one
async function deliverNotification(findingId: number): Promise<void> {
const finding = getFinding(findingId);
@@ -53,26 +67,42 @@ async function deliverNotification(findingId: number): Promise<void> {
return;
}
+ const live = listFindingsForPullRequest(finding.repo, finding.prNumber).find(
+ (other) =>
+ other.discordChannelId !== null &&
+ other.discordMessageId !== null &&
+ (other.status === 'pending' || other.status === 'acting')
+ );
+
+ if (live?.discordChannelId && live.discordMessageId) {
+ setFindingDiscordMessage(finding.id, live.discordChannelId, live.discordMessageId);
+ await refreshNotification(finding.id);
+ return;
+ }
+
+ // Sends to the configured channel when set, otherwise as a direct message
const { discordChannelId, discordUserId } = getConfig();
- const payload = renderFinding(finding);
+ const channel = discordChannelId ? await client.channels.fetch(discordChannelId) : null;
- if (discordChannelId) {
- const channel = await client.channels.fetch(discordChannelId);
+ if (discordChannelId && !channel?.isSendable()) {
+ throw new Error(`Channel ${discordChannelId} cannot receive messages`);
+ }
- if (!channel?.isSendable()) {
- throw new Error(`Channel ${discordChannelId} cannot receive messages`);
- }
+ const target = channel?.isSendable() ? channel : await client.users.fetch(discordUserId);
- const message = await channel.send(payload);
+ // Rendered after the fetch, so findings from the same scan are all in it
+ const rendered = messageGroup(finding);
+ const message = await target.send(renderPullRequest(finding));
+ const unsent = messageGroup(finding);
- setFindingDiscordMessage(finding.id, message.channelId, message.id);
- return;
+ for (const member of unsent) {
+ setFindingDiscordMessage(member.id, message.channelId, message.id);
}
- const user = await client.users.fetch(discordUserId);
- const message = await user.send(payload);
-
- setFindingDiscordMessage(finding.id, message.channelId, message.id);
+ // A finding that arrived while the message was being sent
+ if (unsent.length !== rendered.length) {
+ await refreshNotification(finding.id);
+ }
}
async function refreshNotification(findingId: number): Promise<void> {
@@ -92,7 +122,7 @@ async function refreshNotification(findingId: number): Promise<void> {
return;
}
- await channel.messages.edit(finding.discordMessageId, renderFinding(finding));
+ await channel.messages.edit(finding.discordMessageId, renderPullRequest(finding));
}
// Catches up on findings that could not be delivered earlier
diff --git a/src/lib/server/discord/render.ts b/src/lib/server/discord/render.ts
index 88627bb..117e95c 100644
--- a/src/lib/server/discord/render.ts
+++ b/src/lib/server/discord/render.ts
@@ -14,7 +14,7 @@ import { repoLabel, severityLabels } from '../../labels.ts';
import { getConfig } from '../config.ts';
import { listFindingsForPullRequest } from '../db/findings.ts';
import { bySeverity, getRule } from '../rules/index.ts';
-import type { FindingStatus, FindingWithPullRequest } from '../types.ts';
+import type { FindingRow, FindingStatus, FindingWithPullRequest } from '../types.ts';
export const buttonPrefix = 'tracker';
@@ -44,67 +44,66 @@ export function buildButtonId(decision: 'approve' | 'ignore', findingId: number)
return `${buttonPrefix}:${decision}:${findingId}`;
}
-// Other open violations on the same PR, most serious first
-function describeOtherFindings(finding: FindingWithPullRequest): string {
- const others = listFindingsForPullRequest(finding.repo, finding.prNumber)
- .filter(
- (other) =>
- other.id !== finding.id && (other.status === 'pending' || other.status === 'acting')
+// Findings shown in one PR message: those already on it, or the unsent pending ones
+export function messageGroup(finding: FindingWithPullRequest): FindingRow[] {
+ return listFindingsForPullRequest(finding.repo, finding.prNumber)
+ .filter((other) =>
+ finding.discordMessageId === null
+ ? other.discordMessageId === null && other.status === 'pending'
+ : other.discordMessageId === finding.discordMessageId
)
- .sort(bySeverity)
- .map(
- (other) => `${severityLabels[getRule(other.ruleId).severity]}: ${getRule(other.ruleId).title}`
- );
-
- return others.length === 0 ? 'None' : others.join('\n');
+ .sort(bySeverity);
}
-export function renderFinding(finding: FindingWithPullRequest): BaseMessageOptions {
- const rule = getRule(finding.ruleId);
+// The message takes the colour of its most urgent finding
+const statusPriority: FindingStatus[] = [
+ 'pending',
+ 'acting',
+ 'actioned',
+ 'resolved',
+ 'prClosed',
+ 'ignored'
+];
+
+export function renderPullRequest(finding: FindingWithPullRequest): BaseMessageOptions {
+ const group = messageGroup(finding);
+ const members = group.length > 0 ? group : [finding];
+ const pending = members.filter((member) => member.status === 'pending');
+
+ const leadStatus =
+ statusPriority.find((status) => members.some((member) => member.status === status)) ??
+ finding.status;
+
+ const latest = [...members].sort((first, second) =>
+ second.updatedAt.localeCompare(first.updatedAt)
+ )[0];
const embed = new EmbedBuilder()
.setTitle(truncate(`${repoLabel(finding.repo)} #${finding.prNumber} · ${finding.title}`, 250))
.setURL(finding.url)
- .setColor(statusColours[finding.status])
- .addFields(
- {
- name: 'Violation',
- value: rule.title
- },
- {
- name: 'Severity',
- value: severityLabels[rule.severity],
- inline: true
- },
- {
- name: 'Also on this PR',
- value: truncate(describeOtherFindings(finding), 1000),
- inline: true
- },
- {
- name: 'Author',
- value: `[${finding.author}](https://github.com/${finding.author})`,
- inline: true
- },
- {
- name: 'File',
- value: `\`${finding.filePath}\``,
- inline: true
- },
- {
- name: 'Reason',
- value: truncate(finding.reason, 1000)
- },
- {
- name: 'Status',
- value: statusLabels[finding.status]
- }
- );
-
- if (finding.lastOutcome) {
+ .setColor(statusColours[leadStatus])
+ .addFields({
+ name: 'Author',
+ value: `[${finding.author}](https://github.com/${finding.author})`
+ });
+
+ // Discord allows 25 fields; a registration PR never comes close
+ for (const member of members.slice(0, 20)) {
+ const rule = getRule(member.ruleId);
+
+ embed.addFields({
+ name: truncate(`${severityLabels[rule.severity]}: ${rule.title}`, 250),
+ value: truncate(
+ `\`${member.filePath}\`\n${member.reason}\nStatus: ${statusLabels[member.status]}`,
+ 1000
+ )
+ });
+ }
+
+ if (latest.lastOutcome) {
embed.addFields({
name: 'Last result',
- value: truncate(finding.lastOutcome, 1000)
+ value: truncate(latest.lastOutcome, 1000)
});
}
@@ -112,21 +111,29 @@ export function renderFinding(finding: FindingWithPullRequest): BaseMessageOptio
embed.setFooter({ text: 'Dry run is ON: buttons will not change anything on GitHub' });
}
- if (finding.status !== 'pending') {
+ if (pending.length === 0) {
return {
embeds: [embed],
components: []
};
}
+ const closing = pending.find((member) => getRule(member.ruleId).actionType === 'closePr');
+ const countNote = pending.length > 1 ? ` (${pending.length})` : '';
+
+ // Either button acts on every pending finding of the PR
const approveButton = new ButtonBuilder()
- .setCustomId(buildButtonId('approve', finding.id))
- .setLabel(rule.actionLabel)
- .setStyle(rule.actionType === 'closePr' ? ButtonStyle.Danger : ButtonStyle.Primary);
+ .setCustomId(buildButtonId('approve', pending[0].id))
+ .setLabel(
+ closing
+ ? getRule(closing.ruleId).actionLabel
+ : `${getRule(pending[0].ruleId).actionLabel}${countNote}`
+ )
+ .setStyle(closing ? ButtonStyle.Danger : ButtonStyle.Primary);
const ignoreButton = new ButtonBuilder()
- .setCustomId(buildButtonId('ignore', finding.id))
- .setLabel('Ignore')
+ .setCustomId(buildButtonId('ignore', pending[0].id))
+ .setLabel(pending.length > 1 ? 'Ignore all' : 'Ignore')
.setStyle(ButtonStyle.Secondary);
return {
diff --git a/src/lib/server/messages.ts b/src/lib/server/messages.ts
index 4f92f52..c3d32de 100644
--- a/src/lib/server/messages.ts
+++ b/src/lib/server/messages.ts
@@ -10,32 +10,34 @@ import { createLogger } from './logger.ts';
const logger = createLogger('messages');
+export interface ReviewMessages {
+ reviewComment: string;
+ reviewDismissal: string;
+ reviewSummary: string;
+}
+
export type ModerationMessages = {
nsRecords: {
closeComment: string;
};
- unsupportedCname: {
- reviewComment: string;
- reviewDismissal: string;
- reviewSummary: string;
- };
- noReplyEmail: {
- reviewComment: string;
- reviewDismissal: string;
- reviewSummary: string;
- };
- vercelLogin: {
- reviewComment: string;
- reviewDismissal: string;
+ // Used when one review covers several violations
+ combined: {
reviewSummary: string;
};
+ unsupportedCname: ReviewMessages;
+ noReplyEmail: ReviewMessages;
+ vercelLogin: ReviewMessages;
+ vercelFileName: ReviewMessages;
+ vercelTxtRecord: ReviewMessages;
};
// The committed file, read once, so a later bad edit still has wording to fall back on
let defaultMessages: ModerationMessages | null = null;
function getDefaultMessages(): ModerationMessages {
- defaultMessages ??= loads(readFileSync('config/messages.jp', 'utf8')) as ModerationMessages;
+ defaultMessages ??= loads(
+ readFileSync('config/messages.jp', 'utf8')
+ ) as unknown as ModerationMessages;
return defaultMessages;
}
@@ -49,24 +51,17 @@ export function getMessages(): ModerationMessages {
readFileSync(getConfig().messagesPath, 'utf8')
) as Partial<ModerationMessages>;
- return {
- nsRecords: {
- ...defaultMessages.nsRecords,
- ...overrides.nsRecords
- },
- unsupportedCname: {
- ...defaultMessages.unsupportedCname,
- ...overrides.unsupportedCname
- },
- noReplyEmail: {
- ...defaultMessages.noReplyEmail,
- ...overrides.noReplyEmail
- },
- vercelLogin: {
- ...defaultMessages.vercelLogin,
- ...overrides.vercelLogin
- }
- };
+ // Each section falls back key by key to the committed wording
+ const merged: Record<string, object> = {};
+
+ for (const [section, wording] of Object.entries(defaultMessages)) {
+ merged[section] = {
+ ...wording,
+ ...overrides[section as keyof ModerationMessages]
+ };
+ }
+
+ return merged as ModerationMessages;
} catch (error) {
logger.warn('Could not read the messages file; using built-in wording', error);
diff --git a/src/lib/server/moderation/actions.ts b/src/lib/server/moderation/actions.ts
index 9e82c3b..2975559 100644
--- a/src/lib/server/moderation/actions.ts
+++ b/src/lib/server/moderation/actions.ts
@@ -7,6 +7,7 @@ import { recordAction } from '../db/auditLog.ts';
import {
claimFinding,
getFinding,
+ listFindingsForPullRequest,
setFindingStatus,
updateFindingEvidence
} from '../db/findings.ts';
@@ -14,13 +15,13 @@ import { upsertPullRequest } from '../db/pullRequests.ts';
import { emitFindingEvent } from '../events.ts';
import { getPullRequest } from '../github/pullRequests.ts';
import { createLogger, describeError } from '../logger.ts';
-import { getRule } from '../rules/index.ts';
+import { bySeverity, getRule } from '../rules/index.ts';
import type {
ActionOutcome,
ActionSource,
ActionType,
- FindingStatus,
- FindingWithPullRequest
+ FindingRow,
+ FindingStatus
} from '../types.ts';
import { evaluatePullRequest } from './evaluate.ts';
import { executors } from './executors.ts';
@@ -31,31 +32,46 @@ export type ModerationDecision = 'approve' | 'ignore';
interface Resolution {
outcome: ActionOutcome;
+ actionType: ActionType;
findingStatus: FindingStatus;
+ // Findings the latest commit no longer violates
+ fixedIds?: Set<number>;
}
-// Runs with the finding already claimed; decides what happens and where the finding ends up
+function chooseAction(findings: FindingRow[]): Exclude<ActionType, 'ignore'> {
+ // NS closes the PR, which settles every other issue with it
+ return findings.some((finding) => getRule(finding.ruleId).actionType === 'closePr')
+ ? 'closePr'
+ : 'requestChanges';
+}
+
+// Runs with the findings already claimed; decides what happens and where they end up
async function resolveDecision(
- finding: FindingWithPullRequest,
+ group: FindingRow[],
decision: ModerationDecision
): Promise<Resolution> {
if (decision === 'ignore') {
return {
+ actionType: 'ignore',
findingStatus: 'ignored',
outcome: {
status: 'success',
- summary: 'Ignored. No action was taken on GitHub.'
+ summary: `Ignored ${group.length} issue(s). No action was taken on GitHub.`
}
};
}
+ const [lead] = group;
+ const plannedAction = chooseAction(group);
+
// Revalidate against the latest commit before touching anything
- const pullRequest = await getPullRequest(finding.repo, finding.prNumber, true);
+ const pullRequest = await getPullRequest(lead.repo, lead.prNumber, true);
upsertPullRequest(pullRequest);
if (pullRequest.state !== 'open') {
return {
+ actionType: plannedAction,
findingStatus: 'prClosed',
outcome: {
status: 'skipped',
@@ -69,47 +85,65 @@ async function resolveDecision(
priority: true
});
- const violation = evaluation.violations.find(
- (candidate) => candidate.ruleId === finding.ruleId && candidate.filePath === finding.filePath
- );
+ const stillViolated: FindingRow[] = [];
+ const fixedIds = new Set<number>();
+
+ for (const finding of group) {
+ const violation = evaluation.violations.find(
+ (candidate) => candidate.ruleId === finding.ruleId && candidate.filePath === finding.filePath
+ );
- if (!violation) {
+ if (violation) {
+ updateFindingEvidence(finding.id, pullRequest.headSha, violation.reason);
+ stillViolated.push(finding);
+ } else {
+ fixedIds.add(finding.id);
+ }
+ }
+
+ if (stillViolated.length === 0) {
return {
+ actionType: plannedAction,
findingStatus: 'resolved',
outcome: {
status: 'skipped',
- summary: 'The latest commit no longer has this violation. Nothing was done.'
+ summary: 'The latest commit no longer has these violations. Nothing was done.'
}
};
}
- updateFindingEvidence(finding.id, pullRequest.headSha, violation.reason);
-
- const rule = getRule(finding.ruleId);
+ const actionType = chooseAction(stillViolated);
if (getConfig().dryRun) {
return {
+ actionType,
+ fixedIds,
findingStatus: 'pending',
outcome: {
status: 'dryRun',
- summary: `Dry run: would have run "${rule.actionLabel}" on #${pullRequest.number}.`
+ summary:
+ `Dry run: would have run "${getRule(stillViolated[0].ruleId).actionLabel}" ` +
+ `on #${pullRequest.number} for ${stillViolated.length} issue(s).`
}
};
}
- const outcome = await executors[rule.actionType]({
+ const outcome = await executors[actionType]({
pullRequest,
- finding,
+ findings: stillViolated,
evaluation
});
return {
+ actionType,
+ fixedIds,
findingStatus: 'actioned',
outcome
};
}
-// The single entry point for Discord buttons and dashboard buttons alike
+// The single entry point for Discord buttons and dashboard buttons alike.
+// One decision covers every pending finding on the finding's pull request.
export async function performModerationAction(options: {
findingId: number;
decision: ModerationDecision;
@@ -124,25 +158,28 @@ export async function performModerationAction(options: {
};
}
- if (!claimFinding(finding.id)) {
+ // Each claim is atomic, so two presses can never act on the same finding
+ const group = listFindingsForPullRequest(finding.repo, finding.prNumber)
+ .filter((candidate) => candidate.status === 'pending' && claimFinding(candidate.id))
+ .sort(bySeverity);
+
+ if (group.length === 0) {
return {
status: 'skipped',
summary: `Already handled (status: ${finding.status}).`
};
}
- const rule = getRule(finding.ruleId);
- const actionType: ActionType = options.decision === 'ignore' ? 'ignore' : rule.actionType;
-
let resolution: Resolution;
try {
- resolution = await resolveDecision(finding, options.decision);
+ resolution = await resolveDecision(group, options.decision);
} catch (error) {
- logger.error(`Action on finding ${finding.id} failed`, error);
+ logger.error(`Action on ${finding.repo}#${finding.prNumber} failed`, error);
// Back to pending so it can be retried; the retry revalidates from scratch
resolution = {
+ actionType: options.decision === 'ignore' ? 'ignore' : chooseAction(group),
findingStatus: 'pending',
outcome: {
status: 'failure',
@@ -151,24 +188,31 @@ export async function performModerationAction(options: {
};
}
- const { outcome, findingStatus } = resolution;
+ const { outcome, findingStatus, fixedIds } = resolution;
- setFindingStatus(finding.id, findingStatus, outcome.summary);
+ for (const member of group) {
+ if (fixedIds?.has(member.id)) {
+ setFindingStatus(member.id, 'resolved', 'The latest commit no longer has this violation.');
+ } else {
+ setFindingStatus(member.id, findingStatus, outcome.summary);
+ }
+ emitFindingEvent('findingChanged', member.id);
+ }
+
+ // One audit row per decision, led by the most serious finding
recordAction({
- findingId: finding.id,
+ findingId: group[0].id,
repo: finding.repo,
prNumber: finding.prNumber,
contributor: finding.author,
- ruleId: finding.ruleId,
- actionType,
+ ruleId: group[0].ruleId,
+ actionType: resolution.actionType,
source: options.source,
status: outcome.status,
detail: outcome.summary,
githubUrl: outcome.githubUrl ?? null
});
- emitFindingEvent('findingChanged', finding.id);
-
return outcome;
}
diff --git a/src/lib/server/moderation/executors.ts b/src/lib/server/moderation/executors.ts
index a89348f..09d2197 100644
--- a/src/lib/server/moderation/executors.ts
+++ b/src/lib/server/moderation/executors.ts
@@ -19,6 +19,7 @@ import {
} from '../github/pullRequests.ts';
import { getMessages } from '../messages.ts';
import { getRule } from '../rules/index.ts';
+import { vercelFileFor } from '../rules/vercelVerification.ts';
import type { Violation } from '../rules/types.ts';
import type { ActionOutcome, ActionType, FindingRow, PullRequestSummary } from '../types.ts';
import type { Evaluation } from './evaluate.ts';
@@ -26,25 +27,47 @@ import { retireFindings } from './reconcile.ts';
export interface ExecutorInput {
pullRequest: PullRequestSummary;
- finding: FindingRow;
+ // Every finding on the PR that is still violated, decided together
+ findings: FindingRow[];
evaluation: Evaluation;
}
type Executor = (input: ExecutorInput) => Promise<ActionOutcome>;
+// Wording placeholders that depend on the repository and the file
+function fillWording(text: string, repo: string, filePath: string): string {
+ return text
+ .replaceAll('{service}', repoLabel(repo))
+ .replaceAll('{vercelFile}', vercelFileFor(filePath, repo));
+}
+
+// The automated-tool footer, so a combined review carries it once
+function withoutFooter(text: string): string {
+ return text.replace(/\n*<sub>[\s\S]*<\/sub>\s*$/, '');
+}
+
+function findingKey(item: { ruleId: string; filePath: string }): string {
+ return `${item.ruleId}:${item.filePath}`;
+}
+
async function closeWithPolicyComment(input: ExecutorInput): Promise<ActionOutcome> {
- const { pullRequest, finding } = input;
+ const { pullRequest, findings } = input;
const { repo, number } = pullRequest;
+ const nsFinding = findings.find((finding) => getRule(finding.ruleId).actionType === 'closePr');
+
+ if (!nsFinding) {
+ throw new Error('Closing needs a closePr finding.');
+ }
// A stored comment id means an earlier attempt already explained; never explain twice
- if (finding.commentId === null) {
+ if (nsFinding.commentId === null) {
const comment = await createIssueComment(
repo,
number,
- getMessages().nsRecords.closeComment.replaceAll('{service}', repoLabel(repo))
+ fillWording(getMessages().nsRecords.closeComment, repo, nsFinding.filePath)
);
- setFindingComment(finding.id, comment.id);
+ setFindingComment(nsFinding.id, comment.id);
}
await closePullRequest(repo, number);
@@ -52,17 +75,23 @@ async function closeWithPolicyComment(input: ExecutorInput): Promise<ActionOutco
markPullRequestClosed(repo, number);
retireFindings(repo, number, 'The pull request was closed through the tool.');
+ const others = findings.length - 1;
+
return {
status: 'success',
- summary: `Closed #${pullRequest.number} with the NS policy explanation.`,
+ summary:
+ `Closed #${number} with the NS policy explanation` +
+ (others > 0 ? `, settling ${others} other issue(s) with it.` : '.'),
githubUrl: pullRequest.url
};
}
-function reviewMarker(finding: FindingRow): string {
+function reviewMarker(finding: { ruleId: string; filePath: string }): string {
return `<!-- is-a-tracker:${finding.ruleId}:${finding.filePath} -->`;
}
+const markerPattern = /<!-- is-a-tracker:([^:]+):(.+?) -->/g;
+
function reviewMessages(finding: FindingRow) {
const messages = getMessages();
@@ -73,97 +102,133 @@ function reviewMessages(finding: FindingRow) {
return messages[finding.ruleId];
}
+// One review for every finding: inline where GitHub allows it, the rest in the body
async function requestRuleChanges(input: ExecutorInput): Promise<ActionOutcome> {
- const { pullRequest, finding, evaluation } = input;
- const messages = reviewMessages(finding);
- const marker = reviewMarker(finding);
+ const { pullRequest, findings, evaluation } = input;
+ const { repo, number, headSha } = pullRequest;
+ const markers = findings.map(reviewMarker);
const login = await getAuthenticatedLogin();
- const reviews = await listReviews(pullRequest.repo, pullRequest.number);
+ const reviews = await listReviews(repo, number);
const duplicate = reviews.find(
(review) =>
review.user?.login === login &&
review.state === 'CHANGES_REQUESTED' &&
- review.commit_id === pullRequest.headSha &&
- (review.body ?? '').includes(marker)
+ review.commit_id === headSha &&
+ markers.every((marker) => (review.body ?? '').includes(marker))
);
if (duplicate) {
return {
status: 'skipped',
- summary: 'Changes were already requested for this file on this commit.',
+ summary: 'Changes were already requested for these issues on this commit.',
githubUrl: duplicate.html_url
};
}
- const file = evaluation.files.find((candidate) => candidate.path === finding.filePath);
- const findLine = getRule(finding.ruleId).findLine;
- const line = file && findLine ? findLine(file) : null;
- const canCommentInline = line !== null && getCommentableLines(file?.patch).has(line);
+ const placed = findings.map((finding) => {
+ const file = evaluation.files.find((candidate) => candidate.path === finding.filePath);
+ const findLine = getRule(finding.ruleId).findLine;
+ const line = file && findLine ? findLine(file) : null;
+ const commentable = line !== null && getCommentableLines(file?.patch).has(line);
+
+ return {
+ finding,
+ line: commentable ? line : null
+ };
+ });
+
+ const comment = (finding: FindingRow) =>
+ fillWording(reviewMessages(finding).reviewComment, repo, finding.filePath);
// Rules without a line (like vercelLogin) are about the PR, not a file
- const fileNote = findLine ? `\n\nFile: \`${finding.filePath}\`` : '';
- const fallbackBody = `${messages.reviewComment}${fileNote}\n\n${marker}`;
-
- if (canCommentInline) {
- try {
- const review = await createChangesRequestedReview({
- repo: pullRequest.repo,
- number: pullRequest.number,
- commitId: pullRequest.headSha,
- body: `${messages.reviewSummary}\n\n${marker}`,
- comments: [
- {
- path: finding.filePath,
- line,
- side: 'RIGHT',
- body: messages.reviewComment
- }
- ]
- });
-
- return {
- status: 'success',
- summary: `Requested changes on #${pullRequest.number} with an inline comment on line ${line}.`,
- githubUrl: review.html_url
- };
- } catch (error) {
- // 422 means GitHub refused the line position; fall through to a body-only review
- if (!(error instanceof GitHubError) || error.status !== 422) {
- throw error;
- }
+ const fileNote = (finding: FindingRow) =>
+ getRule(finding.ruleId).findLine ? `\n\nFile: \`${finding.filePath}\`` : '';
+
+ const buildReview = (allowInline: boolean) => {
+ const inline = placed.filter((item) => allowInline && item.line !== null);
+ const inBody = placed.filter((item) => !inline.includes(item));
+ let text: string;
+
+ if (findings.length === 1) {
+ const [only] = findings;
+
+ text =
+ inline.length === 1
+ ? reviewMessages(only).reviewSummary
+ : `${comment(only)}${fileNote(only)}`;
+ } else {
+ text = [
+ ...inBody.map((item) => `${withoutFooter(comment(item.finding))}${fileNote(item.finding)}`),
+ getMessages().combined.reviewSummary
+ ].join('\n\n');
}
+
+ return {
+ inlineCount: inline.length,
+ body: `${text}\n\n${markers.join('\n')}`,
+ comments: inline.map((item) => ({
+ path: item.finding.filePath,
+ line: item.line as number,
+ side: 'RIGHT' as const,
+ body: comment(item.finding)
+ }))
+ };
+ };
+
+ let review = buildReview(true);
+ let created;
+
+ try {
+ created = await createChangesRequestedReview({
+ repo,
+ number,
+ commitId: headSha,
+ body: review.body,
+ comments: review.comments
+ });
+ } catch (error) {
+ // 422 means GitHub refused a line position; fall back to a body-only review
+ if (review.comments.length === 0 || !(error instanceof GitHubError) || error.status !== 422) {
+ throw error;
+ }
+
+ review = buildReview(false);
+
+ created = await createChangesRequestedReview({
+ repo,
+ number,
+ commitId: headSha,
+ body: review.body,
+ comments: []
+ });
}
- const review = await createChangesRequestedReview({
- repo: pullRequest.repo,
- number: pullRequest.number,
- commitId: pullRequest.headSha,
- body: fallbackBody,
- comments: []
- });
+ const inBodyCount = findings.length - review.inlineCount;
return {
status: 'success',
- summary: `Requested changes on #${pullRequest.number} in the review body (line not commentable).`,
- githubUrl: review.html_url
+ summary:
+ `Requested changes on #${number}: ${review.inlineCount} inline comment(s)` +
+ `, ${inBodyCount} in the review body.`,
+ githubUrl: created.html_url
};
}
-// Dismisses our change requests once the latest commit no longer has the violation
+// Dismisses our change requests once the latest commit fixes every issue a review raised
export async function dismissFixedChangeRequests(
pullRequest: PullRequestSummary,
violations: Violation[]
): Promise<void> {
- const fixed = listFindingsForPullRequest(pullRequest.repo, pullRequest.number).filter(
+ const { repo, number } = pullRequest;
+ const stillViolated = new Set(violations.map(findingKey));
+
+ const fixed = listFindingsForPullRequest(repo, number).filter(
(finding) =>
finding.status === 'actioned' &&
getRule(finding.ruleId).actionType === 'requestChanges' &&
- !violations.some(
- (violation) =>
- violation.ruleId === finding.ruleId && violation.filePath === finding.filePath
- )
+ !stillViolated.has(findingKey(finding))
);
if (fixed.length === 0 || getConfig().dryRun) {
@@ -171,31 +236,36 @@ export async function dismissFixedChangeRequests(
}
const login = await getAuthenticatedLogin();
- const reviews = await listReviews(pullRequest.repo, pullRequest.number);
+ const reviews = await listReviews(repo, number);
- for (const finding of fixed) {
- const marker = reviewMarker(finding);
+ for (const review of reviews) {
+ if (review.user?.login !== login || review.state !== 'CHANGES_REQUESTED') {
+ continue;
+ }
- const openReviews = reviews.filter(
- (review) =>
- review.user?.login === login &&
- review.state === 'CHANGES_REQUESTED' &&
- (review.body ?? '').includes(marker)
+ const keys = [...(review.body ?? '').matchAll(markerPattern)].map(
+ (match) => `${match[1]}:${match[2]}`
);
- for (const review of openReviews) {
- await dismissReview(
- pullRequest.repo,
- pullRequest.number,
- review.id,
- reviewMessages(finding).reviewDismissal
- );
+ const covered = fixed.filter((finding) => keys.includes(findingKey(finding)));
+
+ // A combined review stays until every issue it raised is fixed
+ if (covered.length === 0 || keys.some((key) => stillViolated.has(key))) {
+ continue;
}
+ const message = [
+ ...new Set(covered.map((finding) => reviewMessages(finding).reviewDismissal))
+ ].join('\n\n');
+
+ await dismissReview(repo, number, review.id, message);
+ }
+
+ for (const finding of fixed) {
setFindingStatus(
finding.id,
'resolved',
- 'The contributor fixed this; the requested changes were dismissed.'
+ 'The contributor fixed this; its review is dismissed once all of its issues are fixed.'
);
emitFindingEvent('findingChanged', finding.id);
}
diff --git a/src/lib/server/moderation/pipeline.test.ts b/src/lib/server/moderation/pipeline.test.ts
index 32782d7..e0c247a 100644
--- a/src/lib/server/moderation/pipeline.test.ts
+++ b/src/lib/server/moderation/pipeline.test.ts
@@ -405,4 +405,134 @@ describe('moderation pipeline', () => {
true
);
});
+
+ test('one approval sends one review covering every issue on the PR', async () => {
+ addPullRequest({
+ number: 6,
+ author: 'combo',
+ association: 'NONE',
+ sha: 'sha-six',
+ state: 'open',
+ updatedAt: '2026-11-04T00:00:00Z',
+ fileName: 'domains/combo.json',
+ json: {
+ owner: {
+ username: 'combo',
+ email: '[email protected]'
+ },
+ records: {
+ A: ['1.2.3.4'],
+ TXT: 'vc-domain-verify=combo.is-a.dev,abc123'
+ }
+ }
+ });
+
+ await scanOnce(repo);
+
+ const findings = listFindingsForPullRequest(repo, 6);
+
+ assert.deepEqual(findings.map((finding) => finding.ruleId).sort(), [
+ 'noReplyEmail',
+ 'vercelTxtRecord'
+ ]);
+
+ const outcome = await performModerationAction({
+ findingId: findings[0].id,
+ decision: 'approve',
+ source: 'discord'
+ });
+
+ const reviews = writes.filter((write) => write.path === '/pulls/6/reviews');
+
+ assert.equal(outcome.status, 'success');
+ assert.equal(reviews.length, 1);
+ assert.equal(reviews[0].body.comments?.length, 2);
+ assert.ok(
+ reviews[0].body.comments?.some((comment) =>
+ comment.body.includes('domains/_vercel.combo.json')
+ )
+ );
+ assert.ok(
+ listFindingsForPullRequest(repo, 6).every((finding) => finding.status === 'actioned')
+ );
+ });
+
+ test('a combined review is dismissed only once every issue is fixed', async () => {
+ const pullRequest = fakePullRequests.get(6)!;
+ const dismissals = () =>
+ writes.filter((write) => write.method === 'PUT' && write.path.startsWith('/pulls/6/'));
+
+ pullRequest.sha = 'sha-six-email';
+ pullRequest.updatedAt = '2026-11-04T01:00:00Z';
+ pullRequest.json = {
+ owner: { username: 'combo' },
+ records: {
+ A: ['1.2.3.4'],
+ TXT: 'vc-domain-verify=combo.is-a.dev,abc123'
+ }
+ };
+
+ await scanOnce(repo);
+
+ assert.equal(dismissals().length, 0);
+
+ pullRequest.sha = 'sha-six-fixed';
+ pullRequest.updatedAt = '2026-11-04T02:00:00Z';
+ pullRequest.json = {
+ owner: { username: 'combo' },
+ records: { A: ['1.2.3.4'] }
+ };
+
+ await scanOnce(repo);
+
+ assert.equal(dismissals().length, 1);
+ assert.ok(
+ listFindingsForPullRequest(repo, 6).every((finding) => finding.status === 'resolved')
+ );
+ });
+
+ test('NS on the PR closes it and settles every other issue with it', async () => {
+ addPullRequest({
+ number: 7,
+ author: 'mixed',
+ association: 'NONE',
+ sha: 'sha-seven',
+ state: 'open',
+ updatedAt: '2026-11-05T00:00:00Z',
+ fileName: 'domains/mixed.json',
+ json: {
+ owner: {
+ username: 'mixed',
+ email: '[email protected]'
+ },
+ records: {
+ NS: ['ns1.example.com']
+ }
+ }
+ });
+
+ await scanOnce(repo);
+
+ const ignored = listFindingsForPullRequest(repo, 7).find(
+ (finding) => finding.ruleId === 'noReplyEmail'
+ )!;
+
+ // Pressing the button from the less serious finding still closes the PR
+ const outcome = await performModerationAction({
+ findingId: ignored.id,
+ decision: 'approve',
+ source: 'dashboard'
+ });
+
+ assert.equal(outcome.status, 'success');
+ assert.deepEqual(
+ writes
+ .filter((write) => write.path.includes('/7'))
+ .map((write) => `${write.method} ${write.path}`),
+ ['POST /issues/7/comments', 'PATCH /pulls/7']
+ );
+ assert.ok(
+ listFindingsForPullRequest(repo, 7).every((finding) => finding.status === 'actioned')
+ );
+ });
});
diff --git a/src/lib/server/rules/index.ts b/src/lib/server/rules/index.ts
index 6e1c7d7..317d8ef 100644
--- a/src/lib/server/rules/index.ts
+++ b/src/lib/server/rules/index.ts
@@ -8,13 +8,16 @@ import { nsRecordsRule } from './nsRecords.ts';
import type { Rule } from './types.ts';
import { unsupportedCnameRule } from './unsupportedCname.ts';
import { vercelLoginRule } from './vercelLogin.ts';
+import { vercelFileNameRule, vercelTxtRecordRule } from './vercelVerification.ts';
// Add a new rule module here and the scanner, Discord and dashboard all pick it up
export const rules: Rule[] = [
nsRecordsRule,
unsupportedCnameRule,
vercelLoginRule,
- noReplyEmailRule
+ noReplyEmailRule,
+ vercelFileNameRule,
+ vercelTxtRecordRule
];
export function getRule(ruleId: RuleId): Rule {
diff --git a/src/lib/server/rules/rules.test.ts b/src/lib/server/rules/rules.test.ts
index 3c39c18..69d9aa6 100644
--- a/src/lib/server/rules/rules.test.ts
+++ b/src/lib/server/rules/rules.test.ts
@@ -10,6 +10,13 @@ import { findNoReplyEmail, findOwnerEmailLine } from './noReplyEmail.ts';
import { findNsRecords } from './nsRecords.ts';
import { findCnameLine, findUnsupportedCname } from './unsupportedCname.ts';
import { findVercelLinks, redirectsToVercelLogin } from './vercelLogin.ts';
+import {
+ findVercelTxt,
+ vercelFileFor,
+ vercelFileNameRule,
+ vercelTxtRecordRule
+} from './vercelVerification.ts';
+import type { DomainFile, RuleContext } from './types.ts';
describe('findNsRecords', () => {
test('finds NS records under "records"', () => {
@@ -219,3 +226,90 @@ describe('redirectsToVercelLogin', () => {
globalThis.fetch = realFetch;
});
});
+
+function contextFor(repo: string, files: Partial<DomainFile>[]): RuleContext {
+ return {
+ pullRequest: { repo } as RuleContext['pullRequest'],
+ files: files.map((file) => ({
+ path: 'domains/x.json',
+ status: 'added',
+ patch: undefined,
+ content: '',
+ json: null,
+ ...file
+ })),
+ getEligibility: async () => ({
+ eligible: true,
+ explanation: ''
+ })
+ };
+}
+
+describe('Vercel verification records', () => {
+ test('works out the _vercel file from any file of the registration', () => {
+ const dev = 'is-a-dev/register';
+ const bot = 'free-domains/is-a.bot';
+
+ assert.equal(
+ vercelFileFor('domains/_vercel.www.alice.json', dev),
+ 'domains/_vercel.alice.json'
+ );
+ assert.equal(
+ vercelFileFor('domains/_vercel.alice.is-a.dev.json', dev),
+ 'domains/_vercel.alice.json'
+ );
+ assert.equal(
+ vercelFileFor('domains/_vercel.alice.is-a.bot.json', bot),
+ 'domains/_vercel.alice.json'
+ );
+ assert.equal(vercelFileFor('domains/www.alice.json', dev), 'domains/_vercel.alice.json');
+ assert.equal(vercelFileFor('domains/alice.json', dev), 'domains/_vercel.alice.json');
+ });
+
+ test('flags misnamed _vercel files only', async () => {
+ const violations = await vercelFileNameRule.evaluate(
+ contextFor('is-a-dev/register', [
+ { path: 'domains/_vercel.www.alice.json' },
+ { path: 'domains/_vercel.bob.json' },
+ { path: 'domains/www.carol.json' }
+ ])
+ );
+
+ assert.deepEqual(
+ violations.map((violation) => violation.filePath),
+ ['domains/_vercel.www.alice.json']
+ );
+ });
+
+ test('finds Vercel tokens in TXT strings and lists', () => {
+ const token = 'vc-domain-verify=alice.is-a.dev,abc123';
+
+ assert.deepEqual(findVercelTxt({ records: { TXT: token } }), [token]);
+ assert.deepEqual(findVercelTxt({ records: { TXT: ['v=spf1 -all', token] } }), [token]);
+ assert.deepEqual(findVercelTxt({ records: { TXT: 'v=spf1 -all' } }), []);
+ assert.deepEqual(findVercelTxt(null), []);
+ });
+
+ test('flags a Vercel TXT in a domain file, but not in its _vercel file', async () => {
+ const json = { records: { TXT: 'vc-domain-verify=alice.is-a.dev,abc123' } };
+
+ const violations = await vercelTxtRecordRule.evaluate(
+ contextFor('is-a-dev/register', [
+ {
+ path: 'domains/alice.json',
+ json
+ },
+ {
+ path: 'domains/_vercel.alice.json',
+ json
+ }
+ ])
+ );
+
+ assert.deepEqual(
+ violations.map((violation) => violation.filePath),
+ ['domains/alice.json']
+ );
+ assert.ok(violations[0].reason.includes('domains/_vercel.alice.json'));
+ });
+});
diff --git a/src/lib/server/rules/vercelVerification.ts b/src/lib/server/rules/vercelVerification.ts
new file mode 100644
index 0000000..e6ec938
--- /dev/null
+++ b/src/lib/server/rules/vercelVerification.ts
@@ -0,0 +1,113 @@
+/* src/lib/server/rules/vercelVerification.ts
+ * MIT — (c) Doughmination System®
+ */
+
+import { repoLabel } from '../../labels.ts';
+import type { DomainFile, Rule, Violation } from './types.ts';
+import { isPlainObject } from './types.ts';
+
+const verifyPrefix = 'vc-domain-verify=';
+
+function baseName(filePath: string): string {
+ return filePath.replace(/^domains\//, '').replace(/\.json$/i, '');
+}
+
+// The registered name a file belongs to: domains/_vercel.www.alice.json -> alice
+function registeredName(filePath: string, repo: string): string {
+ const name = baseName(filePath)
+ .replace(/^_vercel\./i, '')
+ .replace(new RegExp(`\\.${repoLabel(repo).replaceAll('.', '\\.')}$`, 'i'), '');
+
+ return name.split('.').at(-1) ?? name;
+}
+
+// Where Vercel's verification record belongs, e.g. domains/_vercel.alice.json
+export function vercelFileFor(filePath: string, repo: string): string {
+ return `domains/_vercel.${registeredName(filePath, repo)}.json`;
+}
+
+function isVercelFile(filePath: string): boolean {
+ return /^_vercel\./i.test(baseName(filePath));
+}
+
+// TXT values that are Vercel verification tokens
+export function findVercelTxt(json: unknown): string[] {
+ if (!isPlainObject(json) || !isPlainObject(json.records)) {
+ return [];
+ }
+
+ const txt = json.records.TXT ?? json.records.txt;
+ const values = Array.isArray(txt) ? txt : [txt];
+
+ return values.filter(
+ (value): value is string => typeof value === 'string' && value.trim().startsWith(verifyPrefix)
+ );
+}
+
+// 1-based line of the first Vercel token, or null
+export function findVercelTxtLine(content: string): number | null {
+ const lineIndex = content.split('\n').findIndex((line) => line.includes(verifyPrefix));
+
+ return lineIndex === -1 ? null : lineIndex + 1;
+}
+
+export const vercelFileNameRule: Rule = {
+ id: 'vercelFileName',
+ title: 'Vercel verification file has the wrong name',
+ severity: 1,
+ actionType: 'requestChanges',
+ actionLabel: 'Request Changes',
+
+ // The name is the problem, so the comment goes on the file's first line
+ findLine: () => 1,
+
+ async evaluate(context) {
+ const violations: Violation[] = [];
+
+ for (const file of context.files) {
+ const expected = vercelFileFor(file.path, context.pullRequest.repo);
+
+ if (!isVercelFile(file.path) || expected.toLowerCase() === file.path.toLowerCase()) {
+ continue;
+ }
+
+ violations.push({
+ ruleId: 'vercelFileName',
+ filePath: file.path,
+ reason: `Vercel verification file should be named ${expected}.`
+ });
+ }
+
+ return violations;
+ }
+};
+
+export const vercelTxtRecordRule: Rule = {
+ id: 'vercelTxtRecord',
+ title: 'Vercel TXT record in the domain file',
+ severity: 1,
+ actionType: 'requestChanges',
+ actionLabel: 'Request Changes',
+
+ findLine: (file: DomainFile) => findVercelTxtLine(file.content),
+
+ async evaluate(context) {
+ const violations: Violation[] = [];
+
+ for (const file of context.files) {
+ if (isVercelFile(file.path) || findVercelTxt(file.json).length === 0) {
+ continue;
+ }
+
+ violations.push({
+ ruleId: 'vercelTxtRecord',
+ filePath: file.path,
+ reason:
+ `A Vercel TXT record is in ${file.path}; it belongs in ` +
+ `${vercelFileFor(file.path, context.pullRequest.repo)}.`
+ });
+ }
+
+ return violations;
+ }
+};
diff --git a/src/lib/server/types.ts b/src/lib/server/types.ts
index f7fe02e..c51df52 100644
--- a/src/lib/server/types.ts
+++ b/src/lib/server/types.ts
@@ -2,7 +2,13 @@
* MIT — (c) Doughmination System®
*/
-export type RuleId = 'nsRecords' | 'unsupportedCname' | 'noReplyEmail' | 'vercelLogin';
+export type RuleId =
+ | 'nsRecords'
+ | 'unsupportedCname'
+ | 'noReplyEmail'
+ | 'vercelLogin'
+ | 'vercelFileName'
+ | 'vercelTxtRecord';
export type ActionType = 'closePr' | 'requestChanges' | 'ignore';
diff --git a/src/routes/+layout.server.ts b/src/routes/+layout.server.ts
index 7018e2c..3f55741 100644
--- a/src/routes/+layout.server.ts
+++ b/src/routes/+layout.server.ts
@@ -16,7 +16,7 @@ export const load: LayoutServerLoad = ({ url }) => {
dryRun: getConfig().dryRun,
repos: getConfig().repos,
repoFilter,
- pendingTotal: onLoginPage ? 0 : listOpenFindings(repoFilter).length,
+ pendingTotal: onLoginPage ? 0 : listOpenFindings().length,
showNavigation: !onLoginPage,
canSignOut: isPasswordConfigured()
};
diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelte
index add1682..f48e37e 100644
--- a/src/routes/+layout.svelte
+++ b/src/routes/+layout.svelte
@@ -6,7 +6,6 @@
import '../app.css';
import { page } from '$app/state';
- import { repoLabel } from '#lib/labels.ts';
// Same file the Discord bot uses as its avatar
import favicon from '../../config/avatar.png';
@@ -32,35 +31,6 @@
label: 'Lookup'
}
];
-
- // Same page, with the repository filter set (or cleared for null)
- function filterHref(repo: string | null): string {
- const next = new URL(page.url.href);
-
- if (repo === null) {
- next.searchParams.delete('repo');
- } else {
- next.searchParams.set('repo', repo);
- }
-
- return `${next.pathname}${next.search}`;
- }
-
- // Page links keep the current filter
- const filterQuery = $derived(
- data.repoFilter ? `?repo=${encodeURIComponent(data.repoFilter)}` : ''
- );
-
- const filterOptions = $derived([
- {
- repo: null,
- label: 'All'
- },
- ...data.repos.map((repo) => ({
- repo,
- label: repoLabel(repo)
- }))
- ]);
</script>
<svelte:head>
@@ -73,10 +43,7 @@
<strong>is-a-tracker</strong>
{#each links as link (link.href)}
- <a
- href={`${link.href}${filterQuery}`}
- aria-current={page.url.pathname === link.href ? 'page' : undefined}
- >
+ <a href={link.href} aria-current={page.url.pathname === link.href ? 'page' : undefined}>
{link.label}
{#if link.href === '/pending' && data.pendingTotal > 0}
<span class="count">{data.pendingTotal}</span>
@@ -86,18 +53,6 @@
<span class="spacer"></span>
- <span class="filter" role="group" aria-label="Repository filter">
- {#each filterOptions as option (option.label)}
- <a
- href={filterHref(option.repo)}
- title={option.repo ?? 'Every repository'}
- aria-current={data.repoFilter === option.repo ? 'true' : undefined}
- >
- {option.label}
- </a>
- {/each}
- </span>
-
{#if data.dryRun}
<span class="pill" title="Buttons will not change anything on GitHub">Dry run ON</span>
{/if}
@@ -154,22 +109,4 @@
.spacer {
flex: 1;
}
-
- .filter {
- display: inline-flex;
- border: 1px solid var(--border);
- border-radius: 999px;
- overflow: hidden;
- }
-
- .filter a {
- padding: 0.15rem 0.7rem;
- border-bottom: none;
- font-size: 0.9rem;
- }
-
- .filter a[aria-current='true'] {
- background: var(--accent);
- color: var(--accent-text);
- }
</style>
diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte
index 91a114b..0f77c8d 100644
--- a/src/routes/+page.svelte
+++ b/src/routes/+page.svelte
@@ -4,6 +4,7 @@
<script lang="ts">
import ActionsChart from '#lib/components/ActionsChart.svelte';
+ import RepoFilter from '#lib/components/RepoFilter.svelte';
import { formatTimestamp, repoLabel } from '#lib/labels.ts';
import type { PageProps } from './$types';
@@ -36,6 +37,8 @@
<h1>Overview</h1>
+<RepoFilter repos={data.repos} current={data.repoFilter} />
+
<section class="tiles">
{#each tiles as tile (tile.label)}
<div class="card tile">
diff --git a/src/routes/history/+page.svelte b/src/routes/history/+page.svelte
index ee6f439..8dd4d3a 100644
--- a/src/routes/history/+page.svelte
+++ b/src/routes/history/+page.svelte
@@ -3,6 +3,8 @@
-->
<script lang="ts">
+ import RepoFilter from '#lib/components/RepoFilter.svelte';
+
import {
actionLabels,
formatTimestamp,
@@ -23,6 +25,8 @@
<h1>Moderation history</h1>
+<RepoFilter repos={data.repos} current={data.repoFilter} />
+
<form method="GET" class="formRow card">
<input
type="search"
diff --git a/src/routes/pending/+page.server.ts b/src/routes/pending/+page.server.ts
index 1c1c4e8..e59690d 100644
--- a/src/routes/pending/+page.server.ts
+++ b/src/routes/pending/+page.server.ts
@@ -14,36 +14,49 @@ import { bySeverity, getRule } from '#lib/server/rules/index.ts';
import type { Actions, PageServerLoad } from './$types';
+// One card per PR, most serious first; its buttons act on every pending finding
export const load: PageServerLoad = ({ url }) => {
const openFindings = listOpenFindings(readRepoFilter(url)).sort(bySeverity);
+ const byPullRequest = new Map<string, typeof openFindings>();
- const findings = openFindings.map((finding) => ({
- id: finding.id,
- repo: finding.repo,
- prNumber: finding.prNumber,
- title: finding.title,
- author: finding.author,
- url: finding.url,
- ruleId: finding.ruleId,
- filePath: finding.filePath,
- reason: finding.reason,
- status: finding.status,
- lastOutcome: finding.lastOutcome,
- createdAt: finding.createdAt,
- actionLabel: getRule(finding.ruleId).actionLabel,
- actionType: getRule(finding.ruleId).actionType,
- severity: getRule(finding.ruleId).severity,
- otherRuleIds: openFindings
- .filter(
- (other) =>
- other.repo === finding.repo &&
- other.prNumber === finding.prNumber &&
- other.id !== finding.id
- )
- .map((other) => other.ruleId)
- }));
+ for (const finding of openFindings) {
+ const key = `${finding.repo}#${finding.prNumber}`;
- return { findings };
+ byPullRequest.set(key, [...(byPullRequest.get(key) ?? []), finding]);
+ }
+
+ const pullRequests = [...byPullRequest].map(([key, findings]) => {
+ const [lead] = findings;
+ const pending = findings.filter((finding) => finding.status === 'pending');
+ const closing = pending.find((finding) => getRule(finding.ruleId).actionType === 'closePr');
+ const countNote = pending.length > 1 ? ` (${pending.length})` : '';
+
+ return {
+ key,
+ repo: lead.repo,
+ prNumber: lead.prNumber,
+ title: lead.title,
+ author: lead.author,
+ url: lead.url,
+ actionFindingId: pending[0]?.id ?? null,
+ actionType: closing ? 'closePr' : 'requestChanges',
+ actionLabel: closing
+ ? getRule(closing.ruleId).actionLabel
+ : `${getRule(lead.ruleId).actionLabel}${countNote}`,
+ ignoreLabel: pending.length > 1 ? 'Ignore all' : 'Ignore',
+ lastOutcome: lead.lastOutcome,
+ violations: findings.map((finding) => ({
+ id: finding.id,
+ ruleId: finding.ruleId,
+ severity: getRule(finding.ruleId).severity,
+ filePath: finding.filePath,
+ reason: finding.reason,
+ createdAt: finding.createdAt
+ }))
+ };
+ });
+
+ return { pullRequests };
};
// Same pipeline as the Discord buttons: claim, revalidate, act, audit
diff --git a/src/routes/pending/+page.svelte b/src/routes/pending/+page.svelte
index 34b59b6..f7087b8 100644
--- a/src/routes/pending/+page.svelte
+++ b/src/routes/pending/+page.svelte
@@ -4,6 +4,7 @@
<script lang="ts">
import { enhance } from '$app/forms';
+ import RepoFilter from '#lib/components/RepoFilter.svelte';
import { formatTimestamp, labelFor, repoLabel, ruleLabels, severityLabels } from '#lib/labels.ts';
import type { PageProps } from './$types';
@@ -30,6 +31,8 @@
<h1>Pending reviews</h1>
+<RepoFilter repos={data.repos} current={data.repoFilter} />
+
{#if form?.outcome}
<p class="notice {form.outcome.status}" role="status">
{form.outcome.summary}
@@ -39,65 +42,66 @@
</p>
{/if}
-{#if data.findings.length === 0}
+{#if data.pullRequests.length === 0}
<p class="card muted">Nothing is waiting for a decision.</p>
{/if}
-{#each data.findings as finding (finding.id)}
+{#each data.pullRequests as pullRequest (pullRequest.key)}
<article class="card">
<h2>
- <a href={finding.url} target="_blank" rel="noreferrer">
- {repoLabel(finding.repo)} #{finding.prNumber}
+ <a href={pullRequest.url} target="_blank" rel="noreferrer">
+ {repoLabel(pullRequest.repo)} #{pullRequest.prNumber}
</a>
- {finding.title}
+ {pullRequest.title}
</h2>
- <dl>
- <dt>Violation</dt>
- <dd>{labelFor(ruleLabels, finding.ruleId)}</dd>
-
- <dt>Severity</dt>
- <dd>{severityLabels[finding.severity]}</dd>
-
- {#if finding.otherRuleIds.length > 0}
- <dt>Also on this PR</dt>
- <dd>{finding.otherRuleIds.map((ruleId) => labelFor(ruleLabels, ruleId)).join(', ')}</dd>
- {/if}
-
- <dt>Author</dt>
- <dd>{finding.author}</dd>
-
- <dt>File</dt>
- <dd><code>{finding.filePath}</code></dd>
-
- <dt>Reason</dt>
- <dd>{finding.reason}</dd>
-
- <dt>Detected</dt>
- <dd>{formatTimestamp(finding.createdAt)}</dd>
-
- {#if finding.lastOutcome}
- <dt>Last result</dt>
- <dd>{finding.lastOutcome}</dd>
- {/if}
- </dl>
-
- <div class="formRow">
- <form method="POST" action="?/approve" use:enhance={trackBusy(finding.id)}>
- <input type="hidden" name="findingId" value={finding.id} />
- <button
- class={finding.actionType === 'closePr' ? 'danger' : 'primary'}
- disabled={busyFindingId !== null}
- >
- {busyFindingId === finding.id ? 'Working…' : finding.actionLabel}
- </button>
- </form>
-
- <form method="POST" action="?/ignore" use:enhance={trackBusy(finding.id)}>
- <input type="hidden" name="findingId" value={finding.id} />
- <button disabled={busyFindingId !== null}>Ignore</button>
- </form>
- </div>
+ <p class="muted">By {pullRequest.author}</p>
+
+ {#each pullRequest.violations as violation (violation.id)}
+ <dl>
+ <dt>Violation</dt>
+ <dd>
+ {labelFor(ruleLabels, violation.ruleId)}
+ <span class="muted">({severityLabels[violation.severity]})</span>
+ </dd>
+
+ <dt>File</dt>
+ <dd><code>{violation.filePath}</code></dd>
+
+ <dt>Reason</dt>
+ <dd>{violation.reason}</dd>
+
+ <dt>Detected</dt>
+ <dd>{formatTimestamp(violation.createdAt)}</dd>
+ </dl>
+ {/each}
+
+ {#if pullRequest.lastOutcome}
+ <p class="muted">Last result: {pullRequest.lastOutcome}</p>
+ {/if}
+
+ {#if pullRequest.actionFindingId !== null}
+ {@const findingId = pullRequest.actionFindingId}
+
+ <div class="formRow">
+ <form method="POST" action="?/approve" use:enhance={trackBusy(findingId)}>
+ <input type="hidden" name="findingId" value={findingId} />
+ <button
+ class={pullRequest.actionType === 'closePr' ? 'danger' : 'primary'}
+ disabled={busyFindingId !== null}
+ >
+ {busyFindingId === findingId ? 'Working…' : pullRequest.actionLabel}
+ </button>
+ </form>
+
+ <form method="POST" action="?/ignore" use:enhance={trackBusy(findingId)}>
+ <input type="hidden" name="findingId" value={findingId} />
+ <button disabled={busyFindingId !== null}>{pullRequest.ignoreLabel}</button>
+ </form>
+ </div>
+ {:else}
+ <p class="muted">Working…</p>
+ {/if}
</article>
{/each}
@@ -107,6 +111,8 @@
grid-template-columns: 7rem 1fr;
gap: 0.25rem 1rem;
margin: 0 0 1rem;
+ padding-top: 0.75rem;
+ border-top: 1px solid var(--border);
}
dt {