mirror of
https://github.com/tdurieux/anonymous_github.git
synced 2026-11-18 01:54:23 +01:00
feat(admin): track email delivery attempts
This commit is contained in:
1 parent
104af7d261
commit
6400760fcb
24 files changed
+376
-44
No files matched your search
@@ -0,0 +1,60 @@
|
||||
import { randomUUID } from "crypto";
|
||||
import { mongo } from "mongoose";
|
||||
import UserModel from "./model/users/users.model";
|
||||
import { createLogger } from "./logger";
|
||||
|
||||
const logger = createLogger("email-history");
|
||||
export const EMAIL_HISTORY = "email_delivery_history";
|
||||
export interface EmailHistoryRecord {
|
||||
_id: string;
|
||||
kind: "repository-expiration" | "owner-access";
|
||||
recipient: string;
|
||||
ownerId: string;
|
||||
resourceId: string;
|
||||
resourceKind: string;
|
||||
createdAt: Date;
|
||||
completedAt?: Date;
|
||||
state: "sending" | "accepted" | "rejected" | "unknown";
|
||||
httpStatus?: number;
|
||||
}
|
||||
export const emailHistoryCollection = () => UserModel.db.collection(EMAIL_HISTORY) as unknown as mongo.Collection<EmailHistoryRecord>;
|
||||
let indexed: Promise<unknown> | undefined;
|
||||
export async function ensureEmailHistoryIndexes() {
|
||||
if (!indexed) indexed = Promise.all([
|
||||
emailHistoryCollection().createIndex({ createdAt: -1, _id: -1 }),
|
||||
emailHistoryCollection().createIndex({ state: 1, createdAt: -1, _id: -1 }),
|
||||
emailHistoryCollection().createIndex({ kind: 1, createdAt: -1, _id: -1 }),
|
||||
]).catch(error => { indexed = undefined; throw error; });
|
||||
await indexed;
|
||||
}
|
||||
|
||||
/** Store metadata only: never API keys, message bodies, or provider error bodies. */
|
||||
export async function sendTrackedEmail(metadata: Pick<EmailHistoryRecord, "kind" | "recipient" | "ownerId" | "resourceId" | "resourceKind">,
|
||||
url: string, options: RequestInit): Promise<Response> {
|
||||
const id = randomUUID(), createdAt = new Date();
|
||||
let recorded = false;
|
||||
const recording = (async () => {
|
||||
try {
|
||||
if (UserModel.db.readyState === 1) {
|
||||
await ensureEmailHistoryIndexes();
|
||||
await emailHistoryCollection().insertOne({ _id: id, ...metadata, createdAt, state: "sending" });
|
||||
recorded = true;
|
||||
}
|
||||
} catch { logger.warn("email history write unavailable"); }
|
||||
})();
|
||||
// Start the provider request immediately after the caller commits dispatch.
|
||||
// Auditing must not add a preparation gap to owner lifecycle fencing.
|
||||
const complete = async (state: EmailHistoryRecord["state"], httpStatus?: number) => {
|
||||
const completedAt = new Date();
|
||||
await recording;
|
||||
if (!recorded) return;
|
||||
try {
|
||||
await emailHistoryCollection().updateOne({ _id: id }, { $set: { state, completedAt, ...(httpStatus ? { httpStatus } : {}) } });
|
||||
} catch { logger.warn("email history completion unavailable", { id }); }
|
||||
};
|
||||
let response: Response;
|
||||
try { response = await fetch(url, options); }
|
||||
catch (error) { await complete("unknown"); throw error; }
|
||||
await complete(response.ok ? "accepted" : "rejected", response.status);
|
||||
return response;
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { sendTrackedEmail } from "./email-history";
|
||||
import { createHash, randomUUID } from "crypto";
|
||||
import { mongo, Types } from "mongoose";
|
||||
import { isGitHubRateLimitError } from "./github-rate-limit";
|
||||
@@ -577,7 +578,8 @@ export async function notifyOwnerAccessProblem(ownerId: string, error: unknown,
|
||||
let httpStatus: number | undefined;
|
||||
try {
|
||||
providerStarted = true;
|
||||
const response = await fetch("https://api.resend.com/emails", {
|
||||
const response = await sendTrackedEmail({ kind: "owner-access", recipient: to, ownerId,
|
||||
resourceId: resource.id, resourceKind: resource.kind }, "https://api.resend.com/emails", {
|
||||
method: "POST",
|
||||
headers: { Authorization: `Bearer ${config.RESEND_API_KEY}`, "Content-Type": "application/json",
|
||||
"Idempotency-Key": `owner-access-alert/${attemptId}` },
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { sendTrackedEmail } from "./email-history";
|
||||
import config from "../config";
|
||||
import RepositoryModel from "./model/anonymizedRepositories/anonymizedRepositories.model";
|
||||
import UserModel from "./model/users/users.model";
|
||||
@@ -27,7 +28,8 @@ export async function notifyRepositoryExpired(id: unknown): Promise<void> {
|
||||
}, { $set: { expirationEmailClaimedFor: expirationDate } }).exec();
|
||||
if (!claim.matchedCount) return;
|
||||
// Keep the claim even after a timeout: the provider may have accepted the email.
|
||||
const response = await fetch("https://api.resend.com/emails", {
|
||||
const response = await sendTrackedEmail({ kind: "repository-expiration", recipient: to, ownerId: String(repo.owner),
|
||||
resourceId: String(repo._id), resourceKind: "repository" }, "https://api.resend.com/emails", {
|
||||
method: "POST",
|
||||
headers: { Authorization: `Bearer ${config.RESEND_API_KEY}`, "Content-Type": "application/json",
|
||||
"Idempotency-Key": `repository-expired/${repo._id}/${expirationDate.getTime()}` },
|
||||
|
||||
Reference in new issue
Block a user