mirror of
https://github.com/tdurieux/anonymous_github.git
synced 2026-12-02 17:13:33 +01:00
Merge remote-tracking branch 'origin/main' into fix/expected-errors-info
# Conflicts: # deploy/logging/sanitize.vrl # public/asset-manifest.json # public/script/vendor.min.js # src/core/log-diagnostic-schema.ts
This commit is contained in:
commit
0233d1ad0b
21 files changed
+1050
-156
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 };
|
||||
}
|
||||
@@ -986,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",
|
||||
@@ -1308,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>"
|
||||
],
|
||||
@@ -2004,6 +2002,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",
|
||||
@@ -2945,4 +2985,4 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
};
|
||||
export const LOG_ERROR_TYPES = ["Error","TypeError","RangeError","ReferenceError","SyntaxError","URIError","EvalError","AggregateError","AnonymousError","HTTPError","RequestError","MongoServerError","MongoNetworkError","MongoServerSelectionError","ValidationError","TimeoutError","AbortError","UnknownError"];
|
||||
export const LOG_ROUTES = ["/","other","/dashboard","/anonymize","/healthcheck","/api/healthcheck","/api","/api/download","/api/stat","/api/stat/history","/api/options","/api/message","/api/user","/api/user/quota","/api/user/dashboard","/api/repo","/api/anonymize-preview","/api/admin/overview","/api/admin/performance","/api/admin/errors","/api/admin/errors/stats","/api/admin/queues","/api/admin/queues/metrics","/github/app/webhook","/api/repo/:repoId","/api/repo/:repoId/file/:path","/api/repo/:repoId/files","/api/repo/:repoId/files/counts","/api/repo/:repoId/files/search","/api/repo/:repoId/zip","/api/repo/:repoId/options","/api/repo/:repoId/refresh","/api/repo/:repoId/coauthors","/api/repo/:repoId/extend","/api/repo/:owner/:repo","/api/repo/:owner/:repo/tree","/api/repo/:owner/:repo/file","/api/repo/:owner/:repo/readme","/api/repo/:owner/:repo/branches","/w/:repoId/:path","/r/:repoId/:path","/api/pr/:id/:path","/api/gist/:id/:path","/assets/:path","/github/:action","/api/admin/:action","/api/user/:action","/api/repo/:id/file/:path","/api/repo/:id/files/counts","/api/repo/:id/files/search","/api/repo/:id/files","/api/repo/:id/zip","/api/repo/:id","/viewer/:id/:path","/api/billing","/api/billing/draft","/api/billing/draft/:id","/api/billing/checkout","/api/billing/portal","/api/billing/refresh","/api/billing/webhook","/api/conferences/plans","/profile","/conference/:id"];
|
||||
export const LOG_THROWN_ERROR_CODES = ["another_login_required","billing_address_missing","billing_already_paid","billing_busy","billing_checkout_disabled","billing_checkout_in_progress","billing_city_missing","billing_country_missing","billing_customer_mismatch","billing_draft_not_found","billing_email_missing","billing_invalid_conference","billing_invalid_draft","billing_invalid_purchase","billing_invalid_repository_size","billing_invalid_review_window","billing_missing","billing_name_missing","billing_plan_change_not_supported","billing_plan_unavailable","billing_price_misconfigured","billing_recovery_required","billing_review_window_locked","billing_subscription_exists","billing_unavailable","billing_zip_missing","branch_not_found","branch_not_specified","cache_busy","cache_miss","cannot_coauthor_self","commit_not_found","commit_not_specified","conf_end_date_invalid","conf_end_date_missing","conf_id_missing","conf_id_used","conf_name_missing","conf_not_activated","conf_not_found","conf_start_date_invalid","conf_start_date_missing","conference_not_found","conference_payment_required","connection_changed","download_not_enabled","expiration_limit_reached","file_listing_too_large","file_not_accessible","file_not_found","file_not_supported","file_too_big","folder_not_supported","gistId_already_used","gistId_not_specified","gist_expired","gist_not_available","gist_not_found","gist_not_ready","github_app_access_required","github_app_authorization_cancelled","github_app_disabled","github_app_permissions_invalid","github_app_reconnect_required","github_app_refresh_busy","github_grant_revocation_failed","github_identity_mismatch","github_oauth_required","github_rate_limit_exceeded","github_unavailable","github_user_not_found","invalid_auth_state","invalid_billing_expiration","invalid_commit_format","invalid_connection","invalid_cursor","invalid_file_path","invalid_gistId","invalid_github_path","invalid_path","invalid_plan","invalid_preserve_files_format","invalid_project_name","invalid_pullRequestId","invalid_repo","invalid_repoId","invalid_request","invalid_settings","invalid_sort","invalid_status","invalid_terms_format","invalid_token_id","invalid_token_options","is_removed","not_authorized","not_connected","not_owner","oauth_resources_remaining","options_not_provided","page_not_activated","page_not_supported_on_different_branch","path_not_defined","path_not_specified","pullRequestId_already_used","pullRequestId_is_not_a_number","pullRequestId_not_specified","pull_request_expired","pull_request_not_available","pull_request_not_found","pull_request_not_ready","quota_exceeded","quota_repository_limit","quota_storage_limit","rate_limited","readme_not_available","repoId_already_used","repoId_not_defined","repoUrl_not_defined","repo_access_limited","repo_empty","repo_not_accessible","repo_not_found","repo_saml_enforcement","repository_archived","repository_busy","repository_changed","repository_expired","repository_job_cancelled","repository_not_accessible","repository_not_ready","repository_not_specified","repository_tree_incomplete","repository_tree_too_large","s3_config_not_provided","source_not_provided","storage_delete_failed","storage_write_size_mismatch","streamer_route_not_found","streamer_unexpected_response","streamer_unreachable","streamer_upstream_error","submodule_not_available","subscription_required_for_never_expiration","terms_not_specified","token_expired","token_limit_reached","unable_to_connect_user","unable_to_download","upstream_error","user_banned","user_not_found","username_not_defined","zip_not_available","zip_unsafe_entry_path"];
|
||||
export const LOG_THROWN_ERROR_CODES = ["another_login_required","billing_address_missing","billing_already_paid","billing_busy","billing_checkout_disabled","billing_checkout_in_progress","billing_city_missing","billing_country_missing","billing_customer_mismatch","billing_draft_not_found","billing_email_missing","billing_invalid_conference","billing_invalid_draft","billing_invalid_purchase","billing_invalid_repository_size","billing_invalid_review_window","billing_missing","billing_name_missing","billing_plan_change_not_supported","billing_plan_unavailable","billing_price_misconfigured","billing_recovery_required","billing_review_window_locked","billing_subscription_exists","billing_unavailable","billing_zip_missing","branch_not_found","branch_not_specified","cache_busy","cache_miss","cannot_coauthor_self","commit_not_found","commit_not_specified","conf_end_date_invalid","conf_end_date_missing","conf_id_missing","conf_id_used","conf_name_missing","conf_not_activated","conf_not_found","conf_start_date_invalid","conf_start_date_missing","conference_not_found","conference_payment_required","connection_changed","download_not_enabled","expiration_limit_reached","file_listing_too_large","file_not_accessible","file_not_found","file_not_supported","file_too_big","folder_not_supported","gistId_already_used","gistId_not_specified","gist_expired","gist_not_available","gist_not_found","gist_not_ready","github_app_access_required","github_app_authorization_cancelled","github_app_disabled","github_app_permissions_invalid","github_app_reconnect_required","github_app_refresh_busy","github_grant_revocation_failed","github_identity_mismatch","github_oauth_required","github_rate_limit_exceeded","github_unavailable","github_user_not_found","invalid_auth_state","invalid_billing_expiration","invalid_commit_format","invalid_connection","invalid_cursor","invalid_file_path","invalid_gistId","invalid_github_path","invalid_path","invalid_plan","invalid_preserve_files_format","invalid_project_name","invalid_pullRequestId","invalid_repo","invalid_repoId","invalid_request","invalid_settings","invalid_sort","invalid_status","invalid_terms_format","invalid_token_id","invalid_token_options","is_removed","not_authorized","not_connected","not_owner","oauth_resources_remaining","options_not_provided","page_not_activated","page_not_supported_on_different_branch","path_not_defined","path_not_specified","pullRequestId_already_used","pullRequestId_is_not_a_number","pullRequestId_not_specified","pull_request_expired","pull_request_not_available","pull_request_not_found","pull_request_not_ready","quota_exceeded","quota_repository_limit","quota_storage_limit","rate_limited","readme_not_available","repoId_already_used","repoId_not_defined","repoUrl_not_defined","repo_access_limited","repo_empty","repo_not_accessible","repo_not_found","repo_saml_enforcement","repository_archived","repository_busy","repository_changed","repository_expired","repository_job_cancelled","repository_not_accessible","repository_not_ready","repository_not_specified","repository_tree_incomplete","repository_tree_too_large","s3_config_not_provided","source_not_provided","storage_delete_failed","storage_write_size_mismatch","streamer_route_not_found","streamer_unexpected_response","streamer_unreachable","streamer_upstream_error","submodule_not_available","subscription_required_for_never_expiration","sync_failed","terms_not_specified","token_expired","token_limit_reached","unable_to_connect_user","unable_to_download","upstream_error","user_banned","user_not_found","username_not_defined","zip_not_available","zip_unsafe_entry_path"];
|
||||
@@ -0,0 +1,53 @@
|
||||
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 });
|
||||
// Matches the picker sort, so a page never sorts in memory.
|
||||
schema.index({ ownerId: 1, connection: 1, nameKey: 1, repositoryId: 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,349 @@
|
||||
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;
|
||||
/** Webhooks miss some changes (new org installs, OAuth lists); resync in the background after this. */
|
||||
const STALE_MS = 12 * 60 * 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)
|
||||
|| now - lastSync >= STALE_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); }
|
||||
});
|
||||
@@ -275,6 +277,8 @@ export async function revokeGrant(ownerId: string, provider: "github" | "github-
|
||||
const token = await getCredentialToken(ownerId, provider);
|
||||
const clientId = provider === "github" ? config.CLIENT_ID : config.GITHUB_APP_CLIENT_ID;
|
||||
const clientSecret = provider === "github" ? config.CLIENT_SECRET : config.GITHUB_APP_CLIENT_SECRET;
|
||||
// Before the GitHub call: a failed revoke must not keep private repo names.
|
||||
await clearRepositoryList(ownerId, provider === "github" ? "oauth" : "github-app");
|
||||
if (token) {
|
||||
const response = await fetch(`https://api.github.com/applications/${clientId}/grant`, { method: "DELETE",
|
||||
headers: { Authorization: `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString("base64")}`, "Content-Type": "application/json", Accept: "application/vnd.github+json" },
|
||||
@@ -321,7 +325,12 @@ githubAppWebhook.post("/", express.raw({ type: "application/json", limit: "2mb"
|
||||
phase = "find_grant_owners";
|
||||
const users = await UserModel.find({ "externalIDs.github": String(body.sender.id) }).select("_id").lean();
|
||||
phase = "reconcile_grant";
|
||||
for (const user of users) await reconcileAppGrant(String(user._id));
|
||||
for (const user of users) {
|
||||
await reconcileAppGrant(String(user._id));
|
||||
// Private repository names must not outlive the grant; a live grant
|
||||
// simply resyncs on the next picker load.
|
||||
await clearRepositoryList(String(user._id), "github-app");
|
||||
}
|
||||
}
|
||||
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;
|
||||
@@ -336,6 +345,12 @@ githubAppWebhook.post("/", express.raw({ type: "application/json", limit: "2mb"
|
||||
phase = "reconcile_installation";
|
||||
if (body.action !== "deleted") await reconcileInstallation(installation.id, revision);
|
||||
}
|
||||
if (["installation", "installation_repositories", "repository"].includes(String(event))) {
|
||||
// After the installation block: a failed picker write must never leave a
|
||||
// deleted or suspended installation usable. The lists also resync by age.
|
||||
phase = "update_repository_lists";
|
||||
await applyRepositoryWebhook(String(event), body);
|
||||
}
|
||||
return res.status(204).end();
|
||||
} catch (error) {
|
||||
const delivery = req.headers["x-github-delivery"];
|
||||
|
||||
@@ -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