@nimiplatform/app-tools 0.16.0-rc.13 → 0.16.0-rc.15

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/lib/app-pack.mjs CHANGED
@@ -9,6 +9,7 @@ import { isAppId } from './app-identifiers.mjs';
9
9
  // @nimi-authority: rule.nimi.platform.app-ecosystem.p-napp-034a
10
10
  // @nimi-authority: rule.nimi.platform.app-ecosystem.p-napp-043a
11
11
 
12
+ import { isUtf8 } from 'node:buffer';
12
13
  import { createHash } from 'node:crypto';
13
14
  import {
14
15
  existsSync,
@@ -24,12 +25,20 @@ import {
24
25
  readlinkSync,
25
26
  writeFileSync,
26
27
  } from 'node:fs';
28
+ import * as fsp from 'node:fs/promises';
27
29
  import path from 'node:path';
30
+ import {
31
+ crc32 as nativeCrc32,
32
+ createDeflateRaw,
33
+ createInflateRaw,
34
+ deflateRawSync,
35
+ inflateRawSync,
36
+ } from 'node:zlib';
28
37
  import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
29
38
  import { APP_INFO_DECLARATION_FIELDS, APP_INFO_MAX_BYTES, readAppInfo, readAppStorefront, validateAppInfo } from './app-info.mjs';
30
39
  import { STOREFRONT_ARCHIVE_MAX_BYTES } from './storefront-media.mjs';
31
40
  import { observeWindowsExecutableFacts } from './windows-powershell.mjs';
32
- import { SYMBOLIC_LINK_MODE, validatePayloadLinks } from './payload-links.mjs';
41
+ import { MAX_SYMLINK_TARGET_BYTES, SYMBOLIC_LINK_MODE, validatePayloadLinks } from './payload-links.mjs';
33
42
  import { observeMacOSExecutableFacts } from './macos-native.mjs';
34
43
 
35
44
  const PACKAGE_FORMAT = 'nimi.app-package/v2';
@@ -39,9 +48,33 @@ const BUILD_PROFILE_PATH = '.nimi/config/build-profile.yaml';
39
48
  const MANAGED_WEB_BUILD_PROFILE_REF = 'managed-web-pnpm-vite';
40
49
  const MANAGED_WEB_EXECUTION_PROFILE_REF = 'nimi-managed-web-v1';
41
50
  const MANAGED_WEB_RUNTIME_ENTRY = 'payload/index.html';
42
- const MANAGED_WEB_MAX_RELEASE_BYTES = 64 * 1024 * 1024;
43
- const MANAGED_WEB_MAX_RELEASE_ENTRIES = 10_000;
44
- const MANAGED_WEB_MAX_DIRECTORY_DEPTH = 64;
51
+ export const NATIVE_MAX_ARCHIVE_BYTES = 2000 * 1024 * 1024;
52
+ export const NATIVE_MAX_ENTRY_BYTES = 2000 * 1024 * 1024;
53
+ export const NATIVE_MAX_RELEASE_BYTES = 4 * 1024 * 1024 * 1024;
54
+ export const NATIVE_MAX_DIRECTORIES = 65_535;
55
+ export const MANAGED_WEB_MAX_ARCHIVE_BYTES = 72 * 1024 * 1024;
56
+ export const MANAGED_WEB_MAX_RELEASE_BYTES = 64 * 1024 * 1024;
57
+ export const MANAGED_WEB_MAX_RELEASE_ENTRIES = 10_000;
58
+ export const MAX_ARCHIVE_DIRECTORY_DEPTH = 64;
59
+ export const MAX_ARCHIVE_ENTRY_NAME_BYTES = 1024;
60
+ export const MAX_ZIP32_ENTRIES = 65_535;
61
+ export const MAX_LICENSE_BYTES = 128 * 1024;
62
+ export const MAX_CONTROL_DOCUMENT_BYTES = 1024 * 1024;
63
+ export const EXPANSION_RATIO_FLOOR_BYTES = 8 * 1024 * 1024;
64
+ export const MAX_EXPANSION_RATIO = 20;
65
+ const STREAM_DEFLATE_THRESHOLD = 32 * 1024 * 1024;
66
+ const STREAM_IO_CHUNK_BYTES = 256 * 1024;
67
+ const ZIP_METHOD_STORE = 0;
68
+ const ZIP_METHOD_DEFLATE = 8;
69
+ const ZIP_FLAGS_UTF8 = 0x0800;
70
+ const ZIP_CREATOR_UNIX = 0x0314;
71
+ const ZIP_READER_VERSION = 20;
72
+ const ZIP_MOD_TIME = 0;
73
+ const ZIP_MOD_DATE = 0x0021;
74
+ const EXT_ATTR_REGULAR_0644 = 0x81A40000;
75
+ const EXT_ATTR_REGULAR_0755 = 0x81ED0000;
76
+ const EXT_ATTR_SYMLINK_0777 = 0xA1FF0000;
77
+ const DEFLATE_LEVEL = 6;
45
78
  const ELECTRON_BUILD_PROFILE_REF = 'electron-packager-pnpm-vite';
46
79
  const APP_OWNED_ELECTRON_BUILD_PROFILE_REF = 'electron-pnpm';
47
80
  const OUTPUT_DIR = 'dist/nimi-app';
@@ -52,6 +85,13 @@ const TARGETS = Object.freeze({
52
85
  'desktop-universal': Object.freeze({ os: 'any', arch: 'any' }),
53
86
  });
54
87
  const WINDOWS_RESERVED_BASES = new Set(['CON', 'PRN', 'AUX', 'NUL', 'CLOCK$', 'CONIN$', 'CONOUT$']);
88
+ const UTF8_DECODER = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
89
+ const NIMIAPP_CONTROL_LIMITS = new Map([
90
+ ['LICENSE', MAX_LICENSE_BYTES],
91
+ ['app-info.json', APP_INFO_MAX_BYTES],
92
+ ['manifest.json', MAX_CONTROL_DOCUMENT_BYTES],
93
+ ['nimi.app.yaml', MAX_CONTROL_DOCUMENT_BYTES],
94
+ ]);
55
95
 
56
96
  function validWindowsSegment(segment) {
57
97
  if (/[<>:"|?*]/u.test(segment) || segment.endsWith('.') || segment.endsWith(' ')) {
@@ -84,14 +124,43 @@ function targetPathCollisionKey(name, targetOS) {
84
124
  return normalized;
85
125
  }
86
126
 
127
+ function compareUtf8(left, right) {
128
+ return Buffer.compare(Buffer.from(left, 'utf8'), Buffer.from(right, 'utf8'));
129
+ }
130
+
131
+ function decodeStrictUtf8(buf, label) {
132
+ if (!Buffer.isBuffer(buf) || !isUtf8(buf)) {
133
+ throw new Error(`Invalid ${label}: malformed UTF-8`);
134
+ }
135
+ try {
136
+ return UTF8_DECODER.decode(buf);
137
+ } catch {
138
+ throw new Error(`Invalid ${label}: malformed UTF-8`);
139
+ }
140
+ }
141
+
142
+ function parseCanonicalExternalAttrs(externalAttrs) {
143
+ if (externalAttrs === EXT_ATTR_REGULAR_0644) return 0o644;
144
+ if (externalAttrs === EXT_ATTR_REGULAR_0755) return 0o755;
145
+ if (externalAttrs === EXT_ATTR_SYMLINK_0777) return SYMBOLIC_LINK_MODE;
146
+ throw new Error(`Invalid nimiapp ZIP entry mode attributes: 0x${externalAttrs.toString(16)}`);
147
+ }
148
+
149
+ function encodeCanonicalExternalAttrs(mode) {
150
+ if (mode === SYMBOLIC_LINK_MODE) return EXT_ATTR_SYMLINK_0777;
151
+ if (mode === 0o755) return EXT_ATTR_REGULAR_0755;
152
+ if (mode === 0o644) return EXT_ATTR_REGULAR_0644;
153
+ throw new Error(`Unsupported nimiapp ZIP entry mode: ${String(mode)}`);
154
+ }
155
+
87
156
  function validateCrossPlatformArchiveEntries(entries, targetOS) {
88
157
  const roles = new Map();
89
158
  let fileCount = 0;
90
159
  for (const entry of entries) {
91
160
  const name = entry.name;
92
161
  const segments = name.split('/');
93
- if (targetOS === 'any' && segments.length - 1 > MANAGED_WEB_MAX_DIRECTORY_DEPTH) {
94
- throw new Error(`Managed-web directory depth exceeds ${MANAGED_WEB_MAX_DIRECTORY_DEPTH}: ${name}`);
162
+ if (segments.length - 1 > MAX_ARCHIVE_DIRECTORY_DEPTH) {
163
+ throw new Error(`Archive directory depth exceeds ${MAX_ARCHIVE_DIRECTORY_DEPTH}: ${name}`);
95
164
  }
96
165
  for (const segment of segments) {
97
166
  for (const ch of segment) {
@@ -117,10 +186,14 @@ function validateCrossPlatformArchiveEntries(entries, targetOS) {
117
186
  roles.set(key, { spelling: prefix, file: isFile });
118
187
  }
119
188
  }
120
- fileCount++;
121
- if (targetOS === 'any' && roles.size - fileCount > MANAGED_WEB_MAX_RELEASE_ENTRIES) {
189
+ fileCount += 1;
190
+ const dirCount = roles.size - fileCount;
191
+ if (targetOS === 'any' && dirCount > MANAGED_WEB_MAX_RELEASE_ENTRIES) {
122
192
  throw new Error(`Managed-web package exceeds ${MANAGED_WEB_MAX_RELEASE_ENTRIES} directories`);
123
193
  }
194
+ if (targetOS !== 'any' && dirCount > NATIVE_MAX_DIRECTORIES) {
195
+ throw new Error(`Native package exceeds ${NATIVE_MAX_DIRECTORIES} directories`);
196
+ }
124
197
  }
125
198
  }
126
199
 
@@ -134,10 +207,6 @@ function pathsOverlapOrEqual(left, right) {
134
207
  || cmpB.startsWith(`${cmpA}${path.sep}`);
135
208
  }
136
209
 
137
- function compareText(left, right) {
138
- return left < right ? -1 : left > right ? 1 : 0;
139
- }
140
-
141
210
  function sortedValue(value) {
142
211
  if (Array.isArray(value)) return value.map(sortedValue);
143
212
  if (!value || typeof value !== 'object') return value;
@@ -159,6 +228,31 @@ export function hashAppArchive(bytes) {
159
228
  return hash.digest('hex');
160
229
  }
161
230
 
231
+ export async function hashFileHandle(handle, expectedSize) {
232
+ const hash = createHash('sha256');
233
+ const buf = Buffer.allocUnsafe(Math.min(1024 * 1024, Math.max(1, expectedSize)));
234
+ let pos = 0;
235
+ while (pos < expectedSize) {
236
+ const toRead = Math.min(buf.length, expectedSize - pos);
237
+ const { bytesRead } = await handle.read(buf, 0, toRead, pos);
238
+ if (bytesRead <= 0) throw new Error('App archive ended before its recorded size');
239
+ hash.update(buf.subarray(0, bytesRead));
240
+ pos += bytesRead;
241
+ }
242
+ return hash.digest('hex');
243
+ }
244
+
245
+ async function hashFilePath(filePath) {
246
+ const handle = await fsp.open(filePath, 'r');
247
+ try {
248
+ const stat = await handle.stat();
249
+ if (!stat.isFile()) throw new Error(`Expected regular file: ${filePath}`);
250
+ return await hashFileHandle(handle, stat.size);
251
+ } finally {
252
+ await handle.close();
253
+ }
254
+ }
255
+
162
256
  export function writeAppArchiveFile(filePath, bytes) {
163
257
  const fd = openSync(filePath, 'w');
164
258
  try {
@@ -190,12 +284,12 @@ function sameCanonicalValue(left, right) {
190
284
  }
191
285
 
192
286
  function canonicalRelative(value, field) {
193
- if (typeof value !== 'string' || !value || value !== value.trim() || value.includes('\\')) {
194
- throw new Error(`${field} must be a canonical relative path`);
287
+ if (typeof value !== 'string' || !value || value !== value.trim() || value.includes('\\') || value.includes('\0')) {
288
+ throw new Error(`Invalid ${field}: must be a canonical relative path`);
195
289
  }
196
290
  const parts = value.split('/');
197
291
  if (value.startsWith('/') || parts.some((part) => !part || part === '.' || part === '..')) {
198
- throw new Error(`${field} must be a canonical relative path`);
292
+ throw new Error(`Invalid ${field}: must be a canonical relative path`);
199
293
  }
200
294
  return value;
201
295
  }
@@ -233,22 +327,23 @@ function collectPayload(payloadPath, os) {
233
327
  const stat = lstatSync(payloadPath);
234
328
  if (stat.isSymbolicLink()) throw new Error('Pack payload must not contain symbolic links');
235
329
  if (stat.isFile()) {
236
- return [{ relative: path.basename(payloadPath), bytes: readAppArchiveFile(payloadPath), mode: stat.mode & 0o111 ? 0o755 : 0o644 }];
330
+ return [{ relative: path.basename(payloadPath), filePath: payloadPath, size: stat.size, mode: stat.mode & 0o111 ? 0o755 : 0o644 }];
237
331
  }
238
332
  if (!stat.isDirectory()) throw new Error('Pack payload must be a regular file or directory');
239
333
  const entries = [];
240
334
  const walk = (current, prefix = '') => {
241
- for (const entry of readdirSync(current, { withFileTypes: true }).sort((left, right) => compareText(left.name, right.name))) {
335
+ for (const entry of readdirSync(current, { withFileTypes: true }).sort((left, right) => compareUtf8(left.name, right.name))) {
242
336
  const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
243
337
  const absolute = path.join(current, entry.name);
244
338
  const entryStat = lstatSync(absolute);
245
339
  if (entryStat.isSymbolicLink()) {
246
340
  if (os !== 'macos') throw new Error(`Pack payload must not contain symbolic links: ${relative}`);
247
- entries.push({ relative, bytes: Buffer.from(readlinkSync(absolute)), mode: SYMBOLIC_LINK_MODE });
341
+ const linkBytes = Buffer.from(readlinkSync(absolute), 'utf8');
342
+ entries.push({ relative, bytes: linkBytes, size: linkBytes.length, mode: SYMBOLIC_LINK_MODE });
248
343
  } else if (entryStat.isDirectory()) {
249
344
  walk(absolute, relative);
250
345
  } else if (entryStat.isFile()) {
251
- entries.push({ relative, bytes: readAppArchiveFile(absolute), mode: entryStat.mode & 0o111 ? 0o755 : 0o644 });
346
+ entries.push({ relative, filePath: absolute, size: entryStat.size, mode: entryStat.mode & 0o111 ? 0o755 : 0o644 });
252
347
  } else {
253
348
  throw new Error(`Unsupported pack payload entry: ${relative}`);
254
349
  }
@@ -259,144 +354,907 @@ function collectPayload(payloadPath, os) {
259
354
  return entries;
260
355
  }
261
356
 
262
- const CRC_TABLE = (() => {
263
- const table = new Uint32Array(256);
264
- for (let index = 0; index < 256; index += 1) {
265
- let value = index;
266
- for (let bit = 0; bit < 8; bit += 1) value = (value & 1) ? (0xedb88320 ^ (value >>> 1)) : (value >>> 1);
267
- table[index] = value >>> 0;
357
+ function zipEntryName(value) {
358
+ const name = canonicalRelative(value, 'archive entry');
359
+ if (Buffer.byteLength(name, 'utf8') > MAX_ARCHIVE_ENTRY_NAME_BYTES) {
360
+ throw new Error(`Invalid archive entry path length (exceeds ${MAX_ARCHIVE_ENTRY_NAME_BYTES} bytes): ${name}`);
361
+ }
362
+ if (name.split('/').length - 1 > MAX_ARCHIVE_DIRECTORY_DEPTH) {
363
+ throw new Error(`Invalid archive directory depth exceeds ${MAX_ARCHIVE_DIRECTORY_DEPTH}: ${name}`);
268
364
  }
269
- return table;
270
- })();
365
+ for (const ch of name) {
366
+ const code = ch.codePointAt(0);
367
+ if (code < 0x20 || code === 0x7f) {
368
+ throw new Error(`Invalid archive entry path control character: ${name}`);
369
+ }
370
+ }
371
+ return name;
372
+ }
271
373
 
272
- function crc32(bytes) {
273
- let crc = 0xffffffff;
274
- for (const byte of bytes) crc = CRC_TABLE[(crc ^ byte) & 0xff] ^ (crc >>> 8);
275
- return (crc ^ 0xffffffff) >>> 0;
374
+ function buildLocalHeaderBuffer(rawName, method, crc, compSize, uncompSize) {
375
+ const local = Buffer.alloc(30);
376
+ local.writeUInt32LE(0x04034b50, 0);
377
+ local.writeUInt16LE(ZIP_READER_VERSION, 4);
378
+ local.writeUInt16LE(ZIP_FLAGS_UTF8, 6);
379
+ local.writeUInt16LE(method, 8);
380
+ local.writeUInt16LE(ZIP_MOD_TIME, 10);
381
+ local.writeUInt16LE(ZIP_MOD_DATE, 12);
382
+ local.writeUInt32LE(crc >>> 0, 14);
383
+ local.writeUInt32LE(compSize >>> 0, 18);
384
+ local.writeUInt32LE(uncompSize >>> 0, 22);
385
+ local.writeUInt16LE(rawName.length, 26);
386
+ local.writeUInt16LE(0, 28);
387
+ return local;
276
388
  }
277
389
 
278
- function zipEntryName(value) {
279
- const name = canonicalRelative(value, 'archive entry');
280
- if (Buffer.byteLength(name) > 0xffff) throw new Error(`Archive entry path is too long: ${name}`);
281
- return name;
390
+ function buildCentralHeaderBuffer(rawName, method, crc, compSize, uncompSize, externalAttrs, localOffset) {
391
+ const central = Buffer.alloc(46);
392
+ central.writeUInt32LE(0x02014b50, 0);
393
+ central.writeUInt16LE(ZIP_CREATOR_UNIX, 4);
394
+ central.writeUInt16LE(ZIP_READER_VERSION, 6);
395
+ central.writeUInt16LE(ZIP_FLAGS_UTF8, 8);
396
+ central.writeUInt16LE(method, 10);
397
+ central.writeUInt16LE(ZIP_MOD_TIME, 12);
398
+ central.writeUInt16LE(ZIP_MOD_DATE, 14);
399
+ central.writeUInt32LE(crc >>> 0, 16);
400
+ central.writeUInt32LE(compSize >>> 0, 20);
401
+ central.writeUInt32LE(uncompSize >>> 0, 24);
402
+ central.writeUInt16LE(rawName.length, 28);
403
+ central.writeUInt16LE(0, 30);
404
+ central.writeUInt16LE(0, 32);
405
+ central.writeUInt16LE(0, 34);
406
+ central.writeUInt16LE(0, 36);
407
+ central.writeUInt32LE(externalAttrs >>> 0, 38);
408
+ central.writeUInt32LE(localOffset >>> 0, 42);
409
+ return central;
282
410
  }
283
411
 
284
- export function writeNimiAppArchive(entries) {
285
- const normalized = entries.map((entry) => ({
286
- name: zipEntryName(entry.name),
287
- bytes: Buffer.isBuffer(entry.bytes) ? entry.bytes : Buffer.from(entry.bytes),
288
- mode: entry.mode === SYMBOLIC_LINK_MODE ? SYMBOLIC_LINK_MODE : entry.mode === 0o755 ? 0o755 : 0o644,
289
- })).sort((left, right) => compareText(left.name, right.name));
290
- if (normalized.length === 0) throw new Error('nimiapp archive requires at least one file');
291
- if (new Set(normalized.map((entry) => entry.name)).size !== normalized.length) throw new Error('nimiapp archive entries must be unique');
412
+ function buildEocdBuffer(entryCount, centralSize, centralOffset) {
413
+ const end = Buffer.alloc(22);
414
+ end.writeUInt32LE(0x06054b50, 0);
415
+ end.writeUInt16LE(0, 4);
416
+ end.writeUInt16LE(0, 6);
417
+ end.writeUInt16LE(entryCount, 8);
418
+ end.writeUInt16LE(entryCount, 10);
419
+ end.writeUInt32LE(centralSize >>> 0, 12);
420
+ end.writeUInt32LE(centralOffset >>> 0, 16);
421
+ end.writeUInt16LE(0, 20);
422
+ return end;
423
+ }
424
+
425
+ function validateNimiappLayoutEntry(name, mode, uncompressedSize) {
426
+ const controlLimit = NIMIAPP_CONTROL_LIMITS.get(name);
427
+ if (controlLimit !== undefined) {
428
+ if (mode !== 0o644 || uncompressedSize <= 0 || uncompressedSize > controlLimit) {
429
+ throw new Error(`Invalid nimiapp control entry ${name}`);
430
+ }
431
+ return;
432
+ }
433
+ if (!name.startsWith('payload/')) {
434
+ throw new Error(`Invalid unexpected nimiapp root entry: ${name}`);
435
+ }
436
+ }
437
+
438
+ export function writeNimiAppArchive(entries, options = {}) {
439
+ const compress = options.compress !== false;
440
+ const maxArchiveBytes = options.maxArchiveBytes ?? NATIVE_MAX_ARCHIVE_BYTES;
441
+ const maxTotalUncompressedBytes = options.maxTotalUncompressedBytes ?? NATIVE_MAX_RELEASE_BYTES;
442
+ const normalized = entries.map((entry) => {
443
+ const name = zipEntryName(entry.name);
444
+ const rawName = Buffer.from(name, 'utf8');
445
+ const bytes = Buffer.isBuffer(entry.bytes) ? entry.bytes : Buffer.from(entry.bytes);
446
+ const mode = entry.mode === SYMBOLIC_LINK_MODE ? SYMBOLIC_LINK_MODE : entry.mode === 0o755 ? 0o755 : 0o644;
447
+ return { name, rawName, bytes, mode };
448
+ }).sort((left, right) => Buffer.compare(left.rawName, right.rawName));
449
+ if (normalized.length === 0 || normalized.length > MAX_ZIP32_ENTRIES) {
450
+ throw new Error('nimiapp archive requires between 1 and 65535 files');
451
+ }
452
+ let totalUncompressed = 0;
453
+ for (let index = 0; index < normalized.length; index += 1) {
454
+ const entry = normalized[index];
455
+ if (index > 0 && Buffer.compare(normalized[index - 1].rawName, entry.rawName) >= 0) {
456
+ throw new Error('nimiapp archive entries must be unique');
457
+ }
458
+ const uncompSize = entry.bytes.length;
459
+ if (uncompSize > NATIVE_MAX_ENTRY_BYTES || uncompSize >= 0xffffffff) {
460
+ throw new Error(`Archive entry is too large: ${entry.name}`);
461
+ }
462
+ if (entry.mode === SYMBOLIC_LINK_MODE && (uncompSize === 0 || uncompSize > MAX_SYMLINK_TARGET_BYTES)) {
463
+ throw new Error(`Invalid symbolic link target size: ${entry.name}`);
464
+ }
465
+ totalUncompressed += uncompSize;
466
+ if (totalUncompressed > maxTotalUncompressedBytes) {
467
+ throw new Error(`Archive uncompressed size exceeds ${maxTotalUncompressedBytes} bytes`);
468
+ }
469
+ }
470
+ const enforceExpansionBudget = totalUncompressed > EXPANSION_RATIO_FLOOR_BYTES;
292
471
 
293
472
  const localParts = [];
294
473
  const centralParts = [];
295
474
  let offset = 0;
475
+ let emittedUncompressed = 0;
296
476
  for (const entry of normalized) {
297
- if (entry.bytes.length > 0xffffffff) throw new Error(`Archive entry is too large: ${entry.name}`);
298
- const name = Buffer.from(entry.name, 'utf8');
299
- const crc = crc32(entry.bytes);
300
- const local = Buffer.alloc(30);
301
- local.writeUInt32LE(0x04034b50, 0);
302
- local.writeUInt16LE(20, 4);
303
- local.writeUInt16LE(0x0800, 6);
304
- local.writeUInt16LE(0, 8);
305
- local.writeUInt16LE(0, 10);
306
- local.writeUInt16LE(0x0021, 12);
307
- local.writeUInt32LE(crc, 14);
308
- local.writeUInt32LE(entry.bytes.length, 18);
309
- local.writeUInt32LE(entry.bytes.length, 22);
310
- local.writeUInt16LE(name.length, 26);
311
- local.writeUInt16LE(0, 28);
312
- localParts.push(local, name, entry.bytes);
313
-
314
- const central = Buffer.alloc(46);
315
- central.writeUInt32LE(0x02014b50, 0);
316
- central.writeUInt16LE(0x0314, 4);
317
- central.writeUInt16LE(20, 6);
318
- central.writeUInt16LE(0x0800, 8);
319
- central.writeUInt16LE(0, 10);
320
- central.writeUInt16LE(0, 12);
321
- central.writeUInt16LE(0x0021, 14);
322
- central.writeUInt32LE(crc, 16);
323
- central.writeUInt32LE(entry.bytes.length, 20);
324
- central.writeUInt32LE(entry.bytes.length, 24);
325
- central.writeUInt16LE(name.length, 28);
326
- central.writeUInt16LE(0, 30);
327
- central.writeUInt16LE(0, 32);
328
- central.writeUInt16LE(0, 34);
329
- central.writeUInt16LE(0, 36);
330
- central.writeUInt32LE(((entry.mode === SYMBOLIC_LINK_MODE ? entry.mode : 0o100000 | entry.mode) << 16) >>> 0, 38);
331
- central.writeUInt32LE(offset, 42);
332
- centralParts.push(central, name);
333
- offset += local.length + name.length + entry.bytes.length;
477
+ const uncompSize = entry.bytes.length;
478
+ const crc = uncompSize === 0 ? 0 : nativeCrc32(entry.bytes);
479
+ let method = ZIP_METHOD_STORE;
480
+ let payload = entry.bytes;
481
+ if (compress && entry.mode !== SYMBOLIC_LINK_MODE && uncompSize > 0) {
482
+ const deflated = deflateRawSync(entry.bytes, { level: DEFLATE_LEVEL });
483
+ const fitsBudget = !enforceExpansionBudget
484
+ || emittedUncompressed + uncompSize <= (offset + 30 + entry.rawName.length + deflated.length) * MAX_EXPANSION_RATIO;
485
+ if (deflated.length > 0 && deflated.length < uncompSize && fitsBudget) {
486
+ method = ZIP_METHOD_DEFLATE;
487
+ payload = deflated;
488
+ }
489
+ }
490
+ const compSize = payload.length;
491
+ const nextOffset = offset + 30 + entry.rawName.length + compSize;
492
+ if (nextOffset > maxArchiveBytes || nextOffset >= 0xffffffff) {
493
+ throw new Error(`Archive exceeds maximum size budget (${maxArchiveBytes} bytes)`);
494
+ }
495
+ const local = buildLocalHeaderBuffer(entry.rawName, method, crc, compSize, uncompSize);
496
+ localParts.push(local, entry.rawName, payload);
497
+ const central = buildCentralHeaderBuffer(
498
+ entry.rawName,
499
+ method,
500
+ crc,
501
+ compSize,
502
+ uncompSize,
503
+ encodeCanonicalExternalAttrs(entry.mode),
504
+ offset,
505
+ );
506
+ centralParts.push(central, entry.rawName);
507
+ offset = nextOffset;
508
+ emittedUncompressed += uncompSize;
334
509
  }
335
510
  const central = Buffer.concat(centralParts);
336
- const end = Buffer.alloc(22);
337
- end.writeUInt32LE(0x06054b50, 0);
338
- end.writeUInt16LE(0, 4);
339
- end.writeUInt16LE(0, 6);
340
- end.writeUInt16LE(normalized.length, 8);
341
- end.writeUInt16LE(normalized.length, 10);
342
- end.writeUInt32LE(central.length, 12);
343
- end.writeUInt32LE(offset, 16);
344
- end.writeUInt16LE(0, 20);
511
+ const finalSize = offset + central.length + 22;
512
+ if (finalSize > maxArchiveBytes || finalSize >= 0xffffffff) {
513
+ throw new Error(`Archive exceeds maximum size budget (${maxArchiveBytes} bytes)`);
514
+ }
515
+ if (totalUncompressed > EXPANSION_RATIO_FLOOR_BYTES && totalUncompressed > finalSize * MAX_EXPANSION_RATIO) {
516
+ throw new Error(`Archive expansion ratio exceeds ${MAX_EXPANSION_RATIO}x (${totalUncompressed} / ${finalSize})`);
517
+ }
518
+ const end = buildEocdBuffer(normalized.length, central.length, offset);
345
519
  return Buffer.concat([...localParts, central, end]);
346
520
  }
347
521
 
348
- export function readNimiAppArchive(bytes) {
522
+ async function writeFullBuffer(handle, buf, hash) {
523
+ let off = 0;
524
+ while (off < buf.length) {
525
+ const { bytesWritten } = await handle.write(buf, off, buf.length - off);
526
+ if (bytesWritten <= 0) throw new Error('App archive write did not make progress');
527
+ off += bytesWritten;
528
+ }
529
+ if (hash && buf.length > 0) hash.update(buf);
530
+ }
531
+
532
+ async function readExactFromHandle(handle, buf, position) {
533
+ let off = 0;
534
+ while (off < buf.length) {
535
+ const { bytesRead } = await handle.read(buf, off, buf.length - off, position + off);
536
+ if (bytesRead <= 0) throw new Error('Invalid nimiapp ZIP: unexpected end of archive');
537
+ off += bytesRead;
538
+ }
539
+ return buf;
540
+ }
541
+
542
+ async function streamDeflateFileToShard(sourcePath, shardPath, expectedSize, computeSha) {
543
+ const srcHandle = await fsp.open(sourcePath, 'r');
544
+ const shardHandle = await fsp.open(shardPath, 'w');
545
+ const def = createDeflateRaw({ level: DEFLATE_LEVEL });
546
+ let crc = 0;
547
+ let plainLen = 0;
548
+ let compSize = 0;
549
+ const entrySha = computeSha ? createHash('sha256') : null;
550
+ let writeChain = Promise.resolve();
551
+ let streamErr = null;
552
+ const done = new Promise((resolve, reject) => {
553
+ def.on('data', (chunk) => {
554
+ compSize += chunk.length;
555
+ const copy = Buffer.from(chunk);
556
+ writeChain = writeChain.then(() => writeFullBuffer(shardHandle, copy, null));
557
+ writeChain.catch((e) => {
558
+ if (!streamErr) {
559
+ streamErr = e;
560
+ def.destroy(e);
561
+ }
562
+ });
563
+ });
564
+ def.on('error', (err) => {
565
+ streamErr = err;
566
+ reject(err);
567
+ });
568
+ def.on('end', () => {
569
+ writeChain.then(resolve, reject);
570
+ });
571
+ });
572
+
573
+ try {
574
+ const readBuf = Buffer.allocUnsafe(STREAM_IO_CHUNK_BYTES);
575
+ let pos = 0;
576
+ while (pos < expectedSize && !streamErr) {
577
+ const toRead = Math.min(readBuf.length, expectedSize - pos);
578
+ const { bytesRead } = await srcHandle.read(readBuf, 0, toRead, pos);
579
+ if (bytesRead <= 0) throw new Error(`Pack source truncated during compression: ${sourcePath}`);
580
+ const slice = Buffer.from(readBuf.subarray(0, bytesRead));
581
+ plainLen += bytesRead;
582
+ crc = nativeCrc32(slice, crc);
583
+ if (entrySha) entrySha.update(slice);
584
+ if (!def.write(slice)) {
585
+ await new Promise((resolve) => {
586
+ const finish = () => {
587
+ def.off('drain', finish);
588
+ def.off('close', finish);
589
+ def.off('error', finish);
590
+ resolve();
591
+ };
592
+ def.once('drain', finish);
593
+ def.once('close', finish);
594
+ def.once('error', finish);
595
+ });
596
+ }
597
+ pos += bytesRead;
598
+ }
599
+ // Check no trailing growth occurred in source file.
600
+ const extraBuf = Buffer.allocUnsafe(1);
601
+ const { bytesRead: extraRead } = await srcHandle.read(extraBuf, 0, 1, pos);
602
+ if (extraRead > 0) throw new Error(`Pack source grew during compression: ${sourcePath}`);
603
+ if (!streamErr) def.end();
604
+ await done;
605
+ if (plainLen !== expectedSize) {
606
+ throw new Error(`Pack source size mismatch during compression: ${sourcePath}`);
607
+ }
608
+ return {
609
+ crc: crc >>> 0,
610
+ compSize,
611
+ plainLen,
612
+ entrySha256: entrySha ? entrySha.digest('hex') : null,
613
+ };
614
+ } finally {
615
+ await Promise.allSettled([srcHandle.close(), shardHandle.close()]);
616
+ }
617
+ }
618
+
619
+ async function copyFileIntoArchive(sourcePath, outHandle, expectedSize, expectedCrc, archiveHash, computeSha) {
620
+ const srcHandle = await fsp.open(sourcePath, 'r');
621
+ try {
622
+ const buf = Buffer.allocUnsafe(STREAM_IO_CHUNK_BYTES);
623
+ let pos = 0;
624
+ let crc = 0;
625
+ const entrySha = computeSha ? createHash('sha256') : null;
626
+ while (pos < expectedSize) {
627
+ const toRead = Math.min(buf.length, expectedSize - pos);
628
+ const { bytesRead } = await srcHandle.read(buf, 0, toRead, pos);
629
+ if (bytesRead <= 0) throw new Error(`Source file truncated while writing archive: ${sourcePath}`);
630
+ const slice = buf.subarray(0, bytesRead);
631
+ if (expectedCrc !== null) crc = nativeCrc32(slice, crc);
632
+ if (entrySha) entrySha.update(slice);
633
+ await writeFullBuffer(outHandle, slice, archiveHash);
634
+ pos += bytesRead;
635
+ }
636
+ const extraBuf = Buffer.allocUnsafe(1);
637
+ const { bytesRead: extraRead } = await srcHandle.read(extraBuf, 0, 1, pos);
638
+ if (extraRead > 0) throw new Error(`Source file grew while writing archive: ${sourcePath}`);
639
+ if (expectedCrc !== null && (crc >>> 0) !== (expectedCrc >>> 0)) {
640
+ throw new Error(`Source file changed while writing archive: ${sourcePath}`);
641
+ }
642
+ return entrySha ? entrySha.digest('hex') : null;
643
+ } finally {
644
+ await srcHandle.close();
645
+ }
646
+ }
647
+
648
+ export async function writeNimiAppArchiveToFile(filePath, entries, options = {}) {
649
+ const compress = options.compress !== false;
650
+ const maxArchiveBytes = options.maxArchiveBytes ?? NATIVE_MAX_ARCHIVE_BYTES;
651
+ const maxTotalUncompressedBytes = options.maxTotalUncompressedBytes ?? NATIVE_MAX_RELEASE_BYTES;
652
+ const hashEntryName = options.hashEntryName ?? null;
653
+ const normalized = entries.map((entry) => {
654
+ const name = zipEntryName(entry.name);
655
+ const rawName = Buffer.from(name, 'utf8');
656
+ const mode = entry.mode === SYMBOLIC_LINK_MODE ? SYMBOLIC_LINK_MODE : entry.mode === 0o755 ? 0o755 : 0o644;
657
+ if (entry.bytes !== undefined) {
658
+ const bytes = Buffer.isBuffer(entry.bytes) ? entry.bytes : Buffer.from(entry.bytes);
659
+ return { name, rawName, bytes, filePath: null, size: bytes.length, mode };
660
+ }
661
+ if (!entry.filePath || !Number.isSafeInteger(entry.size) || entry.size < 0) {
662
+ throw new Error(`Invalid archive entry descriptor: ${name}`);
663
+ }
664
+ return { name, rawName, bytes: null, filePath: entry.filePath, size: entry.size, mode };
665
+ }).sort((left, right) => Buffer.compare(left.rawName, right.rawName));
666
+
667
+ if (normalized.length === 0 || normalized.length > MAX_ZIP32_ENTRIES) {
668
+ throw new Error('nimiapp archive requires between 1 and 65535 files');
669
+ }
670
+ let totalUncompressed = 0;
671
+ for (let index = 0; index < normalized.length; index += 1) {
672
+ const entry = normalized[index];
673
+ if (index > 0 && Buffer.compare(normalized[index - 1].rawName, entry.rawName) >= 0) {
674
+ throw new Error('nimiapp archive entries must be unique');
675
+ }
676
+ if (entry.size > NATIVE_MAX_ENTRY_BYTES || entry.size >= 0xffffffff) {
677
+ throw new Error(`Archive entry is too large: ${entry.name}`);
678
+ }
679
+ if (entry.mode === SYMBOLIC_LINK_MODE && (entry.size === 0 || entry.size > MAX_SYMLINK_TARGET_BYTES)) {
680
+ throw new Error(`Invalid symbolic link target size: ${entry.name}`);
681
+ }
682
+ totalUncompressed += entry.size;
683
+ if (totalUncompressed > maxTotalUncompressedBytes) {
684
+ throw new Error(`Archive uncompressed size exceeds ${maxTotalUncompressedBytes} bytes`);
685
+ }
686
+ }
687
+
688
+ const enforceExpansionBudget = totalUncompressed > EXPANSION_RATIO_FLOOR_BYTES;
689
+
690
+ await fsp.mkdir(path.dirname(filePath), { recursive: true });
691
+ const tempPath = `${filePath}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`;
692
+ const shardPath = `${tempPath}.shard`;
693
+ const outHandle = await fsp.open(tempPath, 'w');
694
+ const archiveHash = createHash('sha256');
695
+ const centralParts = [];
696
+ let offset = 0;
697
+ let emittedUncompressed = 0;
698
+ let hashedEntrySha256 = null;
699
+ let renamed = false;
700
+
701
+ try {
702
+ for (const entry of normalized) {
703
+ const wantHash = hashEntryName !== null && entry.name === hashEntryName;
704
+ const uncompSize = entry.size;
705
+ let method = ZIP_METHOD_STORE;
706
+ let crc = 0;
707
+ let compSize = 0;
708
+
709
+ if (uncompSize === 0) {
710
+ // Short-circuit 0 B regular files: never create a stream with end = start - 1.
711
+ if (wantHash) hashedEntrySha256 = createHash('sha256').digest('hex');
712
+ const nextOffset = offset + 30 + entry.rawName.length;
713
+ if (nextOffset > maxArchiveBytes || nextOffset >= 0xffffffff) {
714
+ throw new Error(`Archive exceeds maximum size budget (${maxArchiveBytes} bytes)`);
715
+ }
716
+ const local = buildLocalHeaderBuffer(entry.rawName, ZIP_METHOD_STORE, 0, 0, 0);
717
+ await writeFullBuffer(outHandle, local, archiveHash);
718
+ await writeFullBuffer(outHandle, entry.rawName, archiveHash);
719
+ } else if (entry.bytes !== null || uncompSize <= STREAM_DEFLATE_THRESHOLD) {
720
+ const plain = entry.bytes !== null ? entry.bytes : await fsp.readFile(entry.filePath);
721
+ if (plain.length !== uncompSize) {
722
+ throw new Error(`Pack source size changed before archive write: ${entry.name}`);
723
+ }
724
+ if (wantHash) hashedEntrySha256 = createHash('sha256').update(plain).digest('hex');
725
+ crc = nativeCrc32(plain);
726
+ let payload = plain;
727
+ if (compress && entry.mode !== SYMBOLIC_LINK_MODE) {
728
+ const deflated = deflateRawSync(plain, { level: DEFLATE_LEVEL });
729
+ const fitsBudget = !enforceExpansionBudget
730
+ || emittedUncompressed + uncompSize <= (offset + 30 + entry.rawName.length + deflated.length) * MAX_EXPANSION_RATIO;
731
+ if (deflated.length > 0 && deflated.length < uncompSize && fitsBudget) {
732
+ method = ZIP_METHOD_DEFLATE;
733
+ payload = deflated;
734
+ }
735
+ }
736
+ compSize = payload.length;
737
+ const nextOffset = offset + 30 + entry.rawName.length + compSize;
738
+ if (nextOffset > maxArchiveBytes || nextOffset >= 0xffffffff) {
739
+ throw new Error(`Archive exceeds maximum size budget (${maxArchiveBytes} bytes)`);
740
+ }
741
+ const local = buildLocalHeaderBuffer(entry.rawName, method, crc, compSize, uncompSize);
742
+ await writeFullBuffer(outHandle, local, archiveHash);
743
+ await writeFullBuffer(outHandle, entry.rawName, archiveHash);
744
+ await writeFullBuffer(outHandle, payload, archiveHash);
745
+ } else if (compress) {
746
+ try {
747
+ const stats = await streamDeflateFileToShard(entry.filePath, shardPath, uncompSize, wantHash);
748
+ crc = stats.crc;
749
+ if (wantHash) hashedEntrySha256 = stats.entrySha256;
750
+ const fitsBudget = !enforceExpansionBudget
751
+ || emittedUncompressed + uncompSize <= (offset + 30 + entry.rawName.length + stats.compSize) * MAX_EXPANSION_RATIO;
752
+ if (stats.compSize > 0 && stats.compSize < uncompSize && fitsBudget) {
753
+ method = ZIP_METHOD_DEFLATE;
754
+ compSize = stats.compSize;
755
+ const nextOffset = offset + 30 + entry.rawName.length + compSize;
756
+ if (nextOffset > maxArchiveBytes || nextOffset >= 0xffffffff) {
757
+ throw new Error(`Archive exceeds maximum size budget (${maxArchiveBytes} bytes)`);
758
+ }
759
+ const local = buildLocalHeaderBuffer(entry.rawName, method, crc, compSize, uncompSize);
760
+ await writeFullBuffer(outHandle, local, archiveHash);
761
+ await writeFullBuffer(outHandle, entry.rawName, archiveHash);
762
+ await copyFileIntoArchive(shardPath, outHandle, compSize, null, archiveHash, false);
763
+ } else {
764
+ method = ZIP_METHOD_STORE;
765
+ compSize = uncompSize;
766
+ const nextOffset = offset + 30 + entry.rawName.length + compSize;
767
+ if (nextOffset > maxArchiveBytes || nextOffset >= 0xffffffff) {
768
+ throw new Error(`Archive exceeds maximum size budget (${maxArchiveBytes} bytes)`);
769
+ }
770
+ const local = buildLocalHeaderBuffer(entry.rawName, method, crc, compSize, uncompSize);
771
+ await writeFullBuffer(outHandle, local, archiveHash);
772
+ await writeFullBuffer(outHandle, entry.rawName, archiveHash);
773
+ const storeSha = await copyFileIntoArchive(entry.filePath, outHandle, uncompSize, crc, archiveHash, wantHash);
774
+ if (wantHash && storeSha !== hashedEntrySha256) {
775
+ throw new Error(`Runtime entry changed while writing archive: ${entry.name}`);
776
+ }
777
+ }
778
+ } finally {
779
+ await fsp.rm(shardPath, { force: true });
780
+ }
781
+ } else {
782
+ // Large uncompressed Store entry
783
+ const srcHandle = await fsp.open(entry.filePath, 'r');
784
+ try {
785
+ const buf = Buffer.allocUnsafe(STREAM_IO_CHUNK_BYTES);
786
+ let pos = 0;
787
+ const entrySha = wantHash ? createHash('sha256') : null;
788
+ while (pos < uncompSize) {
789
+ const { bytesRead } = await srcHandle.read(buf, 0, Math.min(buf.length, uncompSize - pos), pos);
790
+ if (bytesRead <= 0) throw new Error(`Source file truncated: ${entry.name}`);
791
+ const slice = buf.subarray(0, bytesRead);
792
+ crc = nativeCrc32(slice, crc);
793
+ if (entrySha) entrySha.update(slice);
794
+ pos += bytesRead;
795
+ }
796
+ if (entrySha) hashedEntrySha256 = entrySha.digest('hex');
797
+ } finally {
798
+ await srcHandle.close();
799
+ }
800
+ method = ZIP_METHOD_STORE;
801
+ compSize = uncompSize;
802
+ const nextOffset = offset + 30 + entry.rawName.length + compSize;
803
+ if (nextOffset > maxArchiveBytes || nextOffset >= 0xffffffff) {
804
+ throw new Error(`Archive exceeds maximum size budget (${maxArchiveBytes} bytes)`);
805
+ }
806
+ const local = buildLocalHeaderBuffer(entry.rawName, method, crc, compSize, uncompSize);
807
+ await writeFullBuffer(outHandle, local, archiveHash);
808
+ await writeFullBuffer(outHandle, entry.rawName, archiveHash);
809
+ await copyFileIntoArchive(entry.filePath, outHandle, uncompSize, crc, archiveHash, false);
810
+ }
811
+
812
+ const central = buildCentralHeaderBuffer(
813
+ entry.rawName,
814
+ method,
815
+ crc,
816
+ compSize,
817
+ uncompSize,
818
+ encodeCanonicalExternalAttrs(entry.mode),
819
+ offset,
820
+ );
821
+ centralParts.push(central, entry.rawName);
822
+ offset += 30 + entry.rawName.length + compSize;
823
+ emittedUncompressed += uncompSize;
824
+ }
825
+
826
+ const central = Buffer.concat(centralParts);
827
+ const finalSize = offset + central.length + 22;
828
+ if (finalSize > maxArchiveBytes || finalSize >= 0xffffffff) {
829
+ throw new Error(`Archive exceeds maximum size budget (${maxArchiveBytes} bytes)`);
830
+ }
831
+ if (totalUncompressed > EXPANSION_RATIO_FLOOR_BYTES && totalUncompressed > finalSize * MAX_EXPANSION_RATIO) {
832
+ throw new Error(`Archive expansion ratio exceeds ${MAX_EXPANSION_RATIO}x (${totalUncompressed} / ${finalSize})`);
833
+ }
834
+ const end = buildEocdBuffer(normalized.length, central.length, offset);
835
+ await writeFullBuffer(outHandle, central, archiveHash);
836
+ await writeFullBuffer(outHandle, end, archiveHash);
837
+ await outHandle.close();
838
+ await fsp.rename(tempPath, filePath);
839
+ renamed = true;
840
+ return {
841
+ size: finalSize,
842
+ sha256: archiveHash.digest('hex'),
843
+ totalUncompressed,
844
+ hashedEntrySha256,
845
+ };
846
+ } finally {
847
+ await outHandle.close().catch(() => {});
848
+ await fsp.rm(shardPath, { force: true }).catch(() => {});
849
+ if (!renamed) {
850
+ await fsp.rm(tempPath, { force: true }).catch(() => {});
851
+ }
852
+ }
853
+ }
854
+
855
+ function parseCentralAndValidateMetadata(archiveSize, eocd, cdBuf, options, readLocalSlice) {
856
+ const maxArchiveBytes = options.maxArchiveBytes ?? NATIVE_MAX_ARCHIVE_BYTES;
857
+ const maxTotalUncompressedBytes = options.maxTotalUncompressedBytes ?? NATIVE_MAX_RELEASE_BYTES;
858
+ const nimiappLayout = options.nimiappLayout === true;
859
+ if (archiveSize < 22 || archiveSize > maxArchiveBytes || archiveSize >= 0xffffffff) {
860
+ throw new Error('Invalid nimiapp ZIP archive size');
861
+ }
862
+ if (eocd.readUInt32LE(0) !== 0x06054b50) throw new Error('Invalid nimiapp ZIP end record');
863
+ const diskNumber = eocd.readUInt16LE(4);
864
+ const centralDisk = eocd.readUInt16LE(6);
865
+ const entriesOnDisk = eocd.readUInt16LE(8);
866
+ const count = eocd.readUInt16LE(10);
867
+ const centralSize = eocd.readUInt32LE(12);
868
+ const centralOffset = eocd.readUInt32LE(16);
869
+ const commentLen = eocd.readUInt16LE(20);
870
+ const endOffset = archiveSize - 22;
871
+ if (
872
+ diskNumber !== 0
873
+ || centralDisk !== 0
874
+ || commentLen !== 0
875
+ || entriesOnDisk !== count
876
+ || count === 0
877
+ || count > MAX_ZIP32_ENTRIES
878
+ || centralSize === 0
879
+ || centralSize === 0xffffffff
880
+ || centralOffset === 0xffffffff
881
+ || centralOffset + centralSize !== endOffset
882
+ ) {
883
+ throw new Error('Invalid nimiapp ZIP directory');
884
+ }
885
+ return { count, centralSize, centralOffset, maxTotalUncompressedBytes, nimiappLayout };
886
+ }
887
+
888
+ function validateCentralEntryFields(cdBuf, cursor, cdEnd, expectedOffset, centralOffset, prevRawName, nimiappLayout, maxTotalUncompressedBytes, totalUncompressed) {
889
+ if (cursor + 46 > cdEnd) throw new Error('Invalid nimiapp ZIP central entry truncated');
890
+ if (cdBuf.readUInt32LE(cursor) !== 0x02014b50) throw new Error('Invalid nimiapp ZIP central entry');
891
+ const creatorVersion = cdBuf.readUInt16LE(cursor + 4);
892
+ const readerVersion = cdBuf.readUInt16LE(cursor + 6);
893
+ const flags = cdBuf.readUInt16LE(cursor + 8);
894
+ const method = cdBuf.readUInt16LE(cursor + 10);
895
+ const modTime = cdBuf.readUInt16LE(cursor + 12);
896
+ const modDate = cdBuf.readUInt16LE(cursor + 14);
897
+ const expectedCrc = cdBuf.readUInt32LE(cursor + 16);
898
+ const compSize = cdBuf.readUInt32LE(cursor + 20);
899
+ const uncompSize = cdBuf.readUInt32LE(cursor + 24);
900
+ const nameLen = cdBuf.readUInt16LE(cursor + 28);
901
+ const extraLen = cdBuf.readUInt16LE(cursor + 30);
902
+ const commentLen = cdBuf.readUInt16LE(cursor + 32);
903
+ const diskStart = cdBuf.readUInt16LE(cursor + 34);
904
+ const internalAttrs = cdBuf.readUInt16LE(cursor + 36);
905
+ const externalAttrs = cdBuf.readUInt32LE(cursor + 38);
906
+ const localOffset = cdBuf.readUInt32LE(cursor + 42);
907
+ if (
908
+ creatorVersion !== ZIP_CREATOR_UNIX
909
+ || readerVersion !== ZIP_READER_VERSION
910
+ || flags !== ZIP_FLAGS_UTF8
911
+ || extraLen !== 0
912
+ || commentLen !== 0
913
+ || diskStart !== 0
914
+ || internalAttrs !== 0
915
+ || compSize === 0xffffffff
916
+ || uncompSize === 0xffffffff
917
+ || localOffset === 0xffffffff
918
+ || nameLen === 0
919
+ || nameLen > MAX_ARCHIVE_ENTRY_NAME_BYTES
920
+ || cursor + 46 + nameLen > cdEnd
921
+ ) {
922
+ throw new Error('Invalid nimiapp ZIP entry header');
923
+ }
924
+ const mode = parseCanonicalExternalAttrs(externalAttrs);
925
+ const rawName = cdBuf.subarray(cursor + 46, cursor + 46 + nameLen);
926
+ const name = zipEntryName(decodeStrictUtf8(rawName, 'nimiapp ZIP entry name'));
927
+ if (prevRawName !== null && Buffer.compare(prevRawName, rawName) >= 0) {
928
+ throw new Error('Invalid nimiapp ZIP entries are not canonical');
929
+ }
930
+ if (mode === SYMBOLIC_LINK_MODE) {
931
+ if (method !== ZIP_METHOD_STORE || compSize !== uncompSize || uncompSize === 0 || uncompSize > MAX_SYMLINK_TARGET_BYTES) {
932
+ throw new Error(`Invalid nimiapp ZIP symbolic link entry: ${name}`);
933
+ }
934
+ } else if (method === ZIP_METHOD_STORE) {
935
+ if (compSize !== uncompSize || uncompSize > NATIVE_MAX_ENTRY_BYTES || (uncompSize === 0 && expectedCrc !== 0)) {
936
+ throw new Error(`Invalid nimiapp ZIP Store entry: ${name}`);
937
+ }
938
+ } else if (method === ZIP_METHOD_DEFLATE) {
939
+ if (compSize === 0 || uncompSize === 0 || compSize >= uncompSize || uncompSize > NATIVE_MAX_ENTRY_BYTES) {
940
+ throw new Error(`Invalid nimiapp ZIP Deflate entry: ${name}`);
941
+ }
942
+ } else {
943
+ throw new Error(`Invalid nimiapp ZIP unsupported compression method ${method}: ${name}`);
944
+ }
945
+ if (nimiappLayout) {
946
+ validateNimiappLayoutEntry(name, mode, uncompSize);
947
+ }
948
+ if (localOffset !== expectedOffset) {
949
+ throw new Error(`Invalid nimiapp ZIP non-contiguous local offset: ${name}`);
950
+ }
951
+ const dataOffset = localOffset + 30 + nameLen;
952
+ const nextOffset = dataOffset + compSize;
953
+ if (nextOffset < dataOffset || nextOffset > centralOffset) {
954
+ throw new Error(`Invalid nimiapp ZIP local data bounds: ${name}`);
955
+ }
956
+ const nextTotalUncompressed = totalUncompressed + uncompSize;
957
+ if (nextTotalUncompressed > maxTotalUncompressedBytes) {
958
+ throw new Error(`Invalid nimiapp ZIP uncompressed size exceeds ${maxTotalUncompressedBytes} bytes`);
959
+ }
960
+ return {
961
+ name,
962
+ rawName,
963
+ mode,
964
+ method,
965
+ modTime,
966
+ modDate,
967
+ expectedCrc,
968
+ compSize,
969
+ uncompSize,
970
+ localOffset,
971
+ dataOffset,
972
+ nextOffset,
973
+ nextCursor: cursor + 46 + nameLen,
974
+ nextTotalUncompressed,
975
+ };
976
+ }
977
+
978
+ function assertLocalHeaderMatches(localBuf, meta) {
979
+ if (
980
+ localBuf.length !== 30 + meta.rawName.length
981
+ || localBuf.readUInt32LE(0) !== 0x04034b50
982
+ || localBuf.readUInt16LE(4) !== ZIP_READER_VERSION
983
+ || localBuf.readUInt16LE(6) !== ZIP_FLAGS_UTF8
984
+ || localBuf.readUInt16LE(8) !== meta.method
985
+ || localBuf.readUInt16LE(10) !== meta.modTime
986
+ || localBuf.readUInt16LE(12) !== meta.modDate
987
+ || localBuf.readUInt32LE(14) !== meta.expectedCrc
988
+ || localBuf.readUInt32LE(18) !== meta.compSize
989
+ || localBuf.readUInt32LE(22) !== meta.uncompSize
990
+ || localBuf.readUInt16LE(26) !== meta.rawName.length
991
+ || localBuf.readUInt16LE(28) !== 0
992
+ || !localBuf.subarray(30).equals(meta.rawName)
993
+ ) {
994
+ throw new Error(`Invalid nimiapp ZIP local header mismatch: ${meta.name}`);
995
+ }
996
+ }
997
+
998
+ export function readNimiAppArchive(bytes, options = {}) {
349
999
  const archive = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes);
350
- if (archive.length < 22 || archive.readUInt32LE(archive.length - 22) !== 0x06054b50) throw new Error('Invalid nimiapp ZIP end record');
351
- const endOffset = archive.length - 22;
352
- const count = archive.readUInt16LE(endOffset + 10);
353
- const centralSize = archive.readUInt32LE(endOffset + 12);
354
- const centralOffset = archive.readUInt32LE(endOffset + 16);
355
- if (centralOffset + centralSize !== endOffset || count !== archive.readUInt16LE(endOffset + 8)) throw new Error('Invalid nimiapp ZIP directory');
356
- const entries = new Map();
357
- let cursor = centralOffset;
1000
+ const maxArchiveBytes = options.maxArchiveBytes ?? NATIVE_MAX_ARCHIVE_BYTES;
1001
+ const retainPredicate = typeof options.retainPredicate === 'function' ? options.retainPredicate : null;
1002
+ if (archive.length < 22 || archive.length > maxArchiveBytes || archive.length >= 0xffffffff) {
1003
+ throw new Error('Invalid nimiapp ZIP end record');
1004
+ }
1005
+ const eocd = archive.subarray(archive.length - 22);
1006
+ const { count, centralSize, centralOffset, maxTotalUncompressedBytes, nimiappLayout } =
1007
+ parseCentralAndValidateMetadata(archive.length, eocd, null, options);
1008
+ const cdBuf = archive.subarray(centralOffset, centralOffset + centralSize);
1009
+ const parsed = [];
1010
+ let cursor = 0;
1011
+ let expectedOffset = 0;
1012
+ let totalUncompressed = 0;
1013
+ let prevRawName = null;
358
1014
  for (let index = 0; index < count; index += 1) {
359
- if (archive.readUInt32LE(cursor) !== 0x02014b50) throw new Error('Invalid nimiapp ZIP central entry');
360
- const method = archive.readUInt16LE(cursor + 10);
361
- const expectedCrc = archive.readUInt32LE(cursor + 16);
362
- const size = archive.readUInt32LE(cursor + 24);
363
- const nameLength = archive.readUInt16LE(cursor + 28);
364
- const extraLength = archive.readUInt16LE(cursor + 30);
365
- const commentLength = archive.readUInt16LE(cursor + 32);
366
- const localOffset = archive.readUInt32LE(cursor + 42);
367
- const unixMode = archive.readUInt32LE(cursor + 38) >>> 16;
368
- const fileType = unixMode & 0o170000;
369
- const specialBits = unixMode & 0o7000;
370
- let mode;
371
- if (unixMode === SYMBOLIC_LINK_MODE) {
372
- mode = SYMBOLIC_LINK_MODE;
373
- } else if ((fileType === 0o100000 || fileType === 0) && specialBits === 0) {
374
- mode = unixMode & 0o777;
1015
+ const meta = validateCentralEntryFields(
1016
+ cdBuf,
1017
+ cursor,
1018
+ centralSize,
1019
+ expectedOffset,
1020
+ centralOffset,
1021
+ prevRawName,
1022
+ nimiappLayout,
1023
+ maxTotalUncompressedBytes,
1024
+ totalUncompressed,
1025
+ );
1026
+ const localBuf = archive.subarray(meta.localOffset, meta.dataOffset);
1027
+ assertLocalHeaderMatches(localBuf, meta);
1028
+ parsed.push(meta);
1029
+ cursor = meta.nextCursor;
1030
+ expectedOffset = meta.nextOffset;
1031
+ totalUncompressed = meta.nextTotalUncompressed;
1032
+ prevRawName = meta.rawName;
1033
+ }
1034
+ if (cursor !== centralSize || expectedOffset !== centralOffset) {
1035
+ throw new Error('Invalid nimiapp ZIP directory layout');
1036
+ }
1037
+ if (totalUncompressed > EXPANSION_RATIO_FLOOR_BYTES && totalUncompressed > archive.length * MAX_EXPANSION_RATIO) {
1038
+ throw new Error(`Invalid nimiapp ZIP expansion ratio exceeds ${MAX_EXPANSION_RATIO}x`);
1039
+ }
1040
+
1041
+ const entries = new Map();
1042
+ for (const meta of parsed) {
1043
+ const rawSlice = archive.subarray(meta.dataOffset, meta.dataOffset + meta.compSize);
1044
+ if (rawSlice.length !== meta.compSize) {
1045
+ throw new Error(`Invalid nimiapp ZIP truncated entry: ${meta.name}`);
1046
+ }
1047
+ let plain;
1048
+ if (meta.method === ZIP_METHOD_STORE) {
1049
+ if (meta.uncompSize > 0 && nativeCrc32(rawSlice) !== meta.expectedCrc) {
1050
+ throw new Error(`Invalid nimiapp ZIP entry digest mismatch: ${meta.name}`);
1051
+ }
1052
+ plain = rawSlice;
375
1053
  } else {
376
- throw new Error('Unsupported nimiapp ZIP entry mode');
377
- }
378
- if (method !== 0 || extraLength !== 0 || commentLength !== 0) throw new Error('Unsupported nimiapp ZIP entry encoding');
379
- if (mode !== 0o644 && mode !== 0o755 && mode !== SYMBOLIC_LINK_MODE) throw new Error('Unsupported nimiapp ZIP entry mode');
380
- const name = zipEntryName(archive.subarray(cursor + 46, cursor + 46 + nameLength).toString('utf8'));
381
- if (entries.has(name) || archive.readUInt32LE(localOffset) !== 0x04034b50) throw new Error('Invalid or duplicate nimiapp ZIP entry');
382
- const localNameLength = archive.readUInt16LE(localOffset + 26);
383
- const localExtraLength = archive.readUInt16LE(localOffset + 28);
384
- const localName = archive.subarray(localOffset + 30, localOffset + 30 + localNameLength).toString('utf8');
385
- if (localName !== name || localExtraLength !== 0 || archive.readUInt16LE(localOffset + 8) !== 0) {
386
- throw new Error('Invalid nimiapp ZIP local entry');
387
- }
388
- const dataOffset = localOffset + 30 + localNameLength + localExtraLength;
389
- const payload = archive.subarray(dataOffset, dataOffset + size);
390
- if (payload.length !== size || crc32(payload) !== expectedCrc) throw new Error(`nimiapp ZIP entry digest mismatch: ${name}`);
391
- entries.set(name, Object.freeze({ bytes: Buffer.from(payload), mode }));
392
- cursor += 46 + nameLength;
393
- }
394
- if (cursor !== centralOffset + centralSize) throw new Error('Invalid nimiapp ZIP directory size');
395
- const names = [...entries.keys()];
396
- if (names.some((name, index) => index > 0 && compareText(names[index - 1], name) >= 0)) throw new Error('nimiapp ZIP entries are not canonical');
1054
+ let inflated;
1055
+ try {
1056
+ inflated = inflateRawSync(rawSlice, { maxOutputLength: meta.uncompSize, info: true });
1057
+ } catch (error) {
1058
+ throw new Error(`Invalid nimiapp ZIP deflate payload for ${meta.name}: ${error instanceof Error ? error.message : String(error)}`);
1059
+ }
1060
+ if (inflated.buffer.length !== meta.uncompSize || inflated.engine.bytesWritten !== meta.compSize) {
1061
+ throw new Error(`Invalid nimiapp ZIP deflate length or trailing bytes: ${meta.name}`);
1062
+ }
1063
+ if (nativeCrc32(inflated.buffer) !== meta.expectedCrc) {
1064
+ throw new Error(`Invalid nimiapp ZIP entry digest mismatch: ${meta.name}`);
1065
+ }
1066
+ plain = inflated.buffer;
1067
+ }
1068
+ const retain = meta.mode === SYMBOLIC_LINK_MODE || !retainPredicate || retainPredicate(meta.name, { mode: meta.mode, size: meta.uncompSize });
1069
+ entries.set(meta.name, Object.freeze({
1070
+ bytes: retain ? Buffer.from(plain) : null,
1071
+ size: meta.uncompSize,
1072
+ mode: meta.mode,
1073
+ }));
1074
+ }
397
1075
  return entries;
398
1076
  }
399
1077
 
1078
+ async function readStoreEntryFromHandle(handle, meta, retain, budgetState) {
1079
+ if (meta.uncompSize === 0) {
1080
+ return retain ? Buffer.alloc(0) : null;
1081
+ }
1082
+ const buf = Buffer.allocUnsafe(Math.min(STREAM_IO_CHUNK_BYTES, meta.compSize));
1083
+ let offset = 0;
1084
+ let crc = 0;
1085
+ const chunks = retain ? [] : null;
1086
+ while (offset < meta.compSize) {
1087
+ const toRead = Math.min(buf.length, meta.compSize - offset);
1088
+ const { bytesRead } = await handle.read(buf, 0, toRead, meta.dataOffset + offset);
1089
+ if (bytesRead <= 0) throw new Error(`Invalid nimiapp ZIP truncated Store entry: ${meta.name}`);
1090
+ const slice = buf.subarray(0, bytesRead);
1091
+ budgetState.total += bytesRead;
1092
+ if (budgetState.total > budgetState.maxTotal) {
1093
+ throw new Error(`Invalid nimiapp ZIP uncompressed budget exceeded: ${meta.name}`);
1094
+ }
1095
+ crc = nativeCrc32(slice, crc);
1096
+ if (chunks) chunks.push(Buffer.from(slice));
1097
+ offset += bytesRead;
1098
+ }
1099
+ if ((crc >>> 0) !== (meta.expectedCrc >>> 0)) {
1100
+ throw new Error(`Invalid nimiapp ZIP entry digest mismatch: ${meta.name}`);
1101
+ }
1102
+ return chunks ? Buffer.concat(chunks) : null;
1103
+ }
1104
+
1105
+ async function readDeflateEntryFromHandle(handle, meta, retain, budgetState) {
1106
+ // Never rely on createInflateRaw({ maxOutputLength }): Node v24 Transform
1107
+ // silently ignores it. Enforce per-entry and total uncompressed bounds
1108
+ // strictly inside our single bounded consumer before updating CRC or retaining.
1109
+ const inf = createInflateRaw();
1110
+ let outLen = 0;
1111
+ let crc = 0;
1112
+ let aborted = null;
1113
+ const chunks = retain ? [] : null;
1114
+ const done = new Promise((resolve, reject) => {
1115
+ inf.on('data', (chunk) => {
1116
+ if (aborted) return;
1117
+ if (outLen + chunk.length > meta.uncompSize || budgetState.total + chunk.length > budgetState.maxTotal) {
1118
+ aborted = new Error(`Invalid nimiapp ZIP deflate uncompressed overflow: ${meta.name}`);
1119
+ inf.destroy(aborted);
1120
+ return;
1121
+ }
1122
+ outLen += chunk.length;
1123
+ budgetState.total += chunk.length;
1124
+ crc = nativeCrc32(chunk, crc);
1125
+ if (chunks) chunks.push(Buffer.from(chunk));
1126
+ });
1127
+ inf.on('error', (error) => {
1128
+ const wrapped = error === aborted
1129
+ ? error
1130
+ : new Error(`Invalid nimiapp ZIP deflate payload for ${meta.name}: ${error instanceof Error ? error.message : String(error)}`);
1131
+ aborted = wrapped;
1132
+ reject(wrapped);
1133
+ });
1134
+ inf.on('end', () => {
1135
+ resolve();
1136
+ });
1137
+ });
1138
+
1139
+ const buf = Buffer.allocUnsafe(Math.min(STREAM_IO_CHUNK_BYTES, meta.compSize));
1140
+ let offset = 0;
1141
+ while (offset < meta.compSize && !aborted) {
1142
+ const toRead = Math.min(buf.length, meta.compSize - offset);
1143
+ const { bytesRead } = await handle.read(buf, 0, toRead, meta.dataOffset + offset);
1144
+ if (bytesRead <= 0) {
1145
+ const truncErr = new Error(`Invalid nimiapp ZIP truncated Deflate entry: ${meta.name}`);
1146
+ aborted = truncErr;
1147
+ inf.destroy(truncErr);
1148
+ break;
1149
+ }
1150
+ const slice = Buffer.from(buf.subarray(0, bytesRead));
1151
+ if (!inf.write(slice)) {
1152
+ await new Promise((resolve) => {
1153
+ const finish = () => {
1154
+ inf.off('drain', finish);
1155
+ inf.off('close', finish);
1156
+ inf.off('error', finish);
1157
+ resolve();
1158
+ };
1159
+ inf.once('drain', finish);
1160
+ inf.once('close', finish);
1161
+ inf.once('error', finish);
1162
+ });
1163
+ }
1164
+ offset += bytesRead;
1165
+ }
1166
+ if (!aborted) inf.end();
1167
+ await done;
1168
+ if (outLen !== meta.uncompSize || inf.bytesWritten !== meta.compSize) {
1169
+ throw new Error(`Invalid nimiapp ZIP deflate length or trailing bytes: ${meta.name}`);
1170
+ }
1171
+ if ((crc >>> 0) !== (meta.expectedCrc >>> 0)) {
1172
+ throw new Error(`Invalid nimiapp ZIP entry digest mismatch: ${meta.name}`);
1173
+ }
1174
+ return chunks ? Buffer.concat(chunks) : null;
1175
+ }
1176
+
1177
+ export async function readNimiAppArchiveFromFile(source, options = {}) {
1178
+ const retainPredicate = typeof options.retainPredicate === 'function' ? options.retainPredicate : null;
1179
+ let handle;
1180
+ let archiveSize;
1181
+ let ownHandle = false;
1182
+ if (typeof source === 'string') {
1183
+ handle = await fsp.open(source, 'r');
1184
+ ownHandle = true;
1185
+ const stat = await handle.stat();
1186
+ if (!stat.isFile()) {
1187
+ await handle.close();
1188
+ throw new Error('Invalid nimiapp ZIP archive source');
1189
+ }
1190
+ archiveSize = stat.size;
1191
+ } else if (source && source.handle && Number.isSafeInteger(source.size)) {
1192
+ handle = source.handle;
1193
+ archiveSize = source.size;
1194
+ } else {
1195
+ throw new Error('Invalid nimiapp ZIP archive source');
1196
+ }
1197
+
1198
+ try {
1199
+ const maxArchiveBytes = options.maxArchiveBytes ?? NATIVE_MAX_ARCHIVE_BYTES;
1200
+ if (archiveSize < 22 || archiveSize > maxArchiveBytes || archiveSize >= 0xffffffff) {
1201
+ throw new Error('Invalid nimiapp ZIP archive size');
1202
+ }
1203
+ const eocd = await readExactFromHandle(handle, Buffer.allocUnsafe(22), archiveSize - 22);
1204
+ const { count, centralSize, centralOffset, maxTotalUncompressedBytes, nimiappLayout } =
1205
+ parseCentralAndValidateMetadata(archiveSize, eocd, null, options);
1206
+ const cdBuf = await readExactFromHandle(handle, Buffer.allocUnsafe(centralSize), centralOffset);
1207
+ const parsed = [];
1208
+ let cursor = 0;
1209
+ let expectedOffset = 0;
1210
+ let totalUncompressed = 0;
1211
+ let prevRawName = null;
1212
+ for (let index = 0; index < count; index += 1) {
1213
+ const meta = validateCentralEntryFields(
1214
+ cdBuf,
1215
+ cursor,
1216
+ centralSize,
1217
+ expectedOffset,
1218
+ centralOffset,
1219
+ prevRawName,
1220
+ nimiappLayout,
1221
+ maxTotalUncompressedBytes,
1222
+ totalUncompressed,
1223
+ );
1224
+ const localBuf = await readExactFromHandle(handle, Buffer.allocUnsafe(30 + meta.rawName.length), meta.localOffset);
1225
+ assertLocalHeaderMatches(localBuf, meta);
1226
+ parsed.push(meta);
1227
+ cursor = meta.nextCursor;
1228
+ expectedOffset = meta.nextOffset;
1229
+ totalUncompressed = meta.nextTotalUncompressed;
1230
+ prevRawName = meta.rawName;
1231
+ }
1232
+ if (cursor !== centralSize || expectedOffset !== centralOffset) {
1233
+ throw new Error('Invalid nimiapp ZIP directory layout');
1234
+ }
1235
+ if (totalUncompressed > EXPANSION_RATIO_FLOOR_BYTES && totalUncompressed > archiveSize * MAX_EXPANSION_RATIO) {
1236
+ throw new Error(`Invalid nimiapp ZIP expansion ratio exceeds ${MAX_EXPANSION_RATIO}x`);
1237
+ }
1238
+
1239
+ const entries = new Map();
1240
+ const budgetState = { total: 0, maxTotal: maxTotalUncompressedBytes };
1241
+ for (const meta of parsed) {
1242
+ const retain = meta.mode === SYMBOLIC_LINK_MODE || !retainPredicate || retainPredicate(meta.name, { mode: meta.mode, size: meta.uncompSize });
1243
+ const data = meta.method === ZIP_METHOD_STORE
1244
+ ? await readStoreEntryFromHandle(handle, meta, retain, budgetState)
1245
+ : await readDeflateEntryFromHandle(handle, meta, retain, budgetState);
1246
+ entries.set(meta.name, Object.freeze({
1247
+ bytes: data,
1248
+ size: meta.uncompSize,
1249
+ mode: meta.mode,
1250
+ }));
1251
+ }
1252
+ return entries;
1253
+ } finally {
1254
+ if (ownHandle) await handle.close().catch(() => {});
1255
+ }
1256
+ }
1257
+
400
1258
  function readNativePackProfile(targetDir) {
401
1259
  const profile = readYaml(path.join(targetDir, BUILD_PROFILE_PATH), BUILD_PROFILE_PATH);
402
1260
  assertDesktopHostSupport(profile.build_profile_ref);
@@ -421,8 +1279,8 @@ function readPackInputs(targetDir, targetId) {
421
1279
  const licensePath = path.join(targetDir, 'LICENSE');
422
1280
  if (!existsSync(licensePath)) throw new Error('App package LICENSE is missing');
423
1281
  const licenseStat = lstatSync(licensePath);
424
- if (!licenseStat.isFile() || licenseStat.isSymbolicLink() || licenseStat.size === 0) {
425
- throw new Error('App package LICENSE must be a non-empty direct regular file');
1282
+ if (!licenseStat.isFile() || licenseStat.isSymbolicLink() || licenseStat.size === 0 || licenseStat.size > MAX_LICENSE_BYTES) {
1283
+ throw new Error(`App package LICENSE must be a non-empty direct regular file within ${MAX_LICENSE_BYTES} bytes`);
426
1284
  }
427
1285
  const manifestPath = path.join(targetDir, 'nimi.app.yaml');
428
1286
  const manifest = readYaml(manifestPath, 'nimi.app.yaml');
@@ -488,18 +1346,18 @@ export function classifyWindowsNativeTrustObservation(observation) {
488
1346
  throw new Error(`Windows Authenticode verification failed: status=${String(status)}, type=${String(signatureType)}, signer=${certificateSubject === null ? 'absent' : 'present'}`);
489
1347
  }
490
1348
 
491
- function observeProductionWindowsFacts(input, archivedRuntimeEntryBytes) {
1349
+ async function observeProductionWindowsFacts(input, expectedRuntimeSha256) {
492
1350
  if (process.platform !== 'win32' || process.arch !== 'x64') throw new Error('Production Windows pack must run on windows-x86_64');
493
1351
  const observed = observeWindowsExecutableFacts(input.runtimeHostPath);
494
- const currentRuntimeEntryBytes = readFileSync(input.runtimeHostPath);
495
- if (!archivedRuntimeEntryBytes.equals(currentRuntimeEntryBytes)) {
1352
+ const currentSha = await hashFilePath(input.runtimeHostPath);
1353
+ if (currentSha !== expectedRuntimeSha256) {
496
1354
  throw new Error('Production Runtime entry changed while native and execution facts were observed');
497
1355
  }
498
1356
  const nativeTrust = classifyWindowsNativeTrustObservation(observed.authenticode);
499
1357
  return { nativeTrust, executionProfile: observed.execution_profile };
500
1358
  }
501
1359
 
502
- function resolveTargetFacts(input, production, archivedRuntimeEntryBytes) {
1360
+ async function resolveTargetFacts(input, production, expectedRuntimeSha256) {
503
1361
  if (input.target.os === 'any') {
504
1362
  return {
505
1363
  nativeTrust: {
@@ -519,10 +1377,12 @@ function resolveTargetFacts(input, production, archivedRuntimeEntryBytes) {
519
1377
  }
520
1378
  if (input.target.os === 'macos') {
521
1379
  const facts = observeMacOSExecutableFacts(input.runtimeHostPath);
522
- if (!archivedRuntimeEntryBytes.equals(readFileSync(input.runtimeHostPath))) throw new Error('Production Runtime entry changed during macOS native observation');
1380
+ if ((await hashFilePath(input.runtimeHostPath)) !== expectedRuntimeSha256) {
1381
+ throw new Error('Production Runtime entry changed during macOS native observation');
1382
+ }
523
1383
  return facts;
524
1384
  }
525
- return observeProductionWindowsFacts(input, archivedRuntimeEntryBytes);
1385
+ return observeProductionWindowsFacts(input, expectedRuntimeSha256);
526
1386
  }
527
1387
 
528
1388
  function validateNativeExecutionFacts(nativeTrust, executionProfile, label, os) {
@@ -598,7 +1458,7 @@ function validateNativeExecutionFacts(nativeTrust, executionProfile, label, os)
598
1458
 
599
1459
  function readPackageManifestFromArchive(entries, label) {
600
1460
  const entry = entries.get('manifest.json');
601
- if (!entry) throw new Error(`${label} archive manifest.json is missing`);
1461
+ if (!entry || !entry.bytes) throw new Error(`${label} archive manifest.json is missing`);
602
1462
  try {
603
1463
  const manifest = JSON.parse(entry.bytes.toString('utf8'));
604
1464
  if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) throw new Error('root must be an object');
@@ -608,7 +1468,7 @@ function readPackageManifestFromArchive(entries, label) {
608
1468
  }
609
1469
  }
610
1470
 
611
- export function packAppTarget(cwd, options = {}) {
1471
+ export async function packAppTarget(cwd, options = {}) {
612
1472
  const targetDir = path.resolve(cwd, String(options.dir || '').trim() || '.');
613
1473
  const targetId = String(options.target || '').trim();
614
1474
  if (!targetId) throw new Error('nimi-app pack requires --target');
@@ -620,12 +1480,18 @@ export function packAppTarget(cwd, options = {}) {
620
1480
  const mode = isManagedWeb
621
1481
  ? 0o644
622
1482
  : name === input.runtimeEntry ? 0o755 : entry.mode;
623
- return { name, bytes: entry.bytes, mode };
1483
+ return {
1484
+ name,
1485
+ ...(entry.bytes !== undefined ? { bytes: entry.bytes } : { filePath: entry.filePath }),
1486
+ size: entry.size,
1487
+ mode,
1488
+ };
624
1489
  });
625
1490
  validatePayloadLinks(new Map(payloadEntries.map((entry) => [entry.name, entry])), input.target.os);
626
1491
  const runtimeEntry = payloadEntries.find((entry) => entry.name === input.runtimeEntry);
627
1492
  if (!runtimeEntry) throw new Error(`runtime_entry is missing from target payload: ${input.runtimeEntry}`);
628
- const { nativeTrust, executionProfile } = resolveTargetFacts(input, options.production === true, runtimeEntry.bytes);
1493
+ const expectedRuntimeSha256 = await hashFilePath(input.runtimeHostPath);
1494
+ const { nativeTrust, executionProfile } = await resolveTargetFacts(input, options.production === true, expectedRuntimeSha256);
629
1495
  const packageManifest = {
630
1496
  format: PACKAGE_FORMAT,
631
1497
  app_id: input.appId,
@@ -645,32 +1511,46 @@ export function packAppTarget(cwd, options = {}) {
645
1511
  ...Object.fromEntries(APP_INFO_DECLARATION_FIELDS.filter((key) => input.appInfo[key] !== undefined).map((key) => [key, input.appInfo[key]])),
646
1512
  ...(input.desktop !== undefined ? { desktop: input.desktop } : {}),
647
1513
  };
1514
+ const licenseBytes = readFileSync(input.licensePath);
1515
+ const manifestBytes = Buffer.from(canonicalJson(packageManifest));
1516
+ const declarationBytes = Buffer.from(stringifyYaml(declaration));
1517
+ if (manifestBytes.length > MAX_CONTROL_DOCUMENT_BYTES || declarationBytes.length > MAX_CONTROL_DOCUMENT_BYTES) {
1518
+ throw new Error('Control document exceeds 1 MiB');
1519
+ }
648
1520
  const archiveEntries = [
649
- { name: 'LICENSE', bytes: readFileSync(input.licensePath), mode: 0o644 },
650
- { name: 'manifest.json', bytes: Buffer.from(canonicalJson(packageManifest)), mode: 0o644 },
651
- { name: 'nimi.app.yaml', bytes: Buffer.from(stringifyYaml(declaration)), mode: 0o644 },
652
- { name: 'app-info.json', bytes: infoBytes, mode: 0o644 },
1521
+ { name: 'LICENSE', bytes: licenseBytes, size: licenseBytes.length, mode: 0o644 },
1522
+ { name: 'manifest.json', bytes: manifestBytes, size: manifestBytes.length, mode: 0o644 },
1523
+ { name: 'nimi.app.yaml', bytes: declarationBytes, size: declarationBytes.length, mode: 0o644 },
1524
+ { name: 'app-info.json', bytes: infoBytes, size: infoBytes.length, mode: 0o644 },
653
1525
  ...payloadEntries,
654
1526
  ];
655
1527
  validateCrossPlatformArchiveEntries(archiveEntries, input.target.os);
656
- if (isManagedWeb) {
657
- if (archiveEntries.length > MANAGED_WEB_MAX_RELEASE_ENTRIES) {
658
- throw new Error(`managed-web package exceeds ${MANAGED_WEB_MAX_RELEASE_ENTRIES} entries (${archiveEntries.length})`);
659
- }
660
- const totalUncompressedBytes = archiveEntries.reduce((sum, entry) => sum + entry.bytes.length, 0);
661
- if (totalUncompressedBytes > MANAGED_WEB_MAX_RELEASE_BYTES) {
662
- throw new Error(`managed-web package exceeds ${MANAGED_WEB_MAX_RELEASE_BYTES} bytes uncompressed (${totalUncompressedBytes})`);
663
- }
1528
+ const maxEntries = isManagedWeb ? MANAGED_WEB_MAX_RELEASE_ENTRIES : MAX_ZIP32_ENTRIES;
1529
+ const maxUncompressed = isManagedWeb ? MANAGED_WEB_MAX_RELEASE_BYTES : NATIVE_MAX_RELEASE_BYTES;
1530
+ const maxArchiveBytes = isManagedWeb ? MANAGED_WEB_MAX_ARCHIVE_BYTES : NATIVE_MAX_ARCHIVE_BYTES;
1531
+ if (archiveEntries.length > maxEntries) {
1532
+ throw new Error(`${isManagedWeb ? 'managed-web' : 'native'} package exceeds ${maxEntries} entries (${archiveEntries.length})`);
1533
+ }
1534
+ const totalUncompressedBytes = archiveEntries.reduce((sum, entry) => sum + entry.size, 0);
1535
+ if (totalUncompressedBytes > maxUncompressed) {
1536
+ throw new Error(`${isManagedWeb ? 'managed-web' : 'native'} package exceeds ${maxUncompressed} bytes uncompressed (${totalUncompressedBytes})`);
664
1537
  }
665
- const archive = writeNimiAppArchive(archiveEntries);
666
- const sha256 = hashAppArchive(archive);
667
1538
  const outputDir = path.join(targetDir, OUTPUT_DIR);
668
1539
  mkdirSync(outputDir, { recursive: true });
669
1540
  const stem = `${input.appId}-${input.version}-${input.targetId}`;
670
1541
  const artifactPath = path.join(outputDir, `${stem}.nimiapp`);
671
1542
  const metadataPath = path.join(outputDir, `${stem}.target.json`);
672
1543
  const appInfoPath = path.join(outputDir, `${stem}.app-info.json`);
673
- writeAppArchiveFile(artifactPath, archive);
1544
+ const written = await writeNimiAppArchiveToFile(artifactPath, archiveEntries, {
1545
+ compress: true,
1546
+ maxArchiveBytes,
1547
+ maxTotalUncompressedBytes: maxUncompressed,
1548
+ hashEntryName: input.runtimeEntry,
1549
+ });
1550
+ if (written.hashedEntrySha256 !== expectedRuntimeSha256) {
1551
+ await fsp.rm(artifactPath, { force: true }).catch(() => {});
1552
+ throw new Error('Production Runtime entry changed while writing archive');
1553
+ }
674
1554
  writeFileSync(appInfoPath, infoBytes);
675
1555
  const metadata = {
676
1556
  format: TARGET_METADATA_FORMAT,
@@ -680,8 +1560,8 @@ export function packAppTarget(cwd, options = {}) {
680
1560
  os: input.target.os,
681
1561
  arch: input.target.arch,
682
1562
  asset_name: path.basename(artifactPath),
683
- size: archive.length,
684
- sha256,
1563
+ size: written.size,
1564
+ sha256: written.sha256,
685
1565
  app_info: { asset_name: path.basename(appInfoPath), size: infoBytes.length, sha256: createHash('sha256').update(infoBytes).digest('hex') },
686
1566
  runtime_entry: input.runtimeEntry,
687
1567
  native_trust: packageManifest.native_trust,
@@ -691,7 +1571,7 @@ export function packAppTarget(cwd, options = {}) {
691
1571
  return { ok: true, command: 'pack', dir: targetDir, artifactPath, metadataPath, appInfoPath, ...metadata };
692
1572
  }
693
1573
 
694
- export function aggregateAppTargetCandidates(cwd, options = {}) {
1574
+ export async function aggregateAppTargetCandidates(cwd, options = {}) {
695
1575
  const targetDir = path.resolve(cwd, String(options.dir || '').trim() || '.');
696
1576
  const buildProfile = readNativePackProfile(targetDir);
697
1577
  const isManagedWebProfile = buildProfile.build_profile_ref === MANAGED_WEB_BUILD_PROFILE_REF;
@@ -713,7 +1593,7 @@ export function aggregateAppTargetCandidates(cwd, options = {}) {
713
1593
  throw new Error(`managed-web-pnpm-vite cannot aggregate non-universal target: ${target.target_id}`);
714
1594
  }
715
1595
  if (!isManagedWebProfile && target.target_id === 'desktop-universal') {
716
- throw new Error(`Native build profile cannot aggregate desktop-universal target`);
1596
+ throw new Error('Native build profile cannot aggregate desktop-universal target');
717
1597
  }
718
1598
  const expectedTarget = TARGETS[target.target_id];
719
1599
  if (!expectedTarget || target.os !== expectedTarget.os || target.arch !== expectedTarget.arch) {
@@ -721,7 +1601,9 @@ export function aggregateAppTargetCandidates(cwd, options = {}) {
721
1601
  }
722
1602
  const assetName = canonicalRelative(target.asset_name, `${metadataLabel}.asset_name`);
723
1603
  if (assetName !== path.basename(assetName)) throw new Error(`Target asset_name must be a direct file name: ${assetName}`);
724
- if (!Number.isSafeInteger(target.size) || target.size <= 0 || !/^[a-f0-9]{64}$/u.test(target.sha256)) {
1604
+ const maxArchiveBytes = target.os === 'any' ? MANAGED_WEB_MAX_ARCHIVE_BYTES : NATIVE_MAX_ARCHIVE_BYTES;
1605
+ const maxUncompressed = target.os === 'any' ? MANAGED_WEB_MAX_RELEASE_BYTES : NATIVE_MAX_RELEASE_BYTES;
1606
+ if (!Number.isSafeInteger(target.size) || target.size <= 0 || target.size > maxArchiveBytes || !/^[a-f0-9]{64}$/u.test(target.sha256)) {
725
1607
  throw new Error(`Target artifact size or SHA-256 is invalid: ${assetName}`);
726
1608
  }
727
1609
  const runtimeEntry = canonicalRelative(target.runtime_entry, `${metadataLabel}.runtime_entry`);
@@ -732,15 +1614,30 @@ export function aggregateAppTargetCandidates(cwd, options = {}) {
732
1614
  validateNativeExecutionFacts(target.native_trust, target.execution_profile, metadataLabel, target.os);
733
1615
  const artifactPath = path.join(outputDir, assetName);
734
1616
  if (!existsSync(artifactPath)) throw new Error(`Target artifact is missing: ${target.asset_name}`);
735
- const bytes = readAppArchiveFile(artifactPath);
736
- if (bytes.length !== target.size || hashAppArchive(bytes) !== target.sha256) throw new Error(`Target artifact changed after pack: ${target.asset_name}`);
737
- const entries = readNimiAppArchive(bytes);
1617
+
1618
+ let entries;
1619
+ const handle = await fsp.open(artifactPath, 'r');
1620
+ try {
1621
+ const stat = await handle.stat();
1622
+ if (!stat.isFile() || stat.size !== target.size || (await hashFileHandle(handle, stat.size)) !== target.sha256) {
1623
+ throw new Error(`Target artifact changed after pack: ${target.asset_name}`);
1624
+ }
1625
+ entries = await readNimiAppArchiveFromFile({ handle, size: stat.size }, {
1626
+ maxArchiveBytes,
1627
+ maxTotalUncompressedBytes: maxUncompressed,
1628
+ nimiappLayout: true,
1629
+ retainPredicate: (name) => NIMIAPP_CONTROL_LIMITS.has(name),
1630
+ });
1631
+ } finally {
1632
+ await handle.close();
1633
+ }
1634
+
738
1635
  const infoAsset = target.app_info;
739
1636
  if (infoAsset?.asset_name !== `${appId}-${version}-${target.target_id}.app-info.json` || !Number.isSafeInteger(infoAsset.size) || infoAsset.size <= 0 || infoAsset.size > APP_INFO_MAX_BYTES) throw new Error(`Target App info reference is invalid: ${target.target_id}`);
740
1637
  const infoPath = path.join(outputDir, infoAsset.asset_name);
741
1638
  if (!existsSync(infoPath)) throw new Error(`Target App info asset is missing: ${infoAsset.asset_name}`);
742
1639
  const infoBytes = readFileSync(infoPath);
743
- if (infoBytes.length !== infoAsset.size || createHash('sha256').update(infoBytes).digest('hex') !== infoAsset.sha256 || !entries.get('app-info.json')?.bytes.equals(infoBytes)) throw new Error(`Target App info changed or differs from archive: ${target.target_id}`);
1640
+ if (infoBytes.length !== infoAsset.size || createHash('sha256').update(infoBytes).digest('hex') !== infoAsset.sha256 || !entries.get('app-info.json')?.bytes?.equals(infoBytes)) throw new Error(`Target App info changed or differs from archive: ${target.target_id}`);
744
1641
  const info = validateAppInfo(JSON.parse(infoBytes));
745
1642
  if (info.app_id !== appId || info.version !== version || info.target_id !== target.target_id) throw new Error(`Target App info identity differs: ${target.target_id}`);
746
1643
  if (target.os === 'any' && info.storage_policy?.kind !== 'nimi-mediated-default') {
@@ -748,9 +1645,9 @@ export function aggregateAppTargetCandidates(cwd, options = {}) {
748
1645
  }
749
1646
  parsedInfos.push({ targetId: target.target_id, info });
750
1647
  validatePayloadLinks(entries, target.os);
751
- validateCrossPlatformArchiveEntries([...entries.entries()].map(([name, entry]) => ({ name, bytes: entry.bytes, mode: entry.mode })), target.os);
1648
+ validateCrossPlatformArchiveEntries([...entries.entries()].map(([name, entry]) => ({ name, size: entry.size, mode: entry.mode })), target.os);
752
1649
  const declarationEntry = entries.get('nimi.app.yaml');
753
- if (declarationEntry) {
1650
+ if (declarationEntry?.bytes) {
754
1651
  const declarationYamlText = declarationEntry.bytes.toString('utf8');
755
1652
  const archivedDeclaration = parseYaml(declarationYamlText);
756
1653
  validateManifestDesktop(archivedDeclaration?.desktop, `${target.asset_name} nimi.app.yaml desktop`, declarationYamlText);
@@ -772,7 +1669,7 @@ export function aggregateAppTargetCandidates(cwd, options = {}) {
772
1669
  throw new Error(`Target managed-web archive exceeds ${MANAGED_WEB_MAX_RELEASE_ENTRIES} entries: ${target.asset_name}`);
773
1670
  }
774
1671
  let totalUncompressedBytes = 0;
775
- for (const entry of entries.values()) totalUncompressedBytes += entry.bytes.length;
1672
+ for (const entry of entries.values()) totalUncompressedBytes += entry.size;
776
1673
  if (totalUncompressedBytes > MANAGED_WEB_MAX_RELEASE_BYTES) {
777
1674
  throw new Error(`Target managed-web archive exceeds ${MANAGED_WEB_MAX_RELEASE_BYTES} bytes uncompressed: ${target.asset_name}`);
778
1675
  }
@@ -796,9 +1693,13 @@ export function aggregateAppTargetCandidates(cwd, options = {}) {
796
1693
  throw new Error('Repository storefront media changed after target packing; rebuild targets and aggregate from the same commit');
797
1694
  }
798
1695
  const archiveEntries = [...mediaEntries.entries()]
799
- .sort(([left], [right]) => compareText(left, right))
1696
+ .sort(([left], [right]) => compareUtf8(left, right))
800
1697
  .map(([name, bytes]) => ({ name, bytes, mode: 0o644 }));
801
- const mediaArchive = writeNimiAppArchive(archiveEntries);
1698
+ const mediaArchive = writeNimiAppArchive(archiveEntries, {
1699
+ compress: false,
1700
+ maxArchiveBytes: STOREFRONT_ARCHIVE_MAX_BYTES,
1701
+ maxTotalUncompressedBytes: STOREFRONT_ARCHIVE_MAX_BYTES,
1702
+ });
802
1703
  if (mediaArchive.length > STOREFRONT_ARCHIVE_MAX_BYTES) {
803
1704
  throw new Error(`Storefront media archive exceeds ${STOREFRONT_ARCHIVE_MAX_BYTES} bytes`);
804
1705
  }
@@ -816,7 +1717,7 @@ export function aggregateAppTargetCandidates(cwd, options = {}) {
816
1717
  app_id: appId,
817
1718
  version,
818
1719
  ...(storefrontMedia ? { storefront_media: storefrontMedia } : {}),
819
- targets: targets.sort((left, right) => compareText(left.target_id, right.target_id)),
1720
+ targets: targets.sort((left, right) => compareUtf8(left.target_id, right.target_id)),
820
1721
  };
821
1722
  const candidatePath = path.join(outputDir, `${appId}-${version}.candidate.json`);
822
1723
  writeFileSync(candidatePath, canonicalJson(candidate));