mirror of
https://github.com/tdurieux/anonymous_github.git
synced 2026-10-21 07:01:16 +02:00
feat: notify owners when GitHub access needs attention
This commit is contained in:
1 parent
f92cfbe795
commit
95f8aef30a
21 files changed
+548
-38
No files matched your search
+12
-3
@@ -1,4 +1,5 @@
|
||||
import { refreshLegacyToken } from "./legacy-token-refresh";
|
||||
import { notifyOwnerAccessProblem } from "./owner-notifications";
|
||||
import AnonymizedRepositoryModel from "./model/anonymizedRepositories/anonymizedRepositories.model";
|
||||
import { isConnected } from "../server/database";
|
||||
import { githubQuotaKey, githubTokenContext } from "./github-token-context";
|
||||
@@ -289,7 +290,7 @@ export function octokit(token: string) {
|
||||
|
||||
export { waitForTokenGate };
|
||||
|
||||
export async function checkToken(token: string) {
|
||||
export async function checkToken(token: string, ownerId?: string) {
|
||||
const oct = octokit(token);
|
||||
try {
|
||||
const context = githubTokenContext(token);
|
||||
@@ -304,6 +305,9 @@ export async function checkToken(token: string) {
|
||||
) {
|
||||
throw err;
|
||||
}
|
||||
if (ownerId && (err as { status?: number }).status === 401) {
|
||||
void notifyOwnerAccessProblem(ownerId, "token_expired");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -311,7 +315,12 @@ export async function checkToken(token: string) {
|
||||
const checkedRepositoryTokens = new WeakMap<Repository, string>();
|
||||
|
||||
export async function getToken(repository: Repository) {
|
||||
return measureStage("authorization", () => resolveRepositoryToken(repository));
|
||||
try {
|
||||
return await measureStage("authorization", () => resolveRepositoryToken(repository));
|
||||
} catch (error) {
|
||||
void notifyOwnerAccessProblem(repository.owner.id, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveRepositoryToken(repository: Repository) {
|
||||
@@ -344,7 +353,7 @@ async function resolveRepositoryToken(repository: Repository) {
|
||||
return refreshed;
|
||||
}
|
||||
}
|
||||
const check = await checkToken(ownerAccessToken);
|
||||
const check = await checkToken(ownerAccessToken, repository.owner.id);
|
||||
if (check) {
|
||||
checkedRepositoryTokens.set(repository, ownerAccessToken);
|
||||
return ownerAccessToken;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { notifyOwnerAccessProblem } from "./owner-notifications";
|
||||
import AnonymizedPathModel from "./model/anonymized-path";
|
||||
import storage from "./storage";
|
||||
import { contentGenerationPrefix, contentRetirementMarker } from "./content-generation";
|
||||
@@ -223,7 +224,10 @@ export default class Repository {
|
||||
const previousPrefix = contentGenerationPrefix(`${previousGeneration || "legacy"}:${this.model.anonymizeDate?.toISOString() || ""}`);
|
||||
const streamed = this.model.source.type !== "Zip";
|
||||
const source = this.source;
|
||||
const files = await source.getFiles(opt.progress);
|
||||
const files = await source.getFiles(opt.progress).catch(error => {
|
||||
void notifyOwnerAccessProblem(this.owner.id, error);
|
||||
throw error;
|
||||
});
|
||||
const sourceWithTruncation = source as unknown as { truncatedFolderList?: string[] };
|
||||
const truncatedFolders = Array.isArray(sourceWithTruncation.truncatedFolderList)
|
||||
? [...sourceWithTruncation.truncatedFolderList] : [];
|
||||
@@ -654,6 +658,9 @@ export default class Repository {
|
||||
repo: this.source.data.repoName,
|
||||
repositoryID: this.model.source.repositoryId,
|
||||
force: true,
|
||||
}).catch(error => {
|
||||
void notifyOwnerAccessProblem(this.owner.id, error);
|
||||
throw error;
|
||||
});
|
||||
|
||||
// update the repository name if it has changed. Persist it
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { notifyOwnerAccessProblem } from "./owner-notifications";
|
||||
import { registerGitHubToken } from "./github-token-context";
|
||||
import { createSign, randomUUID } from "crypto";
|
||||
import { readFileSync } from "fs";
|
||||
@@ -87,6 +88,14 @@ export async function saveAppGrant(ownerId: string, data: AppTokenResponse) {
|
||||
}
|
||||
|
||||
export async function appUserToken(ownerId: string): Promise<string> {
|
||||
try { return await resolveAppUserToken(ownerId); }
|
||||
catch (error) {
|
||||
void notifyOwnerAccessProblem(ownerId, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveAppUserToken(ownerId: string): Promise<string> {
|
||||
if (!config.GITHUB_APP_ENABLED) throw appError("github_app_disabled", 503);
|
||||
const user = await UserModel.findById(ownerId).select("status externalIDs").lean();
|
||||
if (!user || user.status === "removed" || user.status === "banned") throw appError();
|
||||
|
||||
@@ -15,6 +15,8 @@ const UserSchema = new Schema({
|
||||
type: String,
|
||||
index: { unique: true },
|
||||
},
|
||||
emailPromptNever: { type: Boolean, default: false },
|
||||
accessAlertAfter: { type: Date, select: false },
|
||||
emails: [
|
||||
{
|
||||
email: { type: String },
|
||||
|
||||
@@ -20,6 +20,7 @@ export interface IUser {
|
||||
createdAt?: Date;
|
||||
lastUsedAt?: Date;
|
||||
}[];
|
||||
emailPromptNever?: boolean;
|
||||
emails: {
|
||||
email: string;
|
||||
default: boolean;
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import config from "../config";
|
||||
import UserModel from "./model/users/users.model";
|
||||
import { createLogger } from "./logger";
|
||||
|
||||
const logger = createLogger("owner-notifications");
|
||||
const DAY = 24 * 60 * 60 * 1000;
|
||||
const accessErrors = new Set([
|
||||
"token_expired", "github_oauth_required", "github_app_reconnect_required",
|
||||
"github_app_access_required", "repo_not_found", "repository_not_found",
|
||||
"repo_not_accessible", "repo_access_limited", "repo_saml_enforcement",
|
||||
]);
|
||||
|
||||
export function normalizeEmail(value: unknown): string | null {
|
||||
if (typeof value !== "string") return null;
|
||||
const email = value.trim();
|
||||
// Accept one plain mailbox, never a display name or recipient list.
|
||||
if (email.length > 254 || !/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?\.[a-zA-Z]{2,}$/.test(email)) return null;
|
||||
const local = email.split("@")[0];
|
||||
if (local.length > 64 || local.startsWith(".") || local.endsWith(".") || email.includes("..")) return null;
|
||||
return email;
|
||||
}
|
||||
|
||||
export function notificationEmail(emails?: { email: string; default: boolean }[]): string {
|
||||
return normalizeEmail(emails?.find(e => e.default)?.email) ||
|
||||
emails?.map(e => normalizeEmail(e.email)).find(Boolean) || "";
|
||||
}
|
||||
|
||||
export function isAccessFailure(error: unknown): boolean {
|
||||
const code = typeof error === "string" ? error : error instanceof Error ? error.message : "";
|
||||
if (!accessErrors.has(code)) return false;
|
||||
if (error instanceof Error) {
|
||||
const upstream = (error as Error & { cause?: { status?: number; httpStatus?: number } }).cause;
|
||||
// Some legacy paths wrap timeouts or 5xx responses as repo_not_found.
|
||||
// Only a confirmed access failure should prompt the owner to reconnect.
|
||||
if (upstream && ![401, 403, 404].includes(upstream.status || upstream.httpStatus || 0)) return false;
|
||||
const status = (error as Error & { httpStatus?: number }).httpStatus;
|
||||
if (status && (status === 429 || status >= 500)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Best effort; mail and database failures must not change repository behavior. */
|
||||
export async function notifyOwnerAccessProblem(ownerId: string, error: unknown): Promise<void> {
|
||||
if (!config.RESEND_API_KEY || !config.EMAIL_FROM || !isAccessFailure(error)) return;
|
||||
try {
|
||||
const now = new Date();
|
||||
// The atomic claim limits all repositories and workers to one email per owner
|
||||
// per day. Claim before sending so concurrent requests cannot flood an inbox.
|
||||
const owner = await UserModel.findOneAndUpdate({
|
||||
_id: ownerId, status: { $nin: ["removed", "banned"] },
|
||||
"emails.0": { $exists: true },
|
||||
$or: [{ accessAlertAfter: { $exists: false } }, { accessAlertAfter: { $lte: now } }],
|
||||
}, { $set: { accessAlertAfter: new Date(now.getTime() + DAY) } }, { new: true }).lean();
|
||||
if (!owner) return;
|
||||
const to = notificationEmail(owner.emails);
|
||||
if (!to) return;
|
||||
const base = /^https?:\/\//.test(config.APP_HOSTNAME) ? config.APP_HOSTNAME : `https://${config.APP_HOSTNAME}`;
|
||||
const url = new URL("/connections", base).href;
|
||||
try {
|
||||
const response = await fetch("https://api.resend.com/emails", {
|
||||
method: "POST",
|
||||
headers: { Authorization: `Bearer ${config.RESEND_API_KEY}`, "Content-Type": "application/json" },
|
||||
signal: AbortSignal.timeout(15000),
|
||||
body: JSON.stringify({
|
||||
from: config.EMAIL_FROM, to: [to],
|
||||
subject: "Your Anonymous GitHub connection needs attention",
|
||||
text: `Anonymous GitHub could not access GitHub using your connection, or could not read a repository.\n\nOpen your connections page to reconnect your account or restore repository access:\n${url}\n\nYou are receiving this email because you own content on Anonymous GitHub. You can change your alert address on the connections page.\n`,
|
||||
}),
|
||||
});
|
||||
if (!response.ok) throw new Error("email_delivery_failed");
|
||||
} catch {
|
||||
// Permit retry on a later access failure, with a short backoff for outages.
|
||||
await UserModel.updateOne({ _id: ownerId, accessAlertAfter: new Date(now.getTime() + DAY) },
|
||||
{ $set: { accessAlertAfter: new Date(now.getTime() + 10 * 60000) } });
|
||||
logger.warn("owner access email delivery failed");
|
||||
}
|
||||
} catch {
|
||||
// Do not log provider errors, which can contain credentials or addresses.
|
||||
logger.warn("owner access email unavailable");
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
const sensitive = /^(?:authorization|proxy-authorization|cookie|set-cookie|token|access_?tokens?|refresh_?token|encryptedToken|encryptedRefreshToken|private_?key|GITHUB_APP_PRIVATE_KEY|GITHUB_APP_CLIENT_SECRET|GITHUB_APP_WEBHOOK_SECRET|ciphertext|nonce|tag|password|client_?secret|CREDENTIAL_KEYS)$/i;
|
||||
const sensitive = /^(?:authorization|proxy-authorization|cookie|set-cookie|token|access_?tokens?|refresh_?token|encryptedToken|encryptedRefreshToken|private_?key|GITHUB_APP_PRIVATE_KEY|GITHUB_APP_CLIENT_SECRET|GITHUB_APP_WEBHOOK_SECRET|ciphertext|nonce|tag|password|client_?secret|CREDENTIAL_KEYS|RESEND_API_KEY)$/i;
|
||||
export function redactSecrets(value: unknown, seen = new WeakSet<object>()): unknown {
|
||||
if (typeof value === "string") return value
|
||||
.replace(/\b(?:gh[pousr]_[A-Za-z0-9_]+|github_pat_[A-Za-z0-9_]+)\b/g, "[REDACTED]")
|
||||
|
||||
Reference in new issue
Block a user