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

boundedZip.ts

145 lines5.6 KB

1// @effect-diagnostics globalTimers:off globalDate:off - Plain promise code driving JSZip, outside an Effect runtime.
2import JSZip from "jszip";
3import { checkZipDirectory } from "./zipDirectory.ts";
4import { ZipError } from "./zipError.ts";
5​
6const CP437_HIGH_BYTES =
7 "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒ" +
8 "áíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐" +
9 "└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀" +
10 "αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■\u00a0";
11​
12const utf8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
13​
14// JSZip only calls this for names without the UTF-8 flag or a Unicode path field. Many
15// archivers still write UTF-8 there, so CP437 (the ZIP spec's default) is the fallback;
16// replacing invalid bytes instead would collapse distinct legacy names into one key.
17function decodeFileName(name: string[] | Uint8Array) {
18 const raw = Array.isArray(name) ? Uint8Array.from(name, (char) => char.charCodeAt(0)) : name;
19 try {
20 return utf8.decode(raw);
21 } catch {
22 return Array.from(raw, (byte) =>
23 byte < 128 ? String.fromCharCode(byte) : CP437_HIGH_BYTES[byte - 128],
24 ).join("");
25 }
27​
28export const ARCHIVE_MAX_BYTES = 50 * 1024 * 1024;
29export const ARCHIVE_ENTRY_MAX_BYTES = 10 * 1024 * 1024;
30export const ARCHIVE_MAX_ENTRIES = 2048;
31export const ARCHIVE_MAX_RATIO = 200;
32const ABORT_CHECK_INTERVAL_MS = 50;
33​
34export async function boundedZip(
35 bytes: ArrayBuffer,
36 entryLimit = ARCHIVE_MAX_BYTES,
37 limits: {
38 totalLimit?: number;
39 xmlLimit?: number;
40 ratioFloor?: number;
41 markupLimit?: number;
42 password?: string | undefined;
43 maxEntries?: number;
44 signal?: AbortSignal | undefined;
45 } = {},
46) {
47 if (bytes.byteLength > ARCHIVE_MAX_BYTES) throw new ZipError({ code: "file-too-large" });
48 const maxEntries = limits.maxEntries ?? ARCHIVE_MAX_ENTRIES;
49 const { encrypted } = checkZipDirectory(bytes, maxEntries);
50 if (encrypted) {
51 if (limits.password === undefined) throw new ZipError({ code: "password-required" });
52 const { readEncryptedZip } = await import("./encryptedZip.ts");
53 return readEncryptedZip(bytes, limits.password, {
54 entryLimit,
55 totalLimit: Math.min(
56 limits.totalLimit ?? ARCHIVE_MAX_BYTES,
57 Math.max(limits.ratioFloor ?? 0, bytes.byteLength * ARCHIVE_MAX_RATIO),
58 ),
59 xmlLimit: limits.xmlLimit ?? 8 * 1024 * 1024,
60 markupLimit: limits.markupLimit,
61 signal: limits.signal,
62 decodeFileName,
63 });
64 }
65 const { signal } = limits;
66 signal?.throwIfAborted();
67 const zip = await JSZip.loadAsync(bytes, { decodeFileName });
68 signal?.throwIfAborted();
69 const entries = Object.values(zip.files);
70 if (entries.length > maxEntries) throw new ZipError({ code: "archive-too-many-entries" });
71 const files = new Map<
72 string,
73 { bytes: Uint8Array<ArrayBuffer>; date: Date; directory: boolean }
74 >();
75 let total = 0;
76 let markup = 0;
77 let lastYield = Date.now();
78 for (const entry of entries) {
79 if (entry.name.length > 1024) throw new ZipError({ code: "archive-path-too-long" });
80 const chunks: Uint8Array<ArrayBuffer>[] = [];
81 const isXmlEntry = entry.name.toLowerCase().endsWith(".xml");
82 let length = 0;
83 let yielding = false;
84 await new Promise<void>((resolve, reject) => {
85 const stream = (
86 entry as JSZip.JSZipObject & {
87 internalStream(type: "uint8array"): JSZip.JSZipStreamHelper<Uint8Array<ArrayBuffer>>;
88 }
89 ).internalStream("uint8array");
90 let stopped = false;
91 const stop = (cause: unknown) => {
92 stopped = true;
93 stream.pause();
94 reject(cause);
95 };
96 stream
97 .on("data", (chunk) => {
98 // JSZip defers resume(), so a pause from an abort listener could be undone; check per chunk.
99 if (signal?.aborted) return stop(signal.reason);
100 total += chunk.length;
101 length += chunk.length;
102 // Word relationship targets can use arbitrary extensions, so count every part.
103 if (limits.markupLimit !== undefined)
104 for (const byte of chunk) if (byte === 0x3c) markup++;
105 if (
106 markup > (limits.markupLimit ?? Infinity) ||
107 total > (limits.totalLimit ?? ARCHIVE_MAX_BYTES) ||
108 total >
109 Math.max(limits.ratioFloor ?? 0, Math.max(1, bytes.byteLength) * ARCHIVE_MAX_RATIO) ||
110 length > entryLimit ||
111 (isXmlEntry && length > (limits.xmlLimit ?? 8 * 1024 * 1024))
112 ) {
113 stop(new ZipError({ code: "archive-expanded-too-large" }));
114 return;
115 }
116 chunks.push(chunk);
117 // React Native runs setImmediate as a microtask, so JSZip never yields and the UI
118 // event that aborts could not run until every entry was inflated.
119 if (signal && !yielding && Date.now() - lastYield > ABORT_CHECK_INTERVAL_MS) {
120 yielding = true;
121 stream.pause();
122 setTimeout(() => {
123 yielding = false;
124 lastYield = Date.now();
125 if (stopped) return;
126 if (signal.aborted) stop(signal.reason);
127 else stream.resume();
128 }, 0);
129 }
130 })
131 .on("error", reject)
132 .on("end", resolve)
133 .resume();
134 });
135 signal?.throwIfAborted();
136 const content = new Uint8Array(length);
137 let offset = 0;
138 for (const chunk of chunks) {
139 content.set(chunk, offset);
140 offset += chunk.length;
141 }
142 files.set(entry.name, { bytes: content, date: entry.date, directory: entry.dir });
143 }
144 return files;