Email for professionals and teams
Serve attachments and Drive files inline only when their type cannot run script (#103)
Namindu Sanchila Nadeeshanaf266d9533bb
diff --git a/src/app/api/messages/[messageId]/attachments/[attachmentId]/route.ts b/src/app/api/messages/[messageId]/attachments/[attachmentId]/route.tsindex 0949f06..b062e1d 100644--- a/src/app/api/messages/[messageId]/attachments/[attachmentId]/route.ts+++ b/src/app/api/messages/[messageId]/attachments/[attachmentId]/route.ts@@ -1,11 +1,9 @@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 type { AttachmentRouteParams } from "./types";-import {- getAttachmentContentDisposition,- isPreviewableAttachmentType,-} from "./utils";+import { getAttachmentContentDisposition } from "./utils";export async function GET(request: Request, { params }: AttachmentRouteParams) {const env = getEnv();@@ -20,13 +18,14 @@ export async function GET(request: Request, { params }: AttachmentRouteParams) {const url = new URL(request.url);const previewRequested = url.searchParams.get("preview") === "1";const downloadRequested = url.searchParams.get("download") === "1";- const inline =- !downloadRequested &&- (attachment.disposition === "inline" ||- (previewRequested && isPreviewableAttachmentType(attachment.contentType)));+ // The sender chooses both the type and the disposition, so only types that cannot run script ever render here.+ // The sandbox below is not enough on its own: on the Node runtime Next.js keeps the global CSP from next.config+ // and drops a route's own Content-Security-Policy.+ const inlineType = downloadRequested ? null : getInlineContentType(attachment.contentType);+ const inline = inlineType !== null && (attachment.disposition === "inline" || previewRequested);const headers = new Headers();object.writeHttpMetadata(headers);- headers.set("Content-Type", attachment.contentType);+ headers.set("Content-Type", (inline && inlineType) || getMimeEssence(attachment.contentType) || "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");diff --git a/src/app/api/messages/[messageId]/attachments/[attachmentId]/utils.ts b/src/app/api/messages/[messageId]/attachments/[attachmentId]/utils.tsindex 178c9ad..51e073e 100644--- a/src/app/api/messages/[messageId]/attachments/[attachmentId]/utils.ts+++ b/src/app/api/messages/[messageId]/attachments/[attachmentId]/utils.ts@@ -2,16 +2,3 @@ export function getAttachmentContentDisposition(filename: string, inline: booleaconst safeFilename = filename.replace(/["\\\r\n]/g, "_");return `${inline ? "inline" : "attachment"}; filename="${safeFilename}"`;}--export function isPreviewableAttachmentType(contentType: string): boolean {- return (- contentType === "application/pdf" ||- contentType.startsWith("audio/") ||- contentType.startsWith("video/") ||- (contentType.startsWith("image/") && contentType !== "image/svg+xml") ||- contentType.startsWith("text/plain") ||- contentType === "application/json" ||- contentType === "application/xml" ||- contentType === "text/csv"- );-}diff --git a/src/lib/drive/content.ts b/src/lib/drive/content.tsindex dc24a3a..e27f010 100644--- a/src/lib/drive/content.ts+++ b/src/lib/drive/content.ts@@ -1,4 +1,5 @@-import { driveContentDisposition, driveObjectKey, isDriveInlineSafe } from "./utils";+import { getInlineContentType } from "@/lib/http/content-type";+import { driveContentDisposition, driveObjectKey } from "./utils";import type { DriveRow } from "./types";/** Parses a single `bytes=` range. Returns null when absent or unusable (multi-range is served whole), "invalid" when unsatisfiable. */@@ -22,17 +23,18 @@ export function parseByteRange(header: string | null, size: number): { start: nu/** Streams a stored file with support for resumable downloads and seeking (`Range` / `If-Range`). */export async function streamDriveFile(env: CloudflareEnv, request: Request, item: DriveRow, download: boolean): Promise<Response> {if (item.kind !== "file") return new Response("Not a file", { status: 400 });- const inline = !download && isDriveInlineSafe(item.contentType);+ // The uploader chooses the type, so HTML, SVG and anything unparsable download as opaque bytes.+ const inlineType = download ? null : getInlineContentType(item.contentType);const etag = `"${item.id}-${item.updatedAt.getTime().toString(36)}-${item.size.toString(36)}"`;const headers = new Headers();- headers.set("Content-Type", inline ? item.contentType : "application/octet-stream");- headers.set("Content-Disposition", driveContentDisposition(item.name, inline));+ headers.set("Content-Type", inlineType ?? "application/octet-stream");+ headers.set("Content-Disposition", driveContentDisposition(item.name, inlineType !== null));headers.set("Accept-Ranges", "bytes");headers.set("ETag", etag);headers.set("X-Content-Type-Options", "nosniff");// Chrome's PDF viewer is blocked by a sandbox or a restrictive default-src (it needs object/plugin loads), and a// PDF served with nosniff cannot run script, so it only gets the framing rule.- headers.set("Content-Security-Policy", inline && item.contentType === "application/pdf" ? "frame-ancestors 'self'" : "default-src 'none'; style-src 'unsafe-inline'; sandbox");+ headers.set("Content-Security-Policy", inlineType === "application/pdf" ? "frame-ancestors 'self'" : "default-src 'none'; style-src 'unsafe-inline'; sandbox");headers.set("Referrer-Policy", "no-referrer");headers.set("Cache-Control", "private, no-store");diff --git a/src/lib/drive/utils.ts b/src/lib/drive/utils.tsindex 13a15b4..6636a17 100644--- a/src/lib/drive/utils.ts+++ b/src/lib/drive/utils.ts@@ -45,16 +45,3 @@ export function driveContentDisposition(filename: string, inline: boolean): striconst ascii = filename.replace(/[^\x20-\x7e]/g, "_").replace(/["\\]/g, "_");return `${inline ? "inline" : "attachment"}; filename="${ascii}"; filename*=UTF-8''${encodeURIComponent(filename)}`;}--/** Types that are safe to render in the browser; everything else (HTML, SVG, scripts) is forced to download. */-export function isDriveInlineSafe(contentType: string): boolean {- return (- contentType === "application/pdf" ||- contentType.startsWith("audio/") ||- contentType.startsWith("video/") ||- (contentType.startsWith("image/") && contentType !== "image/svg+xml") ||- contentType === "text/plain" ||- contentType === "text/csv" ||- contentType === "application/json"- );-}diff --git a/src/lib/http/content-type.ts b/src/lib/http/content-type.tsnew file mode 100644index 0000000..e7bc697--- /dev/null+++ b/src/lib/http/content-type.ts@@ -0,0 +1,39 @@+const TOKEN = "[a-z0-9!#$&^_.+-]+";+const MIME_ESSENCE = new RegExp(`^${TOKEN}/${TOKEN}$`);+const CHARSET_PARAMETER = /;\s*charset\s*=\s*"?([a-z0-9_.:-]+)"?\s*(?:;|$)/i;++/** Types a browser shows without running script, so they may render inline on our origin. */+const INLINE_TYPES = new Set([+ "application/pdf",+ "application/json",+ "text/plain",+ "text/csv",+ "image/png",+ "image/jpeg",+ "image/gif",+ "image/webp",+ "image/avif",+ "image/bmp",+]);++/** The lowercase `type/subtype` of a Content-Type value, or null when it is not exactly one well-formed type. */+export function getMimeEssence(contentType: string | null | undefined): string | null {+ // Browsers read a comma-joined value as several types and use the last one, so never guess which one wins.+ if (!contentType || contentType.includes(",")) return null;+ const essence = contentType.split(";", 1)[0].trim().toLowerCase();+ return MIME_ESSENCE.test(essence) ? essence : null;+}++/**+ * The Content-Type to serve a sender- or uploader-supplied file with when it may render inline, or null when it must+ * download. Only the parsed essence is checked and only that is sent back, because echoing the raw value would let+ * `image/svg+xml;charset=utf-8` or `image/png; x=1, text/html` pass a check written against the bare type.+ */+export function getInlineContentType(contentType: string | null | undefined): string | null {+ const essence = getMimeEssence(contentType);+ if (!essence) return null;+ if (!INLINE_TYPES.has(essence) && !essence.startsWith("audio/") && !essence.startsWith("video/")) return null;+ if (!essence.startsWith("text/")) return essence;+ const charset = contentType?.match(CHARSET_PARAMETER)?.[1];+ return charset ? `${essence}; charset=${charset}` : essence;+}diff --git a/tests/inline-content-type.test.mjs b/tests/inline-content-type.test.mjsnew file mode 100644index 0000000..3252e18--- /dev/null+++ b/tests/inline-content-type.test.mjs@@ -0,0 +1,47 @@+import assert from "node:assert/strict";+import { test } from "node:test";+import { build } from "esbuild";++const bundle = await build({ entryPoints: ["src/lib/http/content-type.ts"], bundle: true, write: false, platform: "neutral", format: "esm" });+const { getInlineContentType, getMimeEssence } = await import(`data:text/javascript;base64,${Buffer.from(bundle.outputFiles[0].text).toString("base64")}`);++test("inline types are served as their bare essence", () => {+ assert.equal(getInlineContentType("image/PNG"), "image/png");+ assert.equal(getInlineContentType("image/jpeg; name=\"photo.jpg\""), "image/jpeg");+ assert.equal(getInlineContentType("application/pdf"), "application/pdf");+ assert.equal(getInlineContentType("video/mp4"), "video/mp4");+ assert.equal(getInlineContentType("audio/mpeg"), "audio/mpeg");+ assert.equal(getInlineContentType("text/plain; charset=\"ISO-8859-1\"; format=flowed"), "text/plain; charset=ISO-8859-1");+ assert.equal(getInlineContentType("text/csv"), "text/csv");+});++test("active or unparsable types never render inline", () => {+ for (const type of [+ "text/html",+ "TEXT/HTML; charset=utf-8",+ "image/svg+xml",+ "image/svg+xml;charset=utf-8",+ "image/svg+xml ; charset=utf-8",+ "application/xml",+ "text/xml",+ "application/xhtml+xml",+ "application/javascript",+ "image/png, text/html",+ "image/png; x=1, text/html",+ "text/plain; charset=\"a,b\"",+ "image/png\ttext/html",+ "multipart/related",+ "",+ null,+ undefined,+ ]) {+ assert.equal(getInlineContentType(type), null, String(type));+ }+});++test("downloads keep a clean essence or fall back to opaque bytes", () => {+ assert.equal(getMimeEssence("image/svg+xml;charset=utf-8"), "image/svg+xml");+ assert.equal(getMimeEssence(" Text/HTML "), "text/html");+ assert.equal(getMimeEssence("image/png, text/html"), null);+ assert.equal(getMimeEssence("not a type"), null);+});