Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

guestAttachments.ts

103 lines3.9 KB

1import {
2 GUEST_MESSAGE_MAX_ATTACHMENT_BYTES,
3 GUEST_MESSAGE_MAX_ATTACHMENTS,
4 isProviderSendTurnSupportedImageMimeType,
5} from "@t3tools/contracts";
6​
7/** A file from a guest's message request, saved by the multipart parser to a temporary path. */
8export interface GuestUpload {
9 readonly name: string;
10 readonly contentType: string;
11 readonly path: string;
13​
14/** What the server learned about an upload before deciding what it may become. */
15export interface InspectedGuestUpload {
16 readonly name: string;
17 readonly contentType: string;
18 readonly sizeBytes: number;
19 /** The first bytes of the file. */
20 readonly header: Uint8Array;
22​
23export type GuestUploadRejection = "too_many_files" | "too_large" | "unsupported_file";
24​
25/** An attachment before it is stored and gets its id. */
26export interface GuestAttachmentDraft {
27 readonly type: "image" | "file";
28 readonly name: string;
29 readonly mimeType: string;
30 readonly sizeBytes: number;
32​
33/** Bytes of the file the signature check reads. */
34export const GUEST_UPLOAD_HEADER_BYTES = 12;
35​
36const startsWith = (header: Uint8Array, bytes: ReadonlyArray<number>, offset = 0) =>
37 bytes.every((byte, index) => header[offset + index] === byte);
38const ascii = (text: string) => Array.from(text, (character) => character.charCodeAt(0));
39​
40/** An image must be what its type says, so a renamed HTML page never travels as one. */
41const IMAGE_SIGNATURES: Readonly<Record<string, (header: Uint8Array) => boolean>> = {
42 "image/png": (header) => startsWith(header, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
43 "image/jpeg": (header) => startsWith(header, [0xff, 0xd8, 0xff]),
44 "image/gif": (header) => startsWith(header, ascii("GIF8")),
45 "image/webp": (header) =>
46 startsWith(header, ascii("RIFF")) && startsWith(header, ascii("WEBP"), 8),
47};
48​
49/**
50 * Control characters and separators would break the name in headers and on disk, and direction
51 * overrides would let `invoice\u202Efdp.exe` show as a PDF.
52 */
53const safeName = (name: string, fallback: string) =>
54 name
55 .replace(/[\p{Cc}\\/\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/gu, "_")
56 .trim()
57 .slice(0, 255) || fallback;
58​
59/**
60 * The attachments a guest's files become, as the owner's composer takes them: supported images as
61 * images, anything else that is not an image as a file. Other image types (SVG, HEIC) and empty
62 * files are refused, as are too many files or too many bytes in one message.
63 */
64export function classifyGuestUploads(
65 uploads: ReadonlyArray<InspectedGuestUpload>,
66):
67 | { readonly ok: true; readonly attachments: ReadonlyArray<GuestAttachmentDraft> }
68 | { readonly ok: false; readonly reason: GuestUploadRejection } {
69 if (uploads.length > GUEST_MESSAGE_MAX_ATTACHMENTS)
70 return { ok: false, reason: "too_many_files" };
71 const total = uploads.reduce((sum, upload) => sum + upload.sizeBytes, 0);
72 if (total > GUEST_MESSAGE_MAX_ATTACHMENT_BYTES) return { ok: false, reason: "too_large" };
73 const attachments: Array<GuestAttachmentDraft> = [];
74 for (const upload of uploads) {
75 const mimeType =
76 upload.contentType.split(";", 1)[0]!.trim().toLowerCase() || "application/octet-stream";
77 if (upload.sizeBytes === 0) return { ok: false, reason: "unsupported_file" };
78 if (mimeType.startsWith("image/")) {
79 const signatureMatches = IMAGE_SIGNATURES[mimeType];
80 if (
81 !isProviderSendTurnSupportedImageMimeType(mimeType) ||
82 signatureMatches === undefined ||
83 !signatureMatches(upload.header)
84 ) {
85 return { ok: false, reason: "unsupported_file" };
86 }
87 attachments.push({
88 type: "image",
89 name: safeName(upload.name, "image"),
90 mimeType,
91 sizeBytes: upload.sizeBytes,
92 });
93 continue;
94 }
95 attachments.push({
96 type: "file",
97 name: safeName(upload.name, "file"),
98 mimeType: mimeType.length <= 100 ? mimeType : "application/octet-stream",
99 sizeBytes: upload.sizeBytes,
100 });
101 }
102 return { ok: true, attachments };