@innovatorved/code-lab 0.1.7 → 0.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/zip.ts ADDED
@@ -0,0 +1,326 @@
1
+ /**
2
+ * @innovatorved/code-lab — Zero-Dependency PKZip v2.0 Archive Engine
3
+ * ============================================================================
4
+ * Pure TypeScript implementation of PKZip 2.0 (Store method 0 + UTF-8 flag
5
+ * bit 11 + IEEE 802.3 CRC32) for browser and Node/Bun project export & import.
6
+ *
7
+ * Includes built-in Zip-Slip path traversal sanitization and header integrity
8
+ * verification.
9
+ *
10
+ * Strict leaf module: fully typed, zero explicit any, zero empty catches.
11
+ */
12
+
13
+ const LOCAL_FILE_HEADER_SIG = 0x04034b50;
14
+ const CENTRAL_DIR_HEADER_SIG = 0x02014b50;
15
+ const END_OF_CENTRAL_DIR_SIG = 0x06054b50;
16
+ const UTF8_FLAG = 0x0800;
17
+
18
+ /** Precomputed IEEE 802.3 CRC32 lookup table. */
19
+ const CRC32_TABLE = new Uint32Array(256);
20
+ for (let i = 0; i < 256; i++) {
21
+ let c = i;
22
+ for (let k = 0; k < 8; k++) {
23
+ c = (c & 1) !== 0 ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1);
24
+ }
25
+ CRC32_TABLE[i] = c >>> 0;
26
+ }
27
+
28
+ const textEncoder = new TextEncoder();
29
+ const textDecoder = new TextDecoder('utf-8');
30
+
31
+ /**
32
+ * Converts a string or byte buffer into a `Uint8Array`.
33
+ */
34
+ export function toUint8Array(input: string | Uint8Array | ArrayBuffer): Uint8Array {
35
+ if (typeof input === 'string') {
36
+ return textEncoder.encode(input);
37
+ }
38
+ if (input instanceof Uint8Array) {
39
+ return input;
40
+ }
41
+ if (input instanceof ArrayBuffer) {
42
+ return new Uint8Array(input);
43
+ }
44
+ return new Uint8Array(0);
45
+ }
46
+
47
+ /**
48
+ * Computes the standard IEEE 802.3 CRC32 checksum of a string or byte array.
49
+ */
50
+ export function computeCrc32(data: string | Uint8Array | ArrayBuffer): number {
51
+ const bytes = toUint8Array(data);
52
+ let crc = 0xffffffff;
53
+ for (let i = 0; i < bytes.length; i++) {
54
+ const index = (crc ^ bytes[i]) & 0xff;
55
+ crc = (crc >>> 8) ^ CRC32_TABLE[index];
56
+ }
57
+ return (crc ^ 0xffffffff) >>> 0;
58
+ }
59
+
60
+ /**
61
+ * Sanitizes an archive entry path to prevent Zip-Slip directory traversal attacks.
62
+ * Normalizes backslashes, strips drive prefixes and leading slashes, and collapses
63
+ * or removes `..` and `.` segments so the resulting path is strictly relative.
64
+ */
65
+ export function sanitizeZipPath(rawPath: string): string {
66
+ const normalized = String(rawPath || '')
67
+ .replace(/\\/g, '/')
68
+ .replace(/^[A-Za-z]:/, '');
69
+ const parts = normalized.split('/');
70
+ const safeParts: string[] = [];
71
+ for (const part of parts) {
72
+ const trimmed = part.trim();
73
+ if (!trimmed || trimmed === '.') continue;
74
+ if (trimmed === '..') {
75
+ if (safeParts.length > 0) {
76
+ safeParts.pop();
77
+ }
78
+ continue;
79
+ }
80
+ safeParts.push(trimmed);
81
+ }
82
+ return safeParts.join('/');
83
+ }
84
+
85
+ function writeUInt16LE(buf: Uint8Array, offset: number, value: number): void {
86
+ buf[offset] = value & 0xff;
87
+ buf[offset + 1] = (value >>> 8) & 0xff;
88
+ }
89
+
90
+ function writeUInt32LE(buf: Uint8Array, offset: number, value: number): void {
91
+ buf[offset] = value & 0xff;
92
+ buf[offset + 1] = (value >>> 8) & 0xff;
93
+ buf[offset + 2] = (value >>> 16) & 0xff;
94
+ buf[offset + 3] = (value >>> 24) & 0xff;
95
+ }
96
+
97
+ function readUInt16LE(buf: Uint8Array, offset: number): number {
98
+ return (buf[offset] | (buf[offset + 1] << 8)) >>> 0;
99
+ }
100
+
101
+ function readUInt32LE(buf: Uint8Array, offset: number): number {
102
+ return (
103
+ (buf[offset] |
104
+ (buf[offset + 1] << 8) |
105
+ (buf[offset + 2] << 16) |
106
+ (buf[offset + 3] << 24)) >>> 0
107
+ );
108
+ }
109
+
110
+ interface ZipEntryInternal {
111
+ nameBytes: Uint8Array;
112
+ dataBytes: Uint8Array;
113
+ crc32: number;
114
+ offset: number;
115
+ }
116
+
117
+ /**
118
+ * Creates a standard PKZip v2.0 archive from a map of file paths to contents.
119
+ */
120
+ export async function createZip(
121
+ files: Record<string, string | Uint8Array>
122
+ ): Promise<Uint8Array> {
123
+ const entries: ZipEntryInternal[] = [];
124
+ let localSectionSize = 0;
125
+ let centralDirSize = 0;
126
+
127
+ const rawKeys = Object.keys(files || {});
128
+ for (const rawKey of rawKeys) {
129
+ const safePath = sanitizeZipPath(rawKey);
130
+ if (!safePath) continue;
131
+
132
+ const rawContent = files[rawKey];
133
+ const dataBytes = toUint8Array(rawContent);
134
+ const nameBytes = textEncoder.encode(safePath);
135
+ const crc = computeCrc32(dataBytes);
136
+
137
+ entries.push({
138
+ nameBytes,
139
+ dataBytes,
140
+ crc32: crc,
141
+ offset: localSectionSize
142
+ });
143
+
144
+ localSectionSize += 30 + nameBytes.length + dataBytes.length;
145
+ centralDirSize += 46 + nameBytes.length;
146
+ }
147
+
148
+ const totalSize = localSectionSize + centralDirSize + 22;
149
+ const out = new Uint8Array(totalSize);
150
+ let cursor = 0;
151
+
152
+ // 1. Write Local File Headers + File Data
153
+ for (const entry of entries) {
154
+ writeUInt32LE(out, cursor, LOCAL_FILE_HEADER_SIG);
155
+ writeUInt16LE(out, cursor + 4, 20); // Version needed to extract (2.0)
156
+ writeUInt16LE(out, cursor + 6, UTF8_FLAG); // General purpose bit flag (UTF-8)
157
+ writeUInt16LE(out, cursor + 8, 0); // Compression method: 0 (Store)
158
+ writeUInt16LE(out, cursor + 10, 0); // Last mod file time
159
+ writeUInt16LE(out, cursor + 12, 0x2100); // Last mod file date (1980-01-01)
160
+ writeUInt32LE(out, cursor + 14, entry.crc32);
161
+ writeUInt32LE(out, cursor + 18, entry.dataBytes.length); // Compressed size
162
+ writeUInt32LE(out, cursor + 22, entry.dataBytes.length); // Uncompressed size
163
+ writeUInt16LE(out, cursor + 26, entry.nameBytes.length); // File name length
164
+ writeUInt16LE(out, cursor + 28, 0); // Extra field length
165
+ cursor += 30;
166
+
167
+ out.set(entry.nameBytes, cursor);
168
+ cursor += entry.nameBytes.length;
169
+
170
+ out.set(entry.dataBytes, cursor);
171
+ cursor += entry.dataBytes.length;
172
+ }
173
+
174
+ const centralDirOffset = cursor;
175
+
176
+ // 2. Write Central Directory File Headers
177
+ for (const entry of entries) {
178
+ writeUInt32LE(out, cursor, CENTRAL_DIR_HEADER_SIG);
179
+ writeUInt16LE(out, cursor + 4, 20); // Version made by
180
+ writeUInt16LE(out, cursor + 6, 20); // Version needed to extract
181
+ writeUInt16LE(out, cursor + 8, UTF8_FLAG); // General purpose bit flag
182
+ writeUInt16LE(out, cursor + 10, 0); // Compression method: Store
183
+ writeUInt16LE(out, cursor + 12, 0); // Last mod file time
184
+ writeUInt16LE(out, cursor + 14, 0x2100); // Last mod file date
185
+ writeUInt32LE(out, cursor + 16, entry.crc32);
186
+ writeUInt32LE(out, cursor + 20, entry.dataBytes.length); // Compressed size
187
+ writeUInt32LE(out, cursor + 24, entry.dataBytes.length); // Uncompressed size
188
+ writeUInt16LE(out, cursor + 28, entry.nameBytes.length); // File name length
189
+ writeUInt16LE(out, cursor + 30, 0); // Extra field length
190
+ writeUInt16LE(out, cursor + 32, 0); // File comment length
191
+ writeUInt16LE(out, cursor + 34, 0); // Disk number start
192
+ writeUInt16LE(out, cursor + 36, 0); // Internal file attributes
193
+ writeUInt32LE(out, cursor + 38, 0); // External file attributes
194
+ writeUInt32LE(out, cursor + 42, entry.offset); // Relative offset of local header
195
+ cursor += 46;
196
+
197
+ out.set(entry.nameBytes, cursor);
198
+ cursor += entry.nameBytes.length;
199
+ }
200
+
201
+ // 3. Write End of Central Directory Record (EOCD)
202
+ writeUInt32LE(out, cursor, END_OF_CENTRAL_DIR_SIG);
203
+ writeUInt16LE(out, cursor + 4, 0); // Number of this disk
204
+ writeUInt16LE(out, cursor + 6, 0); // Disk where central directory starts
205
+ writeUInt16LE(out, cursor + 8, entries.length); // Number of central dir records on this disk
206
+ writeUInt16LE(out, cursor + 10, entries.length); // Total number of central dir records
207
+ writeUInt32LE(out, cursor + 12, centralDirSize); // Size of central directory
208
+ writeUInt32LE(out, cursor + 16, centralDirOffset); // Offset of start of central directory
209
+ writeUInt16LE(out, cursor + 20, 0); // Comment length
210
+
211
+ return out;
212
+ }
213
+
214
+ /**
215
+ * Extracts a PKZip v2.0 archive into a UTF-8 file dictionary (`Record<string, string>`).
216
+ * Validates magic headers, checks boundaries, and sanitizes paths against Zip-Slip.
217
+ */
218
+ export async function extractZip(
219
+ data: Uint8Array | ArrayBuffer
220
+ ): Promise<Record<string, string>> {
221
+ const bytes = toUint8Array(data);
222
+ if (bytes.length < 22) {
223
+ throw new Error('Invalid or truncated ZIP archive: buffer shorter than minimum 22-byte EOCD record');
224
+ }
225
+
226
+ // Locate End of Central Directory (EOCD) signature scanning backwards from end
227
+ let eocdOffset = -1;
228
+ const minSearchOffset = Math.max(0, bytes.length - 65557);
229
+ for (let i = bytes.length - 22; i >= minSearchOffset; i--) {
230
+ if (readUInt32LE(bytes, i) === END_OF_CENTRAL_DIR_SIG) {
231
+ eocdOffset = i;
232
+ break;
233
+ }
234
+ }
235
+
236
+ if (eocdOffset === -1) {
237
+ throw new Error('Invalid ZIP archive: End of Central Directory (PK\\x05\\x06) signature not found');
238
+ }
239
+
240
+ const totalEntries = readUInt16LE(bytes, eocdOffset + 10);
241
+ const centralDirSize = readUInt32LE(bytes, eocdOffset + 12);
242
+ const centralDirOffset = readUInt32LE(bytes, eocdOffset + 16);
243
+
244
+ if (centralDirOffset + centralDirSize > bytes.length) {
245
+ throw new Error('Corrupted ZIP archive: Central Directory extends past end of buffer');
246
+ }
247
+
248
+ const result: Record<string, string> = {};
249
+ let cdCursor = centralDirOffset;
250
+
251
+ for (let i = 0; i < totalEntries; i++) {
252
+ if (cdCursor + 46 > bytes.length) {
253
+ throw new Error('Corrupted ZIP archive: truncated Central Directory header');
254
+ }
255
+
256
+ const sig = readUInt32LE(bytes, cdCursor);
257
+ if (sig !== CENTRAL_DIR_HEADER_SIG) {
258
+ throw new Error(`Corrupted ZIP archive: invalid Central Directory signature 0x${sig.toString(16)}`);
259
+ }
260
+
261
+ const compressionMethod = readUInt16LE(bytes, cdCursor + 10);
262
+ const expectedCrc = readUInt32LE(bytes, cdCursor + 16);
263
+ const compressedSize = readUInt32LE(bytes, cdCursor + 20);
264
+ const fileNameLen = readUInt16LE(bytes, cdCursor + 28);
265
+ const extraLen = readUInt16LE(bytes, cdCursor + 30);
266
+ const commentLen = readUInt16LE(bytes, cdCursor + 32);
267
+ const localHeaderOffset = readUInt32LE(bytes, cdCursor + 42);
268
+
269
+ const nameStart = cdCursor + 46;
270
+ const nameEnd = nameStart + fileNameLen;
271
+ if (nameEnd > bytes.length) {
272
+ throw new Error('Corrupted ZIP archive: file name exceeds buffer');
273
+ }
274
+
275
+ const rawName = textDecoder.decode(bytes.subarray(nameStart, nameEnd));
276
+ cdCursor = nameEnd + extraLen + commentLen;
277
+
278
+ // Skip explicit directory entries
279
+ if (rawName.endsWith('/')) continue;
280
+
281
+ const safeName = sanitizeZipPath(rawName);
282
+ if (!safeName) continue;
283
+
284
+ if (localHeaderOffset + 30 > bytes.length) {
285
+ throw new Error(`Corrupted ZIP archive: local header offset out of bounds for ${safeName}`);
286
+ }
287
+
288
+ const localSig = readUInt32LE(bytes, localHeaderOffset);
289
+ if (localSig !== LOCAL_FILE_HEADER_SIG) {
290
+ throw new Error(`Corrupted ZIP archive: invalid Local File Header signature for ${safeName}`);
291
+ }
292
+
293
+ const localNameLen = readUInt16LE(bytes, localHeaderOffset + 26);
294
+ const localExtraLen = readUInt16LE(bytes, localHeaderOffset + 28);
295
+ const dataStart = localHeaderOffset + 30 + localNameLen + localExtraLen;
296
+ const dataEnd = dataStart + compressedSize;
297
+
298
+ if (dataEnd > bytes.length) {
299
+ throw new Error(`Corrupted ZIP archive: file data truncated for ${safeName}`);
300
+ }
301
+
302
+ const rawFileBytes = bytes.subarray(dataStart, dataEnd);
303
+ if (compressionMethod !== 0) {
304
+ throw new Error(`Unsupported ZIP compression method ${compressionMethod} for ${safeName} (only Store=0 is supported)`);
305
+ }
306
+
307
+ const actualCrc = computeCrc32(rawFileBytes);
308
+ if (actualCrc !== expectedCrc) {
309
+ throw new Error(
310
+ `CRC32 integrity mismatch for ${safeName}: expected 0x${expectedCrc.toString(16)}, got 0x${actualCrc.toString(16)}`
311
+ );
312
+ }
313
+
314
+ result[safeName] = textDecoder.decode(rawFileBytes);
315
+ }
316
+
317
+ return result;
318
+ }
319
+
320
+ export default {
321
+ createZip,
322
+ extractZip,
323
+ computeCrc32,
324
+ sanitizeZipPath,
325
+ toUint8Array
326
+ };