@nimiplatform/app-tools 0.16.0-rc.12 → 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/README.md +15 -3
- package/bin/nimi-app.mjs +12 -5
- package/lib/app-dependency-combinations.mjs +1 -0
- package/lib/app-doctor-update.mjs +19 -6
- package/lib/app-pack.mjs +1238 -155
- package/lib/app-project-lifecycle.mjs +41 -5
- package/lib/app-scaffold-capabilities.mjs +28 -0
- package/lib/app-scaffold-profiles.mjs +169 -42
- package/lib/app-scaffold.mjs +289 -15
- package/lib/desktop-window.mjs +106 -0
- package/lib/hosted-web-release.mjs +31 -5
- package/lib/index.mjs +4 -3
- package/lib/payload-links.mjs +96 -18
- package/package.json +5 -5
- package/scripts/dev-shell.mjs +13 -1
- package/templates/default-starter/README.md +14 -6
package/lib/app-pack.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { assertDesktopHostSupport } from './app-host-support.mjs';
|
|
2
|
+
import { validateManifestDesktop } from './desktop-window.mjs';
|
|
2
3
|
import { isAppId } from './app-identifiers.mjs';
|
|
3
4
|
// @nimi-authority: rule.nimi.platform.app-ecosystem.p-scaf-009b
|
|
4
5
|
// @nimi-authority: rule.nimi.platform.app-ecosystem.p-napp-014a
|
|
@@ -8,6 +9,7 @@ import { isAppId } from './app-identifiers.mjs';
|
|
|
8
9
|
// @nimi-authority: rule.nimi.platform.app-ecosystem.p-napp-034a
|
|
9
10
|
// @nimi-authority: rule.nimi.platform.app-ecosystem.p-napp-043a
|
|
10
11
|
|
|
12
|
+
import { isUtf8 } from 'node:buffer';
|
|
11
13
|
import { createHash } from 'node:crypto';
|
|
12
14
|
import {
|
|
13
15
|
existsSync,
|
|
@@ -23,29 +25,186 @@ import {
|
|
|
23
25
|
readlinkSync,
|
|
24
26
|
writeFileSync,
|
|
25
27
|
} from 'node:fs';
|
|
28
|
+
import * as fsp from 'node:fs/promises';
|
|
26
29
|
import path from 'node:path';
|
|
30
|
+
import {
|
|
31
|
+
crc32 as nativeCrc32,
|
|
32
|
+
createDeflateRaw,
|
|
33
|
+
createInflateRaw,
|
|
34
|
+
deflateRawSync,
|
|
35
|
+
inflateRawSync,
|
|
36
|
+
} from 'node:zlib';
|
|
27
37
|
import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
|
|
28
38
|
import { APP_INFO_DECLARATION_FIELDS, APP_INFO_MAX_BYTES, readAppInfo, readAppStorefront, validateAppInfo } from './app-info.mjs';
|
|
29
39
|
import { STOREFRONT_ARCHIVE_MAX_BYTES } from './storefront-media.mjs';
|
|
30
40
|
import { observeWindowsExecutableFacts } from './windows-powershell.mjs';
|
|
31
|
-
import { SYMBOLIC_LINK_MODE, validatePayloadLinks } from './payload-links.mjs';
|
|
41
|
+
import { MAX_SYMLINK_TARGET_BYTES, SYMBOLIC_LINK_MODE, validatePayloadLinks } from './payload-links.mjs';
|
|
32
42
|
import { observeMacOSExecutableFacts } from './macos-native.mjs';
|
|
33
43
|
|
|
34
44
|
const PACKAGE_FORMAT = 'nimi.app-package/v2';
|
|
35
45
|
const TARGET_METADATA_FORMAT = 'nimi.app-target-candidate/v1';
|
|
36
46
|
const AGGREGATE_FORMAT = 'nimi.app-release-candidate/v1';
|
|
37
47
|
const BUILD_PROFILE_PATH = '.nimi/config/build-profile.yaml';
|
|
48
|
+
const MANAGED_WEB_BUILD_PROFILE_REF = 'managed-web-pnpm-vite';
|
|
49
|
+
const MANAGED_WEB_EXECUTION_PROFILE_REF = 'nimi-managed-web-v1';
|
|
50
|
+
const MANAGED_WEB_RUNTIME_ENTRY = 'payload/index.html';
|
|
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;
|
|
38
78
|
const ELECTRON_BUILD_PROFILE_REF = 'electron-packager-pnpm-vite';
|
|
39
79
|
const APP_OWNED_ELECTRON_BUILD_PROFILE_REF = 'electron-pnpm';
|
|
40
80
|
const OUTPUT_DIR = 'dist/nimi-app';
|
|
41
|
-
const SEMVER_PATTERN = /^(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)(?:-[0-9A-Za-z]
|
|
81
|
+
const SEMVER_PATTERN = /^(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)(?:-(?:0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*))*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u;
|
|
42
82
|
const TARGETS = Object.freeze({
|
|
43
83
|
'windows-x86_64': Object.freeze({ os: 'windows', arch: 'x86_64' }),
|
|
44
84
|
'macos-aarch64': Object.freeze({ os: 'macos', arch: 'arm64' }),
|
|
85
|
+
'desktop-universal': Object.freeze({ os: 'any', arch: 'any' }),
|
|
45
86
|
});
|
|
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
|
+
]);
|
|
95
|
+
|
|
96
|
+
function validWindowsSegment(segment) {
|
|
97
|
+
if (/[<>:"|?*]/u.test(segment) || segment.endsWith('.') || segment.endsWith(' ')) {
|
|
98
|
+
return false;
|
|
99
|
+
}
|
|
100
|
+
const base = segment.split('.', 1)[0].replace(/ +$/u, '').toUpperCase();
|
|
101
|
+
if (WINDOWS_RESERVED_BASES.has(base)) return false;
|
|
102
|
+
if (/^(?:COM|LPT)(?:[1-9]|¹|²|³)$/u.test(base)) return false;
|
|
103
|
+
return true;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function unicodeCaseFold(input) {
|
|
107
|
+
let out = '';
|
|
108
|
+
for (const ch of input.normalize('NFC')) {
|
|
109
|
+
const cp = ch.codePointAt(0);
|
|
110
|
+
if (cp === 0x0131) out += '\u0131';
|
|
111
|
+
else if (cp === 0x1e9e) out += 'ss';
|
|
112
|
+
else if (cp >= 0x13f8 && cp <= 0x13fd) out += String.fromCodePoint(cp - 8);
|
|
113
|
+
else if (cp >= 0xab70 && cp <= 0xabbf) out += String.fromCodePoint(cp - 0x97d0);
|
|
114
|
+
else out += ch.toUpperCase().toLowerCase();
|
|
115
|
+
}
|
|
116
|
+
return out;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function targetPathCollisionKey(name, targetOS) {
|
|
120
|
+
const normalized = name.normalize('NFC');
|
|
121
|
+
if (targetOS === 'windows' || targetOS === 'any') {
|
|
122
|
+
return unicodeCaseFold(normalized);
|
|
123
|
+
}
|
|
124
|
+
return normalized;
|
|
125
|
+
}
|
|
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
|
+
}
|
|
46
155
|
|
|
47
|
-
function
|
|
48
|
-
|
|
156
|
+
function validateCrossPlatformArchiveEntries(entries, targetOS) {
|
|
157
|
+
const roles = new Map();
|
|
158
|
+
let fileCount = 0;
|
|
159
|
+
for (const entry of entries) {
|
|
160
|
+
const name = entry.name;
|
|
161
|
+
const segments = name.split('/');
|
|
162
|
+
if (segments.length - 1 > MAX_ARCHIVE_DIRECTORY_DEPTH) {
|
|
163
|
+
throw new Error(`Archive directory depth exceeds ${MAX_ARCHIVE_DIRECTORY_DEPTH}: ${name}`);
|
|
164
|
+
}
|
|
165
|
+
for (const segment of segments) {
|
|
166
|
+
for (const ch of segment) {
|
|
167
|
+
const code = ch.codePointAt(0);
|
|
168
|
+
if (code < 0x20 || code === 0x7f) {
|
|
169
|
+
throw new Error(`Archive entry path contains control character: ${name}`);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
if ((targetOS === 'windows' || targetOS === 'any') && !validWindowsSegment(segment)) {
|
|
173
|
+
throw new Error(`Archive entry path uses invalid Windows segment: ${name}`);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
for (let index = 0; index < segments.length; index += 1) {
|
|
177
|
+
const prefix = segments.slice(0, index + 1).join('/');
|
|
178
|
+
const key = targetPathCollisionKey(prefix, targetOS);
|
|
179
|
+
const isFile = index === segments.length - 1;
|
|
180
|
+
const previous = roles.get(key);
|
|
181
|
+
if (previous) {
|
|
182
|
+
if (previous.spelling !== prefix || previous.file || isFile) {
|
|
183
|
+
throw new Error(`Archive entry path collision on ${targetOS}: ${previous.spelling} and ${prefix}`);
|
|
184
|
+
}
|
|
185
|
+
} else {
|
|
186
|
+
roles.set(key, { spelling: prefix, file: isFile });
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
fileCount += 1;
|
|
190
|
+
const dirCount = roles.size - fileCount;
|
|
191
|
+
if (targetOS === 'any' && dirCount > MANAGED_WEB_MAX_RELEASE_ENTRIES) {
|
|
192
|
+
throw new Error(`Managed-web package exceeds ${MANAGED_WEB_MAX_RELEASE_ENTRIES} directories`);
|
|
193
|
+
}
|
|
194
|
+
if (targetOS !== 'any' && dirCount > NATIVE_MAX_DIRECTORIES) {
|
|
195
|
+
throw new Error(`Native package exceeds ${NATIVE_MAX_DIRECTORIES} directories`);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function pathsOverlapOrEqual(left, right) {
|
|
201
|
+
const a = path.resolve(left);
|
|
202
|
+
const b = path.resolve(right);
|
|
203
|
+
const cmpA = process.platform === 'win32' ? a.toLowerCase() : a;
|
|
204
|
+
const cmpB = process.platform === 'win32' ? b.toLowerCase() : b;
|
|
205
|
+
return cmpA === cmpB
|
|
206
|
+
|| cmpA.startsWith(`${cmpB}${path.sep}`)
|
|
207
|
+
|| cmpB.startsWith(`${cmpA}${path.sep}`);
|
|
49
208
|
}
|
|
50
209
|
|
|
51
210
|
function sortedValue(value) {
|
|
@@ -69,6 +228,31 @@ export function hashAppArchive(bytes) {
|
|
|
69
228
|
return hash.digest('hex');
|
|
70
229
|
}
|
|
71
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
|
+
|
|
72
256
|
export function writeAppArchiveFile(filePath, bytes) {
|
|
73
257
|
const fd = openSync(filePath, 'w');
|
|
74
258
|
try {
|
|
@@ -100,12 +284,12 @@ function sameCanonicalValue(left, right) {
|
|
|
100
284
|
}
|
|
101
285
|
|
|
102
286
|
function canonicalRelative(value, field) {
|
|
103
|
-
if (typeof value !== 'string' || !value || value !== value.trim() || value.includes('\\')) {
|
|
104
|
-
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`);
|
|
105
289
|
}
|
|
106
290
|
const parts = value.split('/');
|
|
107
291
|
if (value.startsWith('/') || parts.some((part) => !part || part === '.' || part === '..')) {
|
|
108
|
-
throw new Error(
|
|
292
|
+
throw new Error(`Invalid ${field}: must be a canonical relative path`);
|
|
109
293
|
}
|
|
110
294
|
return value;
|
|
111
295
|
}
|
|
@@ -143,22 +327,23 @@ function collectPayload(payloadPath, os) {
|
|
|
143
327
|
const stat = lstatSync(payloadPath);
|
|
144
328
|
if (stat.isSymbolicLink()) throw new Error('Pack payload must not contain symbolic links');
|
|
145
329
|
if (stat.isFile()) {
|
|
146
|
-
return [{ relative: path.basename(payloadPath),
|
|
330
|
+
return [{ relative: path.basename(payloadPath), filePath: payloadPath, size: stat.size, mode: stat.mode & 0o111 ? 0o755 : 0o644 }];
|
|
147
331
|
}
|
|
148
332
|
if (!stat.isDirectory()) throw new Error('Pack payload must be a regular file or directory');
|
|
149
333
|
const entries = [];
|
|
150
334
|
const walk = (current, prefix = '') => {
|
|
151
|
-
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))) {
|
|
152
336
|
const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
|
|
153
337
|
const absolute = path.join(current, entry.name);
|
|
154
338
|
const entryStat = lstatSync(absolute);
|
|
155
339
|
if (entryStat.isSymbolicLink()) {
|
|
156
340
|
if (os !== 'macos') throw new Error(`Pack payload must not contain symbolic links: ${relative}`);
|
|
157
|
-
|
|
341
|
+
const linkBytes = Buffer.from(readlinkSync(absolute), 'utf8');
|
|
342
|
+
entries.push({ relative, bytes: linkBytes, size: linkBytes.length, mode: SYMBOLIC_LINK_MODE });
|
|
158
343
|
} else if (entryStat.isDirectory()) {
|
|
159
344
|
walk(absolute, relative);
|
|
160
345
|
} else if (entryStat.isFile()) {
|
|
161
|
-
entries.push({ relative,
|
|
346
|
+
entries.push({ relative, filePath: absolute, size: entryStat.size, mode: entryStat.mode & 0o111 ? 0o755 : 0o644 });
|
|
162
347
|
} else {
|
|
163
348
|
throw new Error(`Unsupported pack payload entry: ${relative}`);
|
|
164
349
|
}
|
|
@@ -169,139 +354,896 @@ function collectPayload(payloadPath, os) {
|
|
|
169
354
|
return entries;
|
|
170
355
|
}
|
|
171
356
|
|
|
172
|
-
|
|
173
|
-
const
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
for (let bit = 0; bit < 8; bit += 1) value = (value & 1) ? (0xedb88320 ^ (value >>> 1)) : (value >>> 1);
|
|
177
|
-
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}`);
|
|
178
361
|
}
|
|
179
|
-
|
|
180
|
-
})
|
|
362
|
+
if (name.split('/').length - 1 > MAX_ARCHIVE_DIRECTORY_DEPTH) {
|
|
363
|
+
throw new Error(`Invalid archive directory depth exceeds ${MAX_ARCHIVE_DIRECTORY_DEPTH}: ${name}`);
|
|
364
|
+
}
|
|
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
|
+
}
|
|
181
373
|
|
|
182
|
-
function
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
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;
|
|
186
388
|
}
|
|
187
389
|
|
|
188
|
-
function
|
|
189
|
-
const
|
|
190
|
-
|
|
191
|
-
|
|
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;
|
|
410
|
+
}
|
|
411
|
+
|
|
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
|
+
}
|
|
192
436
|
}
|
|
193
437
|
|
|
194
|
-
export function writeNimiAppArchive(entries) {
|
|
195
|
-
const
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
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
|
+
}
|
|
202
457
|
|
|
203
458
|
const localParts = [];
|
|
204
459
|
const centralParts = [];
|
|
205
460
|
let offset = 0;
|
|
461
|
+
let totalUncompressed = 0;
|
|
206
462
|
for (const entry of normalized) {
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
central
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
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;
|
|
244
502
|
}
|
|
245
503
|
const central = Buffer.concat(centralParts);
|
|
246
|
-
const
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
end.
|
|
254
|
-
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);
|
|
255
512
|
return Buffer.concat([...localParts, central, end]);
|
|
256
513
|
}
|
|
257
514
|
|
|
258
|
-
|
|
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 = {}) {
|
|
259
984
|
const archive = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes);
|
|
260
|
-
|
|
261
|
-
const
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
const
|
|
267
|
-
|
|
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;
|
|
268
999
|
for (let index = 0; index < count; index += 1) {
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
const
|
|
297
|
-
|
|
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;
|
|
1038
|
+
} else {
|
|
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
|
+
}
|
|
298
1060
|
return entries;
|
|
299
1061
|
}
|
|
300
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
|
+
|
|
301
1243
|
function readNativePackProfile(targetDir) {
|
|
302
1244
|
const profile = readYaml(path.join(targetDir, BUILD_PROFILE_PATH), BUILD_PROFILE_PATH);
|
|
303
1245
|
assertDesktopHostSupport(profile.build_profile_ref);
|
|
304
|
-
if (![ELECTRON_BUILD_PROFILE_REF, APP_OWNED_ELECTRON_BUILD_PROFILE_REF].includes(profile.build_profile_ref)) {
|
|
1246
|
+
if (![MANAGED_WEB_BUILD_PROFILE_REF, ELECTRON_BUILD_PROFILE_REF, APP_OWNED_ELECTRON_BUILD_PROFILE_REF].includes(profile.build_profile_ref)) {
|
|
305
1247
|
throw new Error(`${BUILD_PROFILE_PATH} build_profile_ref is unsupported: ${String(profile.build_profile_ref)}`);
|
|
306
1248
|
}
|
|
307
1249
|
return profile;
|
|
@@ -311,16 +1253,27 @@ function readPackInputs(targetDir, targetId) {
|
|
|
311
1253
|
const buildProfile = readNativePackProfile(targetDir);
|
|
312
1254
|
const target = TARGETS[targetId];
|
|
313
1255
|
if (!target) throw new Error(`Unsupported App package target: ${targetId}`);
|
|
1256
|
+
const isManagedWeb = buildProfile.build_profile_ref === MANAGED_WEB_BUILD_PROFILE_REF;
|
|
1257
|
+
if (isManagedWeb && targetId !== 'desktop-universal') {
|
|
1258
|
+
throw new Error(`managed-web-pnpm-vite only supports target desktop-universal, got: ${targetId}`);
|
|
1259
|
+
}
|
|
1260
|
+
if (!isManagedWeb && targetId === 'desktop-universal') {
|
|
1261
|
+
throw new Error(`Target desktop-universal requires build_profile_ref ${MANAGED_WEB_BUILD_PROFILE_REF}`);
|
|
1262
|
+
}
|
|
314
1263
|
const packageJson = readJson(path.join(targetDir, 'package.json'), 'package.json');
|
|
315
1264
|
const licensePath = path.join(targetDir, 'LICENSE');
|
|
316
1265
|
if (!existsSync(licensePath)) throw new Error('App package LICENSE is missing');
|
|
317
1266
|
const licenseStat = lstatSync(licensePath);
|
|
318
|
-
if (!licenseStat.isFile() || licenseStat.isSymbolicLink() || licenseStat.size === 0) {
|
|
319
|
-
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`);
|
|
320
1269
|
}
|
|
321
1270
|
const manifestPath = path.join(targetDir, 'nimi.app.yaml');
|
|
322
1271
|
const manifest = readYaml(manifestPath, 'nimi.app.yaml');
|
|
1272
|
+
const desktop = validateManifestDesktop(manifest.desktop, 'nimi.app.yaml desktop');
|
|
323
1273
|
const appInfo = readAppInfo(targetDir, targetId);
|
|
1274
|
+
if (isManagedWeb && appInfo.storage_policy?.kind !== 'nimi-mediated-default') {
|
|
1275
|
+
throw new Error('managed-web packages require storage_policy.kind: nimi-mediated-default');
|
|
1276
|
+
}
|
|
324
1277
|
const appId = String(manifest.app_id || '');
|
|
325
1278
|
const version = String(packageJson.version || '');
|
|
326
1279
|
if (!isAppId(appId)) throw new Error('nimi.app.yaml app_id must be canonical and dotted');
|
|
@@ -331,15 +1284,22 @@ function readPackInputs(targetDir, targetId) {
|
|
|
331
1284
|
if (!configured || typeof configured !== 'object' || Array.isArray(configured)) throw new Error(`Build profile does not declare target: ${targetId}`);
|
|
332
1285
|
if (configured.os !== target.os || configured.arch !== target.arch) throw new Error(`Build profile target identity mismatch: ${targetId}`);
|
|
333
1286
|
const payload = resolveInside(targetDir, configured.payload_path, `targets.${targetId}.payload_path`);
|
|
1287
|
+
const outputDir = path.join(targetDir, OUTPUT_DIR);
|
|
1288
|
+
if (pathsOverlapOrEqual(payload.resolved, outputDir)) {
|
|
1289
|
+
throw new Error(`Pack payload_path (${payload.normalized}) must not overlap ${OUTPUT_DIR}; emit build output to a sibling directory such as dist/renderer`);
|
|
1290
|
+
}
|
|
334
1291
|
if (!existsSync(payload.resolved)) throw new Error(`Built target payload is missing: ${payload.normalized}`);
|
|
335
1292
|
const runtimeEntry = canonicalRelative(configured.runtime_entry, `targets.${targetId}.runtime_entry`);
|
|
336
1293
|
if (!runtimeEntry.startsWith('payload/')) throw new Error('runtime_entry must resolve inside the packaged payload');
|
|
1294
|
+
if (isManagedWeb && runtimeEntry !== MANAGED_WEB_RUNTIME_ENTRY) {
|
|
1295
|
+
throw new Error(`managed-web runtime_entry must be ${MANAGED_WEB_RUNTIME_ENTRY}`);
|
|
1296
|
+
}
|
|
337
1297
|
const payloadStat = lstatSync(payload.resolved);
|
|
338
1298
|
const runtimeRelative = runtimeEntry.slice('payload/'.length);
|
|
339
1299
|
const runtimeHostPath = payloadStat.isFile()
|
|
340
1300
|
? payload.resolved
|
|
341
1301
|
: resolveInside(payload.resolved, runtimeRelative, `targets.${targetId}.runtime_entry`).resolved;
|
|
342
|
-
return { target, targetId, targetDir, packageJson, licensePath, manifestPath, appInfo, appId, version, payloadPath: payload.resolved, runtimeEntry, runtimeHostPath };
|
|
1302
|
+
return { buildProfile, desktop, target, targetId, targetDir, packageJson, licensePath, manifestPath, appInfo, appId, version, payloadPath: payload.resolved, runtimeEntry, runtimeHostPath };
|
|
343
1303
|
}
|
|
344
1304
|
|
|
345
1305
|
export function classifyWindowsNativeTrustObservation(observation) {
|
|
@@ -371,18 +1331,29 @@ export function classifyWindowsNativeTrustObservation(observation) {
|
|
|
371
1331
|
throw new Error(`Windows Authenticode verification failed: status=${String(status)}, type=${String(signatureType)}, signer=${certificateSubject === null ? 'absent' : 'present'}`);
|
|
372
1332
|
}
|
|
373
1333
|
|
|
374
|
-
function observeProductionWindowsFacts(input,
|
|
1334
|
+
async function observeProductionWindowsFacts(input, expectedRuntimeSha256) {
|
|
375
1335
|
if (process.platform !== 'win32' || process.arch !== 'x64') throw new Error('Production Windows pack must run on windows-x86_64');
|
|
376
1336
|
const observed = observeWindowsExecutableFacts(input.runtimeHostPath);
|
|
377
|
-
const
|
|
378
|
-
if (
|
|
1337
|
+
const currentSha = await hashFilePath(input.runtimeHostPath);
|
|
1338
|
+
if (currentSha !== expectedRuntimeSha256) {
|
|
379
1339
|
throw new Error('Production Runtime entry changed while native and execution facts were observed');
|
|
380
1340
|
}
|
|
381
1341
|
const nativeTrust = classifyWindowsNativeTrustObservation(observed.authenticode);
|
|
382
1342
|
return { nativeTrust, executionProfile: observed.execution_profile };
|
|
383
1343
|
}
|
|
384
1344
|
|
|
385
|
-
function resolveTargetFacts(input, production,
|
|
1345
|
+
async function resolveTargetFacts(input, production, expectedRuntimeSha256) {
|
|
1346
|
+
if (input.target.os === 'any') {
|
|
1347
|
+
return {
|
|
1348
|
+
nativeTrust: {
|
|
1349
|
+
posture: 'nimi-managed-carrier',
|
|
1350
|
+
certificate_subject: null,
|
|
1351
|
+
},
|
|
1352
|
+
executionProfile: {
|
|
1353
|
+
launch_mode: MANAGED_WEB_EXECUTION_PROFILE_REF,
|
|
1354
|
+
},
|
|
1355
|
+
};
|
|
1356
|
+
}
|
|
386
1357
|
if (!production) {
|
|
387
1358
|
return {
|
|
388
1359
|
nativeTrust: { posture: 'development-unsigned' },
|
|
@@ -391,16 +1362,37 @@ function resolveTargetFacts(input, production, archivedRuntimeEntryBytes) {
|
|
|
391
1362
|
}
|
|
392
1363
|
if (input.target.os === 'macos') {
|
|
393
1364
|
const facts = observeMacOSExecutableFacts(input.runtimeHostPath);
|
|
394
|
-
if (
|
|
1365
|
+
if ((await hashFilePath(input.runtimeHostPath)) !== expectedRuntimeSha256) {
|
|
1366
|
+
throw new Error('Production Runtime entry changed during macOS native observation');
|
|
1367
|
+
}
|
|
395
1368
|
return facts;
|
|
396
1369
|
}
|
|
397
|
-
return observeProductionWindowsFacts(input,
|
|
1370
|
+
return observeProductionWindowsFacts(input, expectedRuntimeSha256);
|
|
398
1371
|
}
|
|
399
1372
|
|
|
400
1373
|
function validateNativeExecutionFacts(nativeTrust, executionProfile, label, os) {
|
|
401
1374
|
if (!nativeTrust || typeof nativeTrust !== 'object' || Array.isArray(nativeTrust)) {
|
|
402
1375
|
throw new Error(`${label} native_trust must be an object`);
|
|
403
1376
|
}
|
|
1377
|
+
if (os === 'any') {
|
|
1378
|
+
if (
|
|
1379
|
+
!executionProfile
|
|
1380
|
+
|| typeof executionProfile !== 'object'
|
|
1381
|
+
|| Array.isArray(executionProfile)
|
|
1382
|
+
|| Object.keys(executionProfile).join(',') !== 'launch_mode'
|
|
1383
|
+
|| executionProfile.launch_mode !== MANAGED_WEB_EXECUTION_PROFILE_REF
|
|
1384
|
+
) {
|
|
1385
|
+
throw new Error(`${label} managed-web execution_profile must use ${MANAGED_WEB_EXECUTION_PROFILE_REF}`);
|
|
1386
|
+
}
|
|
1387
|
+
if (
|
|
1388
|
+
Object.keys(nativeTrust).sort().join(',') !== 'certificate_subject,posture'
|
|
1389
|
+
|| nativeTrust.posture !== 'nimi-managed-carrier'
|
|
1390
|
+
|| nativeTrust.certificate_subject !== null
|
|
1391
|
+
) {
|
|
1392
|
+
throw new Error(`${label} managed-web native_trust posture is inconsistent`);
|
|
1393
|
+
}
|
|
1394
|
+
return;
|
|
1395
|
+
}
|
|
404
1396
|
if (nativeTrust.posture === 'development-unsigned') {
|
|
405
1397
|
if (executionProfile !== null || Object.keys(nativeTrust).length !== 1) {
|
|
406
1398
|
throw new Error(`${label} development native/execution posture is inconsistent`);
|
|
@@ -451,7 +1443,7 @@ function validateNativeExecutionFacts(nativeTrust, executionProfile, label, os)
|
|
|
451
1443
|
|
|
452
1444
|
function readPackageManifestFromArchive(entries, label) {
|
|
453
1445
|
const entry = entries.get('manifest.json');
|
|
454
|
-
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`);
|
|
455
1447
|
try {
|
|
456
1448
|
const manifest = JSON.parse(entry.bytes.toString('utf8'));
|
|
457
1449
|
if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) throw new Error('root must be an object');
|
|
@@ -461,20 +1453,30 @@ function readPackageManifestFromArchive(entries, label) {
|
|
|
461
1453
|
}
|
|
462
1454
|
}
|
|
463
1455
|
|
|
464
|
-
export function packAppTarget(cwd, options = {}) {
|
|
1456
|
+
export async function packAppTarget(cwd, options = {}) {
|
|
465
1457
|
const targetDir = path.resolve(cwd, String(options.dir || '').trim() || '.');
|
|
466
1458
|
const targetId = String(options.target || '').trim();
|
|
467
1459
|
if (!targetId) throw new Error('nimi-app pack requires --target');
|
|
468
1460
|
const input = readPackInputs(targetDir, targetId);
|
|
1461
|
+
const isManagedWeb = input.target.os === 'any';
|
|
469
1462
|
const payloadEntries = collectPayload(input.payloadPath, input.target.os).map((entry) => {
|
|
470
1463
|
const name = `payload/${entry.relative.replaceAll('\\', '/')}`;
|
|
471
1464
|
if (name === input.runtimeEntry && entry.mode === SYMBOLIC_LINK_MODE) throw new Error('Runtime entry must be a direct regular file');
|
|
472
|
-
|
|
1465
|
+
const mode = isManagedWeb
|
|
1466
|
+
? 0o644
|
|
1467
|
+
: name === input.runtimeEntry ? 0o755 : entry.mode;
|
|
1468
|
+
return {
|
|
1469
|
+
name,
|
|
1470
|
+
...(entry.bytes !== undefined ? { bytes: entry.bytes } : { filePath: entry.filePath }),
|
|
1471
|
+
size: entry.size,
|
|
1472
|
+
mode,
|
|
1473
|
+
};
|
|
473
1474
|
});
|
|
474
1475
|
validatePayloadLinks(new Map(payloadEntries.map((entry) => [entry.name, entry])), input.target.os);
|
|
475
1476
|
const runtimeEntry = payloadEntries.find((entry) => entry.name === input.runtimeEntry);
|
|
476
1477
|
if (!runtimeEntry) throw new Error(`runtime_entry is missing from target payload: ${input.runtimeEntry}`);
|
|
477
|
-
const
|
|
1478
|
+
const expectedRuntimeSha256 = await hashFilePath(input.runtimeHostPath);
|
|
1479
|
+
const { nativeTrust, executionProfile } = await resolveTargetFacts(input, options.production === true, expectedRuntimeSha256);
|
|
478
1480
|
const packageManifest = {
|
|
479
1481
|
format: PACKAGE_FORMAT,
|
|
480
1482
|
app_id: input.appId,
|
|
@@ -490,22 +1492,50 @@ export function packAppTarget(cwd, options = {}) {
|
|
|
490
1492
|
if (infoBytes.length > APP_INFO_MAX_BYTES) throw new Error('App info exceeds 1 MiB');
|
|
491
1493
|
// An undeclared safety_profile stays absent from the declaration copy; it is
|
|
492
1494
|
// never serialized as an empty or default declaration.
|
|
493
|
-
const declaration =
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
1495
|
+
const declaration = {
|
|
1496
|
+
...Object.fromEntries(APP_INFO_DECLARATION_FIELDS.filter((key) => input.appInfo[key] !== undefined).map((key) => [key, input.appInfo[key]])),
|
|
1497
|
+
...(input.desktop !== undefined ? { desktop: input.desktop } : {}),
|
|
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
|
+
}
|
|
1505
|
+
const archiveEntries = [
|
|
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 },
|
|
499
1510
|
...payloadEntries,
|
|
500
|
-
]
|
|
501
|
-
|
|
1511
|
+
];
|
|
1512
|
+
validateCrossPlatformArchiveEntries(archiveEntries, input.target.os);
|
|
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})`);
|
|
1522
|
+
}
|
|
502
1523
|
const outputDir = path.join(targetDir, OUTPUT_DIR);
|
|
503
1524
|
mkdirSync(outputDir, { recursive: true });
|
|
504
1525
|
const stem = `${input.appId}-${input.version}-${input.targetId}`;
|
|
505
1526
|
const artifactPath = path.join(outputDir, `${stem}.nimiapp`);
|
|
506
1527
|
const metadataPath = path.join(outputDir, `${stem}.target.json`);
|
|
507
1528
|
const appInfoPath = path.join(outputDir, `${stem}.app-info.json`);
|
|
508
|
-
|
|
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
|
+
}
|
|
509
1539
|
writeFileSync(appInfoPath, infoBytes);
|
|
510
1540
|
const metadata = {
|
|
511
1541
|
format: TARGET_METADATA_FORMAT,
|
|
@@ -515,8 +1545,8 @@ export function packAppTarget(cwd, options = {}) {
|
|
|
515
1545
|
os: input.target.os,
|
|
516
1546
|
arch: input.target.arch,
|
|
517
1547
|
asset_name: path.basename(artifactPath),
|
|
518
|
-
size:
|
|
519
|
-
sha256,
|
|
1548
|
+
size: written.size,
|
|
1549
|
+
sha256: written.sha256,
|
|
520
1550
|
app_info: { asset_name: path.basename(appInfoPath), size: infoBytes.length, sha256: createHash('sha256').update(infoBytes).digest('hex') },
|
|
521
1551
|
runtime_entry: input.runtimeEntry,
|
|
522
1552
|
native_trust: packageManifest.native_trust,
|
|
@@ -526,9 +1556,10 @@ export function packAppTarget(cwd, options = {}) {
|
|
|
526
1556
|
return { ok: true, command: 'pack', dir: targetDir, artifactPath, metadataPath, appInfoPath, ...metadata };
|
|
527
1557
|
}
|
|
528
1558
|
|
|
529
|
-
export function aggregateAppTargetCandidates(cwd, options = {}) {
|
|
1559
|
+
export async function aggregateAppTargetCandidates(cwd, options = {}) {
|
|
530
1560
|
const targetDir = path.resolve(cwd, String(options.dir || '').trim() || '.');
|
|
531
|
-
readNativePackProfile(targetDir);
|
|
1561
|
+
const buildProfile = readNativePackProfile(targetDir);
|
|
1562
|
+
const isManagedWebProfile = buildProfile.build_profile_ref === MANAGED_WEB_BUILD_PROFILE_REF;
|
|
532
1563
|
const outputDir = path.join(targetDir, OUTPUT_DIR);
|
|
533
1564
|
if (!existsSync(outputDir)) throw new Error('No target metadata exists to aggregate');
|
|
534
1565
|
const files = readdirSync(outputDir).filter((name) => name.endsWith('.target.json')).sort();
|
|
@@ -543,33 +1574,69 @@ export function aggregateAppTargetCandidates(cwd, options = {}) {
|
|
|
543
1574
|
if (target.format !== TARGET_METADATA_FORMAT || target.app_id !== appId || target.version !== version) throw new Error('Target metadata cannot be aggregated across App releases');
|
|
544
1575
|
if (seen.has(target.target_id)) throw new Error(`Duplicate target metadata: ${target.target_id}`);
|
|
545
1576
|
seen.add(target.target_id);
|
|
1577
|
+
if (isManagedWebProfile && target.target_id !== 'desktop-universal') {
|
|
1578
|
+
throw new Error(`managed-web-pnpm-vite cannot aggregate non-universal target: ${target.target_id}`);
|
|
1579
|
+
}
|
|
1580
|
+
if (!isManagedWebProfile && target.target_id === 'desktop-universal') {
|
|
1581
|
+
throw new Error('Native build profile cannot aggregate desktop-universal target');
|
|
1582
|
+
}
|
|
546
1583
|
const expectedTarget = TARGETS[target.target_id];
|
|
547
1584
|
if (!expectedTarget || target.os !== expectedTarget.os || target.arch !== expectedTarget.arch) {
|
|
548
1585
|
throw new Error(`Target metadata identity is invalid: ${target.target_id}`);
|
|
549
1586
|
}
|
|
550
1587
|
const assetName = canonicalRelative(target.asset_name, `${metadataLabel}.asset_name`);
|
|
551
1588
|
if (assetName !== path.basename(assetName)) throw new Error(`Target asset_name must be a direct file name: ${assetName}`);
|
|
552
|
-
|
|
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)) {
|
|
553
1592
|
throw new Error(`Target artifact size or SHA-256 is invalid: ${assetName}`);
|
|
554
1593
|
}
|
|
555
1594
|
const runtimeEntry = canonicalRelative(target.runtime_entry, `${metadataLabel}.runtime_entry`);
|
|
556
1595
|
if (!runtimeEntry.startsWith('payload/')) throw new Error(`Target runtime_entry must resolve inside payload: ${runtimeEntry}`);
|
|
1596
|
+
if (target.os === 'any' && runtimeEntry !== MANAGED_WEB_RUNTIME_ENTRY) {
|
|
1597
|
+
throw new Error(`Target managed-web runtime_entry must be ${MANAGED_WEB_RUNTIME_ENTRY}: ${runtimeEntry}`);
|
|
1598
|
+
}
|
|
557
1599
|
validateNativeExecutionFacts(target.native_trust, target.execution_profile, metadataLabel, target.os);
|
|
558
1600
|
const artifactPath = path.join(outputDir, assetName);
|
|
559
1601
|
if (!existsSync(artifactPath)) throw new Error(`Target artifact is missing: ${target.asset_name}`);
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
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
|
+
|
|
563
1620
|
const infoAsset = target.app_info;
|
|
564
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}`);
|
|
565
1622
|
const infoPath = path.join(outputDir, infoAsset.asset_name);
|
|
566
1623
|
if (!existsSync(infoPath)) throw new Error(`Target App info asset is missing: ${infoAsset.asset_name}`);
|
|
567
1624
|
const infoBytes = readFileSync(infoPath);
|
|
568
|
-
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}`);
|
|
569
1626
|
const info = validateAppInfo(JSON.parse(infoBytes));
|
|
570
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}`);
|
|
1628
|
+
if (target.os === 'any' && info.storage_policy?.kind !== 'nimi-mediated-default') {
|
|
1629
|
+
throw new Error(`Target managed-web package must use nimi-mediated-default storage: ${target.target_id}`);
|
|
1630
|
+
}
|
|
571
1631
|
parsedInfos.push({ targetId: target.target_id, info });
|
|
572
1632
|
validatePayloadLinks(entries, target.os);
|
|
1633
|
+
validateCrossPlatformArchiveEntries([...entries.entries()].map(([name, entry]) => ({ name, size: entry.size, mode: entry.mode })), target.os);
|
|
1634
|
+
const declarationEntry = entries.get('nimi.app.yaml');
|
|
1635
|
+
if (declarationEntry?.bytes) {
|
|
1636
|
+
const declarationYamlText = declarationEntry.bytes.toString('utf8');
|
|
1637
|
+
const archivedDeclaration = parseYaml(declarationYamlText);
|
|
1638
|
+
validateManifestDesktop(archivedDeclaration?.desktop, `${target.asset_name} nimi.app.yaml desktop`, declarationYamlText);
|
|
1639
|
+
}
|
|
573
1640
|
const manifest = readPackageManifestFromArchive(entries, metadataLabel);
|
|
574
1641
|
if (manifest.format !== PACKAGE_FORMAT) throw new Error(`Target archive manifest format is invalid: ${target.asset_name}`);
|
|
575
1642
|
for (const field of ['app_id', 'version', 'target_id', 'os', 'arch', 'runtime_entry', 'native_trust', 'execution_profile']) {
|
|
@@ -579,7 +1646,19 @@ export function aggregateAppTargetCandidates(cwd, options = {}) {
|
|
|
579
1646
|
}
|
|
580
1647
|
validateNativeExecutionFacts(manifest.native_trust, manifest.execution_profile, `${target.asset_name} archive manifest`, target.os);
|
|
581
1648
|
const runtimeEntryArchive = entries.get(runtimeEntry);
|
|
582
|
-
if (
|
|
1649
|
+
if (target.os === 'any') {
|
|
1650
|
+
if (!runtimeEntryArchive || runtimeEntryArchive.mode !== 0o644) {
|
|
1651
|
+
throw new Error(`Target managed-web archive runtime_entry is missing or not 0644: ${runtimeEntry}`);
|
|
1652
|
+
}
|
|
1653
|
+
if (entries.size > MANAGED_WEB_MAX_RELEASE_ENTRIES) {
|
|
1654
|
+
throw new Error(`Target managed-web archive exceeds ${MANAGED_WEB_MAX_RELEASE_ENTRIES} entries: ${target.asset_name}`);
|
|
1655
|
+
}
|
|
1656
|
+
let totalUncompressedBytes = 0;
|
|
1657
|
+
for (const entry of entries.values()) totalUncompressedBytes += entry.size;
|
|
1658
|
+
if (totalUncompressedBytes > MANAGED_WEB_MAX_RELEASE_BYTES) {
|
|
1659
|
+
throw new Error(`Target managed-web archive exceeds ${MANAGED_WEB_MAX_RELEASE_BYTES} bytes uncompressed: ${target.asset_name}`);
|
|
1660
|
+
}
|
|
1661
|
+
} else if (!runtimeEntryArchive || runtimeEntryArchive.mode !== 0o755) {
|
|
583
1662
|
throw new Error(`Target archive runtime_entry is missing or non-executable: ${runtimeEntry}`);
|
|
584
1663
|
}
|
|
585
1664
|
}
|
|
@@ -599,9 +1678,13 @@ export function aggregateAppTargetCandidates(cwd, options = {}) {
|
|
|
599
1678
|
throw new Error('Repository storefront media changed after target packing; rebuild targets and aggregate from the same commit');
|
|
600
1679
|
}
|
|
601
1680
|
const archiveEntries = [...mediaEntries.entries()]
|
|
602
|
-
.sort(([left], [right]) =>
|
|
1681
|
+
.sort(([left], [right]) => compareUtf8(left, right))
|
|
603
1682
|
.map(([name, bytes]) => ({ name, bytes, mode: 0o644 }));
|
|
604
|
-
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
|
+
});
|
|
605
1688
|
if (mediaArchive.length > STOREFRONT_ARCHIVE_MAX_BYTES) {
|
|
606
1689
|
throw new Error(`Storefront media archive exceeds ${STOREFRONT_ARCHIVE_MAX_BYTES} bytes`);
|
|
607
1690
|
}
|
|
@@ -619,7 +1702,7 @@ export function aggregateAppTargetCandidates(cwd, options = {}) {
|
|
|
619
1702
|
app_id: appId,
|
|
620
1703
|
version,
|
|
621
1704
|
...(storefrontMedia ? { storefront_media: storefrontMedia } : {}),
|
|
622
|
-
targets: targets.sort((left, right) =>
|
|
1705
|
+
targets: targets.sort((left, right) => compareUtf8(left.target_id, right.target_id)),
|
|
623
1706
|
};
|
|
624
1707
|
const candidatePath = path.join(outputDir, `${appId}-${version}.candidate.json`);
|
|
625
1708
|
writeFileSync(candidatePath, canonicalJson(candidate));
|