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

boundedZip.ts

79 lines2.7 KB

1import JSZip from "jszip";
2import { checkZipDirectory } from "./zipDirectory";
3​
4import {
5 ARCHIVE_MAX_ENTRIES,
6 ARCHIVE_MAX_RATIO,
7 BINARY_PREVIEW_MAX_BYTES,
8} from "./binaryPreviewProtocol";
9​
10export async function boundedZip(
11 bytes: ArrayBuffer,
12 entryLimit = BINARY_PREVIEW_MAX_BYTES,
13 limits: {
14 totalLimit?: number;
15 xmlLimit?: number;
16 ratioFloor?: number;
17 markupLimit?: number;
18 } = {},
19) {
20 if (bytes.byteLength > BINARY_PREVIEW_MAX_BYTES)
21 throw new Error("Preview limited to files under 50 MB.");
22 checkZipDirectory(bytes, ARCHIVE_MAX_ENTRIES);
23 const zip = await JSZip.loadAsync(bytes);
24 const entries = Object.values(zip.files);
25 if (entries.length > ARCHIVE_MAX_ENTRIES)
26 throw new Error("This archive contains more than 2,048 entries.");
27 const files = new Map<
28 string,
29 { bytes: Uint8Array<ArrayBuffer>; date: Date; directory: boolean }
30 >();
31 let total = 0;
32 let markup = 0;
33 for (const entry of entries) {
34 if (entry.name.length > 1024) throw new Error("An archive path is too long to preview.");
35 const chunks: Uint8Array<ArrayBuffer>[] = [];
36 let length = 0;
37 await new Promise<void>((resolve, reject) => {
38 const stream = (
39 entry as JSZip.JSZipObject & {
40 internalStream(type: "uint8array"): JSZip.JSZipStreamHelper<Uint8Array<ArrayBuffer>>;
41 }
42 ).internalStream("uint8array");
43 stream
44 .on("data", (chunk) => {
45 total += chunk.length;
46 length += chunk.length;
47 // Word relationship targets can use arbitrary extensions, so count every part.
48 if (limits.markupLimit !== undefined)
49 for (const byte of chunk) if (byte === 0x3c) markup++;
50 if (
51 markup > (limits.markupLimit ?? Infinity) ||
52 total > (limits.totalLimit ?? BINARY_PREVIEW_MAX_BYTES) ||
53 total >
54 Math.max(limits.ratioFloor ?? 0, Math.max(1, bytes.byteLength) * ARCHIVE_MAX_RATIO) ||
55 length > entryLimit ||
56 (entry.name.endsWith(".xml") && length > (limits.xmlLimit ?? 8 * 1024 * 1024))
57 ) {
58 stream.pause();
59 reject(
60 new Error(
61 "The expanded archive exceeds the preview size or compression ratio limit.",
62 ),
63 );
64 } else chunks.push(chunk);
65 })
66 .on("error", reject)
67 .on("end", resolve)
68 .resume();
69 });
70 const content = new Uint8Array(length);
71 let offset = 0;
72 for (const chunk of chunks) {
73 content.set(chunk, offset);
74 offset += chunk.length;
75 }
76 files.set(entry.name, { bytes: content, date: entry.date, directory: entry.dir });
77 }
78 return files;