Open History to see the last commit
1// @effect-diagnostics globalTimers:off - Queues an abort as a separate task, as a UI event would be.
2import * as NodeZlib from "node:zlib";
3import * as DateTime from "effect/DateTime";
4import JSZip from "jszip";
5import { describe, expect, it, onTestFinished, vi } from "vite-plus/test";
6import { boundedZip } from "./boundedZip.ts";
7
8// Writes each name as raw bytes with no UTF-8 flag, as legacy and macOS archivers do.
9async function zipWithRawNames(entries: ReadonlyArray<readonly [number[], string]>) {
10 const placeholders = entries.map(([raw], index) => String(index).padStart(raw.length, "_"));
11 const bytes = new Uint8Array(
12 await entries
13 .reduce((zip, [, content], index) => zip.file(placeholders[index]!, content), new JSZip())
14 .generateAsync({ type: "arraybuffer", compression: "STORE" }),
15 );
16 const text = new TextDecoder("latin1").decode(bytes);
17 entries.forEach(([raw], index) => {
18 for (const match of text.matchAll(new RegExp(placeholders[index]!, "g")))
19 bytes.set(raw, match.index);
20 });
21 return bytes.buffer;
22}
23
24const ascii = (text: string) => Array.from(text, (char) => char.charCodeAt(0));
25
26describe("boundedZip", () => {
27 it("rejects an unencrypted ZIP with an already-aborted signal", async () => {
28 const bytes = await new JSZip().file("a.txt", "hello").generateAsync({ type: "arraybuffer" });
29 const controller = new AbortController();
30 const reason = new Error("cancelled");
31 controller.abort(reason);
32
33 await expect(boundedZip(bytes, undefined, { signal: controller.signal })).rejects.toBe(reason);
34 });
35
36 it("keeps an unencrypted ZIP entry paused when aborted before JSZip's deferred resume", async () => {
37 const bytes = await new JSZip()
38 .file("a.txt", "hello".repeat(10_000))
39 .generateAsync({ type: "arraybuffer", compression: "DEFLATE" });
40 const zip = await JSZip.loadAsync(bytes);
41 const entry = zip.files["a.txt"] as JSZip.JSZipObject & {
42 internalStream(type: "uint8array"): JSZip.JSZipStreamHelper<Uint8Array> & {
43 _worker: { isPaused: boolean; resume(): boolean };
44 };
45 };
46 const stream = entry.internalStream("uint8array");
47 const workerResume = stream._worker.resume.bind(stream._worker);
48 const { promise: resumed, resolve } = Promise.withResolvers<void>();
49 using _resume = vi.spyOn(stream._worker, "resume").mockImplementation(() => {
50 const result = workerResume();
51 resolve();
52 return result;
53 });
54 const controller = new AbortController();
55 const reason = new Error("cancelled");
56 using _internalStream = vi.spyOn(entry, "internalStream").mockImplementation(() => {
57 queueMicrotask(() => controller.abort(reason));
58 return stream;
59 });
60 using _loadAsync = vi.spyOn(JSZip, "loadAsync").mockResolvedValue(zip);
61
62 await expect(
63 boundedZip(bytes, undefined, { ratioFloor: 50_000, signal: controller.signal }),
64 ).rejects.toBe(reason);
65 await resumed;
66 expect(stream._worker.isPaused).toBe(true);
67 });
68
69 it("lets an abort from another task land when setImmediate is a microtask, as in React Native", async () => {
70 const bytes = await new JSZip()
71 .file("a.txt", "hello".repeat(10_000))
72 .generateAsync({ type: "arraybuffer", compression: "DEFLATE" });
73 vi.stubGlobal("setImmediate", (callback: () => void) => queueMicrotask(callback));
74 onTestFinished(() => void vi.unstubAllGlobals());
75 let now = 0;
76 using _now = vi.spyOn(Date, "now").mockImplementation(() => (now += 1_000));
77 const controller = new AbortController();
78 const reason = new Error("cancelled");
79 setTimeout(() => controller.abort(reason));
80
81 await expect(
82 boundedZip(bytes, undefined, { ratioFloor: 50_000, signal: controller.signal }),
83 ).rejects.toBe(reason);
84 });
85
86 it("decodes unflagged names as UTF-8, else CP437, without merging entries", async () => {
87 const files = await boundedZip(
88 await zipWithRawNames([
89 [[...ascii("caf"), 0x82, ...ascii(".txt")], "CP437 e-acute"],
90 [[...ascii("caf"), 0x8a, ...ascii(".txt")], "CP437 e-grave"],
91 [[...ascii("na"), 0xc3, 0xaf, ...ascii("ve.txt")], "UTF-8"],
92 [[0xef, 0xbb, 0xbf, ...ascii("a.txt")], "UTF-8 with BOM"],
93 [ascii("a.txt"), "ASCII"],
94 ]),
95 );
96 expect([...files].map(([name, file]) => [name, new TextDecoder().decode(file.bytes)])).toEqual([
97 ["café.txt", "CP437 e-acute"],
98 ["cafè.txt", "CP437 e-grave"],
99 ["naïve.txt", "UTF-8"],
100 ["\uFEFFa.txt", "UTF-8 with BOM"],
101 ["a.txt", "ASCII"],
102 ]);
103 });
104
105 it("enforces xmlLimit case-insensitively on unencrypted and encrypted ZIP entries", async () => {
106 const payload = "x".repeat(200);
107 const bytes = await new JSZip()
108 .file("word/document.XML", payload)
109 .generateAsync({ type: "arraybuffer", compression: "STORE" });
110 await expect(boundedZip(bytes, 1000, { xmlLimit: 100 })).rejects.toMatchObject({
111 code: "archive-expanded-too-large",
112 });
113
114 const { Uint8ArrayWriter, TextReader, ZipWriter } =
115 await import("@zip.js/zip.js/index-native.js");
116 const writer = new ZipWriter(new Uint8ArrayWriter(), { useWebWorkers: false });
117 await writer.add("word/document.XML", new TextReader(payload), { password: "open me" });
118 const encryptedBytes = (await writer.close()).buffer;
119 await expect(
120 boundedZip(encryptedBytes, 1000, { password: "open me", xmlLimit: 100 }),
121 ).rejects.toMatchObject({
122 code: "archive-expanded-too-large",
123 });
124 });
125});
126
127it.each([false, true])("opens a password-protected ZIP (ZipCrypto: %s)", async (zipCrypto) => {
128 const { Uint8ArrayWriter, TextReader, ZipWriter } =
129 await import("@zip.js/zip.js/index-native.js");
130 const writer = new ZipWriter(new Uint8ArrayWriter(), { useWebWorkers: false });
131 await writer.add("public.txt", new TextReader("Public"), {
132 lastModDate: DateTime.toDateUtc(DateTime.makeUnsafe("2025-01-01T00:00:00.000Z")),
133 rawLastModDate: (44 << 25) | (12 << 21) | (3 << 16) | (14 << 11) | (15 << 5) | 8,
134 });
135 await writer.add("secret.txt", new TextReader("Unlocked ZIP".repeat(30)), {
136 password: "open me",
137 zipCrypto,
138 });
139 const bytes = (await writer.close()).buffer;
140 await expect(boundedZip(bytes)).rejects.toMatchObject({ code: "password-required" });
141 await expect(boundedZip(bytes, undefined, { password: "wrong" })).rejects.toMatchObject({
142 code: "password-incorrect",
143 });
144 const files = await boundedZip(bytes, undefined, { password: "open me" });
145 expect(new TextDecoder().decode(files.get("public.txt")?.bytes)).toBe("Public");
146 expect(files.get("public.txt")?.date.toISOString()).toBe("2024-12-03T14:15:16.000Z");
147 expect(new TextDecoder().decode(files.get("secret.txt")?.bytes)).toBe("Unlocked ZIP".repeat(30));
148 await expect(boundedZip(bytes, 50, { password: "open me" })).rejects.toMatchObject({
149 code: "archive-expanded-too-large",
150 });
151});
152
153it("rejects an encrypted ZIP whose Unicode path field exceeds the filename limit", async () => {
154 const { Uint8ArrayWriter, TextReader, ZipWriter } =
155 await import("@zip.js/zip.js/index-native.js");
156 const writer = new ZipWriter(new Uint8ArrayWriter(), {
157 useWebWorkers: false,
158 useUnicodeFileNames: false,
159 });
160 const fallback = "name.txt";
161 const name = new TextEncoder().encode("a".repeat(1025));
162 const unicodePath = new Uint8Array(5 + name.length);
163 unicodePath[0] = 1;
164 new DataView(unicodePath.buffer).setUint32(1, NodeZlib.crc32(fallback), true);
165 unicodePath.set(name, 5);
166 await writer.add(fallback, new TextReader("Locked"), {
167 password: "open me",
168 extraField: new Map([[0x7075, unicodePath]]),
169 });
170 const bytes = (await writer.close()).buffer;
171 await expect(boundedZip(bytes, undefined, { password: "open me" })).rejects.toMatchObject({
172 code: "archive-path-too-long",
173 });
174});