Email for professionals and teams
fix(security): sweep orphaned raw MIME daily (#219)
Hieu Nguyen (Jack)55d0f2f204fb
diff --git a/server/runtime/file-bucket.ts b/server/runtime/file-bucket.tsindex 34ac6a4..2f8b009 100644--- a/server/runtime/file-bucket.ts+++ b/server/runtime/file-bucket.ts@@ -1,6 +1,6 @@import { randomUUID } from "node:crypto";import { createReadStream, createWriteStream } from "node:fs";-import { mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";+import { mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";import { dirname, join, resolve, sep } from "node:path";import { Readable } from "node:stream";import { pipeline } from "node:stream/promises";@@ -204,8 +204,35 @@ export class FileBucket {}}- async list() {- throw new Error("FileBucket.list is not implemented");+ /** Lists objects under a prefix in key order; the cursor is the last key returned. */+ async list(options: { prefix?: string; cursor?: string; limit?: number } = {}) {+ const prefix = options.prefix ?? "";+ const limit = Math.min(options.limit ?? 1000, 1000);+ const keys: string[] = [];+ const walk = async (directory: string, relative: string): Promise<void> => {+ let entries;+ try {+ entries = await readdir(directory, { withFileTypes: true });+ } catch {+ return;+ }+ for (const entry of entries) {+ const key = relative ? `${relative}/${entry.name}` : entry.name;+ if (entry.isDirectory()) await walk(join(directory, entry.name), key);+ else if (!entry.name.endsWith(".meta.json") && key.startsWith(prefix)) keys.push(key);+ }+ };+ await walk(this.root, "");+ keys.sort();+ const after = options.cursor ? keys.filter((key) => key > options.cursor!) : keys;+ const page = after.slice(0, limit);+ const objects: { key: string; size: number; uploaded: Date }[] = [];+ for (const key of page) {+ const meta = await this.readMeta(key);+ if (meta) objects.push({ key, size: meta.size, uploaded: new Date(meta.uploaded) });+ }+ const truncated = after.length > limit;+ return { objects, truncated, cursor: truncated ? page[page.length - 1] : undefined };}}diff --git a/server/runtime/scheduler.ts b/server/runtime/scheduler.tsindex 053b159..db3739f 100644--- a/server/runtime/scheduler.ts+++ b/server/runtime/scheduler.ts@@ -7,6 +7,7 @@ import { runJmapChangeRetention } from "@/lib/jmap/changes";import { runFollowUpReminders } from "@/lib/follow-ups/service";import { runCalendarReminders } from "@/lib/calendar/reminders";import { sweepImportJobs } from "@/lib/import/jobs";+import { sweepOrphanedRawMail } from "@/lib/email/raw-sweeper";/** Fire the daily 02:00 UTC backup and the recurring maintenance jobs, matching the cron triggers in wrangler.jsonc. */export function startScheduler(env: CloudflareEnv) {@@ -25,6 +26,7 @@ export function startScheduler(env: CloudflareEnv) {runDriveTrashRetention(env, now).catch((error) => console.error("Drive trash retention failed", error));runAccountRetention(env, now).catch((error) => console.error("Account retention failed", error));runJmapChangeRetention(env, now).catch((error) => console.error("JMAP change retention failed", error));+ sweepOrphanedRawMail(env, now).catch((error) => console.error("Raw mail sweep failed", error));}, 60_000);return () => clearInterval(timer);}diff --git a/src/lib/email/raw-sweeper.ts b/src/lib/email/raw-sweeper.tsnew file mode 100644index 0000000..8cedfad--- /dev/null+++ b/src/lib/email/raw-sweeper.ts@@ -0,0 +1,40 @@+import { inArray } from "drizzle-orm";+import { getDb } from "@/db";+import { messages } from "@/db/schema";++const PREFIX = "inbound/";+const MIN_AGE_MS = 24 * 60 * 60 * 1000;+const PAGE = 100;+const MAX_PAGES = 20;+/** D1 allows 100 bound parameters per statement. */+const LOOKUP_BATCH = 50;++/**+ * Deletes raw MIME under `inbound/` that no stored message refers to and that is old enough+ * that its queue message is long finished. This catches what the early-return cleanup in+ * `processInboundMessage` cannot: messages dropped after their final failed retry and+ * mail accepted for addresses that never resolved to a mailbox.+ */+export async function sweepOrphanedRawMail(env: CloudflareEnv, now = new Date()): Promise<number> {+ const db = getDb(env);+ let removed = 0;+ let cursor: string | undefined;+ for (let page = 0; page < MAX_PAGES; page += 1) {+ const listing = await env.BUCKET.list({ prefix: PREFIX, cursor, limit: PAGE });+ const old = listing.objects.filter((object) => now.getTime() - object.uploaded.getTime() > MIN_AGE_MS).map((object) => object.key);+ const orphans: string[] = [];+ for (let index = 0; index < old.length; index += LOOKUP_BATCH) {+ const batch = old.slice(index, index + LOOKUP_BATCH);+ const referenced = await db.select({ key: messages.rawR2Key }).from(messages).where(inArray(messages.rawR2Key, batch));+ const kept = new Set(referenced.map((row) => row.key));+ orphans.push(...batch.filter((key) => !kept.has(key)));+ }+ if (orphans.length) {+ await env.BUCKET.delete(orphans);+ removed += orphans.length;+ }+ if (!listing.truncated || !listing.cursor) break;+ cursor = listing.cursor;+ }+ return removed;+}diff --git a/src/lib/storage/b2-bucket.ts b/src/lib/storage/b2-bucket.tsindex 1de4533..7771c5f 100644--- a/src/lib/storage/b2-bucket.ts+++ b/src/lib/storage/b2-bucket.ts@@ -1,5 +1,5 @@import { awsRequest, AwsError } from "@/lib/aws/client";-import { xmlTag } from "@/lib/aws/xml";+import { xmlBlocks, xmlTag } from "@/lib/aws/xml";import type { AwsConfig } from "@/lib/aws/aws-types";import type { B2Config, B2HttpMetadata } from "@/lib/storage/b2-types";@@ -136,8 +136,19 @@ export class B2Bucket {}}- async list(): Promise<never> {- throw new Error("B2Bucket.list is not implemented");+ /** ListObjectsV2 with the shape of R2's `list`: only key, size and upload time of each object. */+ async list(options: { prefix?: string; cursor?: string; limit?: number } = {}): Promise<{ objects: { key: string; size: number; uploaded: Date }[]; truncated: boolean; cursor?: string }> {+ const query: Record<string, string> = { "list-type": "2", "max-keys": String(Math.min(options.limit ?? 1000, 1000)) };+ if (options.prefix) query.prefix = options.prefix;+ if (options.cursor) query["continuation-token"] = options.cursor;+ const xml = await (await this.request(null, { query })).text();+ const objects = xmlBlocks(xml, "Contents").map((block) => ({+ key: xmlTag(block, "Key") ?? "",+ size: Number(xmlTag(block, "Size") ?? 0),+ uploaded: new Date(xmlTag(block, "LastModified") ?? Date.now()),+ })).filter((object) => object.key);+ const truncated = xmlTag(xml, "IsTruncated") === "true";+ return { objects, truncated, cursor: truncated ? xmlTag(xml, "NextContinuationToken") ?? undefined : undefined };}async createMultipartUpload(key: string, options?: { httpMetadata?: B2HttpMetadata; customMetadata?: Record<string, string> }) {diff --git a/worker.ts b/worker.tsindex f6f9ff3..c2cc291 100644--- a/worker.ts+++ b/worker.ts@@ -8,6 +8,7 @@ import {} from "./src/lib/email/inbound";import { processOutboundQueue, type OutboundQueueMessage } from "./src/lib/email/send";import { isImportJobMessage, isInboundQueueMessage, isWebhookRetryMessage } from "./worker-utils";+import { sweepOrphanedRawMail } from "./src/lib/email/raw-sweeper";import { processImportJob, sweepImportJobs } from "./src/lib/import/jobs";import { processWebhookRetry, type WebhookRetryMessage } from "./src/lib/email/webhooks";import { resolveIncomingMail, forwardMessage } from "./src/lib/email/incoming";@@ -152,5 +153,6 @@ export default {// Drive trash is emptied once a day, with the 02:00 UTC cron; the 5-minute cron is for queue-like upkeep.if (controller.cron === "0 2 * * *") ctx.waitUntil(runDriveTrashRetention(env, new Date(controller.scheduledTime)));if (controller.cron === "0 2 * * *") ctx.waitUntil(runJmapChangeRetention(env, new Date(controller.scheduledTime)));+ if (controller.cron === "0 2 * * *") ctx.waitUntil(sweepOrphanedRawMail(env, new Date(controller.scheduledTime)).catch((error) => console.error("Raw mail sweep failed", error)));},} satisfies ExportedHandler<CloudflareEnv>;