Email for professionals and teams
Auto-delete Trash and Spam after a chosen number of days
midego2b7d78bac777
diff --git a/docs/api.md b/docs/api.mdindex 38aae8f..a6327a5 100644--- a/docs/api.md+++ b/docs/api.md@@ -180,6 +180,8 @@ To send a reply that threads correctly in the recipient's client, pass the paren`POST /api/messages/bulk` (session auth) with `action: "delete"` permanently removes the given messages, including their raw MIME and attachment objects, but only those already in Trash or Spam; others are skipped and counted in `skipped`. `POST /api/messages/empty` with `{ mailboxId, folder: "trash" | "spam" }` permanently deletes that folder's messages in batches of 100 and returns `{ deleted, remaining }`; call it again until `remaining` is 0. Both write an `email.delete` audit entry per message with `permanent: true`.+Each user can also choose **Settings > Inbox > Trash and Spam clean-up** to delete Trash and Spam automatically after a number of days (`GET`/`PATCH /api/settings/trash-retention` with `{ days: number | null }`, 1 to 365, `null` for never). It applies to messages in mailboxes the user owns. `messages.trashed_at` records when a message entered either folder; database triggers keep it current, and the scheduled maintenance run deletes expired messages in batches of 200, with `source: "retention"` in the audit entry.+Messages composed in Mailflare are sent as HTML with a plain-text alternative derived from it. Quoted or forwarded content is wrapped in `<div class="mailflare-quote" data-mailflare-quote="1">` so the reader can fold it. `POST /api/drafts` accepts `forwardOfMessageId`, which copies that message's attachments onto the new draft; `DELETE /api/drafts/{id}/attachments/{attachmentId}` removes one, and `POST /api/send` with `draftId` sends the draft's stored files along with any uploaded in the request.The dashboard composer accepts up to 10 attachments. An administrator sets the outgoing per-file and combined limit from 1 to 25 MB on **General** (`/general`); the default is 25 MB. Attachment metadata is stored in D1 and file content is stored in R2. Normal message downloads require access to the mailbox containing the message.diff --git a/drizzle/migrations/0053_add_trash_retention.sql b/drizzle/migrations/0053_add_trash_retention.sqlnew file mode 100644index 0000000..47269b4--- /dev/null+++ b/drizzle/migrations/0053_add_trash_retention.sql@@ -0,0 +1,14 @@+-- Optional per-user retention for Trash and Spam. `trashed_at` records when a+-- message entered either folder; triggers keep it current whichever code path+-- changes the status, and the scheduled purge deletes rows older than the+-- owner's `trash_retention_days` (NULL means keep forever).+ALTER TABLE `users` ADD `trash_retention_days` integer;--> statement-breakpoint+ALTER TABLE `messages` ADD `trashed_at` integer;--> statement-breakpoint+CREATE INDEX `messages_trashed_at_idx` ON `messages` (`trashed_at`);--> statement-breakpoint+UPDATE `messages` SET `trashed_at` = CAST(strftime('%s', 'now') AS integer) WHERE `status` IN ('trash', 'spam');--> statement-breakpoint+CREATE TRIGGER `messages_trashed_at_ai` AFTER INSERT ON `messages` WHEN new.`status` IN ('trash', 'spam') BEGIN+ UPDATE `messages` SET `trashed_at` = CAST(strftime('%s', 'now') AS integer) WHERE `rowid` = new.`rowid`;+END;--> statement-breakpoint+CREATE TRIGGER `messages_trashed_at_au` AFTER UPDATE OF `status` ON `messages` WHEN (new.`status` IN ('trash', 'spam')) <> (old.`status` IN ('trash', 'spam')) BEGIN+ UPDATE `messages` SET `trashed_at` = CASE WHEN new.`status` IN ('trash', 'spam') THEN CAST(strftime('%s', 'now') AS integer) ELSE NULL END WHERE `rowid` = new.`rowid`;+END;diff --git a/drizzle/migrations/meta/_journal.json b/drizzle/migrations/meta/_journal.jsonindex 11b723f..8ea5a5a 100644--- a/drizzle/migrations/meta/_journal.json+++ b/drizzle/migrations/meta/_journal.json@@ -316,6 +316,13 @@"when": 1788850800016,"tag": "0052_add_receiving_provider","breakpoints": true+ },+ {+ "idx": 45,+ "version": "6",+ "when": 1788850800017,+ "tag": "0053_add_trash_retention",+ "breakpoints": true}]}diff --git a/server/runtime/scheduler.ts b/server/runtime/scheduler.tsindex c989fa1..f8232fc 100644--- a/server/runtime/scheduler.ts+++ b/server/runtime/scheduler.ts@@ -1,11 +1,13 @@import { runScheduledDatabaseBackup } from "@/lib/backups/runner";import { runAgentMaintenance } from "@/lib/agent/maintenance";+import { runTrashRetention } from "@/lib/email/trash-retention";-/** Fire the daily 02:00 UTC backup, matching the cron trigger in wrangler.jsonc. */+/** Fire the daily 02:00 UTC backup and the recurring maintenance jobs, matching the cron triggers in wrangler.jsonc. */export function startScheduler(env: CloudflareEnv) {let lastRunDay = "";const timer = setInterval(() => {runAgentMaintenance(env).catch((error) => console.error("Agent maintenance failed", error));+ runTrashRetention(env).catch((error) => console.error("Trash retention failed", error));const now = new Date();const day = now.toISOString().slice(0, 10);if (now.getUTCHours() !== 2 || lastRunDay === day) return;diff --git a/src/app/(settings)/settings/inbox/page.tsx b/src/app/(settings)/settings/inbox/page.tsxindex f9dd33e..8fed078 100644--- a/src/app/(settings)/settings/inbox/page.tsx+++ b/src/app/(settings)/settings/inbox/page.tsx@@ -5,6 +5,7 @@ import { InboxReadingLayoutSettings } from "@/components/settings/inbox-reading-import { InboxShortcutsSettings } from "@/components/settings/inbox-shortcuts-settings";import { MailboxAutoReplyForm } from "@/components/settings/mailbox-auto-reply-form";import { SpamFilterSettings } from "@/components/settings/spam-filter-settings";+import { TrashRetentionSettings } from "@/components/settings/trash-retention-settings";import { BrowserNotificationSettings } from "@/components/settings/browser-notification-settings";export default function SettingsInboxPage() {@@ -63,7 +64,7 @@ export default function SettingsInboxPage() {<section className="space-y-4"><div><h2 className="text-xl font-semibold text-neutral-900">Message handling</h2>- <p className="mt-1 text-sm text-neutral-500">Manage spam protection and automatic replies.</p>+ <p className="mt-1 text-sm text-neutral-500">Manage spam protection, clean-up and automatic replies.</p></div><div className="divide-y divide-neutral-100 rounded-3xl bg-white p-6"><div className="py-6 first:pt-0 last:pb-0">@@ -73,6 +74,13 @@ export default function SettingsInboxPage() {</div><SpamFilterSettings /></div>+ <div className="py-6 first:pt-0 last:pb-0">+ <div className="mb-4">+ <h3 className="text-base font-semibold text-neutral-900">Trash and Spam clean-up</h3>+ <p className="mt-1 text-sm text-neutral-500">Choose how long deleted and spam messages are kept.</p>+ </div>+ <TrashRetentionSettings />+ </div><div className="py-6 first:pt-0 last:pb-0"><div className="mb-4"><h3 className="text-base font-semibold text-neutral-900">Automatic response</h3>diff --git a/src/app/api/settings/trash-retention/route.ts b/src/app/api/settings/trash-retention/route.tsnew file mode 100644index 0000000..e547771--- /dev/null+++ b/src/app/api/settings/trash-retention/route.ts@@ -0,0 +1,37 @@+import { eq } from "drizzle-orm";+import { NextResponse } from "next/server";+import { ZodError } from "zod";+import { getDb } from "@/db";+import { users } from "@/db/schema";+import { requireSessionUser } from "@/lib/api/auth";+import { getEnv } from "@/lib/cloudflare";+import { normalizeTrashRetentionDays } from "@/lib/email/trash-retention-utils";+import type { UpdateTrashRetentionSettingsInput } from "./types";+import { parseUpdateTrashRetentionSettingsRequest } from "./utils";++export async function GET(request: Request) {+ const env = getEnv();+ const auth = await requireSessionUser(env, request);+ if (auth.error) return auth.error;+ return NextResponse.json({ days: normalizeTrashRetentionDays(auth.user.trashRetentionDays) });+}++export async function PATCH(request: Request) {+ const env = getEnv();+ const auth = await requireSessionUser(env, request);+ if (auth.error) return auth.error;++ let input: UpdateTrashRetentionSettingsInput;+ try {+ input = await parseUpdateTrashRetentionSettingsRequest(request);+ } catch (error) {+ return NextResponse.json({ error: error instanceof ZodError ? error.flatten() : "Invalid request" }, { status: 400 });+ }++ await getDb(env)+ .update(users)+ .set({ trashRetentionDays: input.days })+ .where(eq(users.id, auth.user.id));++ return NextResponse.json({ days: input.days });+}diff --git a/src/app/api/settings/trash-retention/types.d.ts b/src/app/api/settings/trash-retention/types.d.tsnew file mode 100644index 0000000..0deab6f--- /dev/null+++ b/src/app/api/settings/trash-retention/types.d.ts@@ -0,0 +1,9 @@+import type { updateTrashRetentionSettingsSchema } from "@/lib/validators";+import type { z } from "zod";++export type UpdateTrashRetentionSettingsInput = z.infer<typeof updateTrashRetentionSettingsSchema>;++export type TrashRetentionSettingsResponse = {+ days?: number | null;+ error?: unknown;+};diff --git a/src/app/api/settings/trash-retention/utils.ts b/src/app/api/settings/trash-retention/utils.tsnew file mode 100644index 0000000..6f65724--- /dev/null+++ b/src/app/api/settings/trash-retention/utils.ts@@ -0,0 +1,6 @@+import { updateTrashRetentionSettingsSchema } from "@/lib/validators";+import type { UpdateTrashRetentionSettingsInput } from "./types";++export async function parseUpdateTrashRetentionSettingsRequest(request: Request): Promise<UpdateTrashRetentionSettingsInput> {+ return updateTrashRetentionSettingsSchema.parse(await request.json());+}diff --git a/src/components/settings/trash-retention-settings.tsx b/src/components/settings/trash-retention-settings.tsxnew file mode 100644index 0000000..dee10f7--- /dev/null+++ b/src/components/settings/trash-retention-settings.tsx@@ -0,0 +1,76 @@+"use client";++import { useEffect, useState } from "react";+import { authFetch } from "@/lib/auth/client";+import { TRASH_RETENTION_OPTIONS, describeTrashRetention } from "@/lib/email/trash-retention-utils";+import type { TrashRetentionSettingsResponse } from "@/app/api/settings/trash-retention/types";++export function TrashRetentionSettings() {+ const [days, setDays] = useState<number | null>(null);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState<string | null>(null);++ useEffect(() => {+ void authFetch("/api/settings/trash-retention")+ .then(async (response) => {+ const data = await response.json() as TrashRetentionSettingsResponse;+ if (!response.ok) throw new Error(typeof data.error === "string" ? data.error : "Failed to load clean-up settings");+ setDays(data.days ?? null);+ })+ .catch((nextError) => setError(nextError instanceof Error ? nextError.message : "Failed to load clean-up settings"))+ .finally(() => setLoading(false));+ }, []);++ async function updateDays(nextDays: number | null) {+ const previous = days;+ setDays(nextDays);+ setLoading(true);+ setError(null);+ try {+ const response = await authFetch("/api/settings/trash-retention", {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ days: nextDays }),+ });+ const data = await response.json() as TrashRetentionSettingsResponse;+ if (!response.ok) throw new Error(typeof data.error === "string" ? data.error : "Failed to update clean-up settings");+ setDays(data.days ?? null);+ } catch (nextError) {+ setDays(previous);+ setError(nextError instanceof Error ? nextError.message : "Failed to update clean-up settings");+ } finally {+ setLoading(false);+ }+ }++ // Keep a custom value set through the API selectable instead of silently showing "Never".+ const options: number[] = days && !(TRASH_RETENTION_OPTIONS as readonly number[]).includes(days)+ ? [...TRASH_RETENTION_OPTIONS, days].sort((a, b) => a - b)+ : [...TRASH_RETENTION_OPTIONS];++ return (+ <div>+ <label className="flex items-start gap-3 rounded-xl bg-neutral-50 p-4">+ <span className="flex-1">+ <span className="block text-sm font-medium text-neutral-900">Auto-delete Trash and Spam</span>+ <span className="mt-1 block text-sm text-neutral-500">+ Permanently delete messages once they have been in Trash or Spam for this long. Applies to the mailboxes you own.+ </span>+ </span>+ <select+ value={days ?? ""}+ disabled={loading}+ onChange={(event) => void updateDays(event.target.value ? Number(event.target.value) : null)}+ className="rounded-lg border border-neutral-200 bg-white px-3 py-1.5 text-sm text-neutral-800 disabled:opacity-60"+ aria-label="Auto-delete Trash and Spam"+ >+ <option value="">{describeTrashRetention(null)}</option>+ {options.map((value) => (+ <option key={value} value={value}>{describeTrashRetention(value)}</option>+ ))}+ </select>+ </label>+ {error && <p className="mt-2 px-4 text-sm text-red-600">{error}</p>}+ </div>+ );+}diff --git a/src/db/schema/index.ts b/src/db/schema/index.tsindex 4b1724d..3ec5571 100644--- a/src/db/schema/index.ts+++ b/src/db/schema/index.ts@@ -23,6 +23,8 @@ export const users = sqliteTable("users", {canManageUsers: integer("can_manage_users", { mode: "boolean" }).notNull().default(false),keyboardShortcutsEnabled: integer("keyboard_shortcuts_enabled", { mode: "boolean" }).notNull().default(true),spamProtectionEnabled: integer("spam_protection_enabled", { mode: "boolean" }).notNull().default(true),+ /** Days a message may stay in Trash or Spam before the scheduled purge deletes it; null keeps it forever. */+ trashRetentionDays: integer("trash_retention_days"),// Off shows the mailbox only. On shows Name <mailbox> on To, Cc, and Bcc.showFullRecipientAddresses: integer("show_full_recipient_addresses", { mode: "boolean" }).notNull().default(false),// TOTP second factor. The secret is written at enrolment and only counts@@ -258,6 +260,8 @@ export const messages = sqliteTable(spamSignals: text("spam_signals"),spamAnalyzedAt: integer("spam_analyzed_at", { mode: "timestamp" }),spamAnalysisError: text("spam_analysis_error"),+ /** When the message last entered Trash or Spam; maintained by triggers (migration 0053). */+ trashedAt: integer("trashed_at", { mode: "timestamp" }),createdAt: integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),@@ -269,6 +273,7 @@ export const messages = sqliteTable(index("messages_thread_idx").on(t.mailboxId, t.threadId),index("messages_provider_message_idx").on(t.mailboxId, t.providerMessageId),index("messages_raw_r2_key_idx").on(t.rawR2Key),+ index("messages_trashed_at_idx").on(t.trashedAt),index("messages_inbox_page_idx").on(t.mailboxId,t.status,diff --git a/src/lib/auth/types.d.ts b/src/lib/auth/types.d.tsindex 5c28ff9..2e62f60 100644--- a/src/lib/auth/types.d.ts+++ b/src/lib/auth/types.d.ts@@ -16,6 +16,7 @@ export type SessionUser = {canManageUsers: boolean;keyboardShortcutsEnabled: boolean;spamProtectionEnabled: boolean;+ trashRetentionDays: number | null;showFullRecipientAddresses: boolean;createdByUserId: string | null;createdAt: Date;diff --git a/src/lib/email/permanent-delete.ts b/src/lib/email/permanent-delete.tsindex f38270a..00443b5 100644--- a/src/lib/email/permanent-delete.ts+++ b/src/lib/email/permanent-delete.ts@@ -19,7 +19,7 @@ export async function permanentlyDeleteMessages(db: AppDatabase,actorUserId: string,rows: DeletableMessage[],- source: "bulk" | "empty",+ source: "bulk" | "empty" | "retention",): Promise<number> {for (const row of rows) {await deleteMessageWithObjects(env, db, row.id, row.rawR2Key);diff --git a/src/lib/email/trash-retention-utils.ts b/src/lib/email/trash-retention-utils.tsnew file mode 100644index 0000000..21d6eef--- /dev/null+++ b/src/lib/email/trash-retention-utils.ts@@ -0,0 +1,25 @@+/** Choices offered in Settings; any whole number in range is accepted by the API. */+export const TRASH_RETENTION_OPTIONS = [7, 14, 30, 60, 90] as const;+export const MIN_TRASH_RETENTION_DAYS = 1;+export const MAX_TRASH_RETENTION_DAYS = 365;+/** Messages purged per scheduled run, so one invocation stays well inside Worker limits. */+export const TRASH_RETENTION_BATCH_SIZE = 200;++const DAY_MS = 24 * 60 * 60 * 1000;++/** Messages that entered Trash or Spam before this instant are due for deletion. */+export function getTrashRetentionCutoff(now: Date, days: number): Date {+ return new Date(now.getTime() - days * DAY_MS);+}++/** Null (or anything outside the supported range) means "never delete automatically". */+export function normalizeTrashRetentionDays(value: unknown): number | null {+ if (typeof value !== "number" || !Number.isInteger(value)) return null;+ if (value < MIN_TRASH_RETENTION_DAYS || value > MAX_TRASH_RETENTION_DAYS) return null;+ return value;+}++export function describeTrashRetention(days: number | null): string {+ if (!days) return "Never";+ return days === 1 ? "After 1 day" : `After ${days} days`;+}diff --git a/src/lib/email/trash-retention.ts b/src/lib/email/trash-retention.tsnew file mode 100644index 0000000..e7252d7--- /dev/null+++ b/src/lib/email/trash-retention.ts@@ -0,0 +1,38 @@+import { and, eq, inArray, isNotNull, lt } from "drizzle-orm";+import { getDb } from "@/db";+import { messages, users } from "@/db/schema";+import { permanentlyDeleteMessages } from "@/lib/email/permanent-delete";+import { TRASH_RETENTION_BATCH_SIZE, getTrashRetentionCutoff, normalizeTrashRetentionDays } from "./trash-retention-utils";++/**+ * Permanently delete Trash and Spam messages that have been there longer than+ * their owner's retention setting. Runs from the scheduled handler; each run+ * removes at most one batch, so a large backlog drains over several runs.+ */+export async function runTrashRetention(env: CloudflareEnv, now = new Date()): Promise<number> {+ const db = getDb(env);+ const owners = await db+ .select({ id: users.id, days: users.trashRetentionDays })+ .from(users)+ .where(isNotNull(users.trashRetentionDays));++ let budget = TRASH_RETENTION_BATCH_SIZE;+ let deleted = 0;+ for (const owner of owners) {+ const days = normalizeTrashRetentionDays(owner.days);+ if (!days || budget <= 0) continue;+ const expired = await db+ .select({ id: messages.id, mailboxId: messages.mailboxId, rawR2Key: messages.rawR2Key, status: messages.status })+ .from(messages)+ .where(and(+ eq(messages.userId, owner.id),+ inArray(messages.status, ["trash", "spam"]),+ lt(messages.trashedAt, getTrashRetentionCutoff(now, days)),+ ))+ .limit(budget);+ if (expired.length === 0) continue;+ deleted += await permanentlyDeleteMessages(env, db, owner.id, expired, "retention");+ budget -= expired.length;+ }+ return deleted;+}diff --git a/src/lib/validators.ts b/src/lib/validators.tsindex d45c85f..77bd4a6 100644--- a/src/lib/validators.ts+++ b/src/lib/validators.ts@@ -235,6 +235,10 @@ export const updateSpamSettingsSchema = z.object({enabled: z.boolean(),});+export const updateTrashRetentionSettingsSchema = z.object({+ days: z.number().int().min(1).max(365).nullable(),+});+export const updateRecipientAddressSettingsSchema = z.object({enabled: z.boolean(),});diff --git a/tests/permanent-delete.test.mjs b/tests/permanent-delete.test.mjsindex 21c83bf..d9fa99a 100644--- a/tests/permanent-delete.test.mjs+++ b/tests/permanent-delete.test.mjs@@ -13,6 +13,8 @@ await build({contents: `export { isAllowedBulkMessageAction, getStatusForBulkAction, getReadValueForBulkAction, isPermanentlyDeletableStatus, isPermanentDeleteFolder } from "./src/app/api/messages/bulk/utils.ts";export { supportsPermanentDelete, getEmptyFolderLabel, getPermanentDeleteConfirmText, getEmptyFolderConfirmText } from "./src/lib/messages/permanent-delete-utils.ts";+ export { TRASH_RETENTION_OPTIONS, getTrashRetentionCutoff, normalizeTrashRetentionDays, describeTrashRetention } from "./src/lib/email/trash-retention-utils.ts";+ export { updateTrashRetentionSettingsSchema } from "./src/lib/validators.ts";`,resolveDir: root,sourcefile: "permanent-delete-test-entry.ts",@@ -60,3 +62,27 @@ test("confirmation text says how much is lost and that it is irreversible", () =assert.equal(m.getEmptyFolderConfirmText("spam", 1), "Permanently delete the 1 message in Spam? This cannot be undone.");assert.equal(m.getEmptyFolderConfirmText("trash"), "Permanently delete every message in Trash? This cannot be undone.");});++test("retention cutoff is the given number of days before now", () => {+ const now = new Date("2026-10-31T12:00:00Z");+ assert.equal(m.getTrashRetentionCutoff(now, 30).toISOString(), "2026-10-01T12:00:00.000Z");+ assert.equal(m.getTrashRetentionCutoff(now, 1).toISOString(), "2026-10-30T12:00:00.000Z");+});++test("retention days outside 1-365 or non-integers mean never", () => {+ for (const days of m.TRASH_RETENTION_OPTIONS) assert.equal(m.normalizeTrashRetentionDays(days), days);+ for (const days of [null, undefined, 0, -3, 366, 2.5, "30"]) assert.equal(m.normalizeTrashRetentionDays(days), null, String(days));+ assert.equal(m.describeTrashRetention(null), "Never");+ assert.equal(m.describeTrashRetention(1), "After 1 day");+ assert.equal(m.describeTrashRetention(30), "After 30 days");+});++test("the settings API accepts whole days from 1 to 365, or null to turn it off", () => {+ const ok = (days) => m.updateTrashRetentionSettingsSchema.safeParse({ days }).success;+ assert.equal(ok(30), true);+ assert.equal(ok(null), true);+ assert.equal(ok(0), false);+ assert.equal(ok(400), false);+ assert.equal(ok(1.5), false);+ assert.equal(ok("30"), false);+});diff --git a/worker.ts b/worker.tsindex 85d5630..4ecdd36 100644--- a/worker.ts+++ b/worker.ts@@ -19,6 +19,7 @@ import {import { runScheduledDatabaseBackup } from "./src/lib/backups/runner";import { processAgentDraftJob } from "./src/lib/agent/jobs/utils";import { runAgentMaintenance } from "./src/lib/agent/maintenance";+import { runTrashRetention } from "./src/lib/email/trash-retention";export { RealtimeHub } from "./src/lib/realtime/hub";export default {@@ -124,5 +125,6 @@ export default {async scheduled(controller: ScheduledController, env: CloudflareEnv, ctx: ExecutionContext) {if (controller.cron === "0 2 * * *") ctx.waitUntil(runScheduledDatabaseBackup(env, new Date(controller.scheduledTime)));ctx.waitUntil(runAgentMaintenance(env));+ ctx.waitUntil(runTrashRetention(env, new Date(controller.scheduledTime)));},} satisfies ExportedHandler<CloudflareEnv>;