File size: 3,593 Bytes
e81f4e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
import type { ErrorWithMetadata } from "../shared/types";
import { base64DecodedByteLength, base64ToBytes } from "./base64";
import {
	chooseUploadMime,
	detectUploadMimeFromBytes,
	firstNonEmptyString,
	genericFilenameFromMime,
	imageFilenameFromMime,
	mimeFromFilename,
} from "./mime";
import type { AttachmentCandidate, AttachmentDropReason } from "./types";

export type AttachmentLimits = {
	maxFileBytes: number;
	maxImageBytes: number;
};

export type MaterializedAttachment = {
	candidate: AttachmentCandidate;
	bytes: Uint8Array;
	mime: string;
	filename: string;
};

export const DEFAULT_ATTACHMENT_MAX_BYTES = 20 * 1024 * 1024;

export async function materializeAttachment(
	candidate: AttachmentCandidate,
	limits: AttachmentLimits,
): Promise<MaterializedAttachment> {
	const maxBytes = maxBytesForCandidate(candidate, limits);
	if (candidate.source.type === "bytes") {
		ensureWithinLimit(candidate, candidate.source.bytes.byteLength, maxBytes);
		const mime = mimeForCandidate(candidate, candidate.source.bytes);
		return {
			candidate,
			bytes: candidate.source.bytes,
			mime,
			filename: filenameForCandidate(candidate, mime),
		};
	}
	const compact = String(candidate.source.data || "").replace(/\s+/g, "");
	ensureWithinLimit(candidate, base64DecodedByteLength(compact), maxBytes);
	try {
		const bytes = base64ToBytes(compact);
		ensureWithinLimit(candidate, bytes.byteLength, maxBytes);
		const mime = mimeForCandidate(candidate, bytes);
		return {
			candidate,
			bytes,
			mime,
			filename: filenameForCandidate(candidate, mime),
		};
	} catch (e) {
		throw attachmentMaterializeFailure(
			candidate,
			"invalid_base64",
			"invalid base64 payload",
			400,
			e,
		);
	}
}

export function joinByteChunks(
	chunks: readonly Uint8Array[],
	total: number,
): Uint8Array {
	const out = new Uint8Array(total);
	let offset = 0;
	for (const chunk of chunks) {
		out.set(chunk, offset);
		offset += chunk.byteLength;
	}
	return out;
}

export function attachmentMaterializeFailure(
	candidate: AttachmentCandidate,
	code: AttachmentDropReason,
	message: string,
	status: number,
	cause?: unknown,
): ErrorWithMetadata {
	const err: ErrorWithMetadata = new Error(message);
	err.code = code;
	err.status = status;
	(err as ErrorWithMetadata & { attachmentKind?: string }).attachmentKind =
		candidate.kind;
	if (cause !== undefined) err.cause = cause;
	return err;
}

function maxBytesForCandidate(
	candidate: AttachmentCandidate,
	limits: AttachmentLimits,
): number {
	if (candidate.kind === "image") return Math.max(0, limits.maxImageBytes);
	return Math.max(0, limits.maxFileBytes);
}

function ensureWithinLimit(
	candidate: AttachmentCandidate,
	bytes: number,
	maxBytes: number,
): void {
	if (bytes > maxBytes) {
		throw attachmentMaterializeFailure(
			candidate,
			candidate.kind === "image" ? "image_too_large" : "file_too_large",
			`${candidate.kind} attachment is too large (${bytes} bytes > ${maxBytes} bytes)`,
			413,
		);
	}
}

function mimeForCandidate(
	candidate: AttachmentCandidate,
	bytes: Uint8Array,
): string {
	return chooseUploadMime(
		candidate.mime,
		mimeFromFilename(candidate.filename),
		detectUploadMimeFromBytes(bytes),
	);
}

function filenameForCandidate(
	candidate: AttachmentCandidate,
	mimeHint: unknown,
): string {
	const explicit = firstNonEmptyString(candidate.filename);
	if (explicit) return explicit;
	if (candidate.kind === "image")
		return imageFilenameFromMime(candidate.mime || mimeHint || "image/png", 1);
	return genericFilenameFromMime(
		candidate.mime || mimeHint || "application/octet-stream",
		1,
	);
}