Email for professionals and teams
ran security audit
Hieu Nguyen (Jack)7e4c109c7cd9
diff --git a/src/app/(admin)/webhooks/page.tsx b/src/app/(admin)/webhooks/page.tsxindex f459697..fc58d63 100644--- a/src/app/(admin)/webhooks/page.tsx+++ b/src/app/(admin)/webhooks/page.tsx@@ -60,6 +60,14 @@ export default function WebhooksPage() {mutationFn: (hook: Webhook) => updateWebhook(hook.id, { enabled: !hook.enabled }),onSuccess: invalidate,});+ const rotate = useMutation({+ mutationFn: (id: string) => updateWebhook(id, { rotateSecret: true }),+ onSuccess: (result) => {+ setSecret(result.secret ?? null);+ setError(null);+ },+ onError: (cause: Error) => setError(cause.message),+ });const remove = useMutation({ mutationFn: deleteWebhook, onSuccess: invalidate });@@ -112,6 +120,7 @@ export default function WebhooksPage() {</CardContent></Card>)}+ {error && !dialogOpen && <p role="alert" className="text-sm text-red-600">{error}</p>}{webhooks.isLoading ? (<SectionRowSkeleton />@@ -200,6 +209,16 @@ export default function WebhooksPage() {><Send className="h-4 w-4" /> Test</Button>+ <Button+ variant="ghost"+ size="sm"+ onClick={() => {+ if (window.confirm("Rotate this signing secret? The previous secret will stop signing new deliveries immediately.")) rotate.mutate(hook.id);+ }}+ disabled={rotate.isPending}+ >+ <RefreshCw className="h-4 w-4" /> Rotate secret+ </Button><Buttonvariant="ghost"size="sm"diff --git a/src/app/(admin)/webhooks/types.d.ts b/src/app/(admin)/webhooks/types.d.tsindex 801a804..dc59b00 100644--- a/src/app/(admin)/webhooks/types.d.ts+++ b/src/app/(admin)/webhooks/types.d.ts@@ -47,4 +47,5 @@ export type UpdateWebhookInput = {events?: WebhookEvent[];enabled?: boolean;maxAttempts?: number;+ rotateSecret?: true;};diff --git a/src/app/(admin)/webhooks/utils.ts b/src/app/(admin)/webhooks/utils.tsindex c125f6a..54e6944 100644--- a/src/app/(admin)/webhooks/utils.ts+++ b/src/app/(admin)/webhooks/utils.ts@@ -52,7 +52,7 @@ export async function createWebhook(input: CreateWebhookInput) {}export async function updateWebhook(id: string, input: UpdateWebhookInput) {- return readJson(+ return readJson<{ ok: boolean; secret?: string }>(await authFetch(`/api/webhooks/${id}`, {method: "PATCH",headers: { "Content-Type": "application/json" },diff --git a/src/app/api/domains/[id]/dns/setup/route.ts b/src/app/api/domains/[id]/dns/setup/route.tsindex bead730..377a703 100644--- a/src/app/api/domains/[id]/dns/setup/route.ts+++ b/src/app/api/domains/[id]/dns/setup/route.ts@@ -8,6 +8,7 @@ import { getDomainForUser } from "@/lib/domains/service";import { getDomainDnsView } from "@/lib/domains/dns-view";import type { DnsAuthRecord } from "@/lib/domains/dns-audit";import { setupDomainDnsRecord } from "@/lib/domains/dns-setup";+import { hasValidSessionMutationOrigin } from "@/lib/auth/origin";type Params = { params: Promise<{ id: string }> };@@ -17,6 +18,8 @@ export async function POST(request: Request, { params }: Params) {const { id } = await params;const env = getEnv();const user = await requireUser(env, request);+ if (user.role !== "admin") return NextResponse.json({ error: "Forbidden" }, { status: 403 });+ if (!hasValidSessionMutationOrigin(request)) return NextResponse.json({ error: "Invalid origin" }, { status: 403 });const domain = await getDomainForUser(env, user.id, id);if (!domain) return NextResponse.json({ error: "Not found" }, { status: 404 });diff --git a/src/app/api/domains/[id]/route.ts b/src/app/api/domains/[id]/route.tsindex ac296c8..f2d8eec 100644--- a/src/app/api/domains/[id]/route.ts+++ b/src/app/api/domains/[id]/route.ts@@ -2,6 +2,7 @@ import { NextResponse } from "next/server";import { getEnv } from "@/lib/cloudflare";import { requireUser } from "@/lib/auth/cookies";import { getDomainForUser, removeDomainForUser } from "@/lib/domains/service";+import { hasValidSessionMutationOrigin } from "@/lib/auth/origin";type Params = { params: Promise<{ id: string }> };@@ -18,6 +19,8 @@ export async function DELETE(request: Request, { params }: Params) {const { id } = await params;const env = getEnv();const user = await requireUser(env, request);+ if (user.role !== "admin") return NextResponse.json({ error: "Forbidden" }, { status: 403 });+ if (!hasValidSessionMutationOrigin(request)) return NextResponse.json({ error: "Invalid origin" }, { status: 403 });try {await removeDomainForUser(env, user.id, id);return NextResponse.json({ ok: true });diff --git a/src/app/api/domains/route.ts b/src/app/api/domains/route.tsindex a24700b..6b844ce 100644--- a/src/app/api/domains/route.ts+++ b/src/app/api/domains/route.ts@@ -6,6 +6,7 @@ import { addDomainForUser, listUserDomains } from "@/lib/domains/service";import type { DnsStatusSummary } from "@/lib/dns-status";import { summariseDomainDns } from "@/lib/domains/dns-view";import { getDomainProvisioningError } from "@/lib/domains/errors";+import { hasValidSessionMutationOrigin } from "@/lib/auth/origin";export async function GET(request: NextRequest) {const env = getEnv();@@ -43,6 +44,8 @@ export async function GET(request: NextRequest) {export async function POST(request: Request) {const env = getEnv();const user = await requireUser(env, request);+ if (user.role !== "admin") return NextResponse.json({ error: "Forbidden" }, { status: 403 });+ if (!hasValidSessionMutationOrigin(request)) return NextResponse.json({ error: "Invalid origin" }, { status: 403 });const parsed = addDomainSchema.safeParse(await request.json());if (!parsed.success) {return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });diff --git a/src/app/api/webhooks/[id]/route.ts b/src/app/api/webhooks/[id]/route.tsindex fba14bb..beef67a 100644--- a/src/app/api/webhooks/[id]/route.ts+++ b/src/app/api/webhooks/[id]/route.ts@@ -5,6 +5,8 @@ import { parseWebhookEvents } from "@/lib/email/webhooks";import { webhookUpdateSchema } from "@/lib/validators";import { loadOwnedWebhook } from "./utils";import type { WebhookRouteParams } from "./types";+import { newId } from "@/lib/ids";+import { hasValidSessionMutationOrigin } from "@/lib/auth/origin";export async function GET(request: Request, { params }: WebhookRouteParams) {const { id } = await params;@@ -29,6 +31,7 @@ export async function PATCH(request: Request, { params }: WebhookRouteParams) {const { id } = await params;const loaded = await loadOwnedWebhook(request, id);if (loaded.error) return loaded.error;+ if (!hasValidSessionMutationOrigin(request)) return NextResponse.json({ error: "Invalid origin" }, { status: 403 });const parsed = webhookUpdateSchema.safeParse(await request.json());if (!parsed.success) {@@ -41,19 +44,22 @@ export async function PATCH(request: Request, { params }: WebhookRouteParams) {if (parsed.data.events !== undefined) updates.events = JSON.stringify(parsed.data.events);if (parsed.data.enabled !== undefined) updates.enabled = parsed.data.enabled;if (parsed.data.maxAttempts !== undefined) updates.maxAttempts = parsed.data.maxAttempts;+ const secret = parsed.data.rotateSecret ? newId("whsec") : null;+ if (secret) updates.secret = secret;if (Object.keys(updates).length === 0) {return NextResponse.json({ error: "No changes provided" }, { status: 400 });}await loaded.db.update(webhooks).set(updates).where(eq(webhooks.id, id));- return NextResponse.json({ ok: true });+ return NextResponse.json({ ok: true, ...(secret ? { secret } : {}) });}export async function DELETE(request: Request, { params }: WebhookRouteParams) {const { id } = await params;const loaded = await loadOwnedWebhook(request, id);if (loaded.error) return loaded.error;+ if (!hasValidSessionMutationOrigin(request)) return NextResponse.json({ error: "Invalid origin" }, { status: 403 });// Deliveries cascade with the webhook row.await loaded.db.delete(webhooks).where(eq(webhooks.id, id));diff --git a/src/app/api/webhooks/route.ts b/src/app/api/webhooks/route.tsindex 8fbe60e..8279311 100644--- a/src/app/api/webhooks/route.ts+++ b/src/app/api/webhooks/route.ts@@ -10,6 +10,7 @@ import { newId } from "@/lib/ids";import { webhookSchema } from "@/lib/validators";import { readJsonBody } from "@/lib/http/request";import { RequestBodyTooLargeError } from "@/lib/http/errors";+import { hasValidSessionMutationOrigin } from "@/lib/auth/origin";export async function GET(request: Request) {const env = getEnv();@@ -53,6 +54,7 @@ export async function POST(request: Request) {const auth = await requireSessionUser(env, request);if (auth.error) return auth.error;const user = auth.user;+ if (!hasValidSessionMutationOrigin(request)) return NextResponse.json({ error: "Invalid origin" }, { status: 403 });let body: unknown;try {body = await readJsonBody(request, 16 * 1024);diff --git a/src/lib/domains/service.ts b/src/lib/domains/service.tsindex 97e2d5b..14c1325 100644--- a/src/lib/domains/service.ts+++ b/src/lib/domains/service.ts@@ -1,4 +1,4 @@-import { eq, and } from "drizzle-orm";+import { eq, and, ne } from "drizzle-orm";import { getDb } from "@/db";import { domains, mailboxes } from "@/db/schema";import { ensureMailboxDomainRouting } from "@/lib/mailboxes/domain-addresses";@@ -18,6 +18,8 @@ import { getManualDomainDns } from "@/lib/domains/manual-dns";import { rollbackDomainProvisioning } from "@/lib/domains/rollback";import type { DomainProvisioningChanges } from "@/lib/domains/types";import { findSendingSubdomain } from "@/lib/domains/sending-status";+import { preflightDomain } from "@/lib/domains/preflight";+import { hasCloudflareCredentials } from "@/lib/runtime";export type DomainDnsView = {routing: { records: CfDnsRecord[]; missing: CfDnsRecord[]; status?: string };@@ -44,8 +46,23 @@ export async function addDomainForUser(dns: DomainDnsView;changes: DomainProvisioningChanges;}> {- const provisioned = await provisionDomainOnCloudflare(env, hostname, options);const db = getDb(env);+ const normalizedHostname = hostname.toLowerCase().trim();+ const [claimedHostname] = await db.select({ userId: domains.userId }).from(domains).where(eq(domains.hostname, normalizedHostname)).limit(1);+ if (claimedHostname && claimedHostname.userId !== userId) {+ throw new Error("Domain is already registered");+ }+ if (hasCloudflareCredentials(env)) {+ const { zone } = await preflightDomain(env, normalizedHostname);+ const [claimedZone] = await db.select({ userId: domains.userId }).from(domains).where(and(+ eq(domains.zoneId, zone.id),+ ne(domains.userId, userId),+ )).limit(1);+ if (claimedZone) {+ throw new Error("Cloudflare zone is already registered to another account");+ }+ }+ const provisioned = await provisionDomainOnCloudflare(env, hostname, options);let insertedDomainId: string | null = null;let domain: typeof domains.$inferSelect;@@ -183,7 +200,11 @@ export async function removeDomainForUser(console.warn("deleteEmailRoutingRulesForDomain", err);}- if (domain.routingEnabled) {+ const [otherDomainOnZone] = await db.select({ id: domains.id }).from(domains).where(and(+ eq(domains.zoneId, domain.zoneId),+ ne(domains.id, domainId),+ )).limit(1);+ if (domain.routingEnabled && !otherDomainOnZone) {try {await disableEmailRouting(env, domain.zoneId);} catch (err) {diff --git a/src/lib/email/inbound-attachments.ts b/src/lib/email/inbound-attachments.tsnew file mode 100644index 0000000..d10f3c2--- /dev/null+++ b/src/lib/email/inbound-attachments.ts@@ -0,0 +1,19 @@+import {+ MAX_ATTACHMENT_COUNT,+ MAX_ATTACHMENT_SIZE,+ MAX_TOTAL_ATTACHMENT_SIZE,+} from "@/lib/email/attachments";+import type { AttachmentContent } from "@/lib/email/attachment-types";++export function selectInboundAttachments(attachments: AttachmentContent[]): AttachmentContent[] {+ const selected: AttachmentContent[] = [];+ let totalSize = 0;+ for (const attachment of attachments) {+ const size = attachment.content.byteLength;+ if (selected.length >= MAX_ATTACHMENT_COUNT) break;+ if (size > MAX_ATTACHMENT_SIZE || totalSize + size > MAX_TOTAL_ATTACHMENT_SIZE) continue;+ selected.push(attachment);+ totalSize += size;+ }+ return selected;+}diff --git a/src/lib/email/inbound-id.ts b/src/lib/email/inbound-id.tsnew file mode 100644index 0000000..4e7cf09--- /dev/null+++ b/src/lib/email/inbound-id.ts@@ -0,0 +1,5 @@+export async function inboundMessageId(rawR2Key: string): Promise<string> {+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(rawR2Key));+ const hex = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");+ return `msg_${hex}`;+}diff --git a/src/lib/email/inbound.ts b/src/lib/email/inbound.tsindex 1e1642d..ecc999f 100644--- a/src/lib/email/inbound.ts+++ b/src/lib/email/inbound.ts@@ -10,6 +10,8 @@ import { getEmailAddress } from "@/lib/email/address";import { sendMailboxAutoReply } from "@/lib/email/auto-reply";import { getMailboxAccessLevel } from "@/lib/mailboxes/access";import { listMessageAttachments, storeMessageAttachments } from "@/lib/email/attachments";+import { selectInboundAttachments } from "@/lib/email/inbound-attachments";+import { inboundMessageId } from "@/lib/email/inbound-id";import { getUnsubscribeUrlFromRawR2Key } from "@/lib/email/unsubscribe";import { resolveThreadId } from "@/lib/email/threading";import type { SessionUser } from "@/lib/auth/types";@@ -76,7 +78,7 @@ export async function processInboundMessage(const buffer = await raw.arrayBuffer();const parsed = await parseRawMime(buffer);- const messageId = newId("msg");+ const messageId = await inboundMessageId(payload.rawR2Key);const snippet = buildSnippet(parsed.text, parsed.html);const deliveredAddress = getEmailAddress(payload.to) || `${decision.mailbox.localPart}@${decision.mailbox.hostname}`;// Keep the whole To header so reply-all can address everyone; rules and@@ -132,7 +134,7 @@ export async function processInboundMessage(});try {- await db.insert(messages).values({+ const inserted = await db.insert(messages).values({id: messageId,userId: decision.mailbox.userId,mailboxId: decision.mailbox.mailboxId,@@ -156,9 +158,14 @@ export async function processInboundMessage(spamSignals: spamAnalysis ? JSON.stringify(spamAnalysis.signals) : null,spamAnalyzedAt: spamAnalysis ? new Date() : null,spamAnalysisError,- });+ }).onConflictDoNothing().returning({ id: messages.id });+ if (!inserted.length) return;- await storeMessageAttachments(env, messageId, parsed.attachments, { validate: false });+ const attachments = selectInboundAttachments(parsed.attachments);+ if (attachments.length !== parsed.attachments.length) {+ console.warn(`Inbound attachment limits omitted ${parsed.attachments.length - attachments.length} files for ${messageId}`);+ }+ await storeMessageAttachments(env, messageId, attachments);if (spamAnalysis) {try {await recordReputationObservation(env, decision.mailbox.mailboxId, getReputationKeys(parsed, spamAnalysis.fingerprint));diff --git a/src/lib/email/webhooks.ts b/src/lib/email/webhooks.tsindex 5bdd83a..01063aa 100644--- a/src/lib/email/webhooks.ts+++ b/src/lib/email/webhooks.ts@@ -53,9 +53,13 @@ export async function dispatchWebhooks(if (!hook.enabled) continue;if (!parseWebhookEvents(hook.events).includes(eventType)) continue;- const body = JSON.stringify({ type: eventType, data: payload });- const delivery = await createDelivery(db, hook.id, eventType, body);- await attemptDelivery(env, db, hook, delivery);+ try {+ const body = JSON.stringify({ type: eventType, data: payload });+ const delivery = await createDelivery(db, hook.id, eventType, body);+ await attemptDelivery(env, db, hook, delivery);+ } catch (error) {+ console.error(`Webhook dispatch failed for ${hook.id}`, error);+ }}}diff --git a/src/lib/validators.ts b/src/lib/validators.tsindex 03d41c7..be4e616 100644--- a/src/lib/validators.ts+++ b/src/lib/validators.ts@@ -320,4 +320,5 @@ export const webhookUpdateSchema = z.object({.optional(),enabled: z.boolean().optional(),maxAttempts: z.number().int().min(1).max(10).optional(),+ rotateSecret: z.literal(true).optional(),});diff --git a/worker.ts b/worker.tsindex 4867c77..b086872 100644--- a/worker.ts+++ b/worker.ts@@ -11,6 +11,7 @@ import { processWebhookRetry, type WebhookRetryMessage } from "./src/lib/email/wimport { resolveIncomingMail, forwardMessage } from "./src/lib/email/incoming";import { getUserFromSession } from "./src/lib/auth/session";import { getSessionTokenFromRequest } from "./src/lib/realtime/utils";+import { hasValidSessionMutationOrigin } from "./src/lib/auth/origin";import {getAccountForwardingDestination,MAILFLARE_FORWARDED_HEADER,@@ -27,6 +28,9 @@ export default {if (request.headers.get("Upgrade")?.toLowerCase() !== "websocket") {return new Response("Expected WebSocket upgrade", { status: 426 });}+ if (!hasValidSessionMutationOrigin(request)) {+ return new Response("Invalid origin", { status: 403 });+ }const user = await getUserFromSession(env, getSessionTokenFromRequest(request));if (!user || user.disabled) {