Dough Git

commit

Meow

commit
20cacadc67732aa93f966e290d95d85af7b5f849
author
Clove Twilight <[email protected]>
date
2026-11-12 18:53

diff --git a/.env.example b/.env.example
index 221dad9..96621d9 100644
--- a/.env.example
+++ b/.env.example
@@ -2,7 +2,8 @@
 # MIT — (c) Doughmination System®
 # Copy to .env and fill in. In production it lives next to the build (see deploy/run).
 
-# GitHub token for your own account, with pull request read and write on the repository
+# Classic personal access token for your own account, with only the public_repo scope ticked.
+# Create one at https://github.com/settings/tokens (Tokens (classic))
 GITHUB_TOKEN=
 
 GITHUB_REPO_OWNER=is-a-dev
diff --git a/README.md b/README.md
index b220269..d632fd4 100644
--- a/README.md
+++ b/README.md
@@ -21,9 +21,18 @@ One Deno process runs the scanner, the Discord bot, and the SvelteKit dashboard.
 
 ### GitHub token
 
-- Needs **Pull requests: Read and write** on `is-a-dev/register`.
-- A fine-grained token only works if the `is-a-dev` organisation lets you select the repository.
-  If it does not appear in the list, use a classic token with the `public_repo` scope instead.
+Use a **classic** personal access token. Fine-grained tokens cannot select `is-a-dev/register`
+unless the organisation allows it.
+
+1. Open <https://github.com/settings/tokens> and choose **Tokens (classic)**.
+2. Generate a new token and tick only **`public_repo`**.
+3. Paste it into `GITHUB_TOKEN`.
+
+- A classic token reaches every public repository your account can write to. The tool only
+  ever calls the repository set in `GITHUB_REPO_OWNER` and `GITHUB_REPO_NAME`.
+- At startup the tool checks the token and logs its account, its scopes, and whether that
+  account may close pull requests on the repository.
+- If the organisation enforces single sign-on, authorise the token under **Configure SSO**.
 
 ### Discord bot
 
diff --git a/src/lib/server/github/client.ts b/src/lib/server/github/client.ts
index 99ad06b..29c1a47 100644
--- a/src/lib/server/github/client.ts
+++ b/src/lib/server/github/client.ts
@@ -54,6 +54,21 @@ export interface GitHubResponse<Data> {
 	data: Data;
 	etag: string | null;
 	notModified: boolean;
+	// Scopes of a classic token; null when GitHub sends none (fine-grained or no token)
+	scopes: string[] | null;
+}
+
+function readScopes(headers: Headers): string[] | null {
+	const header = headers.get('x-oauth-scopes');
+
+	if (header === null) {
+		return null;
+	}
+
+	return header
+		.split(',')
+		.map((scope) => scope.trim())
+		.filter((scope) => scope !== '');
 }
 
 function assertWithinRateLimit(resource: string, priority: boolean): void {
@@ -159,7 +174,8 @@ async function sendOnce<Data>(request: GitHubRequest): Promise<GitHubResponse<Da
 			status: 304,
 			data: undefined as Data,
 			etag,
-			notModified: true
+			notModified: true,
+			scopes: readScopes(response.headers)
 		};
 	}
 
@@ -175,6 +191,13 @@ async function sendOnce<Data>(request: GitHubRequest): Promise<GitHubResponse<Da
 		throw new RateLimitError(resumeAt);
 	}
 
+	if (response.status === 403 && response.headers.has('x-github-sso')) {
+		throw new GitHubError(
+			403,
+			'The organisation uses single sign-on: authorise this token for it under "Configure SSO" in your GitHub token settings.'
+		);
+	}
+
 	if (!response.ok) {
 		throw new GitHubError(response.status, await readErrorMessage(response));
 	}
@@ -187,7 +210,8 @@ async function sendOnce<Data>(request: GitHubRequest): Promise<GitHubResponse<Da
 		status: response.status,
 		data: data as Data,
 		etag,
-		notModified: false
+		notModified: false,
+		scopes: readScopes(response.headers)
 	};
 }
 
diff --git a/src/lib/server/github/token.test.ts b/src/lib/server/github/token.test.ts
new file mode 100644
index 0000000..1c43b0d
--- /dev/null
+++ b/src/lib/server/github/token.test.ts
@@ -0,0 +1,73 @@
+/* src/lib/server/github/token.test.ts
+ * MIT — (c) Doughmination System®
+ */
+
+import assert from 'node:assert/strict';
+import { describe, test } from 'node:test';
+
+import { describeToken } from './token.ts';
+
+describe('describeToken', () => {
+	test('accepts a classic token with public_repo', () => {
+		const report = describeToken({
+			login: 'clove',
+			scopes: ['public_repo'],
+			canTriage: true
+		});
+
+		assert.equal(report.level, 'info');
+		assert.equal(report.lines.length, 1);
+	});
+
+	test('rejects a classic token without a write scope', () => {
+		const report = describeToken({
+			login: 'clove',
+			scopes: ['read:user'],
+			canTriage: true
+		});
+
+		assert.equal(report.level, 'error');
+		assert.ok(report.lines[0].includes('public_repo'));
+	});
+
+	test('rejects a classic token with no scopes at all', () => {
+		const report = describeToken({
+			login: 'clove',
+			scopes: [],
+			canTriage: true
+		});
+
+		assert.equal(report.level, 'error');
+	});
+
+	test('notes that the repo scope is broader than needed', () => {
+		const report = describeToken({
+			login: 'clove',
+			scopes: ['repo'],
+			canTriage: true
+		});
+
+		assert.equal(report.level, 'info');
+		assert.equal(report.lines.length, 2);
+	});
+
+	test('warns when the account cannot close pull requests', () => {
+		const report = describeToken({
+			login: 'clove',
+			scopes: ['public_repo'],
+			canTriage: false
+		});
+
+		assert.equal(report.level, 'warn');
+	});
+
+	test('a fine-grained token has no scope list to judge', () => {
+		const report = describeToken({
+			login: 'clove',
+			scopes: null,
+			canTriage: true
+		});
+
+		assert.equal(report.level, 'info');
+	});
+});
diff --git a/src/lib/server/github/token.ts b/src/lib/server/github/token.ts
new file mode 100644
index 0000000..d6d136c
--- /dev/null
+++ b/src/lib/server/github/token.ts
@@ -0,0 +1,97 @@
+/* src/lib/server/github/token.ts
+ * MIT — (c) Doughmination System®
+ */
+
+import { getConfig, getRepoPath } from '../config.ts';
+import { createLogger, describeError } from '../logger.ts';
+import { githubRequest } from './client.ts';
+
+const logger = createLogger('token');
+
+// Either scope lets a classic token comment on, review and close PRs in a public repository
+const writeScopes = ['public_repo', 'repo'];
+
+interface RepositoryAccess {
+	permissions?: {
+		triage?: boolean;
+		push?: boolean;
+	};
+}
+
+export interface TokenReport {
+	level: 'info' | 'warn' | 'error';
+	lines: string[];
+}
+
+// Pure, so it can be tested: turns what GitHub said about the token into log lines
+export function describeToken(options: {
+	login: string;
+	scopes: string[] | null;
+	canTriage: boolean;
+}): TokenReport {
+	const { login, scopes, canTriage } = options;
+	const lines: string[] = [];
+	let level: TokenReport['level'] = 'info';
+
+	if (scopes === null) {
+		lines.push(`Signed in as ${login} with a fine-grained token (no scope list to check).`);
+	} else if (scopes.some((scope) => writeScopes.includes(scope))) {
+		lines.push(`Signed in as ${login} with a classic token (scopes: ${scopes.join(', ')}).`);
+	} else {
+		level = 'error';
+		lines.push(
+			`Signed in as ${login}, but the classic token lacks the public_repo scope ` +
+				`(scopes: ${scopes.join(', ') || 'none'}). Actions will fail until it is added.`
+		);
+	}
+
+	if (scopes !== null && scopes.includes('repo')) {
+		lines.push('The repo scope also covers private repositories; public_repo is enough.');
+	}
+
+	if (!canTriage) {
+		level = level === 'error' ? 'error' : 'warn';
+		lines.push(
+			`${login} has no triage or write access to the repository, so closing PRs will fail.`
+		);
+	}
+
+	return {
+		level,
+		lines
+	};
+}
+
+// Runs once at startup so a bad token is reported then, not at the first button press
+export async function checkToken(): Promise<void> {
+	if (!getConfig().githubToken) {
+		logger.warn('GITHUB_TOKEN missing; reads are limited to 60 an hour and actions will fail');
+		return;
+	}
+
+	try {
+		const user = await githubRequest<{ login: string }>({
+			path: '/user',
+			priority: true
+		});
+
+		const repository = await githubRequest<RepositoryAccess>({
+			path: getRepoPath(),
+			priority: true
+		});
+
+		const permissions = repository.data.permissions;
+
+		const report = describeToken({
+			login: user.data.login,
+			scopes: user.scopes,
+			canTriage: Boolean(permissions?.triage || permissions?.push)
+		});
+
+		for (const line of report.lines) {
+			logger[report.level](line);
+		}
+	} catch (error) {
+		logger.error(`Could not verify GITHUB_TOKEN: ${describeError(error)}`);
+	}
+}
diff --git a/src/lib/server/runtime.ts b/src/lib/server/runtime.ts
index 9e0e79a..cbf680d 100644
--- a/src/lib/server/runtime.ts
+++ b/src/lib/server/runtime.ts
@@ -6,6 +6,7 @@ import { getConfig } from './config.ts';
 import { getDatabase } from './db/database.ts';
 import { flushNotifications, startDiscordBot, stopDiscordBot } from './discord/bot.ts';
 import { removeFindingListeners } from './events.ts';
+import { checkToken } from './github/token.ts';
 import { createLogger } from './logger.ts';
 import { startScanner, stopScanner } from './moderation/scanner.ts';
 
@@ -37,9 +38,8 @@ export async function startServices(): Promise<void> {
 
 	logger.info(config.dryRun ? 'Dry run is ON: GitHub will not be changed' : 'Dry run is OFF');
 
-	if (!config.githubToken) {
-		logger.warn('GITHUB_TOKEN missing; reads are limited to 60 an hour and actions will fail');
-	}
+	// Not awaited: a slow or failing GitHub must not delay the dashboard or the bot
+	void checkToken();
 
 	await startDiscordBot().catch((error) => logger.error('Discord failed to start', error));