@nimiplatform/app-tools 0.16.0-rc.13 → 0.16.0-rc.14
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/bin/nimi-app.mjs +1 -1
- package/lib/app-dependency-combinations.mjs +1 -0
- package/lib/app-pack.mjs +1063 -177
- package/lib/app-scaffold-profiles.mjs +119 -42
- package/lib/hosted-web-release.mjs +31 -5
- package/lib/index.mjs +3 -3
- package/lib/payload-links.mjs +96 -18
- package/package.json +5 -5
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
|
|
43
|
-
const
|
|
44
|
-
const
|
|
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 (
|
|
94
|
-
throw new Error(`
|
|
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
|
-
|
|
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(
|
|
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(
|
|
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),
|
|
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) =>
|
|
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
|
-
|
|
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,
|
|
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,892 @@ function collectPayload(payloadPath, os) {
|
|
|
259
354
|
return entries;
|
|
260
355
|
}
|
|
261
356
|
|
|
262
|
-
|
|
263
|
-
const
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
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
|
-
|
|
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
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
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
|
|
279
|
-
const
|
|
280
|
-
|
|
281
|
-
|
|
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
|
-
|
|
285
|
-
const
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
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
|
+
for (let index = 1; index < normalized.length; index += 1) {
|
|
453
|
+
if (Buffer.compare(normalized[index - 1].rawName, normalized[index].rawName) >= 0) {
|
|
454
|
+
throw new Error('nimiapp archive entries must be unique');
|
|
455
|
+
}
|
|
456
|
+
}
|
|
292
457
|
|
|
293
458
|
const localParts = [];
|
|
294
459
|
const centralParts = [];
|
|
295
460
|
let offset = 0;
|
|
461
|
+
let totalUncompressed = 0;
|
|
296
462
|
for (const entry of normalized) {
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
central
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
463
|
+
const uncompSize = entry.bytes.length;
|
|
464
|
+
if (uncompSize > NATIVE_MAX_ENTRY_BYTES || uncompSize >= 0xffffffff) {
|
|
465
|
+
throw new Error(`Archive entry is too large: ${entry.name}`);
|
|
466
|
+
}
|
|
467
|
+
if (entry.mode === SYMBOLIC_LINK_MODE && (uncompSize === 0 || uncompSize > MAX_SYMLINK_TARGET_BYTES)) {
|
|
468
|
+
throw new Error(`Invalid symbolic link target size: ${entry.name}`);
|
|
469
|
+
}
|
|
470
|
+
totalUncompressed += uncompSize;
|
|
471
|
+
if (totalUncompressed > maxTotalUncompressedBytes) {
|
|
472
|
+
throw new Error(`Archive uncompressed size exceeds ${maxTotalUncompressedBytes} bytes`);
|
|
473
|
+
}
|
|
474
|
+
const crc = uncompSize === 0 ? 0 : nativeCrc32(entry.bytes);
|
|
475
|
+
let method = ZIP_METHOD_STORE;
|
|
476
|
+
let payload = entry.bytes;
|
|
477
|
+
if (compress && entry.mode !== SYMBOLIC_LINK_MODE && uncompSize > 0) {
|
|
478
|
+
const deflated = deflateRawSync(entry.bytes, { level: DEFLATE_LEVEL });
|
|
479
|
+
if (deflated.length > 0 && deflated.length < uncompSize) {
|
|
480
|
+
method = ZIP_METHOD_DEFLATE;
|
|
481
|
+
payload = deflated;
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
const compSize = payload.length;
|
|
485
|
+
const nextOffset = offset + 30 + entry.rawName.length + compSize;
|
|
486
|
+
if (nextOffset > maxArchiveBytes || nextOffset >= 0xffffffff) {
|
|
487
|
+
throw new Error(`Archive exceeds maximum size budget (${maxArchiveBytes} bytes)`);
|
|
488
|
+
}
|
|
489
|
+
const local = buildLocalHeaderBuffer(entry.rawName, method, crc, compSize, uncompSize);
|
|
490
|
+
localParts.push(local, entry.rawName, payload);
|
|
491
|
+
const central = buildCentralHeaderBuffer(
|
|
492
|
+
entry.rawName,
|
|
493
|
+
method,
|
|
494
|
+
crc,
|
|
495
|
+
compSize,
|
|
496
|
+
uncompSize,
|
|
497
|
+
encodeCanonicalExternalAttrs(entry.mode),
|
|
498
|
+
offset,
|
|
499
|
+
);
|
|
500
|
+
centralParts.push(central, entry.rawName);
|
|
501
|
+
offset = nextOffset;
|
|
334
502
|
}
|
|
335
503
|
const central = Buffer.concat(centralParts);
|
|
336
|
-
const
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
end.
|
|
344
|
-
end.writeUInt16LE(0, 20);
|
|
504
|
+
const finalSize = offset + central.length + 22;
|
|
505
|
+
if (finalSize > maxArchiveBytes || finalSize >= 0xffffffff) {
|
|
506
|
+
throw new Error(`Archive exceeds maximum size budget (${maxArchiveBytes} bytes)`);
|
|
507
|
+
}
|
|
508
|
+
if (totalUncompressed > EXPANSION_RATIO_FLOOR_BYTES && totalUncompressed > finalSize * MAX_EXPANSION_RATIO) {
|
|
509
|
+
throw new Error(`Archive expansion ratio exceeds ${MAX_EXPANSION_RATIO}x (${totalUncompressed} / ${finalSize})`);
|
|
510
|
+
}
|
|
511
|
+
const end = buildEocdBuffer(normalized.length, central.length, offset);
|
|
345
512
|
return Buffer.concat([...localParts, central, end]);
|
|
346
513
|
}
|
|
347
514
|
|
|
348
|
-
|
|
515
|
+
async function writeFullBuffer(handle, buf, hash) {
|
|
516
|
+
let off = 0;
|
|
517
|
+
while (off < buf.length) {
|
|
518
|
+
const { bytesWritten } = await handle.write(buf, off, buf.length - off);
|
|
519
|
+
if (bytesWritten <= 0) throw new Error('App archive write did not make progress');
|
|
520
|
+
off += bytesWritten;
|
|
521
|
+
}
|
|
522
|
+
if (hash && buf.length > 0) hash.update(buf);
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
async function readExactFromHandle(handle, buf, position) {
|
|
526
|
+
let off = 0;
|
|
527
|
+
while (off < buf.length) {
|
|
528
|
+
const { bytesRead } = await handle.read(buf, off, buf.length - off, position + off);
|
|
529
|
+
if (bytesRead <= 0) throw new Error('Invalid nimiapp ZIP: unexpected end of archive');
|
|
530
|
+
off += bytesRead;
|
|
531
|
+
}
|
|
532
|
+
return buf;
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
async function streamDeflateFileToShard(sourcePath, shardPath, expectedSize, computeSha) {
|
|
536
|
+
const srcHandle = await fsp.open(sourcePath, 'r');
|
|
537
|
+
const shardHandle = await fsp.open(shardPath, 'w');
|
|
538
|
+
const def = createDeflateRaw({ level: DEFLATE_LEVEL });
|
|
539
|
+
let crc = 0;
|
|
540
|
+
let plainLen = 0;
|
|
541
|
+
let compSize = 0;
|
|
542
|
+
const entrySha = computeSha ? createHash('sha256') : null;
|
|
543
|
+
let writeChain = Promise.resolve();
|
|
544
|
+
let streamErr = null;
|
|
545
|
+
const done = new Promise((resolve, reject) => {
|
|
546
|
+
def.on('data', (chunk) => {
|
|
547
|
+
compSize += chunk.length;
|
|
548
|
+
const copy = Buffer.from(chunk);
|
|
549
|
+
writeChain = writeChain.then(() => writeFullBuffer(shardHandle, copy, null));
|
|
550
|
+
writeChain.catch((e) => {
|
|
551
|
+
if (!streamErr) {
|
|
552
|
+
streamErr = e;
|
|
553
|
+
def.destroy(e);
|
|
554
|
+
}
|
|
555
|
+
});
|
|
556
|
+
});
|
|
557
|
+
def.on('error', (err) => {
|
|
558
|
+
streamErr = err;
|
|
559
|
+
reject(err);
|
|
560
|
+
});
|
|
561
|
+
def.on('end', () => {
|
|
562
|
+
writeChain.then(resolve, reject);
|
|
563
|
+
});
|
|
564
|
+
});
|
|
565
|
+
|
|
566
|
+
try {
|
|
567
|
+
const readBuf = Buffer.allocUnsafe(STREAM_IO_CHUNK_BYTES);
|
|
568
|
+
let pos = 0;
|
|
569
|
+
while (pos < expectedSize && !streamErr) {
|
|
570
|
+
const toRead = Math.min(readBuf.length, expectedSize - pos);
|
|
571
|
+
const { bytesRead } = await srcHandle.read(readBuf, 0, toRead, pos);
|
|
572
|
+
if (bytesRead <= 0) throw new Error(`Pack source truncated during compression: ${sourcePath}`);
|
|
573
|
+
const slice = Buffer.from(readBuf.subarray(0, bytesRead));
|
|
574
|
+
plainLen += bytesRead;
|
|
575
|
+
crc = nativeCrc32(slice, crc);
|
|
576
|
+
if (entrySha) entrySha.update(slice);
|
|
577
|
+
if (!def.write(slice)) {
|
|
578
|
+
await new Promise((resolve) => {
|
|
579
|
+
const finish = () => {
|
|
580
|
+
def.off('drain', finish);
|
|
581
|
+
def.off('close', finish);
|
|
582
|
+
def.off('error', finish);
|
|
583
|
+
resolve();
|
|
584
|
+
};
|
|
585
|
+
def.once('drain', finish);
|
|
586
|
+
def.once('close', finish);
|
|
587
|
+
def.once('error', finish);
|
|
588
|
+
});
|
|
589
|
+
}
|
|
590
|
+
pos += bytesRead;
|
|
591
|
+
}
|
|
592
|
+
// Check no trailing growth occurred in source file.
|
|
593
|
+
const extraBuf = Buffer.allocUnsafe(1);
|
|
594
|
+
const { bytesRead: extraRead } = await srcHandle.read(extraBuf, 0, 1, pos);
|
|
595
|
+
if (extraRead > 0) throw new Error(`Pack source grew during compression: ${sourcePath}`);
|
|
596
|
+
if (!streamErr) def.end();
|
|
597
|
+
await done;
|
|
598
|
+
if (plainLen !== expectedSize) {
|
|
599
|
+
throw new Error(`Pack source size mismatch during compression: ${sourcePath}`);
|
|
600
|
+
}
|
|
601
|
+
return {
|
|
602
|
+
crc: crc >>> 0,
|
|
603
|
+
compSize,
|
|
604
|
+
plainLen,
|
|
605
|
+
entrySha256: entrySha ? entrySha.digest('hex') : null,
|
|
606
|
+
};
|
|
607
|
+
} finally {
|
|
608
|
+
await Promise.allSettled([srcHandle.close(), shardHandle.close()]);
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
async function copyFileIntoArchive(sourcePath, outHandle, expectedSize, expectedCrc, archiveHash, computeSha) {
|
|
613
|
+
const srcHandle = await fsp.open(sourcePath, 'r');
|
|
614
|
+
try {
|
|
615
|
+
const buf = Buffer.allocUnsafe(STREAM_IO_CHUNK_BYTES);
|
|
616
|
+
let pos = 0;
|
|
617
|
+
let crc = 0;
|
|
618
|
+
const entrySha = computeSha ? createHash('sha256') : null;
|
|
619
|
+
while (pos < expectedSize) {
|
|
620
|
+
const toRead = Math.min(buf.length, expectedSize - pos);
|
|
621
|
+
const { bytesRead } = await srcHandle.read(buf, 0, toRead, pos);
|
|
622
|
+
if (bytesRead <= 0) throw new Error(`Source file truncated while writing archive: ${sourcePath}`);
|
|
623
|
+
const slice = buf.subarray(0, bytesRead);
|
|
624
|
+
if (expectedCrc !== null) crc = nativeCrc32(slice, crc);
|
|
625
|
+
if (entrySha) entrySha.update(slice);
|
|
626
|
+
await writeFullBuffer(outHandle, slice, archiveHash);
|
|
627
|
+
pos += bytesRead;
|
|
628
|
+
}
|
|
629
|
+
const extraBuf = Buffer.allocUnsafe(1);
|
|
630
|
+
const { bytesRead: extraRead } = await srcHandle.read(extraBuf, 0, 1, pos);
|
|
631
|
+
if (extraRead > 0) throw new Error(`Source file grew while writing archive: ${sourcePath}`);
|
|
632
|
+
if (expectedCrc !== null && (crc >>> 0) !== (expectedCrc >>> 0)) {
|
|
633
|
+
throw new Error(`Source file changed while writing archive: ${sourcePath}`);
|
|
634
|
+
}
|
|
635
|
+
return entrySha ? entrySha.digest('hex') : null;
|
|
636
|
+
} finally {
|
|
637
|
+
await srcHandle.close();
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
export async function writeNimiAppArchiveToFile(filePath, entries, options = {}) {
|
|
642
|
+
const compress = options.compress !== false;
|
|
643
|
+
const maxArchiveBytes = options.maxArchiveBytes ?? NATIVE_MAX_ARCHIVE_BYTES;
|
|
644
|
+
const maxTotalUncompressedBytes = options.maxTotalUncompressedBytes ?? NATIVE_MAX_RELEASE_BYTES;
|
|
645
|
+
const hashEntryName = options.hashEntryName ?? null;
|
|
646
|
+
const normalized = entries.map((entry) => {
|
|
647
|
+
const name = zipEntryName(entry.name);
|
|
648
|
+
const rawName = Buffer.from(name, 'utf8');
|
|
649
|
+
const mode = entry.mode === SYMBOLIC_LINK_MODE ? SYMBOLIC_LINK_MODE : entry.mode === 0o755 ? 0o755 : 0o644;
|
|
650
|
+
if (entry.bytes !== undefined) {
|
|
651
|
+
const bytes = Buffer.isBuffer(entry.bytes) ? entry.bytes : Buffer.from(entry.bytes);
|
|
652
|
+
return { name, rawName, bytes, filePath: null, size: bytes.length, mode };
|
|
653
|
+
}
|
|
654
|
+
if (!entry.filePath || !Number.isSafeInteger(entry.size) || entry.size < 0) {
|
|
655
|
+
throw new Error(`Invalid archive entry descriptor: ${name}`);
|
|
656
|
+
}
|
|
657
|
+
return { name, rawName, bytes: null, filePath: entry.filePath, size: entry.size, mode };
|
|
658
|
+
}).sort((left, right) => Buffer.compare(left.rawName, right.rawName));
|
|
659
|
+
|
|
660
|
+
if (normalized.length === 0 || normalized.length > MAX_ZIP32_ENTRIES) {
|
|
661
|
+
throw new Error('nimiapp archive requires between 1 and 65535 files');
|
|
662
|
+
}
|
|
663
|
+
let totalUncompressed = 0;
|
|
664
|
+
for (let index = 0; index < normalized.length; index += 1) {
|
|
665
|
+
const entry = normalized[index];
|
|
666
|
+
if (index > 0 && Buffer.compare(normalized[index - 1].rawName, entry.rawName) >= 0) {
|
|
667
|
+
throw new Error('nimiapp archive entries must be unique');
|
|
668
|
+
}
|
|
669
|
+
if (entry.size > NATIVE_MAX_ENTRY_BYTES || entry.size >= 0xffffffff) {
|
|
670
|
+
throw new Error(`Archive entry is too large: ${entry.name}`);
|
|
671
|
+
}
|
|
672
|
+
if (entry.mode === SYMBOLIC_LINK_MODE && (entry.size === 0 || entry.size > MAX_SYMLINK_TARGET_BYTES)) {
|
|
673
|
+
throw new Error(`Invalid symbolic link target size: ${entry.name}`);
|
|
674
|
+
}
|
|
675
|
+
totalUncompressed += entry.size;
|
|
676
|
+
if (totalUncompressed > maxTotalUncompressedBytes) {
|
|
677
|
+
throw new Error(`Archive uncompressed size exceeds ${maxTotalUncompressedBytes} bytes`);
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
await fsp.mkdir(path.dirname(filePath), { recursive: true });
|
|
682
|
+
const tempPath = `${filePath}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`;
|
|
683
|
+
const shardPath = `${tempPath}.shard`;
|
|
684
|
+
const outHandle = await fsp.open(tempPath, 'w');
|
|
685
|
+
const archiveHash = createHash('sha256');
|
|
686
|
+
const centralParts = [];
|
|
687
|
+
let offset = 0;
|
|
688
|
+
let hashedEntrySha256 = null;
|
|
689
|
+
let renamed = false;
|
|
690
|
+
|
|
691
|
+
try {
|
|
692
|
+
for (const entry of normalized) {
|
|
693
|
+
const wantHash = hashEntryName !== null && entry.name === hashEntryName;
|
|
694
|
+
const uncompSize = entry.size;
|
|
695
|
+
let method = ZIP_METHOD_STORE;
|
|
696
|
+
let crc = 0;
|
|
697
|
+
let compSize = 0;
|
|
698
|
+
|
|
699
|
+
if (uncompSize === 0) {
|
|
700
|
+
// Short-circuit 0 B regular files: never create a stream with end = start - 1.
|
|
701
|
+
if (wantHash) hashedEntrySha256 = createHash('sha256').digest('hex');
|
|
702
|
+
const nextOffset = offset + 30 + entry.rawName.length;
|
|
703
|
+
if (nextOffset > maxArchiveBytes || nextOffset >= 0xffffffff) {
|
|
704
|
+
throw new Error(`Archive exceeds maximum size budget (${maxArchiveBytes} bytes)`);
|
|
705
|
+
}
|
|
706
|
+
const local = buildLocalHeaderBuffer(entry.rawName, ZIP_METHOD_STORE, 0, 0, 0);
|
|
707
|
+
await writeFullBuffer(outHandle, local, archiveHash);
|
|
708
|
+
await writeFullBuffer(outHandle, entry.rawName, archiveHash);
|
|
709
|
+
} else if (entry.bytes !== null || uncompSize <= STREAM_DEFLATE_THRESHOLD) {
|
|
710
|
+
const plain = entry.bytes !== null ? entry.bytes : await fsp.readFile(entry.filePath);
|
|
711
|
+
if (plain.length !== uncompSize) {
|
|
712
|
+
throw new Error(`Pack source size changed before archive write: ${entry.name}`);
|
|
713
|
+
}
|
|
714
|
+
if (wantHash) hashedEntrySha256 = createHash('sha256').update(plain).digest('hex');
|
|
715
|
+
crc = nativeCrc32(plain);
|
|
716
|
+
let payload = plain;
|
|
717
|
+
if (compress && entry.mode !== SYMBOLIC_LINK_MODE) {
|
|
718
|
+
const deflated = deflateRawSync(plain, { level: DEFLATE_LEVEL });
|
|
719
|
+
if (deflated.length > 0 && deflated.length < uncompSize) {
|
|
720
|
+
method = ZIP_METHOD_DEFLATE;
|
|
721
|
+
payload = deflated;
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
compSize = payload.length;
|
|
725
|
+
const nextOffset = offset + 30 + entry.rawName.length + compSize;
|
|
726
|
+
if (nextOffset > maxArchiveBytes || nextOffset >= 0xffffffff) {
|
|
727
|
+
throw new Error(`Archive exceeds maximum size budget (${maxArchiveBytes} bytes)`);
|
|
728
|
+
}
|
|
729
|
+
const local = buildLocalHeaderBuffer(entry.rawName, method, crc, compSize, uncompSize);
|
|
730
|
+
await writeFullBuffer(outHandle, local, archiveHash);
|
|
731
|
+
await writeFullBuffer(outHandle, entry.rawName, archiveHash);
|
|
732
|
+
await writeFullBuffer(outHandle, payload, archiveHash);
|
|
733
|
+
} else if (compress) {
|
|
734
|
+
try {
|
|
735
|
+
const stats = await streamDeflateFileToShard(entry.filePath, shardPath, uncompSize, wantHash);
|
|
736
|
+
crc = stats.crc;
|
|
737
|
+
if (wantHash) hashedEntrySha256 = stats.entrySha256;
|
|
738
|
+
if (stats.compSize > 0 && stats.compSize < uncompSize) {
|
|
739
|
+
method = ZIP_METHOD_DEFLATE;
|
|
740
|
+
compSize = stats.compSize;
|
|
741
|
+
const nextOffset = offset + 30 + entry.rawName.length + compSize;
|
|
742
|
+
if (nextOffset > maxArchiveBytes || nextOffset >= 0xffffffff) {
|
|
743
|
+
throw new Error(`Archive exceeds maximum size budget (${maxArchiveBytes} bytes)`);
|
|
744
|
+
}
|
|
745
|
+
const local = buildLocalHeaderBuffer(entry.rawName, method, crc, compSize, uncompSize);
|
|
746
|
+
await writeFullBuffer(outHandle, local, archiveHash);
|
|
747
|
+
await writeFullBuffer(outHandle, entry.rawName, archiveHash);
|
|
748
|
+
await copyFileIntoArchive(shardPath, outHandle, compSize, null, archiveHash, false);
|
|
749
|
+
} else {
|
|
750
|
+
method = ZIP_METHOD_STORE;
|
|
751
|
+
compSize = uncompSize;
|
|
752
|
+
const nextOffset = offset + 30 + entry.rawName.length + compSize;
|
|
753
|
+
if (nextOffset > maxArchiveBytes || nextOffset >= 0xffffffff) {
|
|
754
|
+
throw new Error(`Archive exceeds maximum size budget (${maxArchiveBytes} bytes)`);
|
|
755
|
+
}
|
|
756
|
+
const local = buildLocalHeaderBuffer(entry.rawName, method, crc, compSize, uncompSize);
|
|
757
|
+
await writeFullBuffer(outHandle, local, archiveHash);
|
|
758
|
+
await writeFullBuffer(outHandle, entry.rawName, archiveHash);
|
|
759
|
+
const storeSha = await copyFileIntoArchive(entry.filePath, outHandle, uncompSize, crc, archiveHash, wantHash);
|
|
760
|
+
if (wantHash && storeSha !== hashedEntrySha256) {
|
|
761
|
+
throw new Error(`Runtime entry changed while writing archive: ${entry.name}`);
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
} finally {
|
|
765
|
+
await fsp.rm(shardPath, { force: true });
|
|
766
|
+
}
|
|
767
|
+
} else {
|
|
768
|
+
// Large uncompressed Store entry
|
|
769
|
+
const srcHandle = await fsp.open(entry.filePath, 'r');
|
|
770
|
+
try {
|
|
771
|
+
const buf = Buffer.allocUnsafe(STREAM_IO_CHUNK_BYTES);
|
|
772
|
+
let pos = 0;
|
|
773
|
+
const entrySha = wantHash ? createHash('sha256') : null;
|
|
774
|
+
while (pos < uncompSize) {
|
|
775
|
+
const { bytesRead } = await srcHandle.read(buf, 0, Math.min(buf.length, uncompSize - pos), pos);
|
|
776
|
+
if (bytesRead <= 0) throw new Error(`Source file truncated: ${entry.name}`);
|
|
777
|
+
const slice = buf.subarray(0, bytesRead);
|
|
778
|
+
crc = nativeCrc32(slice, crc);
|
|
779
|
+
if (entrySha) entrySha.update(slice);
|
|
780
|
+
pos += bytesRead;
|
|
781
|
+
}
|
|
782
|
+
if (entrySha) hashedEntrySha256 = entrySha.digest('hex');
|
|
783
|
+
} finally {
|
|
784
|
+
await srcHandle.close();
|
|
785
|
+
}
|
|
786
|
+
method = ZIP_METHOD_STORE;
|
|
787
|
+
compSize = uncompSize;
|
|
788
|
+
const nextOffset = offset + 30 + entry.rawName.length + compSize;
|
|
789
|
+
if (nextOffset > maxArchiveBytes || nextOffset >= 0xffffffff) {
|
|
790
|
+
throw new Error(`Archive exceeds maximum size budget (${maxArchiveBytes} bytes)`);
|
|
791
|
+
}
|
|
792
|
+
const local = buildLocalHeaderBuffer(entry.rawName, method, crc, compSize, uncompSize);
|
|
793
|
+
await writeFullBuffer(outHandle, local, archiveHash);
|
|
794
|
+
await writeFullBuffer(outHandle, entry.rawName, archiveHash);
|
|
795
|
+
await copyFileIntoArchive(entry.filePath, outHandle, uncompSize, crc, archiveHash, false);
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
const central = buildCentralHeaderBuffer(
|
|
799
|
+
entry.rawName,
|
|
800
|
+
method,
|
|
801
|
+
crc,
|
|
802
|
+
compSize,
|
|
803
|
+
uncompSize,
|
|
804
|
+
encodeCanonicalExternalAttrs(entry.mode),
|
|
805
|
+
offset,
|
|
806
|
+
);
|
|
807
|
+
centralParts.push(central, entry.rawName);
|
|
808
|
+
offset += 30 + entry.rawName.length + compSize;
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
const central = Buffer.concat(centralParts);
|
|
812
|
+
const finalSize = offset + central.length + 22;
|
|
813
|
+
if (finalSize > maxArchiveBytes || finalSize >= 0xffffffff) {
|
|
814
|
+
throw new Error(`Archive exceeds maximum size budget (${maxArchiveBytes} bytes)`);
|
|
815
|
+
}
|
|
816
|
+
if (totalUncompressed > EXPANSION_RATIO_FLOOR_BYTES && totalUncompressed > finalSize * MAX_EXPANSION_RATIO) {
|
|
817
|
+
throw new Error(`Archive expansion ratio exceeds ${MAX_EXPANSION_RATIO}x (${totalUncompressed} / ${finalSize})`);
|
|
818
|
+
}
|
|
819
|
+
const end = buildEocdBuffer(normalized.length, central.length, offset);
|
|
820
|
+
await writeFullBuffer(outHandle, central, archiveHash);
|
|
821
|
+
await writeFullBuffer(outHandle, end, archiveHash);
|
|
822
|
+
await outHandle.close();
|
|
823
|
+
await fsp.rename(tempPath, filePath);
|
|
824
|
+
renamed = true;
|
|
825
|
+
return {
|
|
826
|
+
size: finalSize,
|
|
827
|
+
sha256: archiveHash.digest('hex'),
|
|
828
|
+
totalUncompressed,
|
|
829
|
+
hashedEntrySha256,
|
|
830
|
+
};
|
|
831
|
+
} finally {
|
|
832
|
+
await outHandle.close().catch(() => {});
|
|
833
|
+
await fsp.rm(shardPath, { force: true }).catch(() => {});
|
|
834
|
+
if (!renamed) {
|
|
835
|
+
await fsp.rm(tempPath, { force: true }).catch(() => {});
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
function parseCentralAndValidateMetadata(archiveSize, eocd, cdBuf, options, readLocalSlice) {
|
|
841
|
+
const maxArchiveBytes = options.maxArchiveBytes ?? NATIVE_MAX_ARCHIVE_BYTES;
|
|
842
|
+
const maxTotalUncompressedBytes = options.maxTotalUncompressedBytes ?? NATIVE_MAX_RELEASE_BYTES;
|
|
843
|
+
const nimiappLayout = options.nimiappLayout === true;
|
|
844
|
+
if (archiveSize < 22 || archiveSize > maxArchiveBytes || archiveSize >= 0xffffffff) {
|
|
845
|
+
throw new Error('Invalid nimiapp ZIP archive size');
|
|
846
|
+
}
|
|
847
|
+
if (eocd.readUInt32LE(0) !== 0x06054b50) throw new Error('Invalid nimiapp ZIP end record');
|
|
848
|
+
const diskNumber = eocd.readUInt16LE(4);
|
|
849
|
+
const centralDisk = eocd.readUInt16LE(6);
|
|
850
|
+
const entriesOnDisk = eocd.readUInt16LE(8);
|
|
851
|
+
const count = eocd.readUInt16LE(10);
|
|
852
|
+
const centralSize = eocd.readUInt32LE(12);
|
|
853
|
+
const centralOffset = eocd.readUInt32LE(16);
|
|
854
|
+
const commentLen = eocd.readUInt16LE(20);
|
|
855
|
+
const endOffset = archiveSize - 22;
|
|
856
|
+
if (
|
|
857
|
+
diskNumber !== 0
|
|
858
|
+
|| centralDisk !== 0
|
|
859
|
+
|| commentLen !== 0
|
|
860
|
+
|| entriesOnDisk !== count
|
|
861
|
+
|| count === 0
|
|
862
|
+
|| count > MAX_ZIP32_ENTRIES
|
|
863
|
+
|| centralSize === 0
|
|
864
|
+
|| centralSize === 0xffffffff
|
|
865
|
+
|| centralOffset === 0xffffffff
|
|
866
|
+
|| centralOffset + centralSize !== endOffset
|
|
867
|
+
) {
|
|
868
|
+
throw new Error('Invalid nimiapp ZIP directory');
|
|
869
|
+
}
|
|
870
|
+
return { count, centralSize, centralOffset, maxTotalUncompressedBytes, nimiappLayout };
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
function validateCentralEntryFields(cdBuf, cursor, cdEnd, expectedOffset, centralOffset, prevRawName, nimiappLayout, maxTotalUncompressedBytes, totalUncompressed) {
|
|
874
|
+
if (cursor + 46 > cdEnd) throw new Error('Invalid nimiapp ZIP central entry truncated');
|
|
875
|
+
if (cdBuf.readUInt32LE(cursor) !== 0x02014b50) throw new Error('Invalid nimiapp ZIP central entry');
|
|
876
|
+
const creatorVersion = cdBuf.readUInt16LE(cursor + 4);
|
|
877
|
+
const readerVersion = cdBuf.readUInt16LE(cursor + 6);
|
|
878
|
+
const flags = cdBuf.readUInt16LE(cursor + 8);
|
|
879
|
+
const method = cdBuf.readUInt16LE(cursor + 10);
|
|
880
|
+
const modTime = cdBuf.readUInt16LE(cursor + 12);
|
|
881
|
+
const modDate = cdBuf.readUInt16LE(cursor + 14);
|
|
882
|
+
const expectedCrc = cdBuf.readUInt32LE(cursor + 16);
|
|
883
|
+
const compSize = cdBuf.readUInt32LE(cursor + 20);
|
|
884
|
+
const uncompSize = cdBuf.readUInt32LE(cursor + 24);
|
|
885
|
+
const nameLen = cdBuf.readUInt16LE(cursor + 28);
|
|
886
|
+
const extraLen = cdBuf.readUInt16LE(cursor + 30);
|
|
887
|
+
const commentLen = cdBuf.readUInt16LE(cursor + 32);
|
|
888
|
+
const diskStart = cdBuf.readUInt16LE(cursor + 34);
|
|
889
|
+
const internalAttrs = cdBuf.readUInt16LE(cursor + 36);
|
|
890
|
+
const externalAttrs = cdBuf.readUInt32LE(cursor + 38);
|
|
891
|
+
const localOffset = cdBuf.readUInt32LE(cursor + 42);
|
|
892
|
+
if (
|
|
893
|
+
creatorVersion !== ZIP_CREATOR_UNIX
|
|
894
|
+
|| readerVersion !== ZIP_READER_VERSION
|
|
895
|
+
|| flags !== ZIP_FLAGS_UTF8
|
|
896
|
+
|| extraLen !== 0
|
|
897
|
+
|| commentLen !== 0
|
|
898
|
+
|| diskStart !== 0
|
|
899
|
+
|| internalAttrs !== 0
|
|
900
|
+
|| compSize === 0xffffffff
|
|
901
|
+
|| uncompSize === 0xffffffff
|
|
902
|
+
|| localOffset === 0xffffffff
|
|
903
|
+
|| nameLen === 0
|
|
904
|
+
|| nameLen > MAX_ARCHIVE_ENTRY_NAME_BYTES
|
|
905
|
+
|| cursor + 46 + nameLen > cdEnd
|
|
906
|
+
) {
|
|
907
|
+
throw new Error('Invalid nimiapp ZIP entry header');
|
|
908
|
+
}
|
|
909
|
+
const mode = parseCanonicalExternalAttrs(externalAttrs);
|
|
910
|
+
const rawName = cdBuf.subarray(cursor + 46, cursor + 46 + nameLen);
|
|
911
|
+
const name = zipEntryName(decodeStrictUtf8(rawName, 'nimiapp ZIP entry name'));
|
|
912
|
+
if (prevRawName !== null && Buffer.compare(prevRawName, rawName) >= 0) {
|
|
913
|
+
throw new Error('Invalid nimiapp ZIP entries are not canonical');
|
|
914
|
+
}
|
|
915
|
+
if (mode === SYMBOLIC_LINK_MODE) {
|
|
916
|
+
if (method !== ZIP_METHOD_STORE || compSize !== uncompSize || uncompSize === 0 || uncompSize > MAX_SYMLINK_TARGET_BYTES) {
|
|
917
|
+
throw new Error(`Invalid nimiapp ZIP symbolic link entry: ${name}`);
|
|
918
|
+
}
|
|
919
|
+
} else if (method === ZIP_METHOD_STORE) {
|
|
920
|
+
if (compSize !== uncompSize || uncompSize > NATIVE_MAX_ENTRY_BYTES || (uncompSize === 0 && expectedCrc !== 0)) {
|
|
921
|
+
throw new Error(`Invalid nimiapp ZIP Store entry: ${name}`);
|
|
922
|
+
}
|
|
923
|
+
} else if (method === ZIP_METHOD_DEFLATE) {
|
|
924
|
+
if (compSize === 0 || uncompSize === 0 || compSize >= uncompSize || uncompSize > NATIVE_MAX_ENTRY_BYTES) {
|
|
925
|
+
throw new Error(`Invalid nimiapp ZIP Deflate entry: ${name}`);
|
|
926
|
+
}
|
|
927
|
+
} else {
|
|
928
|
+
throw new Error(`Invalid nimiapp ZIP unsupported compression method ${method}: ${name}`);
|
|
929
|
+
}
|
|
930
|
+
if (nimiappLayout) {
|
|
931
|
+
validateNimiappLayoutEntry(name, mode, uncompSize);
|
|
932
|
+
}
|
|
933
|
+
if (localOffset !== expectedOffset) {
|
|
934
|
+
throw new Error(`Invalid nimiapp ZIP non-contiguous local offset: ${name}`);
|
|
935
|
+
}
|
|
936
|
+
const dataOffset = localOffset + 30 + nameLen;
|
|
937
|
+
const nextOffset = dataOffset + compSize;
|
|
938
|
+
if (nextOffset < dataOffset || nextOffset > centralOffset) {
|
|
939
|
+
throw new Error(`Invalid nimiapp ZIP local data bounds: ${name}`);
|
|
940
|
+
}
|
|
941
|
+
const nextTotalUncompressed = totalUncompressed + uncompSize;
|
|
942
|
+
if (nextTotalUncompressed > maxTotalUncompressedBytes) {
|
|
943
|
+
throw new Error(`Invalid nimiapp ZIP uncompressed size exceeds ${maxTotalUncompressedBytes} bytes`);
|
|
944
|
+
}
|
|
945
|
+
return {
|
|
946
|
+
name,
|
|
947
|
+
rawName,
|
|
948
|
+
mode,
|
|
949
|
+
method,
|
|
950
|
+
modTime,
|
|
951
|
+
modDate,
|
|
952
|
+
expectedCrc,
|
|
953
|
+
compSize,
|
|
954
|
+
uncompSize,
|
|
955
|
+
localOffset,
|
|
956
|
+
dataOffset,
|
|
957
|
+
nextOffset,
|
|
958
|
+
nextCursor: cursor + 46 + nameLen,
|
|
959
|
+
nextTotalUncompressed,
|
|
960
|
+
};
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
function assertLocalHeaderMatches(localBuf, meta) {
|
|
964
|
+
if (
|
|
965
|
+
localBuf.length !== 30 + meta.rawName.length
|
|
966
|
+
|| localBuf.readUInt32LE(0) !== 0x04034b50
|
|
967
|
+
|| localBuf.readUInt16LE(4) !== ZIP_READER_VERSION
|
|
968
|
+
|| localBuf.readUInt16LE(6) !== ZIP_FLAGS_UTF8
|
|
969
|
+
|| localBuf.readUInt16LE(8) !== meta.method
|
|
970
|
+
|| localBuf.readUInt16LE(10) !== meta.modTime
|
|
971
|
+
|| localBuf.readUInt16LE(12) !== meta.modDate
|
|
972
|
+
|| localBuf.readUInt32LE(14) !== meta.expectedCrc
|
|
973
|
+
|| localBuf.readUInt32LE(18) !== meta.compSize
|
|
974
|
+
|| localBuf.readUInt32LE(22) !== meta.uncompSize
|
|
975
|
+
|| localBuf.readUInt16LE(26) !== meta.rawName.length
|
|
976
|
+
|| localBuf.readUInt16LE(28) !== 0
|
|
977
|
+
|| !localBuf.subarray(30).equals(meta.rawName)
|
|
978
|
+
) {
|
|
979
|
+
throw new Error(`Invalid nimiapp ZIP local header mismatch: ${meta.name}`);
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
|
|
983
|
+
export function readNimiAppArchive(bytes, options = {}) {
|
|
349
984
|
const archive = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes);
|
|
350
|
-
|
|
351
|
-
const
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
const
|
|
357
|
-
|
|
985
|
+
const maxArchiveBytes = options.maxArchiveBytes ?? NATIVE_MAX_ARCHIVE_BYTES;
|
|
986
|
+
const retainPredicate = typeof options.retainPredicate === 'function' ? options.retainPredicate : null;
|
|
987
|
+
if (archive.length < 22 || archive.length > maxArchiveBytes || archive.length >= 0xffffffff) {
|
|
988
|
+
throw new Error('Invalid nimiapp ZIP end record');
|
|
989
|
+
}
|
|
990
|
+
const eocd = archive.subarray(archive.length - 22);
|
|
991
|
+
const { count, centralSize, centralOffset, maxTotalUncompressedBytes, nimiappLayout } =
|
|
992
|
+
parseCentralAndValidateMetadata(archive.length, eocd, null, options);
|
|
993
|
+
const cdBuf = archive.subarray(centralOffset, centralOffset + centralSize);
|
|
994
|
+
const parsed = [];
|
|
995
|
+
let cursor = 0;
|
|
996
|
+
let expectedOffset = 0;
|
|
997
|
+
let totalUncompressed = 0;
|
|
998
|
+
let prevRawName = null;
|
|
358
999
|
for (let index = 0; index < count; index += 1) {
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
1000
|
+
const meta = validateCentralEntryFields(
|
|
1001
|
+
cdBuf,
|
|
1002
|
+
cursor,
|
|
1003
|
+
centralSize,
|
|
1004
|
+
expectedOffset,
|
|
1005
|
+
centralOffset,
|
|
1006
|
+
prevRawName,
|
|
1007
|
+
nimiappLayout,
|
|
1008
|
+
maxTotalUncompressedBytes,
|
|
1009
|
+
totalUncompressed,
|
|
1010
|
+
);
|
|
1011
|
+
const localBuf = archive.subarray(meta.localOffset, meta.dataOffset);
|
|
1012
|
+
assertLocalHeaderMatches(localBuf, meta);
|
|
1013
|
+
parsed.push(meta);
|
|
1014
|
+
cursor = meta.nextCursor;
|
|
1015
|
+
expectedOffset = meta.nextOffset;
|
|
1016
|
+
totalUncompressed = meta.nextTotalUncompressed;
|
|
1017
|
+
prevRawName = meta.rawName;
|
|
1018
|
+
}
|
|
1019
|
+
if (cursor !== centralSize || expectedOffset !== centralOffset) {
|
|
1020
|
+
throw new Error('Invalid nimiapp ZIP directory layout');
|
|
1021
|
+
}
|
|
1022
|
+
if (totalUncompressed > EXPANSION_RATIO_FLOOR_BYTES && totalUncompressed > archive.length * MAX_EXPANSION_RATIO) {
|
|
1023
|
+
throw new Error(`Invalid nimiapp ZIP expansion ratio exceeds ${MAX_EXPANSION_RATIO}x`);
|
|
1024
|
+
}
|
|
1025
|
+
|
|
1026
|
+
const entries = new Map();
|
|
1027
|
+
for (const meta of parsed) {
|
|
1028
|
+
const rawSlice = archive.subarray(meta.dataOffset, meta.dataOffset + meta.compSize);
|
|
1029
|
+
if (rawSlice.length !== meta.compSize) {
|
|
1030
|
+
throw new Error(`Invalid nimiapp ZIP truncated entry: ${meta.name}`);
|
|
1031
|
+
}
|
|
1032
|
+
let plain;
|
|
1033
|
+
if (meta.method === ZIP_METHOD_STORE) {
|
|
1034
|
+
if (meta.uncompSize > 0 && nativeCrc32(rawSlice) !== meta.expectedCrc) {
|
|
1035
|
+
throw new Error(`Invalid nimiapp ZIP entry digest mismatch: ${meta.name}`);
|
|
1036
|
+
}
|
|
1037
|
+
plain = rawSlice;
|
|
375
1038
|
} else {
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
entries.set(name, Object.freeze({
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
1039
|
+
let inflated;
|
|
1040
|
+
try {
|
|
1041
|
+
inflated = inflateRawSync(rawSlice, { maxOutputLength: meta.uncompSize, info: true });
|
|
1042
|
+
} catch (error) {
|
|
1043
|
+
throw new Error(`Invalid nimiapp ZIP deflate payload for ${meta.name}: ${error instanceof Error ? error.message : String(error)}`);
|
|
1044
|
+
}
|
|
1045
|
+
if (inflated.buffer.length !== meta.uncompSize || inflated.engine.bytesWritten !== meta.compSize) {
|
|
1046
|
+
throw new Error(`Invalid nimiapp ZIP deflate length or trailing bytes: ${meta.name}`);
|
|
1047
|
+
}
|
|
1048
|
+
if (nativeCrc32(inflated.buffer) !== meta.expectedCrc) {
|
|
1049
|
+
throw new Error(`Invalid nimiapp ZIP entry digest mismatch: ${meta.name}`);
|
|
1050
|
+
}
|
|
1051
|
+
plain = inflated.buffer;
|
|
1052
|
+
}
|
|
1053
|
+
const retain = meta.mode === SYMBOLIC_LINK_MODE || !retainPredicate || retainPredicate(meta.name, { mode: meta.mode, size: meta.uncompSize });
|
|
1054
|
+
entries.set(meta.name, Object.freeze({
|
|
1055
|
+
bytes: retain ? Buffer.from(plain) : null,
|
|
1056
|
+
size: meta.uncompSize,
|
|
1057
|
+
mode: meta.mode,
|
|
1058
|
+
}));
|
|
1059
|
+
}
|
|
397
1060
|
return entries;
|
|
398
1061
|
}
|
|
399
1062
|
|
|
1063
|
+
async function readStoreEntryFromHandle(handle, meta, retain, budgetState) {
|
|
1064
|
+
if (meta.uncompSize === 0) {
|
|
1065
|
+
return retain ? Buffer.alloc(0) : null;
|
|
1066
|
+
}
|
|
1067
|
+
const buf = Buffer.allocUnsafe(Math.min(STREAM_IO_CHUNK_BYTES, meta.compSize));
|
|
1068
|
+
let offset = 0;
|
|
1069
|
+
let crc = 0;
|
|
1070
|
+
const chunks = retain ? [] : null;
|
|
1071
|
+
while (offset < meta.compSize) {
|
|
1072
|
+
const toRead = Math.min(buf.length, meta.compSize - offset);
|
|
1073
|
+
const { bytesRead } = await handle.read(buf, 0, toRead, meta.dataOffset + offset);
|
|
1074
|
+
if (bytesRead <= 0) throw new Error(`Invalid nimiapp ZIP truncated Store entry: ${meta.name}`);
|
|
1075
|
+
const slice = buf.subarray(0, bytesRead);
|
|
1076
|
+
budgetState.total += bytesRead;
|
|
1077
|
+
if (budgetState.total > budgetState.maxTotal) {
|
|
1078
|
+
throw new Error(`Invalid nimiapp ZIP uncompressed budget exceeded: ${meta.name}`);
|
|
1079
|
+
}
|
|
1080
|
+
crc = nativeCrc32(slice, crc);
|
|
1081
|
+
if (chunks) chunks.push(Buffer.from(slice));
|
|
1082
|
+
offset += bytesRead;
|
|
1083
|
+
}
|
|
1084
|
+
if ((crc >>> 0) !== (meta.expectedCrc >>> 0)) {
|
|
1085
|
+
throw new Error(`Invalid nimiapp ZIP entry digest mismatch: ${meta.name}`);
|
|
1086
|
+
}
|
|
1087
|
+
return chunks ? Buffer.concat(chunks) : null;
|
|
1088
|
+
}
|
|
1089
|
+
|
|
1090
|
+
async function readDeflateEntryFromHandle(handle, meta, retain, budgetState) {
|
|
1091
|
+
// Never rely on createInflateRaw({ maxOutputLength }): Node v24 Transform
|
|
1092
|
+
// silently ignores it. Enforce per-entry and total uncompressed bounds
|
|
1093
|
+
// strictly inside our single bounded consumer before updating CRC or retaining.
|
|
1094
|
+
const inf = createInflateRaw();
|
|
1095
|
+
let outLen = 0;
|
|
1096
|
+
let crc = 0;
|
|
1097
|
+
let aborted = null;
|
|
1098
|
+
const chunks = retain ? [] : null;
|
|
1099
|
+
const done = new Promise((resolve, reject) => {
|
|
1100
|
+
inf.on('data', (chunk) => {
|
|
1101
|
+
if (aborted) return;
|
|
1102
|
+
if (outLen + chunk.length > meta.uncompSize || budgetState.total + chunk.length > budgetState.maxTotal) {
|
|
1103
|
+
aborted = new Error(`Invalid nimiapp ZIP deflate uncompressed overflow: ${meta.name}`);
|
|
1104
|
+
inf.destroy(aborted);
|
|
1105
|
+
return;
|
|
1106
|
+
}
|
|
1107
|
+
outLen += chunk.length;
|
|
1108
|
+
budgetState.total += chunk.length;
|
|
1109
|
+
crc = nativeCrc32(chunk, crc);
|
|
1110
|
+
if (chunks) chunks.push(Buffer.from(chunk));
|
|
1111
|
+
});
|
|
1112
|
+
inf.on('error', (error) => {
|
|
1113
|
+
const wrapped = error === aborted
|
|
1114
|
+
? error
|
|
1115
|
+
: new Error(`Invalid nimiapp ZIP deflate payload for ${meta.name}: ${error instanceof Error ? error.message : String(error)}`);
|
|
1116
|
+
aborted = wrapped;
|
|
1117
|
+
reject(wrapped);
|
|
1118
|
+
});
|
|
1119
|
+
inf.on('end', () => {
|
|
1120
|
+
resolve();
|
|
1121
|
+
});
|
|
1122
|
+
});
|
|
1123
|
+
|
|
1124
|
+
const buf = Buffer.allocUnsafe(Math.min(STREAM_IO_CHUNK_BYTES, meta.compSize));
|
|
1125
|
+
let offset = 0;
|
|
1126
|
+
while (offset < meta.compSize && !aborted) {
|
|
1127
|
+
const toRead = Math.min(buf.length, meta.compSize - offset);
|
|
1128
|
+
const { bytesRead } = await handle.read(buf, 0, toRead, meta.dataOffset + offset);
|
|
1129
|
+
if (bytesRead <= 0) {
|
|
1130
|
+
const truncErr = new Error(`Invalid nimiapp ZIP truncated Deflate entry: ${meta.name}`);
|
|
1131
|
+
aborted = truncErr;
|
|
1132
|
+
inf.destroy(truncErr);
|
|
1133
|
+
break;
|
|
1134
|
+
}
|
|
1135
|
+
const slice = Buffer.from(buf.subarray(0, bytesRead));
|
|
1136
|
+
if (!inf.write(slice)) {
|
|
1137
|
+
await new Promise((resolve) => {
|
|
1138
|
+
const finish = () => {
|
|
1139
|
+
inf.off('drain', finish);
|
|
1140
|
+
inf.off('close', finish);
|
|
1141
|
+
inf.off('error', finish);
|
|
1142
|
+
resolve();
|
|
1143
|
+
};
|
|
1144
|
+
inf.once('drain', finish);
|
|
1145
|
+
inf.once('close', finish);
|
|
1146
|
+
inf.once('error', finish);
|
|
1147
|
+
});
|
|
1148
|
+
}
|
|
1149
|
+
offset += bytesRead;
|
|
1150
|
+
}
|
|
1151
|
+
if (!aborted) inf.end();
|
|
1152
|
+
await done;
|
|
1153
|
+
if (outLen !== meta.uncompSize || inf.bytesWritten !== meta.compSize) {
|
|
1154
|
+
throw new Error(`Invalid nimiapp ZIP deflate length or trailing bytes: ${meta.name}`);
|
|
1155
|
+
}
|
|
1156
|
+
if ((crc >>> 0) !== (meta.expectedCrc >>> 0)) {
|
|
1157
|
+
throw new Error(`Invalid nimiapp ZIP entry digest mismatch: ${meta.name}`);
|
|
1158
|
+
}
|
|
1159
|
+
return chunks ? Buffer.concat(chunks) : null;
|
|
1160
|
+
}
|
|
1161
|
+
|
|
1162
|
+
export async function readNimiAppArchiveFromFile(source, options = {}) {
|
|
1163
|
+
const retainPredicate = typeof options.retainPredicate === 'function' ? options.retainPredicate : null;
|
|
1164
|
+
let handle;
|
|
1165
|
+
let archiveSize;
|
|
1166
|
+
let ownHandle = false;
|
|
1167
|
+
if (typeof source === 'string') {
|
|
1168
|
+
handle = await fsp.open(source, 'r');
|
|
1169
|
+
ownHandle = true;
|
|
1170
|
+
const stat = await handle.stat();
|
|
1171
|
+
if (!stat.isFile()) {
|
|
1172
|
+
await handle.close();
|
|
1173
|
+
throw new Error('Invalid nimiapp ZIP archive source');
|
|
1174
|
+
}
|
|
1175
|
+
archiveSize = stat.size;
|
|
1176
|
+
} else if (source && source.handle && Number.isSafeInteger(source.size)) {
|
|
1177
|
+
handle = source.handle;
|
|
1178
|
+
archiveSize = source.size;
|
|
1179
|
+
} else {
|
|
1180
|
+
throw new Error('Invalid nimiapp ZIP archive source');
|
|
1181
|
+
}
|
|
1182
|
+
|
|
1183
|
+
try {
|
|
1184
|
+
const maxArchiveBytes = options.maxArchiveBytes ?? NATIVE_MAX_ARCHIVE_BYTES;
|
|
1185
|
+
if (archiveSize < 22 || archiveSize > maxArchiveBytes || archiveSize >= 0xffffffff) {
|
|
1186
|
+
throw new Error('Invalid nimiapp ZIP archive size');
|
|
1187
|
+
}
|
|
1188
|
+
const eocd = await readExactFromHandle(handle, Buffer.allocUnsafe(22), archiveSize - 22);
|
|
1189
|
+
const { count, centralSize, centralOffset, maxTotalUncompressedBytes, nimiappLayout } =
|
|
1190
|
+
parseCentralAndValidateMetadata(archiveSize, eocd, null, options);
|
|
1191
|
+
const cdBuf = await readExactFromHandle(handle, Buffer.allocUnsafe(centralSize), centralOffset);
|
|
1192
|
+
const parsed = [];
|
|
1193
|
+
let cursor = 0;
|
|
1194
|
+
let expectedOffset = 0;
|
|
1195
|
+
let totalUncompressed = 0;
|
|
1196
|
+
let prevRawName = null;
|
|
1197
|
+
for (let index = 0; index < count; index += 1) {
|
|
1198
|
+
const meta = validateCentralEntryFields(
|
|
1199
|
+
cdBuf,
|
|
1200
|
+
cursor,
|
|
1201
|
+
centralSize,
|
|
1202
|
+
expectedOffset,
|
|
1203
|
+
centralOffset,
|
|
1204
|
+
prevRawName,
|
|
1205
|
+
nimiappLayout,
|
|
1206
|
+
maxTotalUncompressedBytes,
|
|
1207
|
+
totalUncompressed,
|
|
1208
|
+
);
|
|
1209
|
+
const localBuf = await readExactFromHandle(handle, Buffer.allocUnsafe(30 + meta.rawName.length), meta.localOffset);
|
|
1210
|
+
assertLocalHeaderMatches(localBuf, meta);
|
|
1211
|
+
parsed.push(meta);
|
|
1212
|
+
cursor = meta.nextCursor;
|
|
1213
|
+
expectedOffset = meta.nextOffset;
|
|
1214
|
+
totalUncompressed = meta.nextTotalUncompressed;
|
|
1215
|
+
prevRawName = meta.rawName;
|
|
1216
|
+
}
|
|
1217
|
+
if (cursor !== centralSize || expectedOffset !== centralOffset) {
|
|
1218
|
+
throw new Error('Invalid nimiapp ZIP directory layout');
|
|
1219
|
+
}
|
|
1220
|
+
if (totalUncompressed > EXPANSION_RATIO_FLOOR_BYTES && totalUncompressed > archiveSize * MAX_EXPANSION_RATIO) {
|
|
1221
|
+
throw new Error(`Invalid nimiapp ZIP expansion ratio exceeds ${MAX_EXPANSION_RATIO}x`);
|
|
1222
|
+
}
|
|
1223
|
+
|
|
1224
|
+
const entries = new Map();
|
|
1225
|
+
const budgetState = { total: 0, maxTotal: maxTotalUncompressedBytes };
|
|
1226
|
+
for (const meta of parsed) {
|
|
1227
|
+
const retain = meta.mode === SYMBOLIC_LINK_MODE || !retainPredicate || retainPredicate(meta.name, { mode: meta.mode, size: meta.uncompSize });
|
|
1228
|
+
const data = meta.method === ZIP_METHOD_STORE
|
|
1229
|
+
? await readStoreEntryFromHandle(handle, meta, retain, budgetState)
|
|
1230
|
+
: await readDeflateEntryFromHandle(handle, meta, retain, budgetState);
|
|
1231
|
+
entries.set(meta.name, Object.freeze({
|
|
1232
|
+
bytes: data,
|
|
1233
|
+
size: meta.uncompSize,
|
|
1234
|
+
mode: meta.mode,
|
|
1235
|
+
}));
|
|
1236
|
+
}
|
|
1237
|
+
return entries;
|
|
1238
|
+
} finally {
|
|
1239
|
+
if (ownHandle) await handle.close().catch(() => {});
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
|
|
400
1243
|
function readNativePackProfile(targetDir) {
|
|
401
1244
|
const profile = readYaml(path.join(targetDir, BUILD_PROFILE_PATH), BUILD_PROFILE_PATH);
|
|
402
1245
|
assertDesktopHostSupport(profile.build_profile_ref);
|
|
@@ -421,8 +1264,8 @@ function readPackInputs(targetDir, targetId) {
|
|
|
421
1264
|
const licensePath = path.join(targetDir, 'LICENSE');
|
|
422
1265
|
if (!existsSync(licensePath)) throw new Error('App package LICENSE is missing');
|
|
423
1266
|
const licenseStat = lstatSync(licensePath);
|
|
424
|
-
if (!licenseStat.isFile() || licenseStat.isSymbolicLink() || licenseStat.size === 0) {
|
|
425
|
-
throw new Error(
|
|
1267
|
+
if (!licenseStat.isFile() || licenseStat.isSymbolicLink() || licenseStat.size === 0 || licenseStat.size > MAX_LICENSE_BYTES) {
|
|
1268
|
+
throw new Error(`App package LICENSE must be a non-empty direct regular file within ${MAX_LICENSE_BYTES} bytes`);
|
|
426
1269
|
}
|
|
427
1270
|
const manifestPath = path.join(targetDir, 'nimi.app.yaml');
|
|
428
1271
|
const manifest = readYaml(manifestPath, 'nimi.app.yaml');
|
|
@@ -488,18 +1331,18 @@ export function classifyWindowsNativeTrustObservation(observation) {
|
|
|
488
1331
|
throw new Error(`Windows Authenticode verification failed: status=${String(status)}, type=${String(signatureType)}, signer=${certificateSubject === null ? 'absent' : 'present'}`);
|
|
489
1332
|
}
|
|
490
1333
|
|
|
491
|
-
function observeProductionWindowsFacts(input,
|
|
1334
|
+
async function observeProductionWindowsFacts(input, expectedRuntimeSha256) {
|
|
492
1335
|
if (process.platform !== 'win32' || process.arch !== 'x64') throw new Error('Production Windows pack must run on windows-x86_64');
|
|
493
1336
|
const observed = observeWindowsExecutableFacts(input.runtimeHostPath);
|
|
494
|
-
const
|
|
495
|
-
if (
|
|
1337
|
+
const currentSha = await hashFilePath(input.runtimeHostPath);
|
|
1338
|
+
if (currentSha !== expectedRuntimeSha256) {
|
|
496
1339
|
throw new Error('Production Runtime entry changed while native and execution facts were observed');
|
|
497
1340
|
}
|
|
498
1341
|
const nativeTrust = classifyWindowsNativeTrustObservation(observed.authenticode);
|
|
499
1342
|
return { nativeTrust, executionProfile: observed.execution_profile };
|
|
500
1343
|
}
|
|
501
1344
|
|
|
502
|
-
function resolveTargetFacts(input, production,
|
|
1345
|
+
async function resolveTargetFacts(input, production, expectedRuntimeSha256) {
|
|
503
1346
|
if (input.target.os === 'any') {
|
|
504
1347
|
return {
|
|
505
1348
|
nativeTrust: {
|
|
@@ -519,10 +1362,12 @@ function resolveTargetFacts(input, production, archivedRuntimeEntryBytes) {
|
|
|
519
1362
|
}
|
|
520
1363
|
if (input.target.os === 'macos') {
|
|
521
1364
|
const facts = observeMacOSExecutableFacts(input.runtimeHostPath);
|
|
522
|
-
if (
|
|
1365
|
+
if ((await hashFilePath(input.runtimeHostPath)) !== expectedRuntimeSha256) {
|
|
1366
|
+
throw new Error('Production Runtime entry changed during macOS native observation');
|
|
1367
|
+
}
|
|
523
1368
|
return facts;
|
|
524
1369
|
}
|
|
525
|
-
return observeProductionWindowsFacts(input,
|
|
1370
|
+
return observeProductionWindowsFacts(input, expectedRuntimeSha256);
|
|
526
1371
|
}
|
|
527
1372
|
|
|
528
1373
|
function validateNativeExecutionFacts(nativeTrust, executionProfile, label, os) {
|
|
@@ -598,7 +1443,7 @@ function validateNativeExecutionFacts(nativeTrust, executionProfile, label, os)
|
|
|
598
1443
|
|
|
599
1444
|
function readPackageManifestFromArchive(entries, label) {
|
|
600
1445
|
const entry = entries.get('manifest.json');
|
|
601
|
-
if (!entry) throw new Error(`${label} archive manifest.json is missing`);
|
|
1446
|
+
if (!entry || !entry.bytes) throw new Error(`${label} archive manifest.json is missing`);
|
|
602
1447
|
try {
|
|
603
1448
|
const manifest = JSON.parse(entry.bytes.toString('utf8'));
|
|
604
1449
|
if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) throw new Error('root must be an object');
|
|
@@ -608,7 +1453,7 @@ function readPackageManifestFromArchive(entries, label) {
|
|
|
608
1453
|
}
|
|
609
1454
|
}
|
|
610
1455
|
|
|
611
|
-
export function packAppTarget(cwd, options = {}) {
|
|
1456
|
+
export async function packAppTarget(cwd, options = {}) {
|
|
612
1457
|
const targetDir = path.resolve(cwd, String(options.dir || '').trim() || '.');
|
|
613
1458
|
const targetId = String(options.target || '').trim();
|
|
614
1459
|
if (!targetId) throw new Error('nimi-app pack requires --target');
|
|
@@ -620,12 +1465,18 @@ export function packAppTarget(cwd, options = {}) {
|
|
|
620
1465
|
const mode = isManagedWeb
|
|
621
1466
|
? 0o644
|
|
622
1467
|
: name === input.runtimeEntry ? 0o755 : entry.mode;
|
|
623
|
-
return {
|
|
1468
|
+
return {
|
|
1469
|
+
name,
|
|
1470
|
+
...(entry.bytes !== undefined ? { bytes: entry.bytes } : { filePath: entry.filePath }),
|
|
1471
|
+
size: entry.size,
|
|
1472
|
+
mode,
|
|
1473
|
+
};
|
|
624
1474
|
});
|
|
625
1475
|
validatePayloadLinks(new Map(payloadEntries.map((entry) => [entry.name, entry])), input.target.os);
|
|
626
1476
|
const runtimeEntry = payloadEntries.find((entry) => entry.name === input.runtimeEntry);
|
|
627
1477
|
if (!runtimeEntry) throw new Error(`runtime_entry is missing from target payload: ${input.runtimeEntry}`);
|
|
628
|
-
const
|
|
1478
|
+
const expectedRuntimeSha256 = await hashFilePath(input.runtimeHostPath);
|
|
1479
|
+
const { nativeTrust, executionProfile } = await resolveTargetFacts(input, options.production === true, expectedRuntimeSha256);
|
|
629
1480
|
const packageManifest = {
|
|
630
1481
|
format: PACKAGE_FORMAT,
|
|
631
1482
|
app_id: input.appId,
|
|
@@ -645,32 +1496,46 @@ export function packAppTarget(cwd, options = {}) {
|
|
|
645
1496
|
...Object.fromEntries(APP_INFO_DECLARATION_FIELDS.filter((key) => input.appInfo[key] !== undefined).map((key) => [key, input.appInfo[key]])),
|
|
646
1497
|
...(input.desktop !== undefined ? { desktop: input.desktop } : {}),
|
|
647
1498
|
};
|
|
1499
|
+
const licenseBytes = readFileSync(input.licensePath);
|
|
1500
|
+
const manifestBytes = Buffer.from(canonicalJson(packageManifest));
|
|
1501
|
+
const declarationBytes = Buffer.from(stringifyYaml(declaration));
|
|
1502
|
+
if (manifestBytes.length > MAX_CONTROL_DOCUMENT_BYTES || declarationBytes.length > MAX_CONTROL_DOCUMENT_BYTES) {
|
|
1503
|
+
throw new Error('Control document exceeds 1 MiB');
|
|
1504
|
+
}
|
|
648
1505
|
const archiveEntries = [
|
|
649
|
-
{ name: 'LICENSE', bytes:
|
|
650
|
-
{ name: 'manifest.json', bytes:
|
|
651
|
-
{ name: 'nimi.app.yaml', bytes:
|
|
652
|
-
{ name: 'app-info.json', bytes: infoBytes, mode: 0o644 },
|
|
1506
|
+
{ name: 'LICENSE', bytes: licenseBytes, size: licenseBytes.length, mode: 0o644 },
|
|
1507
|
+
{ name: 'manifest.json', bytes: manifestBytes, size: manifestBytes.length, mode: 0o644 },
|
|
1508
|
+
{ name: 'nimi.app.yaml', bytes: declarationBytes, size: declarationBytes.length, mode: 0o644 },
|
|
1509
|
+
{ name: 'app-info.json', bytes: infoBytes, size: infoBytes.length, mode: 0o644 },
|
|
653
1510
|
...payloadEntries,
|
|
654
1511
|
];
|
|
655
1512
|
validateCrossPlatformArchiveEntries(archiveEntries, input.target.os);
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
1513
|
+
const maxEntries = isManagedWeb ? MANAGED_WEB_MAX_RELEASE_ENTRIES : MAX_ZIP32_ENTRIES;
|
|
1514
|
+
const maxUncompressed = isManagedWeb ? MANAGED_WEB_MAX_RELEASE_BYTES : NATIVE_MAX_RELEASE_BYTES;
|
|
1515
|
+
const maxArchiveBytes = isManagedWeb ? MANAGED_WEB_MAX_ARCHIVE_BYTES : NATIVE_MAX_ARCHIVE_BYTES;
|
|
1516
|
+
if (archiveEntries.length > maxEntries) {
|
|
1517
|
+
throw new Error(`${isManagedWeb ? 'managed-web' : 'native'} package exceeds ${maxEntries} entries (${archiveEntries.length})`);
|
|
1518
|
+
}
|
|
1519
|
+
const totalUncompressedBytes = archiveEntries.reduce((sum, entry) => sum + entry.size, 0);
|
|
1520
|
+
if (totalUncompressedBytes > maxUncompressed) {
|
|
1521
|
+
throw new Error(`${isManagedWeb ? 'managed-web' : 'native'} package exceeds ${maxUncompressed} bytes uncompressed (${totalUncompressedBytes})`);
|
|
664
1522
|
}
|
|
665
|
-
const archive = writeNimiAppArchive(archiveEntries);
|
|
666
|
-
const sha256 = hashAppArchive(archive);
|
|
667
1523
|
const outputDir = path.join(targetDir, OUTPUT_DIR);
|
|
668
1524
|
mkdirSync(outputDir, { recursive: true });
|
|
669
1525
|
const stem = `${input.appId}-${input.version}-${input.targetId}`;
|
|
670
1526
|
const artifactPath = path.join(outputDir, `${stem}.nimiapp`);
|
|
671
1527
|
const metadataPath = path.join(outputDir, `${stem}.target.json`);
|
|
672
1528
|
const appInfoPath = path.join(outputDir, `${stem}.app-info.json`);
|
|
673
|
-
|
|
1529
|
+
const written = await writeNimiAppArchiveToFile(artifactPath, archiveEntries, {
|
|
1530
|
+
compress: true,
|
|
1531
|
+
maxArchiveBytes,
|
|
1532
|
+
maxTotalUncompressedBytes: maxUncompressed,
|
|
1533
|
+
hashEntryName: input.runtimeEntry,
|
|
1534
|
+
});
|
|
1535
|
+
if (written.hashedEntrySha256 !== expectedRuntimeSha256) {
|
|
1536
|
+
await fsp.rm(artifactPath, { force: true }).catch(() => {});
|
|
1537
|
+
throw new Error('Production Runtime entry changed while writing archive');
|
|
1538
|
+
}
|
|
674
1539
|
writeFileSync(appInfoPath, infoBytes);
|
|
675
1540
|
const metadata = {
|
|
676
1541
|
format: TARGET_METADATA_FORMAT,
|
|
@@ -680,8 +1545,8 @@ export function packAppTarget(cwd, options = {}) {
|
|
|
680
1545
|
os: input.target.os,
|
|
681
1546
|
arch: input.target.arch,
|
|
682
1547
|
asset_name: path.basename(artifactPath),
|
|
683
|
-
size:
|
|
684
|
-
sha256,
|
|
1548
|
+
size: written.size,
|
|
1549
|
+
sha256: written.sha256,
|
|
685
1550
|
app_info: { asset_name: path.basename(appInfoPath), size: infoBytes.length, sha256: createHash('sha256').update(infoBytes).digest('hex') },
|
|
686
1551
|
runtime_entry: input.runtimeEntry,
|
|
687
1552
|
native_trust: packageManifest.native_trust,
|
|
@@ -691,7 +1556,7 @@ export function packAppTarget(cwd, options = {}) {
|
|
|
691
1556
|
return { ok: true, command: 'pack', dir: targetDir, artifactPath, metadataPath, appInfoPath, ...metadata };
|
|
692
1557
|
}
|
|
693
1558
|
|
|
694
|
-
export function aggregateAppTargetCandidates(cwd, options = {}) {
|
|
1559
|
+
export async function aggregateAppTargetCandidates(cwd, options = {}) {
|
|
695
1560
|
const targetDir = path.resolve(cwd, String(options.dir || '').trim() || '.');
|
|
696
1561
|
const buildProfile = readNativePackProfile(targetDir);
|
|
697
1562
|
const isManagedWebProfile = buildProfile.build_profile_ref === MANAGED_WEB_BUILD_PROFILE_REF;
|
|
@@ -713,7 +1578,7 @@ export function aggregateAppTargetCandidates(cwd, options = {}) {
|
|
|
713
1578
|
throw new Error(`managed-web-pnpm-vite cannot aggregate non-universal target: ${target.target_id}`);
|
|
714
1579
|
}
|
|
715
1580
|
if (!isManagedWebProfile && target.target_id === 'desktop-universal') {
|
|
716
|
-
throw new Error(
|
|
1581
|
+
throw new Error('Native build profile cannot aggregate desktop-universal target');
|
|
717
1582
|
}
|
|
718
1583
|
const expectedTarget = TARGETS[target.target_id];
|
|
719
1584
|
if (!expectedTarget || target.os !== expectedTarget.os || target.arch !== expectedTarget.arch) {
|
|
@@ -721,7 +1586,9 @@ export function aggregateAppTargetCandidates(cwd, options = {}) {
|
|
|
721
1586
|
}
|
|
722
1587
|
const assetName = canonicalRelative(target.asset_name, `${metadataLabel}.asset_name`);
|
|
723
1588
|
if (assetName !== path.basename(assetName)) throw new Error(`Target asset_name must be a direct file name: ${assetName}`);
|
|
724
|
-
|
|
1589
|
+
const maxArchiveBytes = target.os === 'any' ? MANAGED_WEB_MAX_ARCHIVE_BYTES : NATIVE_MAX_ARCHIVE_BYTES;
|
|
1590
|
+
const maxUncompressed = target.os === 'any' ? MANAGED_WEB_MAX_RELEASE_BYTES : NATIVE_MAX_RELEASE_BYTES;
|
|
1591
|
+
if (!Number.isSafeInteger(target.size) || target.size <= 0 || target.size > maxArchiveBytes || !/^[a-f0-9]{64}$/u.test(target.sha256)) {
|
|
725
1592
|
throw new Error(`Target artifact size or SHA-256 is invalid: ${assetName}`);
|
|
726
1593
|
}
|
|
727
1594
|
const runtimeEntry = canonicalRelative(target.runtime_entry, `${metadataLabel}.runtime_entry`);
|
|
@@ -732,15 +1599,30 @@ export function aggregateAppTargetCandidates(cwd, options = {}) {
|
|
|
732
1599
|
validateNativeExecutionFacts(target.native_trust, target.execution_profile, metadataLabel, target.os);
|
|
733
1600
|
const artifactPath = path.join(outputDir, assetName);
|
|
734
1601
|
if (!existsSync(artifactPath)) throw new Error(`Target artifact is missing: ${target.asset_name}`);
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
const
|
|
1602
|
+
|
|
1603
|
+
let entries;
|
|
1604
|
+
const handle = await fsp.open(artifactPath, 'r');
|
|
1605
|
+
try {
|
|
1606
|
+
const stat = await handle.stat();
|
|
1607
|
+
if (!stat.isFile() || stat.size !== target.size || (await hashFileHandle(handle, stat.size)) !== target.sha256) {
|
|
1608
|
+
throw new Error(`Target artifact changed after pack: ${target.asset_name}`);
|
|
1609
|
+
}
|
|
1610
|
+
entries = await readNimiAppArchiveFromFile({ handle, size: stat.size }, {
|
|
1611
|
+
maxArchiveBytes,
|
|
1612
|
+
maxTotalUncompressedBytes: maxUncompressed,
|
|
1613
|
+
nimiappLayout: true,
|
|
1614
|
+
retainPredicate: (name) => NIMIAPP_CONTROL_LIMITS.has(name),
|
|
1615
|
+
});
|
|
1616
|
+
} finally {
|
|
1617
|
+
await handle.close();
|
|
1618
|
+
}
|
|
1619
|
+
|
|
738
1620
|
const infoAsset = target.app_info;
|
|
739
1621
|
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
1622
|
const infoPath = path.join(outputDir, infoAsset.asset_name);
|
|
741
1623
|
if (!existsSync(infoPath)) throw new Error(`Target App info asset is missing: ${infoAsset.asset_name}`);
|
|
742
1624
|
const infoBytes = readFileSync(infoPath);
|
|
743
|
-
if (infoBytes.length !== infoAsset.size || createHash('sha256').update(infoBytes).digest('hex') !== infoAsset.sha256 || !entries.get('app-info.json')?.bytes
|
|
1625
|
+
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
1626
|
const info = validateAppInfo(JSON.parse(infoBytes));
|
|
745
1627
|
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
1628
|
if (target.os === 'any' && info.storage_policy?.kind !== 'nimi-mediated-default') {
|
|
@@ -748,9 +1630,9 @@ export function aggregateAppTargetCandidates(cwd, options = {}) {
|
|
|
748
1630
|
}
|
|
749
1631
|
parsedInfos.push({ targetId: target.target_id, info });
|
|
750
1632
|
validatePayloadLinks(entries, target.os);
|
|
751
|
-
validateCrossPlatformArchiveEntries([...entries.entries()].map(([name, entry]) => ({ name,
|
|
1633
|
+
validateCrossPlatformArchiveEntries([...entries.entries()].map(([name, entry]) => ({ name, size: entry.size, mode: entry.mode })), target.os);
|
|
752
1634
|
const declarationEntry = entries.get('nimi.app.yaml');
|
|
753
|
-
if (declarationEntry) {
|
|
1635
|
+
if (declarationEntry?.bytes) {
|
|
754
1636
|
const declarationYamlText = declarationEntry.bytes.toString('utf8');
|
|
755
1637
|
const archivedDeclaration = parseYaml(declarationYamlText);
|
|
756
1638
|
validateManifestDesktop(archivedDeclaration?.desktop, `${target.asset_name} nimi.app.yaml desktop`, declarationYamlText);
|
|
@@ -772,7 +1654,7 @@ export function aggregateAppTargetCandidates(cwd, options = {}) {
|
|
|
772
1654
|
throw new Error(`Target managed-web archive exceeds ${MANAGED_WEB_MAX_RELEASE_ENTRIES} entries: ${target.asset_name}`);
|
|
773
1655
|
}
|
|
774
1656
|
let totalUncompressedBytes = 0;
|
|
775
|
-
for (const entry of entries.values()) totalUncompressedBytes += entry.
|
|
1657
|
+
for (const entry of entries.values()) totalUncompressedBytes += entry.size;
|
|
776
1658
|
if (totalUncompressedBytes > MANAGED_WEB_MAX_RELEASE_BYTES) {
|
|
777
1659
|
throw new Error(`Target managed-web archive exceeds ${MANAGED_WEB_MAX_RELEASE_BYTES} bytes uncompressed: ${target.asset_name}`);
|
|
778
1660
|
}
|
|
@@ -796,9 +1678,13 @@ export function aggregateAppTargetCandidates(cwd, options = {}) {
|
|
|
796
1678
|
throw new Error('Repository storefront media changed after target packing; rebuild targets and aggregate from the same commit');
|
|
797
1679
|
}
|
|
798
1680
|
const archiveEntries = [...mediaEntries.entries()]
|
|
799
|
-
.sort(([left], [right]) =>
|
|
1681
|
+
.sort(([left], [right]) => compareUtf8(left, right))
|
|
800
1682
|
.map(([name, bytes]) => ({ name, bytes, mode: 0o644 }));
|
|
801
|
-
const mediaArchive = writeNimiAppArchive(archiveEntries
|
|
1683
|
+
const mediaArchive = writeNimiAppArchive(archiveEntries, {
|
|
1684
|
+
compress: false,
|
|
1685
|
+
maxArchiveBytes: STOREFRONT_ARCHIVE_MAX_BYTES,
|
|
1686
|
+
maxTotalUncompressedBytes: STOREFRONT_ARCHIVE_MAX_BYTES,
|
|
1687
|
+
});
|
|
802
1688
|
if (mediaArchive.length > STOREFRONT_ARCHIVE_MAX_BYTES) {
|
|
803
1689
|
throw new Error(`Storefront media archive exceeds ${STOREFRONT_ARCHIVE_MAX_BYTES} bytes`);
|
|
804
1690
|
}
|
|
@@ -816,7 +1702,7 @@ export function aggregateAppTargetCandidates(cwd, options = {}) {
|
|
|
816
1702
|
app_id: appId,
|
|
817
1703
|
version,
|
|
818
1704
|
...(storefrontMedia ? { storefront_media: storefrontMedia } : {}),
|
|
819
|
-
targets: targets.sort((left, right) =>
|
|
1705
|
+
targets: targets.sort((left, right) => compareUtf8(left.target_id, right.target_id)),
|
|
820
1706
|
};
|
|
821
1707
|
const candidatePath = path.join(outputDir, `${appId}-${version}.candidate.json`);
|
|
822
1708
|
writeFileSync(candidatePath, canonicalJson(candidate));
|