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

encryptedZip.ts

137 lines4.3 KB

1import {
2 ERR_ENCRYPTED,
3 ERR_INVALID_PASSWORD,
4 ERR_INVALID_CRC32,
5 ERR_INVALID_COMPRESSED_DATA,
6 ERR_INVALID_UNCOMPRESSED_SIZE,
7 ERR_UNSUPPORTED_ENCRYPTION,
8 ERR_UNSUPPORTED_COMPRESSION,
9 Uint8ArrayReader,
10 ZipReader,
11 type FileEntry,
12} from "@zip.js/zip.js/index-native.cjs";
13import * as DateTime from "effect/DateTime";
14​
15import { ZipError } from "./zipError.ts";
16​
17export async function readEncryptedZip(
18 bytes: ArrayBuffer,
19 password: string,
20 limits: {
21 readonly entryLimit: number;
22 readonly totalLimit: number;
23 readonly xmlLimit: number;
24 readonly markupLimit: number | undefined;
25 readonly signal: AbortSignal | undefined;
26 readonly decodeFileName: (name: Uint8Array) => string;
27 },
28) {
29 const reader = new ZipReader(new Uint8ArrayReader(new Uint8Array(bytes)), {
30 useWebWorkers: false,
31 decodeText: (name, encoding, type) =>
32 type === "filename" && encoding !== "utf-8" ? limits.decodeFileName(name) : undefined,
33 });
34 const files = new Map<
35 string,
36 { bytes: Uint8Array<ArrayBuffer>; date: Date; directory: boolean }
37 >();
38 let total = 0;
39 let markup = 0;
40 try {
41 for (const entry of await reader.getEntries()) {
42 limits.signal?.throwIfAborted();
43 if (entry.filename.length > 1024) throw new ZipError({ code: "archive-path-too-long" });
44 const name = entry.filename
45 .split("/")
46 .reduce<string[]>((parts, part) => {
47 if (part === "..") parts.pop();
48 else if (part && part !== ".") parts.push(part);
49 return parts;
50 }, [])
51 .join("/");
52 if (!name) continue;
53 total += entry.uncompressedSize;
54 if (
55 total > limits.totalLimit ||
56 entry.uncompressedSize > limits.entryLimit ||
57 (name.toLowerCase().endsWith(".xml") && entry.uncompressedSize > limits.xmlLimit)
58 )
59 throw new ZipError({ code: "archive-expanded-too-large" });
60 const content = entry.directory
61 ? new Uint8Array()
62 : await readEntry(entry, password, limits.signal);
63 if (limits.markupLimit !== undefined) {
64 for (const byte of content) if (byte === 0x3c) markup++;
65 if (markup > limits.markupLimit) throw new ZipError({ code: "archive-expanded-too-large" });
66 }
67 files.set(entry.directory ? `${name}/` : name, {
68 bytes: content,
69 date: dosDateInUtc(Number(entry.rawLastModDate)),
70 directory: entry.directory,
71 });
72 }
73 return files;
74 } catch (cause) {
75 if (cause instanceof Error) {
76 if (cause.message === ERR_INVALID_PASSWORD || cause.message === ERR_ENCRYPTED)
77 throw new ZipError({ code: "password-incorrect" });
78 if (
79 cause.message === ERR_UNSUPPORTED_ENCRYPTION ||
80 cause.message === ERR_UNSUPPORTED_COMPRESSION
81 )
82 throw new ZipError({ code: "encryption-unsupported" });
83 }
84 throw cause;
85 } finally {
86 await reader.close();
87 }
89​
90function dosDateInUtc(packed: number) {
91 // The archive viewer treats DOS dates as wall-clock times and uses UTC to store them.
92 const time = Date.UTC(
93 1980 + (packed >>> 25),
94 ((packed >>> 21) & 15) - 1,
95 (packed >>> 16) & 31,
96 (packed >>> 11) & 31,
97 (packed >>> 5) & 63,
98 (packed & 31) * 2,
99 );
100 return DateTime.toDateUtc(DateTime.makeUnsafe(time));
102​
103async function readEntry(entry: FileEntry, password: string, signal?: AbortSignal) {
104 const content = new Uint8Array(entry.uncompressedSize);
105 let offset = 0;
106 try {
107 await entry.getData(
108 new WritableStream<Uint8Array>({
109 write(chunk) {
110 if (offset + chunk.length > content.length)
111 throw new ZipError({ code: "archive-expanded-too-large" });
112 content.set(chunk, offset);
113 offset += chunk.length;
114 },
115 }),
116 {
117 ...(entry.encrypted ? { password } : {}),
118 checkCrc32: true,
119 checkAuthenticationCode: true,
120 ...(signal ? { signal } : {}),
121 },
122 );
123 } catch (cause) {
124 // ZipCrypto checks only one byte of the password before decompression.
125 if (
126 entry.encrypted &&
127 entry.zipCrypto &&
128 cause instanceof Error &&
129 [ERR_INVALID_CRC32, ERR_INVALID_COMPRESSED_DATA, ERR_INVALID_UNCOMPRESSED_SIZE].includes(
130 cause.message,
131 )
132 )
133 throw new ZipError({ code: "password-incorrect" });
134 throw cause;
135 }
136 return content;