nitro-patcher 0.1.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.
Files changed (44) hide show
  1. package/LICENSE +674 -0
  2. package/README.md +22 -0
  3. package/dist/browser.d.ts +34 -0
  4. package/dist/browser.js +4616 -0
  5. package/dist/browser.js.LEGAL.txt +147 -0
  6. package/dist/browser.js.map +7 -0
  7. package/dist/chunk-ANN47R34.js +1 -0
  8. package/dist/chunk-ANN47R34.js.map +1 -0
  9. package/dist/chunk-GFF67HX4.js +1181 -0
  10. package/dist/chunk-GFF67HX4.js.map +1 -0
  11. package/dist/chunk-L7ZM4LLP.js +396 -0
  12. package/dist/chunk-L7ZM4LLP.js.map +1 -0
  13. package/dist/cli.d.ts +1 -0
  14. package/dist/cli.js +76 -0
  15. package/dist/cli.js.map +1 -0
  16. package/dist/index.d.ts +2 -0
  17. package/dist/index.js +56 -0
  18. package/dist/index.js.map +1 -0
  19. package/dist/nitro-helper.d.ts +315 -0
  20. package/dist/nitro-helper.js +44 -0
  21. package/dist/nitro-helper.js.map +1 -0
  22. package/dist/nitro-patch-helper.d.ts +46 -0
  23. package/dist/nitro-patch-helper.js +16 -0
  24. package/dist/nitro-patch-helper.js.map +1 -0
  25. package/package.json +86 -0
  26. package/src/browser/buffer.ts +1 -0
  27. package/src/browser.ts +60 -0
  28. package/src/cli.ts +76 -0
  29. package/src/index.ts +2 -0
  30. package/src/nitro/banner.ts +77 -0
  31. package/src/nitro/binary.ts +80 -0
  32. package/src/nitro/blz.ts +163 -0
  33. package/src/nitro/crc.ts +23 -0
  34. package/src/nitro/crypto.ts +178 -0
  35. package/src/nitro/filesystem.ts +183 -0
  36. package/src/nitro/header.ts +254 -0
  37. package/src/nitro/nds-file.ts +285 -0
  38. package/src/nitro/twl.ts +338 -0
  39. package/src/nitro-helper.ts +14 -0
  40. package/src/nitro-patch-helper.ts +95 -0
  41. package/src/patch/xdelta.ts +214 -0
  42. package/src/patch/zip.ts +206 -0
  43. package/src/runtime/browser.ts +40 -0
  44. package/src/runtime/node.ts +28 -0
@@ -0,0 +1,95 @@
1
+ // Native TypeScript port of NitroPatchHelper/PatchHelper.cs, GPL-3.0.
2
+ import { hashDigest, readFile } from '#nitro-runtime';
3
+ import { bytes } from './nitro/binary';
4
+ import { NDSFile } from './nitro/nds-file';
5
+ import { readZip } from './patch/zip';
6
+ import { decodeXdelta } from './patch/xdelta';
7
+
8
+ export const PatchReturnValue = Object.freeze({
9
+ SUCCESS: 'SUCCESS',
10
+ MD5_MISMATCH: 'MD5_MISMATCH',
11
+ } as const);
12
+ export type PatchReturnValue = (typeof PatchReturnValue)[keyof typeof PatchReturnValue];
13
+
14
+ export interface PatchResult {
15
+ /** Generated ROM bytes. Also returned when the MD5 does not match, as in the original helper. */
16
+ buffer: Buffer;
17
+ returnValue: PatchReturnValue;
18
+ /** MD5 of the original input, before preprocessing. */
19
+ inputMd5: string;
20
+ outputMd5: string;
21
+ }
22
+
23
+ export interface PatchOptions {
24
+ /** Maximum generated ROM/Xdelta target size in bytes, default 1 GiB. */
25
+ maxOutputSize?: number;
26
+ /** Maximum target size of an individual VCDIFF window, default 16 MiB. */
27
+ maxWindowSize?: number;
28
+ /** Maximum total uncompressed ZIP bytes, default 1 GiB. */
29
+ maxUncompressedSize?: number;
30
+ /** Maximum ZIP entry count. */
31
+ maxEntries?: number;
32
+ }
33
+
34
+ const md5 = (data: Uint8Array): string => hashDigest('md5', data).toString('hex');
35
+
36
+ /** Apply an existing NitroPatcher ZIP package entirely in memory. */
37
+ export const patchBuffer = (
38
+ original: Uint8Array,
39
+ patch: Uint8Array,
40
+ options: PatchOptions = {},
41
+ ): PatchResult => {
42
+ const input = bytes(original, 'original ROM');
43
+ const patches = readZip(patch, options);
44
+ const inputMd5 = md5(input);
45
+ const preprocessing = patches.get(`preprocessing/${inputMd5}.xdelta`);
46
+ const rom = new NDSFile(
47
+ preprocessing ? decodeXdelta(input, preprocessing, options) : input,
48
+ options,
49
+ );
50
+ let matched = true;
51
+ const md5File = patches.get('md5.txt');
52
+ if (md5File) {
53
+ matched = false;
54
+ for (const line of md5File.toString('utf8').split('\n')) {
55
+ const expected = line.trim();
56
+ if (!expected || expected.startsWith('#')) continue;
57
+ // Keep the original format contract: exactly 32 characters, case-insensitive comparison.
58
+ if (expected.length !== 32) throw new Error('md5.txt 格式错误,可能是因为补丁包已损坏。');
59
+ if (expected.toLowerCase() === inputMd5) {
60
+ matched = true;
61
+ break;
62
+ }
63
+ }
64
+ }
65
+ for (const { path } of rom.listFiles()) {
66
+ const normalized = path.replaceAll('\\', '/').toLowerCase();
67
+ const delta = patches.get(`xdelta/${normalized}`);
68
+ const replacement = delta
69
+ ? decodeXdelta(rom.getFile(path), delta, options)
70
+ : patches.get(normalized);
71
+ if (replacement) rom.replaceFile(path, replacement);
72
+ }
73
+ const buffer = rom.toBuffer();
74
+ return {
75
+ buffer,
76
+ returnValue: matched ? PatchReturnValue.SUCCESS : PatchReturnValue.MD5_MISMATCH,
77
+ inputMd5,
78
+ outputMd5: md5(buffer),
79
+ };
80
+ };
81
+
82
+ /** Read input files and apply the patch. Does not write an output file. */
83
+ export const patchIt = async (
84
+ originalPath: string,
85
+ patchPath: string,
86
+ options: PatchOptions = {},
87
+ ): Promise<PatchResult> => {
88
+ const [original, patch] = await Promise.all([readFile(originalPath), readFile(patchPath)]);
89
+ return patchBuffer(original, patch, options);
90
+ };
91
+
92
+ /** Namespaced counterpart of the original C# helper, sharing the same typed functions. */
93
+ export const PatchHelper = Object.freeze({ patchBuffer, patchIt });
94
+ export { decodeXdelta } from './patch/xdelta';
95
+ export type { XdeltaOptions } from './patch/xdelta';
@@ -0,0 +1,214 @@
1
+ /** Native RFC 3284 VCDIFF decoder with the xdelta3 Adler32/app-header extensions.
2
+ * Supports the same default-table, uncompressed format as PleOps.XdeltaSharp 1.3.0.
3
+ * Secondary compression and custom code tables are explicitly unsupported there too.
4
+ */
5
+ const UINT32_MAX = 0xffffffff;
6
+ const fail = (message: string): never => {
7
+ throw new Error(`VCDIFF: ${message}`);
8
+ };
9
+
10
+ class Reader {
11
+ pos = 0;
12
+ constructor(
13
+ readonly bytes: Buffer,
14
+ readonly label = 'patch',
15
+ ) {}
16
+ get remaining() {
17
+ return this.bytes.length - this.pos;
18
+ }
19
+ byte() {
20
+ if (!this.remaining) fail(`truncated ${this.label}`);
21
+ return this.bytes[this.pos++]!;
22
+ }
23
+ integer(): number {
24
+ let value = 0;
25
+ for (let count = 0; count < 5; count++) {
26
+ const byte = this.byte();
27
+ value = value * 128 + (byte & 127);
28
+ if (value > UINT32_MAX) fail(`integer exceeds 32-bit limit in ${this.label}`);
29
+ if (!(byte & 128)) return value;
30
+ }
31
+ return fail(`invalid variable-length integer in ${this.label}`);
32
+ }
33
+ take(size: number): Buffer {
34
+ if (size > this.remaining)
35
+ fail(`truncated ${this.label}: requested ${size} bytes, ${this.remaining} remain`);
36
+ const result = this.bytes.subarray(this.pos, this.pos + size);
37
+ this.pos += size;
38
+ return result;
39
+ }
40
+ }
41
+
42
+ // RFC 3284 section 5.6: (operation, size, COPY address mode), up to two per opcode.
43
+ type Operation = { type: 'ADD' | 'RUN' | 'COPY'; size: number; mode: number };
44
+ const table: Operation[][] = [];
45
+ const op = (type: Operation['type'], size: number, mode = 0): Operation => ({ type, size, mode });
46
+ table.push([op('RUN', 0)]);
47
+ for (let size = 0; size <= 17; size++) table.push([op('ADD', size)]);
48
+ for (let mode = 0; mode <= 8; mode++) {
49
+ table.push([op('COPY', 0, mode)]);
50
+ for (let size = 4; size <= 18; size++) table.push([op('COPY', size, mode)]);
51
+ }
52
+ for (let mode = 0; mode <= 5; mode++) {
53
+ for (let add = 1; add <= 4; add++) {
54
+ for (let copy = 4; copy <= 6; copy++) table.push([op('ADD', add), op('COPY', copy, mode)]);
55
+ }
56
+ }
57
+ for (let mode = 6; mode <= 8; mode++) {
58
+ for (let add = 1; add <= 4; add++) table.push([op('ADD', add), op('COPY', 4, mode)]);
59
+ }
60
+ for (let mode = 0; mode <= 8; mode++) table.push([op('COPY', 4, mode), op('ADD', 1)]);
61
+
62
+ function adler32(bytes: Uint8Array): number {
63
+ let a = 1,
64
+ b = 0;
65
+ for (let start = 0; start < bytes.length; start += 5552) {
66
+ const end = Math.min(start + 5552, bytes.length);
67
+ for (let i = start; i < end; i++) {
68
+ a += bytes[i]!;
69
+ b += a;
70
+ }
71
+ a %= 65521;
72
+ b %= 65521;
73
+ }
74
+ return (b * 65536 + a) >>> 0;
75
+ }
76
+
77
+ function asBuffer(value: Uint8Array, name: string): Buffer {
78
+ if (!(value instanceof Uint8Array)) throw new TypeError(`${name} must be a Buffer or Uint8Array`);
79
+ return Buffer.from(value.buffer, value.byteOffset, value.byteLength);
80
+ }
81
+ function limit(value: number | undefined, fallback: number, name: string): number {
82
+ value ??= fallback;
83
+ if (!Number.isSafeInteger(value) || value < 0 || value > UINT32_MAX)
84
+ throw new RangeError(`${name} must be an integer between 0 and ${UINT32_MAX}`);
85
+ return value;
86
+ }
87
+
88
+ /**
89
+ * @param {Buffer|Uint8Array} source Original bytes.
90
+ * @param {Buffer|Uint8Array} patch VCDIFF bytes.
91
+ * @param {{maxOutputSize?: number, maxWindowSize?: number}} [options]
92
+ * @returns {Buffer} Decoded target, only returned after all windows/checksums validate.
93
+ */
94
+ export interface XdeltaOptions {
95
+ maxOutputSize?: number;
96
+ maxWindowSize?: number;
97
+ }
98
+
99
+ export const decodeXdelta = (
100
+ source: Uint8Array,
101
+ patch: Uint8Array,
102
+ options: XdeltaOptions = {},
103
+ ): Buffer => {
104
+ const sourceBytes = asBuffer(source, 'source');
105
+ const reader = new Reader(asBuffer(patch, 'patch'));
106
+ const maxOutput = limit(options.maxOutputSize, 1024 * 1024 * 1024, 'maxOutputSize');
107
+ const maxWindow = limit(options.maxWindowSize, 16 * 1024 * 1024, 'maxWindowSize');
108
+ if (!reader.take(3).equals(Buffer.from([0xd6, 0xc3, 0xc4]))) fail('invalid file signature');
109
+ if (reader.byte() !== 0) fail('unsupported version (expected 0)');
110
+ const header = reader.byte();
111
+ if (header & ~7) fail('unrecognized header indicator bits');
112
+ if (header & 1)
113
+ fail('secondary compression is unsupported; recreate the patch using xdelta3 -S none');
114
+ if (header & 2) fail('custom code table is unsupported');
115
+ if (header & 4) reader.take(reader.integer());
116
+ const windows: Buffer[] = [];
117
+ let total = 0;
118
+
119
+ while (reader.remaining) {
120
+ const indicator = reader.byte();
121
+ if (indicator & ~7 || (indicator & 3) === 3)
122
+ fail('invalid window indicator: source and target are mutually exclusive');
123
+ let dictionary: Buffer = Buffer.alloc(0);
124
+ if (indicator & 3) {
125
+ const length = reader.integer();
126
+ const offset = reader.integer();
127
+ const available = indicator & 1 ? sourceBytes.length : total;
128
+ if (offset > available || length > available - offset)
129
+ fail('source segment exceeds available source/target bounds');
130
+ if (indicator & 1) dictionary = sourceBytes.subarray(offset, offset + length);
131
+ else {
132
+ dictionary = Buffer.allocUnsafe(length);
133
+ let base = 0;
134
+ for (const previous of windows) {
135
+ const start = Math.max(offset, base),
136
+ end = Math.min(offset + length, base + previous.length);
137
+ if (end > start) previous.copy(dictionary, start - offset, start - base, end - base);
138
+ base += previous.length;
139
+ if (base >= offset + length) break;
140
+ }
141
+ }
142
+ }
143
+ const deltaLength = reader.integer();
144
+ const delta = new Reader(reader.take(deltaLength), 'delta window');
145
+ const targetLength = delta.integer();
146
+ if (targetLength > maxWindow)
147
+ fail(`window size ${targetLength} exceeds maximum limit ${maxWindow}`);
148
+ if (targetLength > maxOutput - total) fail(`output size exceeds maximum limit ${maxOutput}`);
149
+ if (dictionary.length + targetLength > UINT32_MAX)
150
+ fail('window address space exceeds 32-bit limit');
151
+ const compressed = delta.byte();
152
+ if (compressed & ~7) fail('unrecognized delta indicator bits');
153
+ if (compressed) fail('secondary compression in delta sections is unsupported');
154
+ const dataLength = delta.integer(),
155
+ instructionLength = delta.integer(),
156
+ addressLength = delta.integer();
157
+ const checksum = indicator & 4 ? delta.take(4).readUInt32BE() : null;
158
+ const data = new Reader(delta.take(dataLength), 'data section');
159
+ const instructions = new Reader(delta.take(instructionLength), 'instruction section');
160
+ const addresses = new Reader(delta.take(addressLength), 'address section');
161
+ if (delta.remaining) fail('delta encoding length does not match section lengths');
162
+ const target = Buffer.allocUnsafe(targetLength);
163
+ const near = new Uint32Array(4),
164
+ same = new Uint32Array(768);
165
+ let nearIndex = 0,
166
+ position = 0;
167
+ while (instructions.remaining) {
168
+ const operations = table[instructions.byte()]!;
169
+ for (const { type, size: fixedSize, mode } of operations) {
170
+ const size = fixedSize || instructions.integer();
171
+ if (size > targetLength - position) fail(`${type} size exceeds target window length`);
172
+ if (type === 'ADD') {
173
+ data.take(size).copy(target, position);
174
+ } else if (type === 'RUN') {
175
+ target.fill(data.byte(), position, position + size);
176
+ } else {
177
+ const here = dictionary.length + position;
178
+ let address;
179
+ if (mode === 0) address = addresses.integer();
180
+ else if (mode === 1) address = here - addresses.integer();
181
+ else if (mode < 6) address = near[mode - 2]! + addresses.integer();
182
+ else address = same[(mode - 6) * 256 + addresses.byte()]!;
183
+ if (address < 0 || address >= here)
184
+ fail(`COPY address ${address} is outside decoded address space ${here}`);
185
+ near[nearIndex] = address;
186
+ nearIndex = (nearIndex + 1) % near.length;
187
+ same[address % same.length] = address;
188
+ let copied = 0;
189
+ if (address < dictionary.length) {
190
+ copied = Math.min(size, dictionary.length - address);
191
+ dictionary.copy(target, position, address, address + copied);
192
+ }
193
+ // Copy only already available bytes per iteration. Doubling handles overlap
194
+ // (including a copy crossing from dictionary to current target) efficiently.
195
+ const from = Math.max(0, address - dictionary.length);
196
+ while (copied < size) {
197
+ const count = Math.min(size - copied, position + copied - from);
198
+ if (count <= 0) fail('COPY references unavailable target bytes');
199
+ target.copy(target, position + copied, from, from + count);
200
+ copied += count;
201
+ }
202
+ }
203
+ position += size;
204
+ }
205
+ }
206
+ if (position !== targetLength)
207
+ fail(`target window length mismatch: decoded ${position}, expected ${targetLength}`);
208
+ if (data.remaining || addresses.remaining) fail('unused bytes in data/address section');
209
+ if (checksum !== null && adler32(target) !== checksum) fail('Adler32 checksum mismatch');
210
+ windows.push(target);
211
+ total += targetLength;
212
+ }
213
+ return Buffer.concat(windows, total);
214
+ };
@@ -0,0 +1,206 @@
1
+ import { inflateRawSync } from '#nitro-runtime';
2
+ import { crc32 } from '../nitro/crc';
3
+
4
+ /** Resource limits apply to every central-directory entry, including duplicates. */
5
+ export interface ZipOptions {
6
+ maxUncompressedSize?: number;
7
+ maxEntries?: number;
8
+ }
9
+
10
+ const fail = (message: string): never => {
11
+ throw new Error(`ZIP: ${message}`);
12
+ };
13
+ const utf8 = new TextDecoder('utf-8', { fatal: true });
14
+ // IBM code page 437, byte values 0x80..0xff. ASCII bytes retain their literal values.
15
+ const cp437 =
16
+ 'ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ ';
17
+
18
+ function decodeUtf8(bytes: Uint8Array): string {
19
+ try {
20
+ return utf8.decode(bytes);
21
+ } catch {
22
+ return fail('invalid UTF-8 filename');
23
+ }
24
+ }
25
+ function boundOption(value: number | undefined, fallback: number, label: string): number {
26
+ value ??= fallback;
27
+ if (!Number.isSafeInteger(value) || value < 0)
28
+ throw new RangeError(`${label} must be a non-negative safe integer`);
29
+ return value;
30
+ }
31
+ function checkRange(bytes: Buffer, offset: number, length: number, end = bytes.length): void {
32
+ if (offset < 0 || offset > end || length > end - offset)
33
+ fail(`truncated or out-of-bounds record at ${offset} (length ${length})`);
34
+ }
35
+ function extras(bytes: Buffer): Map<number, Buffer> {
36
+ const fields = new Map<number, Buffer>();
37
+ let offset = 0;
38
+ while (offset < bytes.length) {
39
+ checkRange(bytes, offset, 4);
40
+ const id = bytes.readUInt16LE(offset),
41
+ length = bytes.readUInt16LE(offset + 2);
42
+ offset += 4;
43
+ checkRange(bytes, offset, length);
44
+ if (id === 1) fail('ZIP64 archives are unsupported');
45
+ fields.set(id, bytes.subarray(offset, offset + length));
46
+ offset += length;
47
+ }
48
+ return fields;
49
+ }
50
+ function filename(raw: Buffer, flags: number, fields: Map<number, Buffer>): string {
51
+ if (flags & 0x800) return decodeUtf8(raw);
52
+ const unicode = fields.get(0x7075);
53
+ if (unicode && unicode.length >= 5 && unicode[0] === 1 && unicode.readUInt32LE(1) === crc32(raw))
54
+ return decodeUtf8(unicode.subarray(5));
55
+ let result = '';
56
+ for (const byte of raw) result += byte < 128 ? String.fromCharCode(byte) : cp437[byte - 128]!;
57
+ return result;
58
+ }
59
+
60
+ /**
61
+ * Read stored/deflated, single-disk ZIPs entirely in memory. Central-directory
62
+ * sizes support streamed entries with data descriptors. Paths match PatchHelper:
63
+ * backslashes become slashes, names are lowercase, and the final duplicate wins.
64
+ * ZIP64, encryption, split archives and other compression methods fail explicitly.
65
+ * Format reference: https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT
66
+ */
67
+ export const readZip = (input: Uint8Array, options: ZipOptions = {}): Map<string, Buffer> => {
68
+ if (!(input instanceof Uint8Array))
69
+ throw new TypeError('ZIP input must be a Buffer or Uint8Array');
70
+ const bytes = Buffer.from(input.buffer, input.byteOffset, input.byteLength);
71
+ const maxSize = boundOption(
72
+ options.maxUncompressedSize,
73
+ 1024 * 1024 * 1024,
74
+ 'maxUncompressedSize',
75
+ );
76
+ const maxEntries = boundOption(options.maxEntries, 100000, 'maxEntries');
77
+ let eocd = -1;
78
+ for (let offset = bytes.length - 22; offset >= Math.max(0, bytes.length - 65557); offset--) {
79
+ if (
80
+ bytes.readUInt32LE(offset) === 0x06054b50 &&
81
+ offset + 22 + bytes.readUInt16LE(offset + 20) === bytes.length
82
+ ) {
83
+ eocd = offset;
84
+ break;
85
+ }
86
+ }
87
+ if (eocd < 0) fail('end of central directory not found or truncated');
88
+ const disk = bytes.readUInt16LE(eocd + 4),
89
+ centralDisk = bytes.readUInt16LE(eocd + 6);
90
+ const diskEntries = bytes.readUInt16LE(eocd + 8),
91
+ count = bytes.readUInt16LE(eocd + 10);
92
+ const centralSize = bytes.readUInt32LE(eocd + 12),
93
+ centralOffset = bytes.readUInt32LE(eocd + 16);
94
+ if (
95
+ count === 0xffff ||
96
+ diskEntries === 0xffff ||
97
+ centralSize === 0xffffffff ||
98
+ centralOffset === 0xffffffff ||
99
+ (eocd >= 20 && bytes.readUInt32LE(eocd - 20) === 0x07064b50)
100
+ )
101
+ fail('ZIP64 archives are unsupported');
102
+ if (disk || centralDisk || diskEntries !== count)
103
+ fail('split or multiple-disk archives are unsupported');
104
+ if (count > maxEntries) fail(`entry count exceeds limit ${maxEntries}`);
105
+ checkRange(bytes, centralOffset, centralSize, eocd);
106
+ if (centralOffset + centralSize !== eocd) fail('central directory size/offset mismatch');
107
+ if (count > Math.floor(centralSize / 46)) fail('entry count exceeds central directory size');
108
+ const result = new Map<string, Buffer>();
109
+ const ranges: Array<{ start: number; end: number }> = [];
110
+ let offset = centralOffset,
111
+ totalSize = 0;
112
+ for (let index = 0; index < count; index++) {
113
+ checkRange(bytes, offset, 46, eocd);
114
+ if (bytes.readUInt32LE(offset) !== 0x02014b50) fail('invalid central directory signature');
115
+ const flags = bytes.readUInt16LE(offset + 8),
116
+ method = bytes.readUInt16LE(offset + 10);
117
+ const checksum = bytes.readUInt32LE(offset + 16),
118
+ compressedSize = bytes.readUInt32LE(offset + 20),
119
+ size = bytes.readUInt32LE(offset + 24);
120
+ const nameLength = bytes.readUInt16LE(offset + 28),
121
+ extraLength = bytes.readUInt16LE(offset + 30),
122
+ commentLength = bytes.readUInt16LE(offset + 32);
123
+ const startDisk = bytes.readUInt16LE(offset + 34),
124
+ localOffset = bytes.readUInt32LE(offset + 42);
125
+ if (
126
+ size === 0xffffffff ||
127
+ compressedSize === 0xffffffff ||
128
+ localOffset === 0xffffffff ||
129
+ startDisk === 0xffff
130
+ )
131
+ fail('ZIP64 entry is unsupported');
132
+ if (startDisk) fail('split or multiple-disk entry is unsupported');
133
+ if (flags & 0x2041) fail('encrypted entries are unsupported');
134
+ if (flags & ~0x80e) fail('unsupported general purpose flags');
135
+ if (method !== 0 && method !== 8) fail(`unsupported compression method ${method}`);
136
+ if (size > maxSize - totalSize) fail(`uncompressed size exceeds limit ${maxSize}`);
137
+ totalSize += size;
138
+ checkRange(bytes, offset + 46, nameLength + extraLength + commentLength, eocd);
139
+ const rawName = bytes.subarray(offset + 46, offset + 46 + nameLength);
140
+ const fields = extras(
141
+ bytes.subarray(offset + 46 + nameLength, offset + 46 + nameLength + extraLength),
142
+ );
143
+ const name = filename(rawName, flags, fields).replaceAll('\\', '/').toLowerCase();
144
+ offset += 46 + nameLength + extraLength + commentLength;
145
+
146
+ checkRange(bytes, localOffset, 30, centralOffset);
147
+ if (bytes.readUInt32LE(localOffset) !== 0x04034b50) fail('invalid local header signature');
148
+ if (
149
+ bytes.readUInt16LE(localOffset + 6) !== flags ||
150
+ bytes.readUInt16LE(localOffset + 8) !== method
151
+ )
152
+ fail('local header flags/compression method mismatch');
153
+ const localNameLength = bytes.readUInt16LE(localOffset + 26),
154
+ localExtraLength = bytes.readUInt16LE(localOffset + 28);
155
+ const dataOffset = localOffset + 30 + localNameLength + localExtraLength;
156
+ checkRange(bytes, localOffset + 30, localNameLength + localExtraLength, centralOffset);
157
+ if (!rawName.equals(bytes.subarray(localOffset + 30, localOffset + 30 + localNameLength)))
158
+ fail('local filename differs from central directory');
159
+ extras(bytes.subarray(localOffset + 30 + localNameLength, dataOffset));
160
+ if (
161
+ !(flags & 8) &&
162
+ (bytes.readUInt32LE(localOffset + 14) !== checksum ||
163
+ bytes.readUInt32LE(localOffset + 18) !== compressedSize ||
164
+ bytes.readUInt32LE(localOffset + 22) !== size)
165
+ )
166
+ fail('local header CRC/size mismatch');
167
+ checkRange(bytes, dataOffset, compressedSize, centralOffset);
168
+ let dataEnd = dataOffset + compressedSize;
169
+ if (flags & 8) {
170
+ // A descriptor may omit its signature. Use the CRC and both sizes to
171
+ // disambiguate the rare case of an unsigned CRC equal to the signature.
172
+ checkRange(bytes, dataEnd, 12, centralOffset);
173
+ const matches = (at: number): boolean =>
174
+ at + 12 <= centralOffset &&
175
+ bytes.readUInt32LE(at) === checksum &&
176
+ bytes.readUInt32LE(at + 4) === compressedSize &&
177
+ bytes.readUInt32LE(at + 8) === size;
178
+ if (matches(dataEnd)) dataEnd += 12;
179
+ else if (bytes.readUInt32LE(dataEnd) === 0x08074b50 && matches(dataEnd + 4)) dataEnd += 16;
180
+ else fail('data descriptor CRC/size mismatch');
181
+ }
182
+ ranges.push({ start: localOffset, end: dataEnd });
183
+ const compressed = bytes.subarray(dataOffset, dataOffset + compressedSize);
184
+ let data: Buffer;
185
+ if (method === 0) {
186
+ if (compressedSize !== size) fail('stored entry compressed/uncompressed size mismatch');
187
+ data = Buffer.from(compressed);
188
+ } else {
189
+ try {
190
+ data = inflateRawSync(compressed, { maxOutputLength: Math.max(1, size) });
191
+ } catch (error) {
192
+ return fail(
193
+ `cannot inflate entry ${JSON.stringify(name)} within declared size: ${error instanceof Error ? error.message : String(error)}`,
194
+ );
195
+ }
196
+ }
197
+ if (data.length !== size) fail(`uncompressed size mismatch for ${JSON.stringify(name)}`);
198
+ if (crc32(data) !== checksum) fail(`CRC32 mismatch for ${JSON.stringify(name)}`);
199
+ if (name && !name.endsWith('/')) result.set(name, data);
200
+ }
201
+ if (offset !== eocd) fail('central directory entry count/length mismatch');
202
+ ranges.sort((a, b) => a.start - b.start);
203
+ for (let i = 1; i < ranges.length; i++)
204
+ if (ranges[i]!.start < ranges[i - 1]!.end) fail('overlapping local entry ranges');
205
+ return result;
206
+ };
@@ -0,0 +1,40 @@
1
+ import { md5, sha1 } from '#browser-hashes';
2
+ import { hmac } from '#browser-hmac';
3
+ import { ecb } from '#browser-aes';
4
+ import { Inflate } from 'fflate';
5
+
6
+ export const hashDigest = (algorithm: 'md5' | 'sha1', data: Uint8Array): Buffer =>
7
+ Buffer.from((algorithm === 'md5' ? md5 : sha1)(data));
8
+ export const hmacSha1 = (key: Uint8Array, data: Uint8Array): Buffer =>
9
+ Buffer.from(hmac(sha1, key, data));
10
+ export const createAesBlockCipher =
11
+ (key: Uint8Array): ((block: Uint8Array) => Buffer) =>
12
+ (block) =>
13
+ Buffer.from(ecb(key, { disablePadding: true }).encrypt(block));
14
+
15
+ /** Bound decompression output even when a ZIP entry lies about its size. */
16
+ export const inflateRawSync = (data: Uint8Array, options: { maxOutputLength: number }): Buffer => {
17
+ const output = Buffer.alloc(options.maxOutputLength);
18
+ let length = 0;
19
+ const stream = new Inflate((chunk) => {
20
+ if (chunk.length > output.length - length)
21
+ throw new RangeError('Inflated data exceeds declared size');
22
+ output.set(chunk, length);
23
+ length += chunk.length;
24
+ });
25
+ for (let offset = 0; offset < data.length; offset += 1024) {
26
+ stream.push(data.subarray(offset, offset + 1024), offset + 1024 >= data.length);
27
+ }
28
+ if (!data.length) stream.push(data, true);
29
+ return output.subarray(0, length);
30
+ };
31
+
32
+ // These Node-only methods are not exposed by the browser public API. Keep a
33
+ // clear error if a future internal call accidentally crosses that boundary.
34
+ const nodeOnly = (): never => {
35
+ throw new Error('Filesystem and RSA APIs are only available in the Node entry');
36
+ };
37
+ export const readFile = nodeOnly;
38
+ export const writeFile = nodeOnly;
39
+ export const readFileSync = nodeOnly;
40
+ export const verifyRsaSha1 = nodeOnly;
@@ -0,0 +1,28 @@
1
+ import { createHash, createHmac, createCipheriv, createPublicKey, verify } from 'node:crypto';
2
+ export { readFile, writeFile } from 'node:fs/promises';
3
+ export { readFileSync } from 'node:fs';
4
+ export { inflateRawSync } from 'node:zlib';
5
+
6
+ export const hashDigest = (algorithm: 'md5' | 'sha1', data: Uint8Array): Buffer =>
7
+ createHash(algorithm).update(data).digest();
8
+ export const hmacSha1 = (key: Uint8Array, data: Uint8Array): Buffer =>
9
+ createHmac('sha1', key).update(data).digest();
10
+ export const createAesBlockCipher = (key: Uint8Array): ((block: Uint8Array) => Buffer) => {
11
+ const cipher = createCipheriv('aes-128-ecb', key, null);
12
+ cipher.setAutoPadding(false);
13
+ return (block) => cipher.update(block);
14
+ };
15
+ export const verifyRsaSha1 = (data: Uint8Array, signature: Uint8Array): boolean => {
16
+ const key = createPublicKey({
17
+ key: {
18
+ kty: 'RSA',
19
+ n: Buffer.from(
20
+ '956F790DF08BB85A76AAEFA27FE874758BED9EDF9E9A670CD818BEB9B2885203B3FA11AEAA186513B5D6BB85A384D0D0EFB366CBC6051AAA86827AB74311F59C9BFC6C7079D5F17BD0819F522056738C721F40CF2361932590A3C5DC94CFD17A8CBC954A918AA858F4D804BAF7D3C1C4D7B8F077012FA170260B2C049056F3A5',
21
+ 'hex',
22
+ ).toString('base64url'),
23
+ e: 'AQAB',
24
+ },
25
+ format: 'jwk',
26
+ });
27
+ return verify('RSA-SHA1', data, key, signature);
28
+ };