commit
Separate GitHub read and maintainer credentials
Use the read account for scans and lookups, isolate credential quotas and backoff, and retain legacy GITHUB_TOKEN compatibility. Keep moderation writes and their safety checks on the maintainer account. Co-Authored-By: Sandrone <[email protected]>
diff --git a/.env.example b/.env.example
index ee77cd7..c8b4b74 100644
--- a/.env.example
+++ b/.env.example
@@ -2,9 +2,15 @@
# MIT — (c) Doughmination System®
# Copy to .env and fill in. In production it lives next to the build (see deploy/run).
-# 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=
+# Alt account: classic token with no scopes for reading public repositories.
+READ_GITHUB_TOKEN=
+
+# Your maintainer account: classic token with only public_repo for moderation actions.
+# Create tokens at https://github.com/settings/tokens (Tokens (classic)).
+MAINTAINER_GITHUB_TOKEN=
+
+# Existing GITHUB_TOKEN settings still work as the fallback maintainer token.
+# If READ_GITHUB_TOKEN is empty, reads use the maintainer token too.
# Repositories to track, comma separated owner/name
GITHUB_REPOS=is-a-dev/register,free-domains/is-a.bot
@@ -25,7 +31,7 @@ DASHBOARD_PASSWORD=
# The public address of the dashboard, needed for form posts in production
ORIGIN=http://localhost:3101
-# Optional tuning
+# Optional tuning: 30 is the minimum interval; rate limits still pause scanning.
POLL_INTERVAL_SECONDS=120
SCANNER_ENABLED=true
DATABASE_PATH=data/tracker.sqlite
diff --git a/README.md b/README.md
index 2172682..e297118 100644
--- a/README.md
+++ b/README.md
@@ -9,8 +9,8 @@ repository picker.
Overview (`/`), History, and Lookup are public. Overview shows moderation totals,
the 30-day chart, pending finding counts, and scanner health. Pending reviews and
-moderation actions require the existing password login. Public lookups respect the
-GitHub quota reserve held back for moderation. Raw scanner errors are only included for signed-in moderators.
+moderation actions require the existing password login. Public lookups use the read token; moderation actions and their safety checks use
+the maintainer token. Raw scanner errors are only included for signed-in moderators.
Signing in opens Pending; signing out returns to the public overview.
Without `DASHBOARD_PASSWORD`, moderation stays unavailable in production.
@@ -38,25 +38,42 @@ One Deno process runs the scanner, the Discord bot, and the SvelteKit dashboard.
## Setup
1. Copy the example settings: `cp .env.example .env`
-2. Fill in `GITHUB_TOKEN`, `DISCORD_BOT_TOKEN`, `DISCORD_USER_ID` and `DASHBOARD_PASSWORD`
+2. Fill in `READ_GITHUB_TOKEN`, `MAINTAINER_GITHUB_TOKEN`, the Discord settings and `DASHBOARD_PASSWORD`
3. Install: `deno install`
4. Develop: `deno task dev`
5. Or run for real: `deno task build`, then `deno task start`
-### GitHub token
+### GitHub tokens
-Use a **classic** personal access token. Fine-grained tokens cannot select the tracked
-repositories unless their organisations allow it.
+Use two **classic** personal access tokens from <https://github.com/settings/tokens>:
-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`.
+- `READ_GITHUB_TOKEN`: your alt account's token, with **no scopes** for public repository reads.
+ Scanning and Lookup use this token, including lookups made while signed in.
+- `MAINTAINER_GITHUB_TOKEN`: your maintainer account's token, with only **`public_repo`**.
+ Comments, reviews, closures, dismissals, and action revalidation use this account.
+ The review author identity is always checked using this token.
-- A classic token reaches every public repository your account can write to. The tool only
- ever calls the repositories set in `GITHUB_REPOS`.
-- At startup the tool checks the token and logs its account, its scopes, and whether that
- account may close pull requests on each repository.
-- If the organisation enforces single sign-on, authorise the token under **Configure SSO**.
+Keep both in `.env`, never in source or a commit. The alt needs no repository write access.
+At startup, the tool logs each token's account and checks the maintainer's permissions on
+all configured repositories. If an organisation uses SSO, authorise the maintainer token
+under **Configure SSO**.
+
+Existing `GITHUB_TOKEN` settings remain a fallback for `MAINTAINER_GITHUB_TOKEN`.
+If `READ_GITHUB_TOKEN` is empty, reads use that same maintainer credential and retain the
+existing quota reserve. A read-only setup can scan without a maintainer token, but cannot
+perform moderation actions. An exhausted or invalid read token never falls back to the
+maintainer token.
+
+Distinct accounts have their own primary quota; multiple tokens for the same account
+share that account's quota. GitHub normally allows 5,000 authenticated REST requests per
+hour per account, with tighter search and secondary limits. The tool tracks response
+headers and pauses when throttled; it does not rotate tokens to evade a limit.
+See [GitHub's rate limits](https://docs.github.com/en/rest/using-the-rest-api/rate-limits-for-the-rest-api).
+
+To check more often, set `POLL_INTERVAL_SECONDS=30` in `.env` and restart. The default
+remains 120 seconds, and the minimum is 30. Each cycle waits this interval after its work
+finishes; rate-limit backoff can extend the wait. Faster polling does not increase GitHub's
+quota, and large scans or frequent public lookups can still exhaust the read account.
### Discord bot
@@ -121,7 +138,8 @@ the other open violations on the same PR.
- A finding can only be claimed once, so two clicks never post twice.
- Writes to GitHub are never retried automatically.
- Statistics count successful actions only. Every attempt lands in the audit log.
-- The scanner keeps a reserve of the GitHub rate limit free for your approved actions.
+- Scan and lookup traffic uses the read credential; moderation uses the maintainer credential.
+- When both roles share one credential, scanning preserves a reserve for approved actions.
## Adding a rule
diff --git a/src/lib/server/config.test.ts b/src/lib/server/config.test.ts
new file mode 100644
index 0000000..4db07e6
--- /dev/null
+++ b/src/lib/server/config.test.ts
@@ -0,0 +1,64 @@
+/* src/lib/server/config.test.ts */
+
+import assert from 'node:assert/strict';
+import { test } from 'node:test';
+
+const tokenVariables = ['GITHUB_TOKEN', 'READ_GITHUB_TOKEN', 'MAINTAINER_GITHUB_TOKEN'];
+
+test('GitHub token configuration supports split credentials and legacy deployments', async () => {
+ const previous = tokenVariables.map((name) => process.env[name]);
+ const cases = [
+ {
+ values: ['legacy-fixture', undefined, undefined],
+ reader: 'legacy-fixture',
+ maintainer: 'legacy-fixture'
+ },
+ {
+ values: ['legacy-fixture', 'reader-fixture', 'maintainer-fixture'],
+ reader: 'reader-fixture',
+ maintainer: 'maintainer-fixture'
+ },
+ {
+ values: [undefined, undefined, 'maintainer-fixture'],
+ reader: 'maintainer-fixture',
+ maintainer: 'maintainer-fixture'
+ },
+ {
+ values: [undefined, 'reader-fixture', undefined],
+ reader: 'reader-fixture',
+ maintainer: ''
+ }
+ ];
+
+ try {
+ for (const [index, fixture] of cases.entries()) {
+ for (const [position, name] of tokenVariables.entries()) {
+ const value = fixture.values[position];
+
+ if (value === undefined) {
+ delete process.env[name];
+ } else {
+ process.env[name] = value;
+ }
+ }
+
+ // A fresh module instance gives each fixture its own cached configuration.
+ const moduleUrl = new URL(`./config.ts?token-fixture=${index}`, import.meta.url);
+ const { getConfig } = await import(moduleUrl.href);
+ const config = getConfig();
+
+ assert.equal(config.readGithubToken, fixture.reader);
+ assert.equal(config.maintainerGithubToken, fixture.maintainer);
+ }
+ } finally {
+ for (const [index, name] of tokenVariables.entries()) {
+ const value = previous[index];
+
+ if (value === undefined) {
+ delete process.env[name];
+ } else {
+ process.env[name] = value;
+ }
+ }
+ }
+});
diff --git a/src/lib/server/config.ts b/src/lib/server/config.ts
index 8f6b0cb..a2f386a 100644
--- a/src/lib/server/config.ts
+++ b/src/lib/server/config.ts
@@ -3,7 +3,8 @@
*/
export interface AppConfig {
- githubToken: string;
+ readGithubToken: string;
+ maintainerGithubToken: string;
// Each entry is owner/name
repos: string[];
discordToken: string;
@@ -47,8 +48,15 @@ function readFlag(name: string, fallback: boolean): boolean {
let cachedConfig: AppConfig | undefined;
export function getConfig(): AppConfig {
- cachedConfig ??= {
- githubToken: readText('GITHUB_TOKEN'),
+ if (cachedConfig) {
+ return cachedConfig;
+ }
+
+ const maintainerGithubToken = readText('MAINTAINER_GITHUB_TOKEN', readText('GITHUB_TOKEN'));
+
+ cachedConfig = {
+ readGithubToken: readText('READ_GITHUB_TOKEN', maintainerGithubToken),
+ maintainerGithubToken,
repos: readText('GITHUB_REPOS', 'is-a-dev/register,free-domains/is-a.bot')
.split(',')
.map((repo) => repo.trim())
diff --git a/src/lib/server/github/client.test.ts b/src/lib/server/github/client.test.ts
new file mode 100644
index 0000000..d3a00ee
--- /dev/null
+++ b/src/lib/server/github/client.test.ts
@@ -0,0 +1,253 @@
+/* src/lib/server/github/client.test.ts */
+
+import assert from 'node:assert/strict';
+import { afterEach, beforeEach, describe, test } from 'node:test';
+
+import { getConfig } from '../config.ts';
+import { GitHubError, RateLimitError, getRateLimitSnapshot, githubRequest } from './client.ts';
+import {
+ closePullRequest,
+ createChangesRequestedReview,
+ createIssueComment,
+ dismissReview,
+ getAuthenticatedLogin,
+ getPullRequest,
+ listPullRequests,
+ listReviews
+} from './pullRequests.ts';
+
+const originalFetch = globalThis.fetch;
+const config = getConfig();
+let sequence = 0;
+let calls: { path: string; method: string; authorization: string | null }[];
+
+function responseWithQuota(remaining: number, resource = 'core'): Response {
+ return Response.json(
+ {},
+ {
+ headers: {
+ 'x-ratelimit-limit': '5000',
+ 'x-ratelimit-remaining': String(remaining),
+ 'x-ratelimit-reset': String(Math.floor(Date.now() / 1000) + 3600),
+ 'x-ratelimit-resource': resource
+ }
+ }
+ );
+}
+
+describe('GitHub credentials and quotas', () => {
+ beforeEach(() => {
+ sequence += 1;
+ config.readGithubToken = `reader-fixture-${sequence}`;
+ config.maintainerGithubToken = `maintainer-fixture-${sequence}`;
+ calls = [];
+
+ globalThis.fetch = async (input, options) => {
+ calls.push({
+ path: new URL(String(input)).pathname,
+ method: options?.method ?? 'GET',
+ authorization: new Headers(options?.headers).get('Authorization')
+ });
+
+ return responseWithQuota(4999);
+ };
+ });
+
+ afterEach(() => {
+ globalThis.fetch = originalFetch;
+ });
+
+ test('ordinary reads use the reader, while action safety checks use the maintainer', async () => {
+ await githubRequest({ path: '/repos/example/repo/pulls' });
+ await githubRequest({
+ path: '/repos/example/repo/pulls/1',
+ priority: true
+ });
+
+ assert.deepEqual(
+ calls.map((call) => call.authorization),
+ [`Bearer ${config.readGithubToken}`, `Bearer ${config.maintainerGithubToken}`]
+ );
+ });
+
+ test('every write uses the maintainer even without the priority flag', async () => {
+ for (const method of ['POST', 'PATCH', 'PUT'] as const) {
+ await githubRequest({
+ method,
+ path: '/repos/example/repo/pulls/1'
+ });
+ }
+
+ assert.ok(
+ calls.every((call) => call.authorization === `Bearer ${config.maintainerGithubToken}`)
+ );
+ });
+
+ test('an exhausted reader neither blocks actions nor falls back to the maintainer', async () => {
+ globalThis.fetch = async () => responseWithQuota(0);
+ await githubRequest({ path: '/repos/example/repo/pulls' });
+ await assert.rejects(githubRequest({ path: '/repos/example/repo/pulls' }), RateLimitError);
+ await githubRequest({
+ method: 'PATCH',
+ path: '/repos/example/repo/pulls/1'
+ });
+
+ const snapshot = getRateLimitSnapshot();
+
+ assert.equal(snapshot.read.core.remaining, 0);
+ assert.equal(snapshot.maintainer.core.remaining, 0);
+ assert.equal(JSON.stringify(snapshot).includes(config.readGithubToken), false);
+ });
+
+ test('the reader can use its own budget below the old shared-token reserve', async () => {
+ globalThis.fetch = async () => responseWithQuota(1);
+ await githubRequest({ path: '/repos/example/repo/pulls' });
+ await githubRequest({ path: '/repos/example/repo/pulls' });
+ });
+
+ test('one shared credential retains the moderation reserve', async () => {
+ config.readGithubToken = config.maintainerGithubToken;
+ globalThis.fetch = async () => responseWithQuota(100);
+ await githubRequest({ path: '/repos/example/repo/pulls' });
+ await assert.rejects(githubRequest({ path: '/repos/example/repo/pulls' }), RateLimitError);
+ await githubRequest({
+ path: '/repos/example/repo/pulls/1',
+ priority: true
+ });
+ });
+
+ test('exhausted search quota does not block core reads', async () => {
+ globalThis.fetch = async () => responseWithQuota(0, 'search');
+ await githubRequest({ path: '/search/issues' });
+ await assert.rejects(githubRequest({ path: '/search/issues' }), RateLimitError);
+ await githubRequest({ path: '/repos/example/repo/pulls' });
+ });
+
+ test('secondary throttles without headers back off without retrying or switching tokens', async () => {
+ let fetchCount = 0;
+
+ globalThis.fetch = async () => {
+ fetchCount += 1;
+ return Response.json(
+ { message: 'You have exceeded a secondary rate limit.' },
+ { status: 403 }
+ );
+ };
+
+ const startedAt = Date.now();
+
+ await assert.rejects(githubRequest({ path: '/repos/example/repo/pulls' }), (error) => {
+ assert.ok(error instanceof RateLimitError);
+ assert.ok(error.resumeAt >= startedAt + 60_000);
+ return true;
+ });
+ await assert.rejects(githubRequest({ path: '/search/issues' }), RateLimitError);
+ assert.equal(fetchCount, 1);
+
+ globalThis.fetch = async () => responseWithQuota(4999);
+ await githubRequest({
+ method: 'PATCH',
+ path: '/repos/example/repo/pulls/1'
+ });
+ });
+
+ test('Retry-After applies to the selected credential', async () => {
+ globalThis.fetch = async () =>
+ Response.json(
+ {},
+ {
+ status: 429,
+ headers: { 'retry-after': '120' }
+ }
+ );
+
+ const startedAt = Date.now();
+
+ await assert.rejects(githubRequest({ path: '/repos/example/repo/pulls' }), (error) => {
+ assert.ok(error instanceof RateLimitError);
+ assert.ok(error.resumeAt >= startedAt + 120_000);
+ return true;
+ });
+ });
+
+ test('read-only configuration cannot send a write using the alt token', async () => {
+ config.maintainerGithubToken = '';
+
+ await assert.rejects(
+ githubRequest({
+ method: 'POST',
+ path: '/repos/example/repo/issues/1/comments'
+ }),
+ GitHubError
+ );
+ assert.equal(calls.length, 0);
+ });
+
+ test('writes are never retried after a server error', async () => {
+ let fetchCount = 0;
+
+ globalThis.fetch = async () => {
+ fetchCount += 1;
+ return Response.json({ message: 'unavailable' }, { status: 503 });
+ };
+
+ await assert.rejects(
+ githubRequest({
+ method: 'POST',
+ path: '/repos/example/repo/issues/1/comments'
+ }),
+ GitHubError
+ );
+ assert.equal(fetchCount, 1);
+ });
+
+ test('the maintainer identity and moderation helpers use the maintainer credential', async () => {
+ globalThis.fetch = async (input, options) => {
+ assert.equal(
+ new Headers(options?.headers).get('Authorization'),
+ `Bearer ${config.maintainerGithubToken}`
+ );
+
+ return Response.json({ login: 'maintainer-fixture' });
+ };
+
+ assert.equal(await getAuthenticatedLogin(), 'maintainer-fixture');
+ await createIssueComment('example/repo', 1, 'comment');
+ await closePullRequest('example/repo', 1);
+ await listReviews('example/repo', 1);
+ await dismissReview('example/repo', 1, 2, 'fixed');
+ await createChangesRequestedReview({
+ repo: 'example/repo',
+ number: 1,
+ commitId: 'fixture-sha',
+ body: 'review',
+ comments: []
+ });
+ });
+
+ test('scanner and lookup pull request helpers use the read credential', async () => {
+ globalThis.fetch = async (input, options) => {
+ assert.equal(
+ new Headers(options?.headers).get('Authorization'),
+ `Bearer ${config.readGithubToken}`
+ );
+
+ const pullRequest = {
+ number: 1,
+ title: 'Fixture',
+ head: { sha: 'fixture-sha' }
+ };
+
+ return Response.json(
+ new URL(String(input)).pathname.endsWith('/pulls') ? [pullRequest] : pullRequest
+ );
+ };
+
+ await listPullRequests({
+ repo: 'example/repo',
+ state: 'open',
+ page: 1
+ });
+ await getPullRequest('example/repo', 1);
+ });
+});
diff --git a/src/lib/server/github/client.ts b/src/lib/server/github/client.ts
index 1a0ce0e..96169d3 100644
--- a/src/lib/server/github/client.ts
+++ b/src/lib/server/github/client.ts
@@ -34,9 +34,27 @@ interface RateBucket {
resetAt: number;
}
-const rateBuckets = new Map<string, RateBucket>();
+interface RateState {
+ buckets: Map<string, RateBucket>;
+ blockedUntil: number;
+}
+
+// Key by credential so the single-token fallback shares its budget and cooldown.
+const rateStates = new Map<string, RateState>();
+
+function getRateState(token: string): RateState {
+ let state = rateStates.get(token);
+
+ if (!state) {
+ state = {
+ buckets: new Map(),
+ blockedUntil: 0
+ };
+ rateStates.set(token, state);
+ }
-let blockedUntil = 0;
+ return state;
+}
export interface GitHubRequest {
method?: 'GET' | 'POST' | 'PATCH' | 'PUT';
@@ -45,7 +63,7 @@ export interface GitHubRequest {
body?: unknown;
accept?: string;
etag?: string | null;
- // Moderator-approved actions may spend the reserve kept back from the scanner
+ // Actions and their safety checks use the maintainer token and its reserved quota
priority?: boolean;
}
@@ -71,20 +89,24 @@ function readScopes(headers: Headers): string[] | null {
.filter((scope) => scope !== '');
}
-function assertWithinRateLimit(resource: string, priority: boolean): void {
+function assertWithinRateLimit(state: RateState, resource: string, priority: boolean): void {
const now = Date.now();
- if (now < blockedUntil) {
- throw new RateLimitError(blockedUntil);
+ if (now < state.blockedUntil) {
+ throw new RateLimitError(state.blockedUntil);
}
- const bucket = rateBuckets.get(resource);
+ const bucket = state.buckets.get(resource);
if (!bucket || now >= bucket.resetAt) {
return;
}
- const scannerReserve = Math.min(getConfig().rateLimitReserve, Math.floor(bucket.limit * 0.1));
+ const config = getConfig();
+ const sharedToken = config.readGithubToken === config.maintainerGithubToken;
+ const scannerReserve = sharedToken
+ ? Math.min(config.rateLimitReserve, Math.floor(bucket.limit * 0.1))
+ : 0;
const floor = priority ? 0 : scannerReserve;
if (bucket.remaining <= floor) {
@@ -92,7 +114,7 @@ function assertWithinRateLimit(resource: string, priority: boolean): void {
}
}
-function recordRateLimit(headers: Headers, fallbackResource: string): void {
+function recordRateLimit(state: RateState, headers: Headers, fallbackResource: string): void {
const remaining = headers.get('x-ratelimit-remaining');
const reset = headers.get('x-ratelimit-reset');
@@ -100,7 +122,7 @@ function recordRateLimit(headers: Headers, fallbackResource: string): void {
return;
}
- rateBuckets.set(headers.get('x-ratelimit-resource') ?? fallbackResource, {
+ state.buckets.set(headers.get('x-ratelimit-resource') ?? fallbackResource, {
limit: Number(headers.get('x-ratelimit-limit') ?? 0),
remaining: Number(remaining),
resetAt: Number(reset) * 1000
@@ -117,17 +139,15 @@ function buildUrl(request: GitHubRequest): string {
return url.toString();
}
-function buildHeaders(request: GitHubRequest): Headers {
+function buildHeaders(request: GitHubRequest, token: string): Headers {
const headers = new Headers({
Accept: request.accept ?? 'application/vnd.github+json',
'User-Agent': 'isATracker',
'X-GitHub-Api-Version': '2022-11-28'
});
- const { githubToken } = getConfig();
-
- if (githubToken) {
- headers.set('Authorization', `Bearer ${githubToken}`);
+ if (token) {
+ headers.set('Authorization', `Bearer ${token}`);
}
if (request.etag) {
@@ -156,16 +176,27 @@ async function readErrorMessage(response: Response): Promise<string> {
async function sendOnce<Data>(request: GitHubRequest): Promise<GitHubResponse<Data>> {
const resource = request.path.startsWith('/search') ? 'search' : 'core';
- assertWithinRateLimit(resource, request.priority ?? false);
+ const config = getConfig();
+ const isWrite = (request.method ?? 'GET') !== 'GET';
+ const maintainer = isWrite || request.priority === true;
+ const token = maintainer ? config.maintainerGithubToken : config.readGithubToken;
+
+ if (maintainer && !token) {
+ throw new GitHubError(401, 'Set MAINTAINER_GITHUB_TOKEN to perform moderation actions.');
+ }
+
+ const state = getRateState(token);
+
+ assertWithinRateLimit(state, resource, maintainer);
const response = await fetch(buildUrl(request), {
method: request.method ?? 'GET',
- headers: buildHeaders(request),
+ headers: buildHeaders(request, token),
body: request.body === undefined ? undefined : JSON.stringify(request.body),
signal: AbortSignal.timeout(requestTimeoutMs)
});
- recordRateLimit(response.headers, resource);
+ recordRateLimit(state, response.headers, resource);
const etag = response.headers.get('etag');
@@ -182,11 +213,23 @@ async function sendOnce<Data>(request: GitHubRequest): Promise<GitHubResponse<Da
const retryAfter = Number(response.headers.get('retry-after') ?? 0);
const exhausted = response.headers.get('x-ratelimit-remaining') === '0';
- if ((response.status === 403 || response.status === 429) && (retryAfter > 0 || exhausted)) {
+ const errorMessage = response.ok ? '' : await readErrorMessage(response);
+ const secondaryLimit = /secondary rate limit|abuse detection/i.test(errorMessage);
+
+ if (
+ response.status === 429 ||
+ (response.status === 403 && (retryAfter > 0 || exhausted || secondaryLimit))
+ ) {
const resetAt = Number(response.headers.get('x-ratelimit-reset') ?? 0) * 1000;
- const resumeAt = retryAfter > 0 ? Date.now() + retryAfter * 1000 : resetAt;
+ const resumeAt = Math.max(
+ retryAfter > 0 ? Date.now() + retryAfter * 1000 : 0,
+ exhausted ? resetAt : 0,
+ retryAfter <= 0 && !exhausted ? Date.now() + 60_000 : 0
+ );
- blockedUntil = Math.max(blockedUntil, resumeAt);
+ if (retryAfter > 0 || secondaryLimit || !exhausted) {
+ state.blockedUntil = Math.max(state.blockedUntil, resumeAt);
+ }
throw new RateLimitError(resumeAt);
}
@@ -199,7 +242,7 @@ async function sendOnce<Data>(request: GitHubRequest): Promise<GitHubResponse<Da
}
if (!response.ok) {
- throw new GitHubError(response.status, await readErrorMessage(response));
+ throw new GitHubError(response.status, errorMessage);
}
const isJson = (response.headers.get('content-type') ?? '').includes('json');
@@ -248,6 +291,11 @@ export async function githubRequest<Data>(request: GitHubRequest): Promise<GitHu
}
}
-export function getRateLimitSnapshot(): Record<string, RateBucket> {
- return Object.fromEntries(rateBuckets);
+export function getRateLimitSnapshot() {
+ const config = getConfig();
+
+ return {
+ read: Object.fromEntries(getRateState(config.readGithubToken).buckets),
+ maintainer: Object.fromEntries(getRateState(config.maintainerGithubToken).buckets)
+ };
}
diff --git a/src/lib/server/github/token.ts b/src/lib/server/github/token.ts
index 9004036..cd38b95 100644
--- a/src/lib/server/github/token.ts
+++ b/src/lib/server/github/token.ts
@@ -64,8 +64,22 @@ export function describeToken(options: {
// 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');
+ const config = getConfig();
+
+ if (config.readGithubToken) {
+ try {
+ const reader = await githubRequest<{ login: string }>({ path: '/user' });
+
+ logger.info(`READ_GITHUB_TOKEN: signed in as ${reader.data.login}.`);
+ } catch (error) {
+ logger.error(`Could not verify READ_GITHUB_TOKEN: ${describeError(error)}`);
+ }
+ } else {
+ logger.warn('READ_GITHUB_TOKEN missing; public reads are limited to 60 an hour.');
+ }
+
+ if (!config.maintainerGithubToken) {
+ logger.warn('MAINTAINER_GITHUB_TOKEN missing; moderation actions will fail.');
return;
}
@@ -90,10 +104,10 @@ export async function checkToken(): Promise<void> {
});
for (const line of report.lines) {
- logger[report.level](`${repo}: ${line}`);
+ logger[report.level](`MAINTAINER_GITHUB_TOKEN ${repo}: ${line}`);
}
}
} catch (error) {
- logger.error(`Could not verify GITHUB_TOKEN: ${describeError(error)}`);
+ logger.error(`Could not verify MAINTAINER_GITHUB_TOKEN: ${describeError(error)}`);
}
}
diff --git a/src/lib/server/moderation/scanner.ts b/src/lib/server/moderation/scanner.ts
index 811fe96..62cffe7 100644
--- a/src/lib/server/moderation/scanner.ts
+++ b/src/lib/server/moderation/scanner.ts
@@ -188,7 +188,7 @@ async function runCycle(afterScan: () => Promise<void>): Promise<void> {
setValue(lastErrorKey(repo), describeError(error));
if (error instanceof RateLimitError) {
- // One token serves every repository, so the rest would hit the same limit
+ // The read token serves every repository, so the rest would hit the same limit
delayMs = Math.max(delayMs, error.resumeAt - Date.now() + 5_000);
logger.warn(`Paused for ${Math.round(delayMs / 1000)}s`, error);
break;
diff --git a/src/routes/lookup/+page.server.ts b/src/routes/lookup/+page.server.ts
index 70d629c..60444e4 100644
--- a/src/routes/lookup/+page.server.ts
+++ b/src/routes/lookup/+page.server.ts
@@ -34,7 +34,7 @@ function parsePullRequest(
}
// Read-only: fetches and validates live, and stores nothing
-export const load: PageServerLoad = async ({ url, locals }) => {
+export const load: PageServerLoad = async ({ url }) => {
const query = url.searchParams.get('pr') ?? '';
if (query.trim() === '') {
@@ -68,11 +68,11 @@ export const load: PageServerLoad = async ({ url, locals }) => {
}
try {
- const pullRequest = await getPullRequest(repo, number, locals.authenticated);
+ const pullRequest = await getPullRequest(repo, number);
const evaluation = await evaluatePullRequest(pullRequest, {
fresh: true,
- priority: locals.authenticated
+ priority: false
});
return {