dsh-zipfix 0.0.0-stage → 0.4.0

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.
@@ -0,0 +1,842 @@
1
+ /**
2
+ * ZIP 容器读写(纯 Node 标准库,无第三方依赖)。
3
+ *
4
+ * 与常见库不同,本实现**保留中央目录里的文件名字节**(`entry.nameBytes`),
5
+ * 不先行解码——这正是编码嗅探与无损还原的前提(见 ALG-1)。
6
+ *
7
+ * 支持:
8
+ * - 读取 ZIP64(EOCD64 / ZIP64 扩展字段),条目数或体积超 4GB 不溢出;
9
+ * - 提取时流式解压,逐条校验 uncompressedSize 与 CRC32;
10
+ * - 重建「修复版 ZIP」时显式置位 UTF-8 文件名标志 0x0800,并在取值后回填
11
+ * 本地文件头(不使用数据描述符),使 Windows 资源管理器 / 7-Zip 直接识别;
12
+ * - 写入时以 `wx` 打开目标文件,绝不覆盖已有文件。
13
+ *
14
+ * 安全:所有输出路径由调用方保证唯一;本模块不删除任何源文件。
15
+ */
16
+
17
+ import fs from 'node:fs';
18
+ import fsp from 'node:fs/promises';
19
+ import path from 'node:path';
20
+ import zlib from 'node:zlib';
21
+ import crypto from 'node:crypto';
22
+ import { Transform, Writable } from 'node:stream';
23
+ import { pipeline } from 'node:stream/promises';
24
+
25
+ /** ZIP 通用位标记:文件名是 UTF-8(bit 11)。 */
26
+ export const ZIP_UTF8_FLAG = 0x0800;
27
+ /** ZIP 通用位标记:数据描述符(bit 3)。 */
28
+ export const ZIP_DATA_DESCRIPTOR_FLAG = 0x0008;
29
+ /** ZIP 通用位标记:加密(bit 0)。 */
30
+ export const ZIP_ENCRYPTED_FLAG = 0x0001;
31
+ /** 压缩方式:存储。 */
32
+ export const METHOD_STORE = 0;
33
+ /** 压缩方式:deflate。 */
34
+ export const METHOD_DEFLATE = 8;
35
+
36
+ const SIG_LOCAL = 0x04034b50;
37
+ const SIG_CENTRAL = 0x02014b50;
38
+ const SIG_EOCD = 0x06054b50;
39
+ const SIG_EOCD64 = 0x06064b50;
40
+ const SIG_EOCD64_LOCATOR = 0x07064b50;
41
+ const ZIP64_EXTRA_ID = 0x0001;
42
+ const U32_MAX = 0xffffffff;
43
+
44
+ /** 计算(或增量续算)CRC32。 */
45
+ export function crc32(buf, previous = 0) {
46
+ return zlib.crc32(buf, previous) >>> 0;
47
+ }
48
+
49
+ /** CRC32 的 8 位大写十六进制形式。 */
50
+ export function formatCrc(value) {
51
+ return (value >>> 0).toString(16).toUpperCase().padStart(8, '0');
52
+ }
53
+
54
+ /* ------------------------------------------------------------------ *
55
+ * 解析
56
+ * ------------------------------------------------------------------ */
57
+
58
+ function readAt(fd, position, length) {
59
+ if (length === 0) return Buffer.alloc(0);
60
+ const buf = Buffer.allocUnsafe(length);
61
+ let read = 0;
62
+ while (read < length) {
63
+ const n = fs.readSync(fd, buf, read, length - read, position + read);
64
+ if (n <= 0) throw new Error(`读取 ZIP 失败:偏移 ${position + read} 处提前结束`);
65
+ read += n;
66
+ }
67
+ return buf;
68
+ }
69
+
70
+ function u16(buf, offset) {
71
+ return buf.readUInt16LE(offset);
72
+ }
73
+
74
+ function u32(buf, offset) {
75
+ return buf.readUInt32LE(offset);
76
+ }
77
+
78
+ function u64(buf, offset) {
79
+ return Number(buf.readBigUInt64LE(offset));
80
+ }
81
+
82
+ /** 遍历扩展字段,返回 id → 数据 的映射(同 id 取第一个)。 */
83
+ function parseExtraFields(extra) {
84
+ const fields = new Map();
85
+ let pos = 0;
86
+ while (pos + 4 <= extra.length) {
87
+ const id = u16(extra, pos);
88
+ const size = u16(extra, pos + 2);
89
+ if (pos + 4 + size > extra.length) break;
90
+ if (!fields.has(id)) fields.set(id, extra.subarray(pos + 4, pos + 4 + size));
91
+ pos += 4 + size;
92
+ }
93
+ return fields;
94
+ }
95
+
96
+ /**
97
+ * 解析一个 ZIP 文件,返回中央目录条目(保留原始文件名字节)。
98
+ * @param {string} zipPath ZIP 文件绝对路径
99
+ * @returns {ZipCatalog}
100
+ */
101
+ export class ZipCatalog {
102
+ /** @type {number} */
103
+ #fd;
104
+ /** @type {string} */
105
+ path;
106
+ /** @type {number} */
107
+ size;
108
+ /** @type {Array<object>} */
109
+ entries = [];
110
+ /** @type {string} */
111
+ comment = '';
112
+ /** @type {boolean} */
113
+ zip64 = false;
114
+ /** @type {string[]} */
115
+ warnings = [];
116
+ #closed = false;
117
+
118
+ /**
119
+ * @param {string} zipPath 绝对路径
120
+ */
121
+ constructor(zipPath) {
122
+ this.path = zipPath;
123
+ this.#fd = fs.openSync(zipPath, 'r');
124
+ try {
125
+ const stat = fs.fstatSync(this.#fd);
126
+ if (!stat.isFile()) throw new Error(`不是普通文件:${zipPath}`);
127
+ this.size = stat.size;
128
+ this.#parse();
129
+ } catch (error) {
130
+ try {
131
+ fs.closeSync(this.#fd);
132
+ } catch {
133
+ /* ignore */
134
+ }
135
+ this.#closed = true;
136
+ throw error;
137
+ }
138
+ }
139
+
140
+ get fd() {
141
+ if (this.#closed) throw new Error('ZIP 句柄已关闭');
142
+ return this.#fd;
143
+ }
144
+
145
+ #parse() {
146
+ const size = this.size;
147
+ if (size < 22) throw new Error('不是 ZIP 文件:文件长度不足 22 字节');
148
+ const tailLength = Math.min(size, 66_000 + 22);
149
+ const tailStart = size - tailLength;
150
+ const tail = readAt(this.#fd, tailStart, tailLength);
151
+
152
+ let eocdInTail = -1;
153
+ let fallback = -1;
154
+ for (let i = tail.length - 22; i >= 0; i--) {
155
+ if (tail.readUInt32LE(i) !== SIG_EOCD) continue;
156
+ const commentLength = tail.readUInt16LE(i + 20);
157
+ if (i + 22 + commentLength === tail.length) {
158
+ eocdInTail = i;
159
+ break;
160
+ }
161
+ if (fallback < 0 && i + 22 + commentLength <= tail.length) fallback = i;
162
+ }
163
+ if (eocdInTail < 0) eocdInTail = fallback;
164
+ if (eocdInTail < 0) throw new Error('不是 ZIP 文件:找不到中央目录结尾记录(EOCD)');
165
+
166
+ let entriesTotal = u16(tail, eocdInTail + 10);
167
+ let cdSize = u32(tail, eocdInTail + 12);
168
+ let cdOffset = u32(tail, eocdInTail + 16);
169
+ this.comment = tail.subarray(eocdInTail + 22, eocdInTail + 22 + u16(tail, eocdInTail + 20)).toString('utf8');
170
+
171
+ const needsZip64 =
172
+ entriesTotal === 0xffff || cdSize === U32_MAX || cdOffset === U32_MAX;
173
+ if (needsZip64) {
174
+ const locatorPos = eocdInTail - 20;
175
+ let zip64Offset = -1;
176
+ if (locatorPos >= 0 && u32(tail, locatorPos) === SIG_EOCD64_LOCATOR) {
177
+ zip64Offset = u64(tail, locatorPos + 8);
178
+ }
179
+ if (zip64Offset < 0 || zip64Offset + 56 > size) {
180
+ throw new Error('ZIP64 结构中缺少定位记录,无法解析中央目录');
181
+ }
182
+ const rec = readAt(this.#fd, zip64Offset, 56);
183
+ if (u32(rec, 0) !== SIG_EOCD64) throw new Error('ZIP64 结尾记录签名错误');
184
+ entriesTotal = u64(rec, 32);
185
+ cdSize = u64(rec, 40);
186
+ cdOffset = u64(rec, 48);
187
+ this.zip64 = true;
188
+ }
189
+
190
+ if (cdOffset + cdSize > size) {
191
+ throw new Error(`ZIP 中央目录越界(offset=${cdOffset}, size=${cdSize}, file=${size})`);
192
+ }
193
+
194
+ const cd = readAt(this.#fd, cdOffset, cdSize);
195
+ let pos = 0;
196
+ let index = 0;
197
+ while (pos + 46 <= cd.length) {
198
+ if (u32(cd, pos) !== SIG_CENTRAL) break;
199
+ const flags = u16(cd, pos + 8);
200
+ const method = u16(cd, pos + 10);
201
+ const modTime = u16(cd, pos + 12);
202
+ const modDate = u16(cd, pos + 14);
203
+ const crc = u32(cd, pos + 16);
204
+ let compressedSize = u32(cd, pos + 20);
205
+ let uncompressedSize = u32(cd, pos + 24);
206
+ const nameLength = u16(cd, pos + 28);
207
+ const extraLength = u16(cd, pos + 30);
208
+ const commentLength = u16(cd, pos + 32);
209
+ const diskStart = u16(cd, pos + 34);
210
+ const internalAttr = u16(cd, pos + 36);
211
+ const externalAttr = u32(cd, pos + 38);
212
+ let localHeaderOffset = u32(cd, pos + 42);
213
+ const nameStart = pos + 46;
214
+ const extraStart = nameStart + nameLength;
215
+ const extraEnd = extraStart + extraLength;
216
+ if (extraEnd > cd.length) throw new Error('ZIP 中央目录条目越界');
217
+ const nameBytes = Buffer.from(cd.subarray(nameStart, extraStart));
218
+ const extra = cd.subarray(extraStart, extraEnd);
219
+
220
+ if (
221
+ uncompressedSize === U32_MAX ||
222
+ compressedSize === U32_MAX ||
223
+ localHeaderOffset === U32_MAX ||
224
+ diskStart === 0xffff
225
+ ) {
226
+ const z = parseExtraFields(extra).get(ZIP64_EXTRA_ID);
227
+ if (z) {
228
+ let q = 0;
229
+ if (uncompressedSize === U32_MAX && q + 8 <= z.length) {
230
+ uncompressedSize = u64(z, q);
231
+ q += 8;
232
+ }
233
+ if (compressedSize === U32_MAX && q + 8 <= z.length) {
234
+ compressedSize = u64(z, q);
235
+ q += 8;
236
+ }
237
+ if (localHeaderOffset === U32_MAX && q + 8 <= z.length) {
238
+ localHeaderOffset = u64(z, q);
239
+ q += 8;
240
+ }
241
+ }
242
+ }
243
+
244
+ if (diskStart !== 0) this.warnings.push(`条目 ${index} 位于分卷磁盘 ${diskStart},不支持分卷 ZIP`);
245
+
246
+ const isDirectory =
247
+ (nameLength > 0 && nameBytes[nameBytes.length - 1] === 0x2f) ||
248
+ ((externalAttr >>> 16) & 0x10) !== 0;
249
+
250
+ this.entries.push({
251
+ index,
252
+ nameBytes,
253
+ flags,
254
+ method,
255
+ modTime,
256
+ modDate,
257
+ crc,
258
+ compressedSize,
259
+ uncompressedSize,
260
+ diskStart,
261
+ internalAttr,
262
+ externalAttr,
263
+ localHeaderOffset,
264
+ versionMadeBy: u16(cd, pos + 4),
265
+ versionNeeded: u16(cd, pos + 6),
266
+ isDirectory,
267
+ encrypted: (flags & ZIP_ENCRYPTED_FLAG) !== 0,
268
+ utf8Flag: (flags & ZIP_UTF8_FLAG) !== 0,
269
+ dataDescriptor: (flags & ZIP_DATA_DESCRIPTOR_FLAG) !== 0,
270
+ });
271
+ pos = extraEnd + commentLength;
272
+ index++;
273
+ }
274
+
275
+ if (entriesTotal !== 0 && this.entries.length !== entriesTotal) {
276
+ this.warnings.push(
277
+ `中央目录声明 ${entriesTotal} 个条目,实际解析 ${this.entries.length} 个(ZIP 可能损坏)`,
278
+ );
279
+ }
280
+ // 加密与不支持的压缩方式不在这里抛错:扫描仍应能列出条目,具体操作时再报错。
281
+ for (const entry of this.entries) {
282
+ entry.supported = !entry.encrypted && (entry.method === METHOD_STORE || entry.method === METHOD_DEFLATE);
283
+ }
284
+ if (this.entries.some((e) => e.encrypted)) this.warnings.push('ZIP 含加密条目,相关条目无法解压');
285
+ if (this.entries.some((e) => !e.supported && !e.encrypted)) {
286
+ this.warnings.push('ZIP 含不支持的压缩方式条目,相关条目无法解压');
287
+ }
288
+ }
289
+
290
+ /** 关闭底层文件句柄(可重复调用)。 */
291
+ close() {
292
+ if (this.#closed) return;
293
+ this.#closed = true;
294
+ try {
295
+ fs.closeSync(this.#fd);
296
+ } catch {
297
+ /* ignore */
298
+ }
299
+ }
300
+
301
+ /** 计算条目数据区在文件中的起始偏移。 */
302
+ entryDataOffset(entry) {
303
+ const header = readAt(this.fd, entry.localHeaderOffset, 30);
304
+ if (u32(header, 0) !== SIG_LOCAL) {
305
+ throw new Error(`条目「${entry.index}」本地文件头签名错误,ZIP 可能损坏`);
306
+ }
307
+ const nameLength = u16(header, 26);
308
+ const extraLength = u16(header, 28);
309
+ return entry.localHeaderOffset + 30 + nameLength + extraLength;
310
+ }
311
+
312
+ /**
313
+ * 读取一个条目的完整内容(仅用于小文件,如 OOXML 元数据)。
314
+ * @param {object} entry 条目
315
+ * @param {{maxBytes?: number}} [options] 上限,默认 32 MiB
316
+ * @returns {Buffer} 解压后的内容
317
+ */
318
+ readEntryBuffer(entry, { maxBytes = 32 * 1024 * 1024 } = {}) {
319
+ if (entry.uncompressedSize > maxBytes) {
320
+ throw new Error(`条目解压后 ${entry.uncompressedSize} 字节,超过读取上限 ${maxBytes}`);
321
+ }
322
+ const dataOffset = this.entryDataOffset(entry);
323
+ const compressed = readAt(this.fd, dataOffset, entry.compressedSize);
324
+ let data;
325
+ if (entry.method === METHOD_STORE) data = compressed;
326
+ else data = zlib.inflateRawSync(compressed, { maxOutputLength: maxBytes });
327
+ if (data.length !== entry.uncompressedSize) {
328
+ throw new Error(`条目数据长度不符:期望 ${entry.uncompressedSize},实际 ${data.length}`);
329
+ }
330
+ if (crc32(data) !== entry.crc) throw new Error('条目 CRC32 校验失败');
331
+ return data;
332
+ }
333
+
334
+ /** 为条目创建只读压缩数据流(调用方负责 pipeline 消费)。 */
335
+ createEntryStream(entry) {
336
+ if (entry.compressedSize === 0) return null;
337
+ const dataOffset = this.entryDataOffset(entry);
338
+ return fs.createReadStream(null, {
339
+ fd: this.fd,
340
+ start: dataOffset,
341
+ end: dataOffset + entry.compressedSize - 1,
342
+ autoClose: false,
343
+ });
344
+ }
345
+ }
346
+
347
+ /**
348
+ * 打开 ZIP 目录(解析中央目录,不读取条目内容)。
349
+ * @param {string} zipPath ZIP 绝对路径
350
+ * @returns {ZipCatalog}
351
+ */
352
+ export function openZipCatalog(zipPath) {
353
+ return new ZipCatalog(zipPath);
354
+ }
355
+
356
+ /* ------------------------------------------------------------------ *
357
+ * 流式校验与提取
358
+ * ------------------------------------------------------------------ */
359
+
360
+ class IntegrityTransform extends Transform {
361
+ constructor(entry) {
362
+ super();
363
+ this.entry = entry;
364
+ this.size = 0;
365
+ this.crc = 0;
366
+ this.hash = crypto.createHash('sha256');
367
+ }
368
+
369
+ _transform(chunk, _enc, callback) {
370
+ this.size += chunk.length;
371
+ this.crc = crc32(chunk, this.crc);
372
+ this.hash.update(chunk);
373
+ callback(null, chunk);
374
+ }
375
+
376
+ finish() {
377
+ if (this.size !== this.entry.uncompressedSize) {
378
+ throw new Error(
379
+ `条目大小校验失败:中央目录 ${this.entry.uncompressedSize} 字节,实际 ${this.size} 字节`,
380
+ );
381
+ }
382
+ if (this.crc !== this.entry.crc) {
383
+ throw new Error(
384
+ `条目 CRC32 校验失败:中央目录 ${formatCrc(this.entry.crc)},实际 ${formatCrc(this.crc)}`,
385
+ );
386
+ }
387
+ return { size: this.size, crc: this.crc, sha256: this.hash.digest('hex') };
388
+ }
389
+ }
390
+
391
+ /** 丢弃数据但保持流式消费的 Writable。 */
392
+ class NullSink extends Writable {
393
+ _write(_chunk, _enc, callback) {
394
+ callback();
395
+ }
396
+ }
397
+
398
+ /** 直接写入 fd 并统计字节数的 Writable。 */
399
+ class FdSink extends Writable {
400
+ constructor(fd) {
401
+ super();
402
+ this.fd = fd;
403
+ this.count = 0;
404
+ }
405
+
406
+ _write(chunk, _enc, callback) {
407
+ try {
408
+ fs.writeSync(this.fd, chunk);
409
+ this.count += chunk.length;
410
+ callback();
411
+ } catch (error) {
412
+ callback(error);
413
+ }
414
+ }
415
+ }
416
+
417
+ /**
418
+ * 提取单个条目到文件,并校验大小与 CRC32。
419
+ * 目标文件以独占方式创建(`wx`),绝不覆盖。
420
+ * @param {ZipCatalog} catalog 目录
421
+ * @param {object} entry 条目
422
+ * @param {string} outPath 目标文件路径(必须不存在)
423
+ * @param {{signal?: AbortSignal}} [options]
424
+ * @returns {Promise<{size: number, crc: number, sha256: string}>}
425
+ */
426
+ export async function extractEntry(catalog, entry, outPath, { signal } = {}) {
427
+ await fsp.mkdir(path.dirname(outPath), { recursive: true });
428
+ if (entry.compressedSize === 0) {
429
+ await fsp.writeFile(outPath, Buffer.alloc(0), { flag: 'wx' });
430
+ if (entry.uncompressedSize !== 0 || entry.crc !== 0) throw new Error('空条目的大小/CRC 与中央目录不符');
431
+ return { size: 0, crc: 0, sha256: crypto.createHash('sha256').digest('hex') };
432
+ }
433
+ const source = catalog.createEntryStream(entry);
434
+ const integrity = new IntegrityTransform(entry);
435
+ const stages = [source];
436
+ if (entry.method === METHOD_DEFLATE) stages.push(zlib.createInflateRaw());
437
+ stages.push(integrity, fs.createWriteStream(outPath, { flags: 'wx' }));
438
+ try {
439
+ await pipeline(stages, signal === undefined ? {} : { signal });
440
+ } catch (error) {
441
+ await fsp.rm(outPath, { force: true }).catch(() => {});
442
+ throw error;
443
+ }
444
+ try {
445
+ return integrity.finish();
446
+ } catch (error) {
447
+ await fsp.rm(outPath, { force: true }).catch(() => {});
448
+ throw error;
449
+ }
450
+ }
451
+
452
+ /**
453
+ * 流式读取并校验单个条目(不落盘)。
454
+ * @param {ZipCatalog} catalog 目录
455
+ * @param {object} entry 条目
456
+ * @param {{signal?: AbortSignal}} [options]
457
+ * @returns {Promise<{size: number, crc: number, sha256: string}>}
458
+ */
459
+ export async function verifyEntry(catalog, entry, { signal } = {}) {
460
+ if (entry.compressedSize === 0) {
461
+ if (entry.uncompressedSize !== 0 || entry.crc !== 0) throw new Error('空条目的大小/CRC 与中央目录不符');
462
+ return { size: 0, crc: 0, sha256: crypto.createHash('sha256').digest('hex') };
463
+ }
464
+ const source = catalog.createEntryStream(entry);
465
+ const integrity = new IntegrityTransform(entry);
466
+ const stages = [source];
467
+ if (entry.method === METHOD_DEFLATE) stages.push(zlib.createInflateRaw());
468
+ stages.push(integrity, new NullSink());
469
+ await pipeline(stages, signal === undefined ? {} : { signal });
470
+ return integrity.finish();
471
+ }
472
+
473
+ /* ------------------------------------------------------------------ *
474
+ * 写出「修复版 ZIP」
475
+ * ------------------------------------------------------------------ */
476
+
477
+ function buildLocalHeader({
478
+ versionNeeded,
479
+ flags,
480
+ method,
481
+ modTime,
482
+ modDate,
483
+ nameBytes,
484
+ extra,
485
+ }) {
486
+ const header = Buffer.alloc(30 + nameBytes.length + extra.length);
487
+ header.writeUInt32LE(SIG_LOCAL, 0);
488
+ header.writeUInt16LE(versionNeeded, 4);
489
+ header.writeUInt16LE(flags, 6);
490
+ header.writeUInt16LE(method, 8);
491
+ header.writeUInt16LE(modTime, 10);
492
+ header.writeUInt16LE(modDate, 12);
493
+ header.writeUInt32LE(0, 14); // crc32,稍后回填
494
+ header.writeUInt32LE(0, 18); // compressed size,稍后回填
495
+ header.writeUInt32LE(0, 22); // uncompressed size,稍后回填
496
+ header.writeUInt16LE(nameBytes.length, 26);
497
+ header.writeUInt16LE(extra.length, 28);
498
+ nameBytes.copy(header, 30);
499
+ extra.copy(header, 30 + nameBytes.length);
500
+ return header;
501
+ }
502
+
503
+ function buildZip64LocalExtra(uncompressedSize, compressedSize) {
504
+ const extra = Buffer.alloc(4 + 16);
505
+ extra.writeUInt16LE(ZIP64_EXTRA_ID, 0);
506
+ extra.writeUInt16LE(16, 2);
507
+ extra.writeBigUInt64LE(BigInt(uncompressedSize), 4);
508
+ extra.writeBigUInt64LE(BigInt(compressedSize), 12);
509
+ return extra;
510
+ }
511
+
512
+ function buildCentralHeader(record) {
513
+ const { nameBytes, extra } = record;
514
+ const header = Buffer.alloc(46 + nameBytes.length + extra.length);
515
+ header.writeUInt32LE(SIG_CENTRAL, 0);
516
+ header.writeUInt16LE(record.versionMadeBy, 4);
517
+ header.writeUInt16LE(record.versionNeeded, 6);
518
+ header.writeUInt16LE(ZIP_UTF8_FLAG, 8);
519
+ header.writeUInt16LE(record.method, 10);
520
+ header.writeUInt16LE(record.modTime, 12);
521
+ header.writeUInt16LE(record.modDate, 14);
522
+ header.writeUInt32LE(record.crc >>> 0, 16);
523
+ // ZIP64 记录必须与本地文件头保持一致:本地头写了 0xFFFFFFFF 占位,
524
+ // 中央目录同样占位并在扩展字段里给出 8 字节真值。
525
+ header.writeUInt32LE(record.zip64 ? U32_MAX : record.compressedSize, 20);
526
+ header.writeUInt32LE(record.zip64 ? U32_MAX : record.uncompressedSize, 24);
527
+ header.writeUInt16LE(nameBytes.length, 28);
528
+ header.writeUInt16LE(extra.length, 30);
529
+ header.writeUInt16LE(record.commentLength ?? 0, 32);
530
+ header.writeUInt16LE(0, 34); // disk start
531
+ header.writeUInt16LE(record.internalAttr, 36);
532
+ header.writeUInt32LE(record.externalAttr >>> 0, 38);
533
+ header.writeUInt32LE(record.zip64 && record.localHeaderOffset > U32_MAX - 1 ? U32_MAX : record.localHeaderOffset, 42);
534
+ nameBytes.copy(header, 46);
535
+ extra.copy(header, 46 + nameBytes.length);
536
+ return header;
537
+ }
538
+
539
+ function buildZip64CentralExtra(record) {
540
+ const parts = [];
541
+ const usize = Buffer.alloc(8);
542
+ usize.writeBigUInt64LE(BigInt(record.uncompressedSize));
543
+ parts.push(usize);
544
+ const csize = Buffer.alloc(8);
545
+ csize.writeBigUInt64LE(BigInt(record.compressedSize));
546
+ parts.push(csize);
547
+ if (record.localHeaderOffset > U32_MAX - 1) {
548
+ const offsetPart = Buffer.alloc(8);
549
+ offsetPart.writeBigUInt64LE(BigInt(record.localHeaderOffset));
550
+ parts.push(offsetPart);
551
+ }
552
+ const payload = Buffer.concat(parts);
553
+ const extra = Buffer.alloc(4 + payload.length);
554
+ extra.writeUInt16LE(ZIP64_EXTRA_ID, 0);
555
+ extra.writeUInt16LE(payload.length, 2);
556
+ payload.copy(extra, 4);
557
+ return extra;
558
+ }
559
+
560
+ /**
561
+ * 写出「修复版 ZIP」:所有条目置位 UTF-8 文件名标志 0x0800,
562
+ * 文件名按 UTF-8 编码,逐条重新压缩并校验源数据 CRC32。
563
+ *
564
+ * @param {object} options
565
+ * @param {ZipCatalog} options.sourceCatalog 源 ZIP
566
+ * @param {string} options.destPath 目标 ZIP(必须不存在)
567
+ * @param {Array<{entry: object, name: string}>} options.plans 条目 → 修正后名字
568
+ * @param {AbortSignal} [options.signal]
569
+ * @param {boolean} [options.forceZip64] 测试用:强制 ZIP64 结构
570
+ * @param {(done: number, total: number) => void} [options.onProgress]
571
+ * @returns {Promise<{entries: number, compressedBytes: number, zip64: boolean}>}
572
+ */
573
+ export async function writeFixedZip({
574
+ sourceCatalog,
575
+ destPath,
576
+ plans,
577
+ signal,
578
+ forceZip64 = false,
579
+ onProgress,
580
+ }) {
581
+ const fd = fs.openSync(destPath, 'wx');
582
+ let offset = 0;
583
+ const records = [];
584
+ const write = (buffer) => {
585
+ fs.writeSync(fd, buffer);
586
+ offset += buffer.length;
587
+ };
588
+ try {
589
+ for (const [index, plan] of plans.entries()) {
590
+ if (signal?.aborted) throw new DOMException('操作已取消', 'AbortError');
591
+ const entry = plan.entry;
592
+ const name = plan.name;
593
+ if (!entry.isDirectory && !entry.supported) {
594
+ throw new Error(
595
+ `条目 #${entry.index} ${entry.encrypted ? '已加密' : `压缩方式 ${entry.method} 不受支持`},无法重建修复版 ZIP`,
596
+ );
597
+ }
598
+ const nameBytes = Buffer.from(name, 'utf8');
599
+ const isDirectory = name.endsWith('/');
600
+ const zip64 = forceZip64 || entry.uncompressedSize > 0xf0000000;
601
+ const versionNeeded = zip64 ? 45 : 20;
602
+
603
+ if (isDirectory) {
604
+ const extra = zip64 ? buildZip64LocalExtra(0, 0) : Buffer.alloc(0);
605
+ const localOffset = offset;
606
+ write(
607
+ buildLocalHeader({
608
+ versionNeeded,
609
+ flags: ZIP_UTF8_FLAG,
610
+ method: METHOD_STORE,
611
+ modTime: entry.modTime,
612
+ modDate: entry.modDate,
613
+ nameBytes,
614
+ extra,
615
+ }),
616
+ );
617
+ records.push({
618
+ nameBytes,
619
+ versionMadeBy: entry.versionMadeBy,
620
+ versionNeeded,
621
+ method: METHOD_STORE,
622
+ modTime: entry.modTime,
623
+ modDate: entry.modDate,
624
+ crc: 0,
625
+ compressedSize: 0,
626
+ uncompressedSize: 0,
627
+ localHeaderOffset: localOffset,
628
+ internalAttr: entry.internalAttr,
629
+ externalAttr: entry.externalAttr,
630
+ zip64,
631
+ });
632
+ if (zip64) {
633
+ // ZIP64 目录条目的本地文件头同样用 0xFFFFFFFF 占位,真值在扩展字段里
634
+ const sizes = Buffer.alloc(8);
635
+ sizes.writeUInt32LE(U32_MAX, 0);
636
+ sizes.writeUInt32LE(U32_MAX, 4);
637
+ fs.writeSync(fd, sizes, 0, 8, localOffset + 18);
638
+ }
639
+ } else {
640
+ const extra = zip64 ? buildZip64LocalExtra(0, 0) : Buffer.alloc(0);
641
+ const localOffset = offset;
642
+ write(
643
+ buildLocalHeader({
644
+ versionNeeded,
645
+ flags: ZIP_UTF8_FLAG,
646
+ method: entry.method,
647
+ modTime: entry.modTime,
648
+ modDate: entry.modDate,
649
+ nameBytes,
650
+ extra,
651
+ }),
652
+ );
653
+
654
+ const integrity = new IntegrityTransform(entry);
655
+ const sink = new FdSink(fd);
656
+ const stages = [];
657
+ const source = sourceCatalog.createEntryStream(entry);
658
+ if (source) stages.push(source);
659
+ if (entry.method === METHOD_DEFLATE) stages.push(zlib.createInflateRaw());
660
+ if (stages.length > 0) {
661
+ stages.push(integrity);
662
+ if (entry.method === METHOD_DEFLATE) stages.push(zlib.createDeflateRaw({ level: 6 }));
663
+ stages.push(sink);
664
+ await pipeline(stages, signal === undefined ? {} : { signal });
665
+ }
666
+ const { size, crc } = integrity.finish();
667
+ const compressedSize = sink.count;
668
+ offset += compressedSize;
669
+
670
+ // 回填本地文件头(不使用数据描述符,flag 保持 0x0800)
671
+ if (!zip64 && (size > U32_MAX - 1 || compressedSize > U32_MAX - 1)) {
672
+ throw new Error('条目超过 4GB 但未启用 ZIP64,请重试');
673
+ }
674
+ const header = Buffer.alloc(16);
675
+ header.writeUInt32LE(crc, 0);
676
+ header.writeUInt32LE(zip64 ? U32_MAX : compressedSize, 4);
677
+ header.writeUInt32LE(zip64 ? U32_MAX : size, 8);
678
+ header.writeUInt16LE(ZIP_UTF8_FLAG, 12);
679
+ header.writeUInt16LE(versionNeeded, 14);
680
+ // flags 位于 +6,crc 位于 +14,尺寸位于 +18/+22
681
+ fs.writeSync(fd, header.subarray(0, 4), 0, 4, localOffset + 14);
682
+ fs.writeSync(fd, header.subarray(4, 8), 0, 4, localOffset + 18);
683
+ fs.writeSync(fd, header.subarray(8, 12), 0, 4, localOffset + 22);
684
+ fs.writeSync(fd, header.subarray(12, 14), 0, 2, localOffset + 6);
685
+ fs.writeSync(fd, header.subarray(14, 16), 0, 2, localOffset + 4);
686
+ if (zip64) {
687
+ const extraStart = localOffset + 30 + nameBytes.length;
688
+ const usizeBuf = Buffer.alloc(8);
689
+ usizeBuf.writeBigUInt64LE(BigInt(size));
690
+ const csizeBuf = Buffer.alloc(8);
691
+ csizeBuf.writeBigUInt64LE(BigInt(compressedSize));
692
+ fs.writeSync(fd, usizeBuf, 0, 8, extraStart + 4);
693
+ fs.writeSync(fd, csizeBuf, 0, 8, extraStart + 12);
694
+ }
695
+ records.push({
696
+ nameBytes,
697
+ versionMadeBy: entry.versionMadeBy,
698
+ versionNeeded,
699
+ method: entry.method,
700
+ modTime: entry.modTime,
701
+ modDate: entry.modDate,
702
+ crc,
703
+ compressedSize,
704
+ uncompressedSize: size,
705
+ localHeaderOffset: localOffset,
706
+ internalAttr: entry.internalAttr,
707
+ externalAttr: entry.externalAttr,
708
+ zip64,
709
+ });
710
+ }
711
+ if (onProgress) onProgress(index + 1, plans.length);
712
+ }
713
+
714
+ const cdOffset = offset;
715
+ for (const record of records) {
716
+ if (record.zip64) record.extra = buildZip64CentralExtra(record);
717
+ else record.extra = Buffer.alloc(0);
718
+ write(buildCentralHeader(record));
719
+ }
720
+ const cdSize = offset - cdOffset;
721
+
722
+ const needsZip64 =
723
+ forceZip64 ||
724
+ records.length > 0xfffe ||
725
+ cdOffset > U32_MAX - 1 ||
726
+ cdSize > U32_MAX - 1 ||
727
+ records.some(
728
+ (r) =>
729
+ r.uncompressedSize > U32_MAX - 1 ||
730
+ r.compressedSize > U32_MAX - 1 ||
731
+ r.localHeaderOffset > U32_MAX - 1,
732
+ );
733
+
734
+ if (needsZip64) {
735
+ const zip64EocdOffset = offset;
736
+ const eocd64 = Buffer.alloc(56);
737
+ eocd64.writeUInt32LE(SIG_EOCD64, 0);
738
+ eocd64.writeBigUInt64LE(44n, 4);
739
+ eocd64.writeUInt16LE(45, 12);
740
+ eocd64.writeUInt16LE(45, 14);
741
+ eocd64.writeUInt32LE(0, 16);
742
+ eocd64.writeUInt32LE(0, 20);
743
+ eocd64.writeBigUInt64LE(BigInt(records.length), 24);
744
+ eocd64.writeBigUInt64LE(BigInt(records.length), 32);
745
+ eocd64.writeBigUInt64LE(BigInt(cdSize), 40);
746
+ eocd64.writeBigUInt64LE(BigInt(cdOffset), 48);
747
+ write(eocd64);
748
+ const locator = Buffer.alloc(20);
749
+ locator.writeUInt32LE(SIG_EOCD64_LOCATOR, 0);
750
+ locator.writeUInt32LE(0, 4);
751
+ locator.writeBigUInt64LE(BigInt(zip64EocdOffset), 8);
752
+ locator.writeUInt32LE(1, 16);
753
+ write(locator);
754
+ const eocd = Buffer.alloc(22);
755
+ eocd.writeUInt32LE(SIG_EOCD, 0);
756
+ eocd.writeUInt16LE(0, 4);
757
+ eocd.writeUInt16LE(0, 6);
758
+ eocd.writeUInt16LE(0xffff, 8);
759
+ eocd.writeUInt16LE(0xffff, 10);
760
+ eocd.writeUInt32LE(U32_MAX, 12);
761
+ eocd.writeUInt32LE(U32_MAX, 16);
762
+ eocd.writeUInt16LE(0, 20);
763
+ write(eocd);
764
+ } else {
765
+ const eocd = Buffer.alloc(22);
766
+ eocd.writeUInt32LE(SIG_EOCD, 0);
767
+ eocd.writeUInt16LE(0, 4);
768
+ eocd.writeUInt16LE(0, 6);
769
+ eocd.writeUInt16LE(records.length, 8);
770
+ eocd.writeUInt16LE(records.length, 10);
771
+ eocd.writeUInt32LE(cdSize, 12);
772
+ eocd.writeUInt32LE(cdOffset, 16);
773
+ eocd.writeUInt16LE(0, 20);
774
+ write(eocd);
775
+ }
776
+
777
+ return { entries: records.length, compressedBytes: offset, zip64: needsZip64 };
778
+ } catch (error) {
779
+ fs.closeSync(fd);
780
+ await fsp.rm(destPath, { force: true }).catch(() => {});
781
+ throw error;
782
+ } finally {
783
+ try {
784
+ fs.closeSync(fd);
785
+ } catch {
786
+ /* already closed */
787
+ }
788
+ }
789
+ }
790
+
791
+ /* ------------------------------------------------------------------ *
792
+ * 回读自检
793
+ * ------------------------------------------------------------------ */
794
+
795
+ /**
796
+ * 回读校验修复版 ZIP。
797
+ * @param {string} zipPath ZIP 路径
798
+ * @param {{full?: boolean, signal?: AbortSignal}} [options] full=true 时逐条解压校验 CRC
799
+ * @returns {Promise<{entries: number, allUtf8Flag: boolean, zip64: boolean, fullChecked: boolean, warnings: string[]}>}
800
+ */
801
+ export async function verifyFixedZip(zipPath, { full = true, signal } = {}) {
802
+ const catalog = openZipCatalog(zipPath);
803
+ try {
804
+ const allUtf8Flag = catalog.entries.every((entry) => (entry.flags & ZIP_UTF8_FLAG) !== 0);
805
+ if (full) {
806
+ for (const entry of catalog.entries) {
807
+ if (signal?.aborted) throw new DOMException('操作已取消', 'AbortError');
808
+ if (entry.isDirectory) continue;
809
+ await verifyEntry(catalog, entry, { signal });
810
+ }
811
+ }
812
+ return {
813
+ entries: catalog.entries.length,
814
+ allUtf8Flag,
815
+ zip64: catalog.zip64,
816
+ fullChecked: full,
817
+ warnings: [...catalog.warnings],
818
+ };
819
+ } finally {
820
+ catalog.close();
821
+ }
822
+ }
823
+
824
+ /** 计算磁盘文件的 CRC32 与大小(流式)。 */
825
+ export async function fileCrc32(filePath, { signal } = {}) {
826
+ const stat = await fsp.stat(filePath);
827
+ if (!stat.isFile()) throw new Error(`不是普通文件:${filePath}`);
828
+ const hash = crypto.createHash('sha256');
829
+ let crc = 0;
830
+ let size = 0;
831
+ const stream = fs.createReadStream(filePath);
832
+ const collector = new Transform({
833
+ transform(chunk, _enc, callback) {
834
+ size += chunk.length;
835
+ crc = crc32(chunk, crc);
836
+ hash.update(chunk);
837
+ callback();
838
+ },
839
+ });
840
+ await pipeline(stream, collector, new NullSink(), signal === undefined ? {} : { signal });
841
+ return { size, crc: crc >>> 0, sha256: hash.digest('hex') };
842
+ }