Open History to see the last commit
1import JSZip from "jszip";
2import { checkZipDirectory } from "./zipDirectory.ts";
3import { ZipError } from "./zipError.ts";
4
5const CP437_HIGH_BYTES =
6 "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒ" +
7 "áíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐" +
8 "└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀" +
9 "αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■\u00a0";
10
11const utf8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
12
13// JSZip only calls this for names without the UTF-8 flag or a Unicode path field. Many
14// archivers still write UTF-8 there, so CP437 (the ZIP spec's default) is the fallback;
15// replacing invalid bytes instead would collapse distinct legacy names into one key.
16function decodeFileName(name: string[] | Uint8Array) {
17 const raw = Array.isArray(name) ? Uint8Array.from(name, (char) => char.charCodeAt(0)) : name;
18 try {
19 return utf8.decode(raw);
20 } catch {
21 return Array.from(raw, (byte) =>
22 byte < 128 ? String.fromCharCode(byte) : CP437_HIGH_BYTES[byte - 128],
23 ).join("");
24 }
25}
26
27export const ARCHIVE_MAX_BYTES = 50 * 1024 * 1024;
28export const ARCHIVE_ENTRY_MAX_BYTES = 10 * 1024 * 1024;
29export const ARCHIVE_MAX_ENTRIES = 2048;
30export const ARCHIVE_MAX_RATIO = 200;
31
32export async function boundedZip(
33 bytes: ArrayBuffer,
34 entryLimit = ARCHIVE_MAX_BYTES,
35 limits: {
36 totalLimit?: number;
37 xmlLimit?: number;
38 ratioFloor?: number;
39 markupLimit?: number;
40 } = {},
41) {
42 if (bytes.byteLength > ARCHIVE_MAX_BYTES) throw new ZipError({ code: "file-too-large" });
43 checkZipDirectory(bytes, ARCHIVE_MAX_ENTRIES);
44 const zip = await JSZip.loadAsync(bytes, { decodeFileName });
45 const entries = Object.values(zip.files);
46 if (entries.length > ARCHIVE_MAX_ENTRIES)
47 throw new ZipError({ code: "archive-too-many-entries" });
48 const files = new Map<
49 string,
50 { bytes: Uint8Array<ArrayBuffer>; date: Date; directory: boolean }
51 >();
52 let total = 0;
53 let markup = 0;
54 for (const entry of entries) {
55 if (entry.name.length > 1024) throw new ZipError({ code: "archive-path-too-long" });
56 const chunks: Uint8Array<ArrayBuffer>[] = [];
57 let length = 0;
58 await new Promise<void>((resolve, reject) => {
59 const stream = (
60 entry as JSZip.JSZipObject & {
61 internalStream(type: "uint8array"): JSZip.JSZipStreamHelper<Uint8Array<ArrayBuffer>>;
62 }
63 ).internalStream("uint8array");
64 stream
65 .on("data", (chunk) => {
66 total += chunk.length;
67 length += chunk.length;
68 // Word relationship targets can use arbitrary extensions, so count every part.
69 if (limits.markupLimit !== undefined)
70 for (const byte of chunk) if (byte === 0x3c) markup++;
71 if (
72 markup > (limits.markupLimit ?? Infinity) ||
73 total > (limits.totalLimit ?? ARCHIVE_MAX_BYTES) ||
74 total >
75 Math.max(limits.ratioFloor ?? 0, Math.max(1, bytes.byteLength) * ARCHIVE_MAX_RATIO) ||
76 length > entryLimit ||
77 (entry.name.endsWith(".xml") && length > (limits.xmlLimit ?? 8 * 1024 * 1024))
78 ) {
79 stream.pause();
80 reject(new ZipError({ code: "archive-expanded-too-large" }));
81 } else chunks.push(chunk);
82 })
83 .on("error", reject)
84 .on("end", resolve)
85 .resume();
86 });
87 const content = new Uint8Array(length);
88 let offset = 0;
89 for (const chunk of chunks) {
90 content.set(chunk, offset);
91 offset += chunk.length;
92 }
93 files.set(entry.name, { bytes: content, date: entry.date, directory: entry.dir });
94 }
95 return files;
96}