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 feat/viewer-toc-pr-layout
# Conflicts: # public/asset-manifest.json # public/css/all.min.css # public/css/style.css # public/script/vendor.min.js # test/vue-ui.test.js
This commit is contained in:
commit
85422b897a
53 files changed
+2184
-316
No files matched your search
+24
-28
@@ -59,14 +59,16 @@ function defaultMaskCandidateRegex(value: string): RegExp {
|
||||
// generic 404. Without this, a corrupt cache, a 5xx from the streamer, an
|
||||
// LFS pointer issue, and a missing file all surface to the user as the
|
||||
// same `file_not_found` — which makes incidents impossible to triage.
|
||||
// The request's handleError logs the result once. When the streamer answered,
|
||||
// it already logged its side under the same requestId.
|
||||
function streamerErrorToAnonymous(
|
||||
err: Error & { response?: { statusCode?: number; body?: unknown } },
|
||||
context: { repoId: string; filePath: string }
|
||||
err: Error & { response?: { statusCode?: number; body?: unknown } }
|
||||
): { error: AnonymousError; upstreamStatus?: number; upstreamBody?: string } {
|
||||
const upstreamStatus = err?.response?.statusCode;
|
||||
let errCode = "file_not_found";
|
||||
let httpStatus = 404;
|
||||
let upstreamBody: string | undefined;
|
||||
let streamerCode = false;
|
||||
|
||||
if (err?.response?.body != null) {
|
||||
try {
|
||||
@@ -84,6 +86,7 @@ function streamerErrorToAnonymous(
|
||||
const parsed = JSON.parse(upstreamBody);
|
||||
if (parsed && typeof parsed.error === "string") {
|
||||
errCode = parsed.error;
|
||||
streamerCode = true;
|
||||
}
|
||||
} catch {
|
||||
// body wasn't JSON — keep the default code
|
||||
@@ -97,6 +100,12 @@ function streamerErrorToAnonymous(
|
||||
httpStatus = upstreamStatus >= 500 ? 502 : upstreamStatus;
|
||||
if (upstreamStatus >= 500 && errCode === "file_not_found") {
|
||||
errCode = "streamer_upstream_error";
|
||||
} else if (!streamerCode) {
|
||||
// The streamer's handleError always sends a code. An uncoded 4xx came
|
||||
// from something in front of it (body-size limit, ingress, wrong
|
||||
// entrypoint), which is a fault, not a missing file.
|
||||
errCode = "streamer_unexpected_response";
|
||||
httpStatus = 502;
|
||||
}
|
||||
} else if (errCode === "file_not_found") {
|
||||
// No HTTP response at all (connection refused, timeout, DNS) — that's
|
||||
@@ -105,27 +114,14 @@ function streamerErrorToAnonymous(
|
||||
httpStatus = 502;
|
||||
}
|
||||
|
||||
logger.warn("streamer fetch failed", {
|
||||
code: errCode,
|
||||
const error = new AnonymousError(errCode, {
|
||||
httpStatus,
|
||||
repoId: context.repoId,
|
||||
filePath: context.filePath,
|
||||
upstreamStatus,
|
||||
upstreamBody: upstreamBody?.slice(0, 500),
|
||||
url: config.STREAMER_ENTRYPOINT
|
||||
? join(config.STREAMER_ENTRYPOINT, "api")
|
||||
: undefined,
|
||||
err: serializeError(err),
|
||||
cause: err,
|
||||
});
|
||||
|
||||
return {
|
||||
error: new AnonymousError(errCode, {
|
||||
httpStatus,
|
||||
cause: err,
|
||||
}),
|
||||
upstreamStatus,
|
||||
upstreamBody,
|
||||
};
|
||||
error.upstreamStatus = upstreamStatus;
|
||||
// A coded body comes from the streamer's handleError, which logged it.
|
||||
error.upstreamLogged = streamerCode && typeof upstreamStatus === "number";
|
||||
return { error, upstreamStatus, upstreamBody };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -434,7 +430,7 @@ export default class AnonymizedFile {
|
||||
},
|
||||
}));
|
||||
content.on("error", err => {
|
||||
const { error } = streamerErrorToAnonymous(err, { repoId: this.repository.repoId, filePath: this.anonymizedPath });
|
||||
const { error } = streamerErrorToAnonymous(err);
|
||||
void notifyOwnerAccessProblem(this.repository.owner.id, error, { kind: "repository", id: String(this.repository.model._id) });
|
||||
});
|
||||
return content;
|
||||
@@ -493,7 +489,7 @@ export default class AnonymizedFile {
|
||||
headersDone(true);
|
||||
const { error } = streamerErrorToAnonymous(err as Error & {
|
||||
response?: { statusCode?: number; body?: unknown };
|
||||
}, { repoId: this.repository.repoId, filePath: this.anonymizedPath });
|
||||
});
|
||||
void notifyOwnerAccessProblem(this.repository.owner.id, error, { kind: "repository", id: String(this.repository.model._id) });
|
||||
error.value = this;
|
||||
throw error;
|
||||
@@ -540,16 +536,16 @@ export default class AnonymizedFile {
|
||||
const { error } = streamerErrorToAnonymous(
|
||||
err as Error & {
|
||||
response?: { statusCode?: number; body?: unknown };
|
||||
},
|
||||
{
|
||||
repoId: this.repository.repoId,
|
||||
filePath: this.anonymizedPath,
|
||||
}
|
||||
);
|
||||
void notifyOwnerAccessProblem(this.repository.owner.id, error, { kind: "repository", id: String(this.repository.model._id) });
|
||||
error.value = this;
|
||||
// Only a response that was already streaming body bytes must be
|
||||
// cut. handleError's own reply can be mid-write: express-session
|
||||
// holds back its last byte until the session store touch ends.
|
||||
const streaming = res.headersSent;
|
||||
handleError(error, res);
|
||||
if (res.headersSent && !res.writableEnded) res.destroy();
|
||||
if (streaming && !res.writableEnded) res.destroy();
|
||||
});
|
||||
resolve();
|
||||
return;
|
||||
|
||||
@@ -12,6 +12,10 @@ export default class AnonymousError extends CustomError {
|
||||
value?: unknown;
|
||||
httpStatus?: number;
|
||||
cause?: Error;
|
||||
/** Status of the internal service response this error relays. */
|
||||
upstreamStatus?: number;
|
||||
/** The internal service that answered already logged this failure. */
|
||||
upstreamLogged?: boolean;
|
||||
private explicitUrl?: string;
|
||||
|
||||
constructor(
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { recordResponseFailure } from "./request-evidence";
|
||||
import { watchClientClose } from "./response-cancellation";
|
||||
import { createGzip } from "zlib";
|
||||
import { createHash } from "crypto";
|
||||
import { Readable, PassThrough } from "stream";
|
||||
@@ -53,12 +54,19 @@ async function sendCached(content: Readable, res: Response,
|
||||
// Install evidence before pipeline's listeners destroy the response.
|
||||
const localFailure = () => { if (!res.destroyed) recordResponseFailure(res, "unknown", "local_abort"); };
|
||||
stream.once("error", localFailure);
|
||||
if (record.encoding === "identity" && !res.req.acceptsEncodings("identity")) {
|
||||
res.setHeader("Content-Encoding", "gzip"); res.removeHeader("Content-Length");
|
||||
const gzip = createGzip();
|
||||
gzip.once("error", localFailure);
|
||||
await pipeline(stream, gzip, res);
|
||||
} else await pipeline(stream, res);
|
||||
const clientClosed = watchClientClose(res, stream);
|
||||
try {
|
||||
if (record.encoding === "identity" && !res.req.acceptsEncodings("identity")) {
|
||||
res.setHeader("Content-Encoding", "gzip"); res.removeHeader("Content-Length");
|
||||
const gzip = createGzip();
|
||||
gzip.once("error", localFailure);
|
||||
await pipeline(stream, gzip, res);
|
||||
} else await pipeline(stream, res);
|
||||
} catch (error) {
|
||||
// A visitor who stops a download is not a server fault.
|
||||
if (clientClosed()) throw Object.assign(new Error("response_cancelled"), { cause: error });
|
||||
throw error;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
const decision = results.decision(key);
|
||||
|
||||
@@ -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>"
|
||||
],
|
||||
@@ -1570,11 +1570,13 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
],
|
||||
"src/core/response-cancellation.ts": [
|
||||
"<anonymous>",
|
||||
"isResponseCancellation"
|
||||
"isResponseCancellation",
|
||||
"watchClientClose"
|
||||
],
|
||||
"build/core/response-cancellation.js": [
|
||||
"<anonymous>",
|
||||
"isResponseCancellation"
|
||||
"isResponseCancellation",
|
||||
"watchClientClose"
|
||||
],
|
||||
"src/core/response-stream.ts": [
|
||||
"<anonymous>",
|
||||
@@ -1643,6 +1645,7 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
"admitResolvedBytes",
|
||||
"assertActive",
|
||||
"assertDownloadUrl",
|
||||
"assertHost",
|
||||
"cached",
|
||||
"confirmOwnerAccess",
|
||||
"deferredRawDownload",
|
||||
@@ -1651,6 +1654,7 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
"downloadFile",
|
||||
"downloadFileViaRaw",
|
||||
"downloadRaw",
|
||||
"downloadViaJsDelivr",
|
||||
"downloadWithFallback",
|
||||
"fallbackToRaw",
|
||||
"fetchContent",
|
||||
@@ -1663,9 +1667,12 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
"githubRawFileUrl",
|
||||
"iterateFiles",
|
||||
"iterateTreeBatches",
|
||||
"jsDelivrFileUrl",
|
||||
"lfsPointerGuard",
|
||||
"normalize",
|
||||
"pMap",
|
||||
"produce",
|
||||
"rejectLfsPointer",
|
||||
"resolve",
|
||||
"resolveLfsPointer",
|
||||
"stopSourceOnDestroy",
|
||||
@@ -1679,6 +1686,7 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
"admitResolvedBytes",
|
||||
"assertActive",
|
||||
"assertDownloadUrl",
|
||||
"assertHost",
|
||||
"cached",
|
||||
"confirmOwnerAccess",
|
||||
"deferredRawDownload",
|
||||
@@ -1687,6 +1695,7 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
"downloadFile",
|
||||
"downloadFileViaRaw",
|
||||
"downloadRaw",
|
||||
"downloadViaJsDelivr",
|
||||
"downloadWithFallback",
|
||||
"fallbackToRaw",
|
||||
"fetchContent",
|
||||
@@ -1699,9 +1708,12 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
"githubRawFileUrl",
|
||||
"iterateFiles",
|
||||
"iterateTreeBatches",
|
||||
"jsDelivrFileUrl",
|
||||
"lfsPointerGuard",
|
||||
"normalize",
|
||||
"pMap",
|
||||
"produce",
|
||||
"rejectLfsPointer",
|
||||
"resolve",
|
||||
"resolveLfsPointer",
|
||||
"stopSourceOnDestroy",
|
||||
@@ -1990,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",
|
||||
@@ -2623,6 +2677,7 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
"src/server/routes/route-utils.ts": [
|
||||
"<anonymous>",
|
||||
"ensureUrl",
|
||||
"errorLogLevel",
|
||||
"explicitErrorStatus",
|
||||
"extendExpirationDate",
|
||||
"getGist",
|
||||
@@ -2640,6 +2695,7 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
"build/server/routes/route-utils.js": [
|
||||
"<anonymous>",
|
||||
"ensureUrl",
|
||||
"errorLogLevel",
|
||||
"explicitErrorStatus",
|
||||
"extendExpirationDate",
|
||||
"getGist",
|
||||
@@ -2918,12 +2974,15 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
],
|
||||
"src/streamer/route.ts": [
|
||||
"<anonymous>",
|
||||
"handleStreamError"
|
||||
"handleStreamError",
|
||||
"replyError"
|
||||
],
|
||||
"build/streamer/route.js": [
|
||||
"<anonymous>",
|
||||
"handleStreamError"
|
||||
"handleStreamError",
|
||||
"replyError"
|
||||
]
|
||||
};
|
||||
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","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"];
|
||||
@@ -1,7 +1,7 @@
|
||||
import { ANONYMIZATION_ERRORS } from "./anonymization-errors";
|
||||
import { requestReproduction, safeReproductionPath } from "./log-reproduction";
|
||||
import { safeDiagnosticFields, errorDiagnostics } from "./log-diagnostics";
|
||||
import { LOG_ROUTES } from "./log-diagnostic-schema";
|
||||
import { LOG_ROUTES, LOG_THROWN_ERROR_CODES } from "./log-diagnostic-schema";
|
||||
import { LOG_MODULES, ERROR_CODES, LOG_EVENTS } from "./log-schema";
|
||||
import { randomUUID } from "crypto";
|
||||
import { logContext, validTraceId } from "./log-context";
|
||||
@@ -17,8 +17,9 @@ const events: Record<string, string> = {
|
||||
"process heartbeat": "process_heartbeat", "job started": "job_started", "job completed": "job_completed",
|
||||
"job failed": "job_failed", "job stalled": "job_stalled", "queue heartbeat": "queue_heartbeat",
|
||||
};
|
||||
const errorCodes = new Set([
|
||||
...ERROR_CODES, ...ANONYMIZATION_ERRORS, "zip_unsafe_entry_path",
|
||||
// LOG_THROWN_ERROR_CODES is generated from the codes the source throws.
|
||||
export const LOG_ERROR_CODES: ReadonlySet<string> = new Set([
|
||||
...ERROR_CODES, ...ANONYMIZATION_ERRORS, ...LOG_THROWN_ERROR_CODES, "zip_unsafe_entry_path",
|
||||
"repo_renamed", "preparation_interrupted", "commit_not_found", "zip_not_available", "token_refresh_failed", "quota_exceeded", "quota_repository_limit", "quota_storage_limit", "github_rate_limit_exceeded", "github_app_reconnect_required", "github_token_invalid",
|
||||
"repository_expired", "repository_not_ready", "repository_not_found", "repository_job_cancelled",
|
||||
"ECONNRESET", "ECONNREFUSED", "ETIMEDOUT", "ENOTFOUND", "EPIPE", "ABORT_ERR",
|
||||
@@ -57,7 +58,7 @@ export function logRecord(level: string, module: string, args: unknown[]) {
|
||||
}
|
||||
if (Number.isSafeInteger(context.attempt)) record.attempt = context.attempt;
|
||||
for (const key of LOG_NUMBERS) if (typeof details[key] === "number" && Number.isFinite(details[key])) record[key] = details[key];
|
||||
const code = [details.code, details.message].find(value => typeof value === "string" && errorCodes.has(value));
|
||||
const code = [details.code, details.message].find(value => typeof value === "string" && LOG_ERROR_CODES.has(value));
|
||||
if (code) record.errorCode = code;
|
||||
if (allowed(["protocol", "credentials", "port", "host"], details.reason)) record.reason = details.reason;
|
||||
if (allowed(["parse", "find_grant_owners", "reconcile_grant", "persist_installation_block", "reconcile_installation"], details.phase)) record.phase = details.phase;
|
||||
|
||||
@@ -325,6 +325,7 @@ type ErrorLike = {
|
||||
stack?: string;
|
||||
status?: number;
|
||||
httpStatus?: number;
|
||||
upstreamStatus?: number;
|
||||
code?: string | number;
|
||||
cause?: unknown;
|
||||
request?: { url?: string; method?: string };
|
||||
@@ -353,6 +354,7 @@ export function serializeError(err: unknown, seen = new WeakSet<object>(), depth
|
||||
|
||||
// AnonymousError carries an httpStatus and an inner cause.
|
||||
if (typeof e.httpStatus === "number") out.httpStatus = e.httpStatus;
|
||||
if (typeof e.upstreamStatus === "number") out.upstreamStatus = e.upstreamStatus;
|
||||
// Octokit's deprecated `code` getter emits a stack on every read. Only
|
||||
// inspect data properties so logging never invokes that getter.
|
||||
const code = Object.getOwnPropertyDescriptor(e, "code")?.value;
|
||||
|
||||
@@ -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);
|
||||
@@ -14,3 +14,19 @@ export function isResponseCancellation(error: unknown, response?: { destroyed?:
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* pipeline() rejects with ERR_STREAM_PREMATURE_CLOSE both when the client goes
|
||||
* away and when the source ends early. Call before piping; the returned check
|
||||
* is true only when the response closed unfinished before the source failed.
|
||||
*/
|
||||
export function watchClientClose(response: { writableFinished?: boolean; once(event: "close", listener: () => void): unknown },
|
||||
source: { readableEnded?: boolean; once(event: "close" | "error", listener: () => void): unknown }): () => boolean {
|
||||
let sourceFailed = false;
|
||||
let clientClosed = false;
|
||||
source.once("error", () => { sourceFailed = true; });
|
||||
// A source that closes without ending was cut short.
|
||||
source.once("close", () => { if (!source.readableEnded) sourceFailed = true; });
|
||||
response.once("close", () => { if (!sourceFailed && !response.writableFinished) clientClosed = true; });
|
||||
return () => clientClosed;
|
||||
}
|
||||
@@ -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"];
|
||||
|
||||
@@ -17,13 +17,10 @@ import { RepositoryStatus } from "../../core/types";
|
||||
import User from "../../core/User";
|
||||
import { streamAnonymizedZip } from "../../core/zipStream";
|
||||
import FileModel from "../../core/model/files/files.model";
|
||||
import { createLogger, serializeError } from "../../core/logger";
|
||||
import { githubTokenForStreamer } from "../../core/github-token-context";
|
||||
import gh = require("parse-github-url");
|
||||
import { requestHeaders, startStage } from "../../core/request-monitoring";
|
||||
|
||||
const logger = createLogger("repository-public");
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
router.get(
|
||||
@@ -94,6 +91,7 @@ router.get(
|
||||
headersDone(true);
|
||||
const upstreamStatus = err?.response?.statusCode;
|
||||
let upstreamBody: string | undefined;
|
||||
let streamerCode = false;
|
||||
let errCode = "zip_not_available";
|
||||
let httpStatus = 502;
|
||||
if (err?.response?.body != null) {
|
||||
@@ -112,6 +110,7 @@ router.get(
|
||||
const parsed = JSON.parse(upstreamBody);
|
||||
if (parsed && typeof parsed.error === "string") {
|
||||
errCode = parsed.error;
|
||||
streamerCode = true;
|
||||
}
|
||||
} catch {
|
||||
/* not JSON */
|
||||
@@ -121,26 +120,17 @@ router.get(
|
||||
if (typeof upstreamStatus === "number") {
|
||||
httpStatus = upstreamStatus >= 500 ? 502 : upstreamStatus;
|
||||
}
|
||||
logger.warn("streamer zip fetch failed", {
|
||||
code: errCode,
|
||||
httpStatus,
|
||||
repoId: repo.repoId,
|
||||
upstreamStatus,
|
||||
upstreamBody: upstreamBody?.slice(0, 500),
|
||||
url: config.STREAMER_ENTRYPOINT
|
||||
? join(config.STREAMER_ENTRYPOINT, "api/download")
|
||||
: undefined,
|
||||
err: serializeError(err),
|
||||
});
|
||||
const streaming = res.headersSent;
|
||||
handleError(
|
||||
new AnonymousError(errCode, {
|
||||
url: req.originalUrl,
|
||||
httpStatus,
|
||||
cause: err,
|
||||
}),
|
||||
res
|
||||
);
|
||||
const error = new AnonymousError(errCode, {
|
||||
url: req.originalUrl,
|
||||
httpStatus,
|
||||
cause: err,
|
||||
});
|
||||
error.upstreamStatus = upstreamStatus;
|
||||
// A coded body comes from the streamer's handleError, which
|
||||
// already logged this failure under the same requestId.
|
||||
error.upstreamLogged = streamerCode && typeof upstreamStatus === "number";
|
||||
handleError(error, res);
|
||||
// Once ZIP bytes have been sent, handleError cannot send JSON.
|
||||
// Terminate the truncated response so the client reports failure
|
||||
// instead of waiting forever for the ZIP's central directory.
|
||||
|
||||
@@ -184,8 +184,44 @@ export function explicitErrorStatus(error: unknown): number | undefined {
|
||||
.find(status => Number.isInteger(status) && status! >= 400 && status! <= 599);
|
||||
}
|
||||
|
||||
// Request end states that need no operator action: the visitor asked for
|
||||
// something that is gone, expired, unsupported or not theirs. They are logged
|
||||
// at info so the admin Errors page (warn and error) keeps to faults. Rate
|
||||
// limits, expired owner tokens and upstream failures are left out on purpose.
|
||||
export const EXPECTED_CLIENT_ERRORS: ReadonlySet<string> = new Set([
|
||||
"repo_not_found", "repository_not_found", "commit_not_found", "branch_not_found",
|
||||
"file_not_found", "folder_not_supported", "file_not_supported", "file_too_big",
|
||||
"readme_not_available", "submodule_not_available",
|
||||
"repository_expired", "repository_archived", "repository_not_ready", "is_removed",
|
||||
"github_app_access_required", "not_connected", "not_authorized",
|
||||
"page_not_activated", "page_not_supported_on_different_branch", "download_not_enabled",
|
||||
"gist_not_found", "gist_expired", "gist_not_ready",
|
||||
"pull_request_not_found", "pull_request_expired", "pull_request_not_ready",
|
||||
"conf_not_found", "conference_not_found", "repoId_already_used", "invalid_repoId",
|
||||
]);
|
||||
|
||||
export type ErrorLogOptions = {
|
||||
/** The reply goes to another service that logs the request's end state. */
|
||||
internal?: boolean;
|
||||
};
|
||||
|
||||
type LogLevel = "debug" | "info" | "warn" | "error";
|
||||
|
||||
/** One record per failed request, at a level that matches who has to act. */
|
||||
export function errorLogLevel(error: unknown, options: ErrorLogOptions = {}): LogLevel {
|
||||
const status = explicitErrorStatus(error);
|
||||
let level: LogLevel = status !== undefined && status < 500 ? "warn" : "error";
|
||||
if (error instanceof AnonymousError) {
|
||||
// The internal service that answered logged the failure at its own level.
|
||||
if (error.upstreamLogged) level = "info";
|
||||
else if (level === "warn" && EXPECTED_CLIENT_ERRORS.has(error.message)) level = "info";
|
||||
}
|
||||
return level === "info" && options.internal ? "debug" : level;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
function printError(error: any, req?: express.Request) {
|
||||
function printError(error: any, req?: express.Request, options: ErrorLogOptions = {}) {
|
||||
const level = errorLogLevel(error, options);
|
||||
if (error instanceof AnonymousError) {
|
||||
if (req?.originalUrl === "/api/repo/undefined/options") return;
|
||||
const payload: Record<string, unknown> = serializeError(error);
|
||||
@@ -194,20 +230,11 @@ function printError(error: any, req?: express.Request) {
|
||||
// Errors page surfaces something meaningful (e.g. "repoId_already_used")
|
||||
// instead of a generic "anonymous error" wrapper.
|
||||
const summary = error.message || error.name || "AnonymousError";
|
||||
// 4xx are expected client errors (not_found, expired, not_connected) —
|
||||
// route them to warn so the admin Errors page can split server faults
|
||||
// (5xx) from client misuse (4xx) cleanly.
|
||||
const status = explicitErrorStatus(error);
|
||||
if (typeof status === "number" && status >= 400 && status < 500) {
|
||||
logger.warn(summary, payload);
|
||||
} else {
|
||||
logger.error(summary, payload);
|
||||
}
|
||||
logger[level](summary, payload);
|
||||
} else if (error instanceof HTTPError) {
|
||||
const payload: Record<string, unknown> = serializeError(error);
|
||||
ensureUrl(payload, req);
|
||||
const status = explicitErrorStatus(error);
|
||||
logger[status && status < 500 ? "warn" : "error"](error.code || error.name || "HTTPError", payload);
|
||||
logger[level](error.code || error.name || "HTTPError", payload);
|
||||
} else {
|
||||
// Unhandled errors: use the error class name (SyntaxError, TypeError,
|
||||
// RangeError, ...) as the summary so the admin page shows
|
||||
@@ -225,8 +252,7 @@ function printError(error: any, req?: express.Request) {
|
||||
((error as { name?: string }).name ||
|
||||
(error as { message?: string }).message)) ||
|
||||
"UnhandledError";
|
||||
const status = explicitErrorStatus(error);
|
||||
logger[status && status < 500 ? "warn" : "error"](summary, serialized);
|
||||
logger[level](summary, serialized);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -234,10 +260,11 @@ export function handleError(
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
error: any,
|
||||
res?: express.Response,
|
||||
req?: express.Request
|
||||
req?: express.Request,
|
||||
options?: ErrorLogOptions
|
||||
) {
|
||||
if (isResponseCancellation(error, res)) return;
|
||||
printError(error, req);
|
||||
printError(error, req, options);
|
||||
let errorCode = error;
|
||||
if (error instanceof Error) {
|
||||
errorCode = error.message;
|
||||
|
||||
@@ -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); }
|
||||
});
|
||||
|
||||
|
||||
@@ -43,7 +43,8 @@ app.get("/healthcheck", async (_, res) => {
|
||||
|
||||
app.all("/{*path}", (req, res) => {
|
||||
handleError(
|
||||
new AnonymousError("file_not_found", {
|
||||
// Callers only use known routes; reaching here is a misconfiguration.
|
||||
new AnonymousError("streamer_route_not_found", {
|
||||
httpStatus: 404,
|
||||
url: req.originalUrl,
|
||||
}),
|
||||
|
||||
+17
-8
@@ -6,10 +6,17 @@ import {
|
||||
AnonymizeTransformer,
|
||||
isTextFile,
|
||||
} from "../core/anonymize-utils";
|
||||
import AnonymousError from "../core/AnonymousError";
|
||||
import { handleError } from "../server/routes/route-utils";
|
||||
import { lookup } from "mime-types";
|
||||
import { streamAnonymizedZip } from "../core/zipStream";
|
||||
|
||||
// The API relays these replies and logs each request's end state, so expected
|
||||
// outcomes are only debug here. Faults keep their level and streamer stack.
|
||||
function replyError(error: unknown, res: express.Response) {
|
||||
handleError(error, res, undefined, { internal: true });
|
||||
}
|
||||
|
||||
export const router = express.Router();
|
||||
|
||||
router.post(
|
||||
@@ -18,7 +25,7 @@ router.post(
|
||||
req.body = req.body || {};
|
||||
const token: string = req.body.token;
|
||||
if (typeof req.body.repoFullName !== "string" || typeof token !== "string") {
|
||||
return res.status(400).json({ error: "invalid_request" });
|
||||
return replyError(new AnonymousError("invalid_request", { httpStatus: 400 }), res);
|
||||
}
|
||||
const repoFullName = req.body.repoFullName.split("/");
|
||||
const repoId = req.body.repoId;
|
||||
@@ -41,8 +48,9 @@ router.post(
|
||||
res
|
||||
);
|
||||
} catch (error) {
|
||||
handleError(error, res);
|
||||
if (res.headersSent && !res.writableEnded) res.destroy();
|
||||
const streaming = res.headersSent;
|
||||
replyError(error, res);
|
||||
if (streaming && !res.writableEnded) res.destroy();
|
||||
}
|
||||
}
|
||||
);
|
||||
@@ -50,7 +58,7 @@ router.post("/", async (req: express.Request, res: express.Response) => {
|
||||
req.body = req.body || {};
|
||||
const token: string = req.body.token;
|
||||
if (typeof req.body.repoFullName !== "string" || typeof token !== "string") {
|
||||
return res.status(400).json({ error: "invalid_request" });
|
||||
return replyError(new AnonymousError("invalid_request", { httpStatus: 400 }), res);
|
||||
}
|
||||
const repoFullName = req.body.repoFullName.split("/");
|
||||
const repoId = req.body.repoId;
|
||||
@@ -76,7 +84,7 @@ router.post("/", async (req: express.Request, res: express.Response) => {
|
||||
.split(/[\\/]/)
|
||||
.some((segment) => segment === ".." || segment === "")
|
||||
) {
|
||||
return res.status(400).json({ error: "invalid_file_path" });
|
||||
return replyError(new AnonymousError("invalid_file_path", { httpStatus: 400 }), res);
|
||||
}
|
||||
|
||||
const source = new GitHubStream({
|
||||
@@ -121,8 +129,9 @@ router.post("/", async (req: express.Request, res: express.Response) => {
|
||||
if (!content.closed && !content.destroyed) {
|
||||
content.destroy();
|
||||
}
|
||||
handleError(error, res);
|
||||
if (res.headersSent && !res.writableEnded) res.destroy();
|
||||
const streaming = res.headersSent;
|
||||
replyError(error, res);
|
||||
if (streaming && !res.writableEnded) res.destroy();
|
||||
anonymizer.destroy();
|
||||
}
|
||||
content
|
||||
@@ -144,7 +153,7 @@ router.post("/", async (req: express.Request, res: express.Response) => {
|
||||
res.status(409).end();
|
||||
return;
|
||||
}
|
||||
handleError(error, res);
|
||||
replyError(error, res);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
Reference in new issue
Block a user