import { createHash } from "node:crypto"; import { readFile } from "node:fs/promises"; import path from "node:path"; import { type InboxAttachment } from "./schemas.js"; export const MAX_INBOX_ATTACHMENTS = 10; export const MAX_INBOX_ATTACHMENT_SIZE = 10 * 1024 * 1024; export const MAX_INBOX_ATTACHMENTS_TOTAL_SIZE = 25 * 1024 * 1024; const attachmentTypes = { ".avif": "image/avif", ".csv": "text/csv", ".doc": "application/msword", ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", ".gif": "image/gif", ".jpeg": "image/jpeg", ".jpg": "image/jpeg", ".json": "application/json", ".md": "text/markdown", ".odp": "application/vnd.oasis.opendocument.presentation", ".ods": "application/vnd.oasis.opendocument.spreadsheet", ".odt": "application/vnd.oasis.opendocument.text", ".pdf": "application/pdf", ".png": "image/png", ".ppt": "application/vnd.ms-powerpoint", ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation", ".txt": "text/plain", ".webp": "image/webp", ".xls": "application/vnd.ms-excel", ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", } as const; export const ACCEPTED_INBOX_ATTACHMENT_EXTENSIONS = Object.keys(attachmentTypes).join(","); export interface InboxAttachmentInput { name: string; mediaType?: string | null; data: Uint8Array; } export interface PreparedInboxAttachment { data: Uint8Array; metadata: InboxAttachment; } export interface InboxAttachmentFile { absolutePath: string; metadata: InboxAttachment; } function normalizedOriginalName(name: string): string { const normalized = name.replaceAll("\\", "/"); const baseName = path.posix.basename(normalized).trim(); if (!baseName || baseName === "." || baseName === "..") { throw new Error("Attachment names must contain a file name."); } return baseName; } function canonicalMediaType(name: string, declaredMediaType?: string | null) { const extension = path.extname(name).toLowerCase(); const expected = attachmentTypes[extension as keyof typeof attachmentTypes]; if (!expected) { throw new Error( `Attachment type "${extension || "unknown"}" is not allowed.`, ); } const declared = declaredMediaType?.trim().toLowerCase(); if (declared && declared !== expected) { throw new Error( `Attachment "${name}" has media type "${declared}", expected "${expected}".`, ); } return expected; } function storedAttachmentName(index: number, originalName: string): string { const extension = path.extname(originalName).toLowerCase(); const stem = path.basename(originalName, path.extname(originalName)); const safeStem = stem .normalize("NFKD") .replace(/[\u0300-\u036f]/g, "") .replace(/[^a-zA-Z0-9_-]+/g, "-") .replace(/^-+|-+$/g, "") .slice(0, 60); return `${String(index + 1).padStart(3, "0")}-${safeStem || "attachment"}${extension}`; } export function sha256(data: Uint8Array): string { return createHash("sha256").update(data).digest("hex"); } export function prepareInboxAttachments( messageId: string, inputs: InboxAttachmentInput[] = [], ): PreparedInboxAttachment[] { if (inputs.length > MAX_INBOX_ATTACHMENTS) { throw new Error( `Inbox messages support at most ${MAX_INBOX_ATTACHMENTS} attachments.`, ); } let totalSize = 0; return inputs.map((input, index) => { const name = normalizedOriginalName(input.name); const size = input.data.byteLength; if (size > MAX_INBOX_ATTACHMENT_SIZE) { throw new Error(`Attachment "${name}" exceeds the 10 MiB limit.`); } totalSize += size; if (totalSize > MAX_INBOX_ATTACHMENTS_TOTAL_SIZE) { throw new Error("Inbox attachments exceed the 25 MiB total limit."); } const storedName = storedAttachmentName(index, name); return { data: input.data, metadata: { name, path: `${messageId}.attachments/${storedName}`, media_type: canonicalMediaType(name, input.mediaType), size, sha256: sha256(input.data), }, }; }); } export function isInlineInboxImage(mediaType: string): boolean { return [ "image/avif", "image/gif", "image/jpeg", "image/png", "image/webp", ].includes(mediaType); } function contentDisposition(name: string, inline: boolean): string { const fallback = name.replace(/[^\x20-\x7e]|["\\]/g, "_"); return `${inline ? "inline" : "attachment"}; filename="${fallback}"; filename*=UTF-8''${encodeURIComponent(name)}`; } export async function createInboxAttachmentResponse( attachment: InboxAttachmentFile, ): Promise { // Only inert raster formats render inline. Documents are downloads so their // active content cannot inherit the Pony page's browser context. const inline = isInlineInboxImage(attachment.metadata.media_type); const data = await readFile(attachment.absolutePath); return new Response(data, { headers: { "Cache-Control": "private, no-store", "Content-Disposition": contentDisposition( attachment.metadata.name, inline, ), "Content-Length": String(data.byteLength), "Content-Type": attachment.metadata.media_type, "X-Content-Type-Options": "nosniff", }, }); }