mirror of
https://github.com/tdurieux/anonymous_github.git
synced 2026-12-02 17:13:33 +01:00
feat: store the repository picker list and update it by webhook
The anonymize page's "Your repositories" picker now pages and searches a per-user list stored in MongoDB instead of calling GitHub on every page and search. GitHub is read only when the list is empty, when the user presses the new refresh button, or after an installation change marks it stale. - One sync per list (Mongo lock with a renewed lease); full pagination in the background after the first page is returned; rate limits pause syncs. - GitHub App installation, installation_repositories and repository webhooks update the stored lists idempotently. The App must subscribe to the Repository event (documented in docs/github-app-setup.md). - Legacy OAuth lists change only on refresh. - Picker header shows "Updated 3 min ago" and a refresh button. - dev-mock: stored list, simulated refresh and webhook endpoint. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
0640d741f1
commit
c73e992b7c
22 files changed
+1026
-153
No files matched your search
@@ -6,6 +6,7 @@ import AnonymousError from "./AnonymousError";
|
||||
import CredentialModel from "./model/credentials/credentials.model";
|
||||
import InstallationModel from "./model/github-installation";
|
||||
import UserModel from "./model/users/users.model";
|
||||
import { UserRepositorySyncModel } from "./model/user-repositories";
|
||||
import { credentialCipher, getCredentialToken } from "./credentials";
|
||||
import { RepositoryAccess } from "./repository-access.types";
|
||||
|
||||
@@ -84,6 +85,8 @@ export async function saveAppGrant(ownerId: string, data: AppTokenResponse) {
|
||||
$set: tokenFields(ownerId, data), $unset: { refreshLock: "", refreshLockUntil: "" },
|
||||
}, { upsert: true, runValidators: true });
|
||||
await UserModel.updateOne({ _id: ownerId }, { $set: { repositories: [] } });
|
||||
// A new grant may see other installations: refresh the stored picker list.
|
||||
await UserRepositorySyncModel.updateOne({ ownerId, connection: "github-app" }, { $set: { needsSyncAt: new Date() } });
|
||||
}
|
||||
|
||||
export async function appUserToken(ownerId: string): Promise<string> {
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
import { octokit } from "./GitHubUtils";
|
||||
|
||||
/** One upstream page per request. Search cursors resume within that page. */
|
||||
export async function repositoryPickerPage(token: string, cursor = 0, query = "") {
|
||||
const size = query ? 100 : 20;
|
||||
const page = Math.floor(cursor / size) + 1;
|
||||
const offset = cursor % size;
|
||||
const response = await octokit(token).request("GET /user/repos", {
|
||||
visibility: "all", sort: "full_name", direction: "asc", per_page: size, page,
|
||||
});
|
||||
const items: { id: number; fullName: string }[] = [];
|
||||
let index = offset;
|
||||
for (; index < response.data.length; index++) {
|
||||
const repo = response.data[index];
|
||||
if (!query || repo.full_name.toLowerCase().includes(query.toLowerCase())) {
|
||||
items.push({ id: repo.id, fullName: repo.full_name });
|
||||
if (items.length === 20) { index++; break; }
|
||||
}
|
||||
}
|
||||
const hasNext = index < response.data.length || /rel="next"/.test(response.headers.link || "");
|
||||
return { items, nextCursor: hasNext ? (page - 1) * size + index : null };
|
||||
}
|
||||
@@ -142,6 +142,7 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
"getToken",
|
||||
"getTokenGateResetAt",
|
||||
"octokit",
|
||||
"ownerGitHubAccessRequired",
|
||||
"rateLimitDetail",
|
||||
"resolveRepositoryToken",
|
||||
"run",
|
||||
@@ -160,6 +161,7 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
"getToken",
|
||||
"getTokenGateResetAt",
|
||||
"octokit",
|
||||
"ownerGitHubAccessRequired",
|
||||
"rateLimitDetail",
|
||||
"resolveRepositoryToken",
|
||||
"run",
|
||||
@@ -984,14 +986,6 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
"<anonymous>",
|
||||
"isGitHubRateLimitError"
|
||||
],
|
||||
"src/core/github-repository-picker.ts": [
|
||||
"<anonymous>",
|
||||
"repositoryPickerPage"
|
||||
],
|
||||
"build/core/github-repository-picker.js": [
|
||||
"<anonymous>",
|
||||
"repositoryPickerPage"
|
||||
],
|
||||
"src/core/github-token-context.ts": [
|
||||
"<anonymous>",
|
||||
"githubQuotaKey",
|
||||
@@ -1306,6 +1300,12 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
"build/core/model/repository-access.schema.js": [
|
||||
"<anonymous>"
|
||||
],
|
||||
"src/core/model/user-repositories.ts": [
|
||||
"<anonymous>"
|
||||
],
|
||||
"build/core/model/user-repositories.js": [
|
||||
"<anonymous>"
|
||||
],
|
||||
"src/core/model/users/users.model.ts": [
|
||||
"<anonymous>"
|
||||
],
|
||||
@@ -1643,6 +1643,7 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
"admitResolvedBytes",
|
||||
"assertActive",
|
||||
"assertDownloadUrl",
|
||||
"assertHost",
|
||||
"cached",
|
||||
"confirmOwnerAccess",
|
||||
"deferredRawDownload",
|
||||
@@ -1651,6 +1652,7 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
"downloadFile",
|
||||
"downloadFileViaRaw",
|
||||
"downloadRaw",
|
||||
"downloadViaJsDelivr",
|
||||
"downloadWithFallback",
|
||||
"fallbackToRaw",
|
||||
"fetchContent",
|
||||
@@ -1663,9 +1665,12 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
"githubRawFileUrl",
|
||||
"iterateFiles",
|
||||
"iterateTreeBatches",
|
||||
"jsDelivrFileUrl",
|
||||
"lfsPointerGuard",
|
||||
"normalize",
|
||||
"pMap",
|
||||
"produce",
|
||||
"rejectLfsPointer",
|
||||
"resolve",
|
||||
"resolveLfsPointer",
|
||||
"stopSourceOnDestroy",
|
||||
@@ -1679,6 +1684,7 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
"admitResolvedBytes",
|
||||
"assertActive",
|
||||
"assertDownloadUrl",
|
||||
"assertHost",
|
||||
"cached",
|
||||
"confirmOwnerAccess",
|
||||
"deferredRawDownload",
|
||||
@@ -1687,6 +1693,7 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
"downloadFile",
|
||||
"downloadFileViaRaw",
|
||||
"downloadRaw",
|
||||
"downloadViaJsDelivr",
|
||||
"downloadWithFallback",
|
||||
"fallbackToRaw",
|
||||
"fetchContent",
|
||||
@@ -1699,9 +1706,12 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
"githubRawFileUrl",
|
||||
"iterateFiles",
|
||||
"iterateTreeBatches",
|
||||
"jsDelivrFileUrl",
|
||||
"lfsPointerGuard",
|
||||
"normalize",
|
||||
"pMap",
|
||||
"produce",
|
||||
"rejectLfsPointer",
|
||||
"resolve",
|
||||
"resolveLfsPointer",
|
||||
"stopSourceOnDestroy",
|
||||
@@ -1990,6 +2000,48 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
"<anonymous>",
|
||||
"joinUrl"
|
||||
],
|
||||
"src/core/user-repository-list.ts": [
|
||||
"<anonymous>",
|
||||
"acquireLock",
|
||||
"appUsers",
|
||||
"applyRepositoryWebhook",
|
||||
"clearRepositoryList",
|
||||
"date",
|
||||
"escapeRegex",
|
||||
"hasApp",
|
||||
"installationOwners",
|
||||
"markRepositoryListStale",
|
||||
"pickerConnection",
|
||||
"repositoryListPage",
|
||||
"retryDelay",
|
||||
"runSync",
|
||||
"settleRepositorySyncs",
|
||||
"startRepositorySync",
|
||||
"toRow",
|
||||
"upsertRows",
|
||||
"upstreamPages"
|
||||
],
|
||||
"build/core/user-repository-list.js": [
|
||||
"<anonymous>",
|
||||
"acquireLock",
|
||||
"appUsers",
|
||||
"applyRepositoryWebhook",
|
||||
"clearRepositoryList",
|
||||
"date",
|
||||
"escapeRegex",
|
||||
"hasApp",
|
||||
"installationOwners",
|
||||
"markRepositoryListStale",
|
||||
"pickerConnection",
|
||||
"repositoryListPage",
|
||||
"retryDelay",
|
||||
"runSync",
|
||||
"settleRepositorySyncs",
|
||||
"startRepositorySync",
|
||||
"toRow",
|
||||
"upsertRows",
|
||||
"upstreamPages"
|
||||
],
|
||||
"src/core/zipStream.ts": [
|
||||
"<anonymous>",
|
||||
"fail",
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { model, Schema } from "mongoose";
|
||||
|
||||
export type RepositoryConnection = "oauth" | "github-app";
|
||||
|
||||
/**
|
||||
* One GitHub repository a user can pick on the anonymize page, as seen through
|
||||
* one connection. The landing picker pages and searches these rows instead of
|
||||
* calling GitHub. Rows are written by a full sync (`syncId`) and by App
|
||||
* webhooks (`syncedAt`), so a sync only removes rows it did not see that no
|
||||
* webhook touched after the sync started.
|
||||
*/
|
||||
const schema = new Schema({
|
||||
ownerId: { type: String, required: true },
|
||||
connection: { type: String, enum: ["oauth", "github-app"], required: true },
|
||||
repositoryId: { type: Number, required: true },
|
||||
fullName: { type: String, required: true },
|
||||
/** Lower-case `fullName`, used for sorting and substring search. */
|
||||
nameKey: { type: String, required: true },
|
||||
private: Boolean,
|
||||
defaultBranch: String,
|
||||
githubUpdatedAt: Date,
|
||||
pushedAt: Date,
|
||||
/** App rows only: the installation that grants access. */
|
||||
installationId: Number,
|
||||
/** Hidden while the installation is suspended; restored on unsuspend. */
|
||||
suspended: { type: Boolean, default: undefined },
|
||||
syncId: String,
|
||||
syncedAt: { type: Date, required: true },
|
||||
});
|
||||
schema.index({ ownerId: 1, connection: 1, repositoryId: 1 }, { unique: true });
|
||||
schema.index({ ownerId: 1, connection: 1, nameKey: 1 });
|
||||
schema.index({ repositoryId: 1 });
|
||||
schema.index({ installationId: 1 }, { partialFilterExpression: { installationId: { $exists: true } } });
|
||||
export const UserRepositoryModel = model("UserRepository", schema);
|
||||
|
||||
/** Per user and connection: when the list was last complete, and the sync lock. */
|
||||
const syncSchema = new Schema({
|
||||
ownerId: { type: String, required: true },
|
||||
connection: { type: String, enum: ["oauth", "github-app"], required: true },
|
||||
/** Last time a full sync finished. Absent until the first one completes. */
|
||||
syncedAt: Date,
|
||||
lockId: String,
|
||||
lockUntil: Date,
|
||||
startedAt: Date,
|
||||
/** Set by installation changes; a sync started after it clears it. */
|
||||
needsSyncAt: Date,
|
||||
/** GitHub asked us to slow down: no sync before this time. */
|
||||
retryAfter: Date,
|
||||
error: String,
|
||||
});
|
||||
syncSchema.index({ ownerId: 1, connection: 1 }, { unique: true });
|
||||
export const UserRepositorySyncModel = model("UserRepositorySync", syncSchema);
|
||||
@@ -0,0 +1,346 @@
|
||||
import { randomUUID } from "crypto";
|
||||
import config from "../config";
|
||||
import { octokit } from "./GitHubUtils";
|
||||
import { isGitHubRateLimitError } from "./github-rate-limit";
|
||||
import { APP_PROVIDER, appError, appUserToken, githubRequest, GitHubRepositoryInfo, userInstallations } from "./github-app";
|
||||
import { getCredentialToken } from "./credentials";
|
||||
import CredentialModel from "./model/credentials/credentials.model";
|
||||
import UserModel from "./model/users/users.model";
|
||||
import { RepositoryConnection, UserRepositoryModel, UserRepositorySyncModel } from "./model/user-repositories";
|
||||
import { createLogger, serializeError } from "./logger";
|
||||
|
||||
const logger = createLogger("user-repository-list");
|
||||
|
||||
export const PAGE_SIZE = 20;
|
||||
/** A sync holds its lock this long past its last page; a crashed sync is taken over after it. */
|
||||
const LOCK_MS = 60_000;
|
||||
/** The first request waits this long for the first upstream page of an empty list. */
|
||||
const FIRST_PAGE_WAIT_MS = 10_000;
|
||||
/** Ignore forced refreshes this soon after a completed sync. */
|
||||
const FORCE_MIN_INTERVAL_MS = 10_000;
|
||||
/** An empty list that synced recently is a user with no repositories, not a missing list. */
|
||||
const EMPTY_RECHECK_MS = 5 * 60_000;
|
||||
/** Default pause after a rate-limit response without a reset time. */
|
||||
const RATE_LIMIT_PAUSE_MS = 60_000;
|
||||
/** Bound a runaway pagination: 100,000 repositories. */
|
||||
const MAX_PAGES = 1000;
|
||||
|
||||
type Upstream = Pick<GitHubRepositoryInfo, "id" | "full_name"> & Partial<GitHubRepositoryInfo> & {
|
||||
updated_at?: string | null; pushed_at?: string | null;
|
||||
};
|
||||
interface Row {
|
||||
repositoryId: number; fullName: string; nameKey: string; private?: boolean; defaultBranch?: string;
|
||||
githubUpdatedAt?: Date; pushedAt?: Date; installationId?: number;
|
||||
}
|
||||
|
||||
const date = (value: unknown) => {
|
||||
const time = typeof value === "string" ? Date.parse(value) : NaN;
|
||||
return Number.isFinite(time) ? new Date(time) : undefined;
|
||||
};
|
||||
function toRow(repo: Upstream, installationId?: number): Row | null {
|
||||
if (!Number.isSafeInteger(repo?.id) || typeof repo.full_name !== "string" || !/^[^/\s]+\/[^/\s]+$/.test(repo.full_name)) return null;
|
||||
const row: Row = { repositoryId: repo.id, fullName: repo.full_name, nameKey: repo.full_name.toLowerCase() };
|
||||
if (typeof repo.private === "boolean") row.private = repo.private;
|
||||
if (typeof repo.default_branch === "string") row.defaultBranch = repo.default_branch;
|
||||
const updated = date(repo.updated_at), pushed = date(repo.pushed_at);
|
||||
if (updated) row.githubUpdatedAt = updated;
|
||||
if (pushed) row.pushedAt = pushed;
|
||||
if (Number.isSafeInteger(installationId)) row.installationId = installationId;
|
||||
return row;
|
||||
}
|
||||
|
||||
async function upsertRows(ownerId: string, connection: RepositoryConnection, rows: Row[], syncId?: string) {
|
||||
if (!rows.length) return;
|
||||
const now = new Date();
|
||||
await UserRepositoryModel.bulkWrite(rows.map(row => ({ updateOne: {
|
||||
filter: { ownerId, connection, repositoryId: row.repositoryId },
|
||||
update: { $set: { ...row, syncedAt: now, ...(syncId ? { syncId } : {}) }, $unset: { suspended: "" } },
|
||||
upsert: true,
|
||||
} })), { ordered: false });
|
||||
}
|
||||
|
||||
/** Pages of the repositories one connection can see, in a stable order. */
|
||||
async function* upstreamPages(ownerId: string, connection: RepositoryConnection): AsyncGenerator<Row[]> {
|
||||
if (connection === "oauth") {
|
||||
const token = await getCredentialToken(ownerId);
|
||||
if (!token) throw appError("github_oauth_required", 401);
|
||||
for (let page = 1; page <= MAX_PAGES; page++) {
|
||||
const response = await octokit(token).request("GET /user/repos", {
|
||||
visibility: "all", sort: "full_name", direction: "asc", per_page: 100, page,
|
||||
});
|
||||
yield (response.data as Upstream[]).map(r => toRow(r)).filter((r): r is Row => !!r);
|
||||
if (response.data.length < 100 || !/rel="next"/.test(response.headers.link || "")) return;
|
||||
}
|
||||
return;
|
||||
}
|
||||
const installations = await userInstallations(ownerId);
|
||||
let yielded = false;
|
||||
for (const installation of installations) {
|
||||
if (installation.suspended_at) continue;
|
||||
for (let page = 1; page <= MAX_PAGES; page++) {
|
||||
const data = await githubRequest<{ repositories: Upstream[] }>(
|
||||
`/user/installations/${installation.id}/repositories?per_page=100&page=${page}`, await appUserToken(ownerId));
|
||||
yielded = true;
|
||||
yield data.repositories.map(r => toRow(r, installation.id)).filter((r): r is Row => !!r);
|
||||
if (data.repositories.length < 100) break;
|
||||
}
|
||||
}
|
||||
if (!yielded) yield [];
|
||||
}
|
||||
|
||||
function retryDelay(error: unknown): number | null {
|
||||
if (error instanceof Error && error.message === "github_rate_limit_exceeded") return RATE_LIMIT_PAUSE_MS;
|
||||
if (!isGitHubRateLimitError(error)) return null;
|
||||
const headers = (error as { response?: { headers?: Record<string, string | undefined> } }).response?.headers || {};
|
||||
const retry = Number(headers["retry-after"]);
|
||||
if (Number.isFinite(retry) && retry > 0) return retry * 1000;
|
||||
const reset = Number(headers["x-ratelimit-reset"]) * 1000;
|
||||
if (Number.isFinite(reset) && reset > Date.now()) return Math.min(reset - Date.now(), 3600_000);
|
||||
return RATE_LIMIT_PAUSE_MS;
|
||||
}
|
||||
|
||||
async function acquireLock(ownerId: string, connection: RepositoryConnection) {
|
||||
const lockId = randomUUID();
|
||||
const startedAt = new Date();
|
||||
try {
|
||||
const row = await UserRepositorySyncModel.findOneAndUpdate(
|
||||
{ ownerId, connection, $or: [{ lockUntil: { $exists: false } }, { lockUntil: null }, { lockUntil: { $lt: startedAt } }] },
|
||||
{ $set: { lockId, lockUntil: new Date(startedAt.getTime() + LOCK_MS), startedAt } },
|
||||
{ upsert: true, new: true }).lean();
|
||||
return row?.lockId === lockId ? { lockId, startedAt } : null;
|
||||
} catch (error) {
|
||||
// The upsert races an existing, locked row: someone else is syncing.
|
||||
if ((error as { code?: number })?.code === 11000) return null;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function runSync(ownerId: string, connection: RepositoryConnection, lock: { lockId: string; startedAt: Date }, firstPage: () => void) {
|
||||
const { lockId, startedAt } = lock;
|
||||
try {
|
||||
for await (const rows of upstreamPages(ownerId, connection)) {
|
||||
await upsertRows(ownerId, connection, rows, lockId);
|
||||
const kept = await UserRepositorySyncModel.updateOne({ ownerId, connection, lockId },
|
||||
{ $set: { lockUntil: new Date(Date.now() + LOCK_MS) } });
|
||||
if (!kept.matchedCount) return; // Another process took over a stalled lock.
|
||||
firstPage();
|
||||
}
|
||||
// Drop what this sync did not see, unless a webhook wrote it after the sync began.
|
||||
await UserRepositoryModel.deleteMany({ ownerId, connection, syncId: { $ne: lockId }, syncedAt: { $lt: startedAt } });
|
||||
await UserRepositorySyncModel.updateOne({ ownerId, connection, lockId },
|
||||
{ $set: { syncedAt: new Date() }, $unset: { lockId: "", lockUntil: "", error: "", retryAfter: "" } });
|
||||
await UserRepositorySyncModel.updateOne({ ownerId, connection, needsSyncAt: { $lte: startedAt } }, { $unset: { needsSyncAt: "" } });
|
||||
} catch (error) {
|
||||
const delay = retryDelay(error);
|
||||
const code = delay !== null ? "github_rate_limit_exceeded" : error instanceof Error && /^[a-z_]{1,64}$/.test(error.message) ? error.message : "sync_failed";
|
||||
await UserRepositorySyncModel.updateOne({ ownerId, connection, lockId }, {
|
||||
$set: { error: code, ...(delay !== null ? { retryAfter: new Date(Date.now() + delay) } : {}) },
|
||||
$unset: { lockId: "", lockUntil: "" },
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
const running = new Map<string, Promise<void>>();
|
||||
|
||||
/**
|
||||
* Start a sync unless one is running for this list (in this process or, via the
|
||||
* Mongo lock, in another). Returns null when one is already running, otherwise
|
||||
* `first`, a promise that resolves once the first page is stored (or rejects if the sync
|
||||
* fails before it). The rest of the pages continue in the background.
|
||||
*/
|
||||
export async function startRepositorySync(ownerId: string, connection: RepositoryConnection): Promise<{ first: Promise<void> } | null> {
|
||||
const key = `${ownerId}:${connection}`;
|
||||
if (running.has(key)) return null;
|
||||
const lock = await acquireLock(ownerId, connection);
|
||||
if (!lock) return null;
|
||||
let resolveFirst!: () => void, rejectFirst!: (error: unknown) => void;
|
||||
const first = new Promise<void>((resolve, reject) => { resolveFirst = resolve; rejectFirst = reject; });
|
||||
first.catch(() => { /* callers that do not wait for the first page */ });
|
||||
const work = runSync(ownerId, connection, lock, resolveFirst)
|
||||
.then(() => resolveFirst(), error => {
|
||||
rejectFirst(error);
|
||||
logger.warn("repository list sync failed", { connection, ...serializeError(error) });
|
||||
})
|
||||
.finally(() => running.delete(key));
|
||||
running.set(key, work);
|
||||
return { first };
|
||||
}
|
||||
|
||||
/** For tests: wait for this process's background syncs. */
|
||||
export async function settleRepositorySyncs() {
|
||||
while (running.size) await Promise.all([...running.values()]);
|
||||
}
|
||||
|
||||
/** Which stored list the picker reads, mirroring how the picker chose a token. */
|
||||
export async function pickerConnection(ownerId: string, requested?: unknown): Promise<RepositoryConnection | null> {
|
||||
const hasApp = async () => config.GITHUB_APP_ENABLED &&
|
||||
!!(await CredentialModel.exists({ ownerId, provider: APP_PROVIDER, revoked: { $ne: true } }));
|
||||
if (requested === "github-app") return await hasApp() ? "github-app" : null;
|
||||
if (await getCredentialToken(ownerId)) return "oauth";
|
||||
if (requested === "oauth") return null;
|
||||
return await hasApp() ? "github-app" : null;
|
||||
}
|
||||
|
||||
const escapeRegex = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
|
||||
/**
|
||||
* One picker page from the stored list. Fetches from GitHub only when the list
|
||||
* is empty, when forced, or after an installation change.
|
||||
*/
|
||||
export async function repositoryListPage(ownerId: string, connection: RepositoryConnection, opts: { cursor?: number; query?: string; force?: boolean } = {}) {
|
||||
const cursor = opts.cursor || 0;
|
||||
const query = (opts.query || "").toLowerCase();
|
||||
const [state, hasRows] = await Promise.all([
|
||||
UserRepositorySyncModel.findOne({ ownerId, connection }).lean(),
|
||||
UserRepositoryModel.exists({ ownerId, connection }),
|
||||
]);
|
||||
const now = Date.now();
|
||||
const lastSync = state?.syncedAt?.getTime() || 0;
|
||||
const wanted = !lastSync || !!state?.needsSyncAt
|
||||
|| (opts.force === true && now - lastSync >= FORCE_MIN_INTERVAL_MS)
|
||||
|| (!hasRows && now - lastSync >= EMPTY_RECHECK_MS);
|
||||
const paused = !!state?.retryAfter && state.retryAfter.getTime() > now;
|
||||
if (wanted && !paused) {
|
||||
const started = await startRepositorySync(ownerId, connection);
|
||||
if (started && !hasRows) {
|
||||
// Return the first page quickly; a large account keeps paginating behind it.
|
||||
let timer: NodeJS.Timeout | undefined;
|
||||
await Promise.race([started.first, new Promise(resolve => { timer = setTimeout(resolve, FIRST_PAGE_WAIT_MS); })])
|
||||
.catch(error => { throw retryDelay(error) !== null ? appError("github_rate_limit_exceeded", 429) : error; })
|
||||
.finally(() => clearTimeout(timer));
|
||||
}
|
||||
} else if (paused && !hasRows) {
|
||||
throw appError("github_rate_limit_exceeded", 429);
|
||||
}
|
||||
const filter: Record<string, unknown> = { ownerId, connection, suspended: { $ne: true } };
|
||||
if (query) filter.nameKey = { $regex: escapeRegex(query) };
|
||||
const rows = await UserRepositoryModel.find(filter).sort({ nameKey: 1, repositoryId: 1 })
|
||||
.skip(cursor).limit(PAGE_SIZE + 1).select("repositoryId fullName private").lean();
|
||||
const current = await UserRepositorySyncModel.findOne({ ownerId, connection }).select("syncedAt lockUntil").lean();
|
||||
return {
|
||||
items: rows.slice(0, PAGE_SIZE).map(r => ({ id: r.repositoryId, fullName: r.fullName, private: r.private })),
|
||||
nextCursor: rows.length > PAGE_SIZE ? cursor + PAGE_SIZE : null,
|
||||
syncedAt: current?.syncedAt || null,
|
||||
syncing: !!current?.lockUntil && current.lockUntil.getTime() > Date.now(),
|
||||
// Only App connections receive webhooks; OAuth lists change on refresh.
|
||||
webhooks: connection === "github-app",
|
||||
};
|
||||
}
|
||||
|
||||
/** Forget a connection's stored list, e.g. when its grant is revoked. */
|
||||
export async function clearRepositoryList(ownerId: string, connection: RepositoryConnection) {
|
||||
await UserRepositoryModel.deleteMany({ ownerId, connection });
|
||||
await UserRepositorySyncModel.deleteMany({ ownerId, connection });
|
||||
}
|
||||
|
||||
/** The next picker load syncs this App list in the background. */
|
||||
export async function markRepositoryListStale(ownerIds: string[], connection: RepositoryConnection = "github-app") {
|
||||
const ids = [...new Set(ownerIds)];
|
||||
if (!ids.length) return;
|
||||
await UserRepositorySyncModel.updateMany({ ownerId: { $in: ids }, connection }, { $set: { needsSyncAt: new Date() } });
|
||||
}
|
||||
|
||||
// ---- GitHub App webhooks ----------------------------------------------------
|
||||
|
||||
interface WebhookBody {
|
||||
action?: string;
|
||||
installation?: { id?: number; account?: { id?: number; type?: string } };
|
||||
sender?: { id?: number };
|
||||
repositories?: Upstream[];
|
||||
repositories_added?: Upstream[];
|
||||
repositories_removed?: Upstream[];
|
||||
repository_selection?: string;
|
||||
repository?: Upstream;
|
||||
}
|
||||
|
||||
/** Local users behind GitHub accounts, limited to those with an App grant. */
|
||||
async function appUsers(githubIds: unknown[]): Promise<string[]> {
|
||||
const ids = [...new Set(githubIds.filter(id => Number.isSafeInteger(id)).map(String))];
|
||||
if (!ids.length) return [];
|
||||
const users = await UserModel.find({ "externalIDs.github": { $in: ids } }).select("_id").lean();
|
||||
const owners = users.map(u => String(u._id));
|
||||
if (!owners.length) return [];
|
||||
const granted = await CredentialModel.find({ ownerId: { $in: owners }, provider: APP_PROVIDER, revoked: { $ne: true } })
|
||||
.select("ownerId").lean();
|
||||
return [...new Set(granted.map(c => String(c.ownerId)))];
|
||||
}
|
||||
async function installationOwners(installationId: number): Promise<string[]> {
|
||||
return (await UserRepositoryModel.distinct("ownerId", { connection: "github-app", installationId })).map(String);
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply one verified App webhook to the stored lists. Every branch is a set,
|
||||
* upsert or delete keyed by GitHub ids, so redelivery is harmless.
|
||||
*
|
||||
* Users named by the event (the sender, or the personal account that owns the
|
||||
* installation) get the change directly. Other users of an installation only
|
||||
* get removals and metadata updates; additions are left to a background sync,
|
||||
* because only GitHub knows whether they can see a newly added private repository.
|
||||
*/
|
||||
export async function applyRepositoryWebhook(event: string, body: WebhookBody) {
|
||||
const installationId = body.installation?.id;
|
||||
const action = body.action;
|
||||
const personal = body.installation?.account?.type === "User" ? body.installation.account.id : undefined;
|
||||
if (event === "installation" && Number.isSafeInteger(installationId)) {
|
||||
if (action === "deleted") {
|
||||
await UserRepositoryModel.deleteMany({ connection: "github-app", installationId });
|
||||
} else if (action === "suspend") {
|
||||
await UserRepositoryModel.updateMany({ connection: "github-app", installationId }, { $set: { suspended: true } });
|
||||
} else if (action === "unsuspend") {
|
||||
const owners = await installationOwners(installationId!);
|
||||
await UserRepositoryModel.updateMany({ connection: "github-app", installationId }, { $unset: { suspended: "" } });
|
||||
await markRepositoryListStale([...owners, ...await appUsers([body.sender?.id, personal])]);
|
||||
} else if (action === "created" || action === "new_permissions_accepted") {
|
||||
const direct = await appUsers([body.sender?.id, personal]);
|
||||
const rows = (body.repositories || []).map(r => toRow(r, installationId)).filter((r): r is Row => !!r);
|
||||
for (const ownerId of direct) await upsertRows(ownerId, "github-app", rows);
|
||||
await markRepositoryListStale(direct);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (event === "installation_repositories" && Number.isSafeInteger(installationId)) {
|
||||
const removed = (body.repositories_removed || []).map(r => r.id).filter(id => Number.isSafeInteger(id));
|
||||
if (removed.length) {
|
||||
await UserRepositoryModel.deleteMany({ connection: "github-app", installationId, repositoryId: { $in: removed } });
|
||||
}
|
||||
const added = (body.repositories_added || []).map(r => toRow(r, installationId)).filter((r): r is Row => !!r);
|
||||
if (added.length) {
|
||||
const direct = await appUsers([body.sender?.id, personal]);
|
||||
for (const ownerId of direct) await upsertRows(ownerId, "github-app", added);
|
||||
const others = (await installationOwners(installationId!)).filter(id => !direct.includes(id));
|
||||
// Rows from the payload lack the default branch; switching to "all" can add many.
|
||||
await markRepositoryListStale([...others, ...(body.repository_selection === "all" ? direct : [])]);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (event === "repository" && body.repository && Number.isSafeInteger(body.repository.id)) {
|
||||
const repositoryId = body.repository.id;
|
||||
if (action === "deleted") {
|
||||
await UserRepositoryModel.deleteMany({ repositoryId });
|
||||
return;
|
||||
}
|
||||
const row = toRow(body.repository, installationId);
|
||||
if (!row) return;
|
||||
if (action === "created") {
|
||||
if (!Number.isSafeInteger(installationId)) return;
|
||||
const direct = await appUsers([body.sender?.id]);
|
||||
for (const ownerId of direct) await upsertRows(ownerId, "github-app", [row]);
|
||||
await markRepositoryListStale((await installationOwners(installationId!)).filter(id => !direct.includes(id)));
|
||||
return;
|
||||
}
|
||||
if (["renamed", "transferred", "privatized", "publicized", "edited"].includes(action || "")) {
|
||||
const { installationId: _ignored, repositoryId: _id, ...fields } = row;
|
||||
// Never let a delayed delivery undo a newer change.
|
||||
const fresh = row.githubUpdatedAt
|
||||
? { $or: [{ githubUpdatedAt: { $exists: false } }, { githubUpdatedAt: null }, { githubUpdatedAt: { $lte: row.githubUpdatedAt } }] }
|
||||
: {};
|
||||
await UserRepositoryModel.updateMany({ repositoryId, ...fresh }, { $set: fields });
|
||||
if (action === "transferred" || action === "privatized") {
|
||||
// Access may have changed with the owner or visibility; let GitHub decide.
|
||||
const owners = (await UserRepositoryModel.distinct("ownerId", { repositoryId, connection: "github-app" })).map(String);
|
||||
await markRepositoryListStale(owners);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { installDatabaseTiming } from "../core/database-timing";
|
||||
import InstallationModel from "../core/model/github-installation";
|
||||
import { UserRepositoryModel, UserRepositorySyncModel } from "../core/model/user-repositories";
|
||||
import { credentialCipher } from "../core/credentials";
|
||||
import CredentialModel from "../core/model/credentials/credentials.model";
|
||||
import mongoose, { ConnectOptions } from "mongoose";
|
||||
@@ -37,6 +38,8 @@ export async function connect(overrides: Pick<ConnectOptions, "appName" | "maxPo
|
||||
await mongoose.connect(getMongoUrl(), options);
|
||||
await CredentialModel.createIndexes();
|
||||
if (config.GITHUB_APP_ENABLED) await InstallationModel.createIndexes();
|
||||
await UserRepositoryModel.createIndexes();
|
||||
await UserRepositorySyncModel.createIndexes();
|
||||
await initializeOwnerAccessAlerts();
|
||||
isConnected = true;
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ import { getCredentialToken } from "../../core/credentials";
|
||||
import { APP_PROVIDER, appError, appUserToken, AppInstallation, clearAppTokenCache, exchangeAppToken,
|
||||
githubRequest, GitHubRepositoryInfo, reconcileAppGrant, reconcileInstallation, installationURL, saveAppGrant, selectRepositoryAccess, userInstallations } from "../../core/github-app";
|
||||
import { explicitErrorStatus, getUser, handleError } from "./route-utils";
|
||||
import { applyRepositoryWebhook, clearRepositoryList, markRepositoryListStale } from "../../core/user-repository-list";
|
||||
import { isDisabledAccount, safeAuthReturnTo } from "./auth-utils";
|
||||
|
||||
type Flow = { state: string; expires: number; ownerId?: string; returnTo: string; repository?: string; install?: boolean };
|
||||
@@ -156,6 +157,7 @@ router.get("/app/setup", enabled, async (req, res) => {
|
||||
await resetOwnerAccessAlerts(user.id);
|
||||
}
|
||||
await UserModel.updateOne({ _id: user.id }, { $set: { repositories: [] } });
|
||||
await markRepositoryListStale([user.id]);
|
||||
res.redirect(flow.returnTo);
|
||||
} catch (error) { handleError(error, res, req); }
|
||||
});
|
||||
@@ -284,6 +286,7 @@ export async function revokeGrant(ownerId: string, provider: "github" | "github-
|
||||
await CredentialModel.deleteMany({ ownerId, provider });
|
||||
if (provider === "github") await UserModel.updateOne({ _id: ownerId }, { $unset: { "accessTokens.github": "", "accessTokenDates.github": "" } });
|
||||
await UserModel.updateOne({ _id: ownerId }, { $set: { repositories: [] } });
|
||||
await clearRepositoryList(ownerId, provider === "github" ? "oauth" : "github-app");
|
||||
}
|
||||
router.post("/connections/disconnect-oauth", async (req, res) => {
|
||||
try {
|
||||
@@ -323,6 +326,12 @@ githubAppWebhook.post("/", express.raw({ type: "application/json", limit: "2mb"
|
||||
phase = "reconcile_grant";
|
||||
for (const user of users) await reconcileAppGrant(String(user._id));
|
||||
}
|
||||
if (["installation", "installation_repositories", "repository"].includes(String(event))) {
|
||||
// Stored picker lists first: these writes are idempotent and need no
|
||||
// GitHub call, so they apply even if the installation check below fails.
|
||||
phase = "update_repository_lists";
|
||||
await applyRepositoryWebhook(String(event), body);
|
||||
}
|
||||
if (["installation", "installation_repositories"].includes(String(event)) && Number.isSafeInteger(body.installation?.id) && String(body.installation.app_id) === config.GITHUB_APP_ID) {
|
||||
const installation = body.installation as AppInstallation;
|
||||
// Fail closed immediately. Reconcile from GitHub, never trust event order
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
import { repositoryPickerPage } from "../../core/github-repository-picker";
|
||||
import { appUserToken } from "../../core/github-app";
|
||||
import { getCredentialToken } from "../../core/credentials";
|
||||
import { pickerConnection, repositoryListPage } from "../../core/user-repository-list";
|
||||
import AnonymousError from "../../core/AnonymousError";
|
||||
import { BillingQuota, BillingDraft } from "../../core/billing/models";
|
||||
import { cancelAccountBilling } from "../../core/billing/stripe";
|
||||
@@ -383,11 +381,12 @@ router.get("/repository_picker", async (req, res) => {
|
||||
res.status(400).json({ error: "Invalid repository search" });
|
||||
return;
|
||||
}
|
||||
const token = connection === "github-app" ? await appUserToken(user.id)
|
||||
: connection === "oauth" ? await getCredentialToken(user.id) : await user.getAccessToken();
|
||||
if (!token) { res.status(401).json({ error: "GitHub connection required" }); return; }
|
||||
// Served from the stored list; GitHub is only asked when it is empty,
|
||||
// forced, or stale after an installation change.
|
||||
const list = await pickerConnection(user.id, connection);
|
||||
if (!list) { res.status(401).json({ error: "GitHub connection required" }); return; }
|
||||
res.set("Cache-Control", "no-store");
|
||||
res.json(await repositoryPickerPage(token, cursor, query));
|
||||
res.json(await repositoryListPage(user.id, list, { cursor, query, force: req.query.force === "1" }));
|
||||
} catch (error) { handleError(error, res, req); }
|
||||
});
|
||||
|
||||
|
||||
Reference in new issue
Block a user