Email for professionals and teams
fix(security): tie shared-file links to message state and serve downloads as octet-stream (#222)
Hieu Nguyen (Jack)2ab6f0de29d4
diff --git a/docs/security.md b/docs/security.mdnew file mode 100644index 0000000..5bdfd72--- /dev/null+++ b/docs/security.md@@ -0,0 +1,36 @@+# Security notes for inbound mail++## Deleted attachments stay in the original message++Deleting an attachment removes its stored file and its row, so it can no longer be+downloaded, previewed or shared. The message's original MIME (`rawR2Key`) is a faithful+copy of what arrived and is not rewritten, so **Download original** and the JMAP raw+blob still contain the attachment bytes. Delete the whole message to remove the original.++Public shared-file links stop working as soon as the message is moved to trash or spam+or its mailbox is disabled; they also expire on their own.++## Authentication results++* Cloudflare receiving: SPF, DKIM and DMARC come from the `Authentication-Results`+ header Cloudflare writes (authserv-id `mx.cloudflare.net`). A failure in any such clause+ wins over a pass.+* SES and Resend receiving: the provider's own verdicts are used.+* Self-hosted SMTP: the listener verifies nothing, so no authentication signal exists and+ the DMARC/SPF/DKIM policy does not apply. Put a verifying filter in front of it or receive+ through a provider.++Sender-written `Authentication-Results`, `Received-SPF` and `Received` headers are never+trusted on the SMTP path.++## Webhooks++Webhook URLs must be `https://` on a public host. Redirects are not followed, and hooks+saved before this rule are re-checked at delivery. Mail filed as spam or trash does not+trigger `message.inbound`.++## Forwarding loop guard++Mail Mailflare forwards carries `X-Mailflare-Forwarded`, an HMAC keyed with a server secret+(`CF_TOKEN`, `CF_API_KEY` or `INBOUND_WEBHOOK_SECRET`). A sender cannot switch forwarding+off by adding the header. With none of those set the header falls back to `1`.diff --git a/src/app/api/messages/[messageId]/attachments/[attachmentId]/route.ts b/src/app/api/messages/[messageId]/attachments/[attachmentId]/route.tsindex b062e1d..8add0d9 100644--- a/src/app/api/messages/[messageId]/attachments/[attachmentId]/route.ts+++ b/src/app/api/messages/[messageId]/attachments/[attachmentId]/route.ts@@ -1,7 +1,7 @@import { getCurrentUser } from "@/lib/auth/cookies";import { getEnv } from "@/lib/cloudflare";import { getAttachmentForUser } from "@/lib/email/attachments";-import { getInlineContentType, getMimeEssence } from "@/lib/http/content-type";+import { getInlineContentType } from "@/lib/http/content-type";import type { AttachmentRouteParams } from "./types";import { getAttachmentContentDisposition } from "./utils";@@ -25,7 +25,7 @@ export async function GET(request: Request, { params }: AttachmentRouteParams) {const inline = inlineType !== null && (attachment.disposition === "inline" || previewRequested);const headers = new Headers();object.writeHttpMetadata(headers);- headers.set("Content-Type", (inline && inlineType) || getMimeEssence(attachment.contentType) || "application/octet-stream");+ headers.set("Content-Type", (inline && inlineType) || "application/octet-stream");headers.set("Content-Length", String(attachment.size));headers.set("Content-Disposition", getAttachmentContentDisposition(attachment.filename, inline));headers.set("X-Content-Type-Options", "nosniff");@@ -33,7 +33,7 @@ export async function GET(request: Request, { params }: AttachmentRouteParams) {"Content-Security-Policy","default-src 'none'; img-src 'self' data: blob:; media-src 'self' blob:; style-src 'unsafe-inline'; sandbox",);- headers.set("Cache-Control", "private, max-age=3600");+ headers.set("Cache-Control", "private, max-age=300");return new Response(object.body, { headers });}diff --git a/src/app/api/shared-files/[id]/route.ts b/src/app/api/shared-files/[id]/route.tsindex 0c011db..29eaa36 100644--- a/src/app/api/shared-files/[id]/route.ts+++ b/src/app/api/shared-files/[id]/route.ts@@ -1,6 +1,6 @@-import { and, eq, gt } from "drizzle-orm";+import { and, eq, gt, ne } from "drizzle-orm";import { getDb } from "@/db";-import { messageAttachments, sharedAttachmentLinks } from "@/db/schema";+import { mailboxes, messageAttachments, messages, sharedAttachmentLinks } from "@/db/schema";import { getEnv } from "@/lib/cloudflare";import { getAttachmentContentDisposition } from "@/app/api/messages/[messageId]/attachments/[attachmentId]/utils";import type { SharedFileParams } from "./types";@@ -12,13 +12,17 @@ export async function GET(_request: Request, { params }: SharedFileParams) {.select({ r2Key: messageAttachments.r2Key, filename: messageAttachments.filename, size: messageAttachments.size, contentType: messageAttachments.contentType }).from(sharedAttachmentLinks).innerJoin(messageAttachments, eq(sharedAttachmentLinks.attachmentId, messageAttachments.id))- .where(and(eq(sharedAttachmentLinks.id, id), gt(sharedAttachmentLinks.expiresAt, new Date())))+ .innerJoin(messages, eq(messageAttachments.messageId, messages.id))+ .innerJoin(mailboxes, eq(messages.mailboxId, mailboxes.id))+ // A link dies with the message going to trash or spam, or the mailbox being disabled.+ .where(and(eq(sharedAttachmentLinks.id, id), gt(sharedAttachmentLinks.expiresAt, new Date()), ne(messages.status, "trash"), ne(messages.status, "spam"), eq(mailboxes.disabled, false))).limit(1);if (!file) return new Response("Link expired or not found", { status: 404 });const object = await env.BUCKET.get(file.r2Key);if (!object) return new Response("File not found", { status: 404 });const headers = new Headers();- headers.set("Content-Type", file.contentType);+ // Always a download of opaque bytes: the sender picked the declared type.+ headers.set("Content-Type", "application/octet-stream");headers.set("Content-Length", String(file.size));headers.set("Content-Disposition", getAttachmentContentDisposition(file.filename, false));headers.set("X-Content-Type-Options", "nosniff");diff --git a/src/lib/email/attachments.ts b/src/lib/email/attachments.tsindex a647359..7bfb9b9 100644--- a/src/lib/email/attachments.ts+++ b/src/lib/email/attachments.ts@@ -135,7 +135,7 @@ export async function copyMessageAttachments(const object = await env.BUCKET.get(row.r2Key);if (!object) continue;const id = newId("att");- const r2Key = `attachments/${toMessageId}/${id}/${row.filename}`;+ const r2Key = `attachments/${toMessageId}/${id}/${sanitizeFilename(row.filename)}`;await env.BUCKET.put(r2Key, await object.arrayBuffer(), {httpMetadata: { contentType: row.contentType },customMetadata: { filename: row.filename, messageId: toMessageId },